Trims leaves from tree that are not observed at highest-resolution level

        This is a bit hacky-- what it does is
345031
def trim(self):
        
        # Only allow leaves to stay on list (highest-resolution) level
        return

        for l in self._levels[-2::-1]:
            for n in l:
                if n.is_leaf:
                    n.parent.remove_child(n.label)

        self._clear_all_leaves()
574898
def patch_tree(actions, tree):
    """"""
    patcher = patch.Patcher()
    return patcher.patch(actions, tree)
1149938
function cleanBogus( block ) {
			var bogus = [];
			var last = getLast( block ), node, previous;

			if ( last ) {
				// Check for bogus at the end of this block.
				// e.g. <p>foo<br /></p>
				maybeBogus( last, 1 ) && bogus.push( last );

				while ( last ) {
					// Check for bogus at the end of any pseudo block contained.
					if ( isBlockBoundary( last ) && ( node = getPrevious( last ) ) && maybeBogus( node ) ) {
						// Bogus must have inline proceeding, instead single BR between two blocks,
						// is considered as filler, e.g. <hr /><br /><hr />
						if ( ( previous = getPrevious( node ) ) && !isBlockBoundary( previous ) )
							bogus.push( node );
						// Convert the filler into appropriate form.
						else {
							createFiller( isOutput ).insertAfter( node );
							node.remove();
						}
					}

					last = last.previous;
				}
			}

			// Now remove all bogus collected from above.
			for ( var i = 0 ; i < bogus.length ; i++ )
				bogus[ i ].remove();
		}
440895
function Leaf__modify(edit, keyEq, shift, f, h, k, size) {
    if (keyEq(k, this.key)) {
        var _v = f(this.value);
        if (_v === this.value) return this;else if (_v === nothing) {
            --size.value;
            return empty;
        }
        if (canEditNode(edit, this)) {
            this.value = _v;
            return this;
        }
        return Leaf(edit, h, k, _v);
    }
    var v = f();
    if (v === nothing) return this;
    ++size.value;
    return mergeLeaves(edit, shift, this.hash, this, h, Leaf(edit, h, k, v));
}
961228
def ms_cutlo(self, viewer, event, data_x, data_y):
        
        if not self.cancut:
            return True

        x, y = self.get_win_xy(viewer)

        if event.state == 'move':
            self._cutlow_xy(viewer, x, y)

        elif event.state == 'down':
            self._start_x, self._start_y = x, y
            self._loval, self._hival = viewer.get_cut_levels()

        else:
            viewer.onscreen_message(None)
        return True
1340853
def trim_sample(data):
    
    data = utils.to_single_data(data)
    trim_reads = dd.get_trim_reads(data)
    # this block is to maintain legacy configuration files
    if not trim_reads:
        logger.info("Skipping trimming of %s." % dd.get_sample_name(data))
    else:
        if "skewer" in dd.get_tools_on(data) or trim_reads == "skewer":
            trim_adapters = skewer.trim_adapters
        else:
            trim_adapters = trim.trim_adapters
        out_files = trim_adapters(data)
        data["files"] = out_files
    return [[data]]
465876
def _do_crop(self, lines, width, height, x_crop, y_crop):
        '''
        '''
        lines = crop_or_expand(
            lines, height, default=[self.fillchar * width],
            scheme=self._schemes[y_crop])
        for i, line in enumerate(lines):
            lines[i] = crop_or_expand(
                line, width, default=self.fillchar,
                scheme=self._schemes[x_crop])
        return lines
1290
function trimEndBlankLines(array) {

    if (!array || array.length < 1) {
        return array;
    }

    let temp;
    while (array.length > 0) {
        temp = array[array.length - 1];
        if (temp === '' || Str.trim(temp, ' \t') === '') {
            array.pop();
        } else {
            break;
        }
    }

    return array;

}
175409
@Override protected boolean toJavaCheckTooBig() {
    // If the number of leaves in a forest is more than N, don't try to render it in the browser as POJO code.
    return _output==null || _output._treeStats._num_trees * _output._treeStats._mean_leaves > 1000000;
  }
455009
def sample_greedy(self):
            
        if self.leafnode:
            return self.sample_bounds()
        else:
            lp = self.lower.max_leaf_progress
            gp = self.greater.max_leaf_progress
            maxp = max(lp, gp)
        
            if self.sampling_mode['multiscale']:                
                tp = self.progress        
                if tp > maxp:
                    return self.sample_bounds()
            if gp == maxp:
                sampling_mode = self.sampling_mode
                sampling_mode['mode'] = 'greedy'
                return self.greater.sample(sampling_mode=sampling_mode)
            else:
                sampling_mode = self.sampling_mode
                sampling_mode['mode'] = 'greedy'
                return self.lower.sample(sampling_mode=sampling_mode)
1297827
def clean(self):
        
        data = self.cleaned_data
        photo = data['photo']
        if (
            (data['crop_left'] > photo.width) or
            (data['crop_top'] > photo.height) or
            ((data['crop_left'] + data['crop_width']) > photo.width) or
            ((data['crop_top'] + data['crop_height']) > photo.height)
        ):
            # raise forms.ValidationError, ugettext("The specified crop coordinates do not fit into the source photo.")
            raise ValidationError(ugettext("The specified crop coordinates do not fit into the source photo."))
        return data
1014949
def prune_tree_for_supertree(self,
                                 ott,
                                 to_prune_fsi_set,
                                 root_ott_id,
                                 taxonomy_treefile=None,
                                 id_to_other_prune_reason=None):
        
        if id_to_other_prune_reason is None:
            id_to_other_prune_reason = {}
        self.prune_to_ingroup()
        self.prune_unmapped_leaves()
        other_pruned = set()
        if id_to_other_prune_reason:
            id2p = set(id_to_other_prune_reason.keys()).intersection(set(self.by_ott_id.keys()))
            for ott_id in id2p:
                reason = id_to_other_prune_reason[ott_id]
                self.prune_ott_problem_leaves_by_id(ott_id, reason)
        # Check the stored OTT Ids against the current version of OTT
        mapped, unrecog, forward2unrecog, pruned, above_root, old2new = ott.map_ott_ids(self.by_ott_id.keys(),
                                                                                        to_prune_fsi_set, root_ott_id)
        for ott_id in unrecog:
            self.prune_ott_problem_leaves_by_id(ott_id, 'unrecognized_ott_id')
        for ott_id in forward2unrecog:
            self.prune_ott_problem_leaves_by_id(ott_id, 'forwarded_to_unrecognized_ott_id')
        for ott_id in pruned:
            self.prune_ott_problem_leaves_by_id(ott_id, 'flagged')
        for ott_id in above_root:
            self.prune_ott_problem_leaves_by_id(ott_id, 'above_root')
        for old_id, new_id in old2new.items():
            old_node_list = self.by_ott_id[old_id]
            del self.by_ott_id[old_id]
            if new_id in self.by_ott_id:
                v = self.by_ott_id[new_id]
                v.extend(old_node_list)
                v.sort() # I think only the last step requires sorting (NEED to check that,
                         # If so, we could move this sort to that point to avoid multiple sortings.
            else:
                self.by_ott_id[new_id] = old_node_list
            for sortable_el in old_node_list:
                otu = sortable_el[3]
                assert otu['^ot:ottId'] == old_id
                otu['^ot:ottId'] = new_id
                assert '^ot:ottTaxonName' in otu
                otu['^ot:ottTaxonName'] = ott.get_name(new_id)
        lost_tips = set(unrecog)
        lost_tips.update(forward2unrecog)
        lost_tips.update(pruned)
        lost_tips.update(other_pruned)
        # Get the induced tree...
        assert self.root_node_id
        try:
            ott_tree = ott.induced_tree(mapped, create_monotypic_nodes=True)
        except SpikeTreeError:
            error('SpikeTreeError from mapped ott_id list = {}'.format(', '.join([str(i) for i in mapped])))
            raise EmptyTreeError()
        if taxonomy_treefile is not None:
            with codecs.open(taxonomy_treefile, 'w', encoding='utf-8') as tto:
                ott_tree.write_newick(tto)
        # ... so that we can look for leaves mapped to ancestors of other leaves
        taxon_contains_other_ott_ids = []
        to_retain = []
        for ott_id in self.by_ott_id:
            if ott_id in lost_tips:
                continue
            n = old2new.get(ott_id)
            if n is None:
                n = ott_id
            nd = ott_tree.find_node(n)
            assert nd is not None
            if nd.children:
                # nd must be an internal node.
                #   given that the descendants of this node are mapped in a more specific
                #   way, we will prune this ott_id from the tree
                taxon_contains_other_ott_ids.append(ott_id)
            else:
                to_retain.append(ott_id)

        for ott_id in taxon_contains_other_ott_ids:
            self.prune_ott_problem_leaves_by_id(ott_id, 'mapped_to_taxon_containing_other_mapped_tips')
        # finally, we walk through any ott_id's mapped to multiple nodes
        for ott_id in to_retain:
            nm = self.by_ott_id[ott_id]
            if len(nm) > 1:
                el = nm.pop(0)
                reason = 'replaced_by_exemplar_node' if (el[0] == -1) else 'replaced_by_arbitrary_node'
                self.prune_ott_problem_leaves_by_id(ott_id, reason)
        return self
1060017
function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
    var nodeLayout = node.getLayout();
    var nodeInViewAbovePath = viewAbovePath[depth];
    var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;

    if (
        (nodeInViewAbovePath && !isAboveViewRoot)
        || (depth === viewAbovePath.length && node !== viewRoot)
    ) {
        return;
    }

    node.setLayout({
        // isInView means: viewRoot sub tree + viewAbovePath
        isInView: true,
        // invisible only means: outside view clip so that the node can not
        // see but still layout for animation preparation but not render.
        invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
        isAboveViewRoot: isAboveViewRoot
    }, true);

    // Transform to child coordinate.
    var childClipRect = new BoundingRect(
        clipRect.x - nodeLayout.x,
        clipRect.y - nodeLayout.y,
        clipRect.width,
        clipRect.height
    );

    each(node.viewChildren || [], function (child) {
        prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
    });
}
674006
private function pruneNodeCache(): void
    {
        if ($this->maxItems > 0 && count($this->nodes) > $this->maxItems) {
            $this->nodes = array_slice($this->nodes, (int)($this->maxItems * 0.2), null, true);
        }
    }
1337692
private void groomTruncationSnapshots() {
        ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
        boolean foundMostRecentSuccess = false;
        Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
            m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
        loggingLog.info("Snapshot daemon grooming truncation snapshots");
        while (iter.hasNext()) {
            Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
            TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
            if (!foundMostRecentSuccess) {
                if (snapshotAttempt.finished) {
                    loggingLog.info("Found most recent successful snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                            + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                    foundMostRecentSuccess = true;
                } else {
                    loggingLog.info("Retaining possible partial snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                            + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                }
            } else {
                loggingLog.info("Deleting old unecessary snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                        + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                toDelete.add(entry.getValue());
                iter.remove();
            }
        }

        String paths[] = new String[toDelete.size()];
        String nonces[] = new String[toDelete.size()];

        int ii = 0;
        for (TruncationSnapshotAttempt attempt : toDelete) {
            paths[ii] = attempt.path;
            paths[ii] = SnapshotUtil.getRealPath(SnapshotPathType.valueOf(attempt.pathType), paths[ii]);
            nonces[ii++] = attempt.nonce;
        }

        Object params[] =
            new Object[] {
                paths,
                nonces,
                SnapshotPathType.SNAP_CL.toString()
                };
        long handle = m_nextCallbackHandle++;
        m_procedureCallbacks.put(handle, new ProcedureCallback() {

            @Override
            public void clientCallback(ClientResponse clientResponse)
                    throws Exception {
                if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
                    SNAP_LOG.error(clientResponse.getStatusString());
                }
            }

        });
        m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
    }
259546
def _remove_tree(self, tree, parent=None):
        
        # remove sub-trees
        for sub_tree in tree.sub_trees:
            self._remove_tree(sub_tree, parent=tree)

        # remove itself
        for index in tree.indexes:
            if not getattr(tree, index):
                continue

            self._remove_from(
                getattr(self, index + "_db"),
                getattr(tree, index),
                tree,
            )

        if parent:
            self._remove_from(self.parent_db, tree.path, parent)

        self.zeo.pack()
1250319
def is_leaf(obj):
    '''
        
    '''
    if(is_dict(obj)):
        length = obj.__len__()
        if(length == 0):
            return(True)
        else:
            return(False)
    else:
        return(True)