Check if there are any compounds and add them to the variant
        
            The compounds that are added should be sorted on rank score
498651
def _add_compounds(self, variant_obj, info_dict):
        
        compound_list = []
        compound_entry = info_dict.get('Compounds')
        if compound_entry:
            for family_annotation in compound_entry.split(','):
                compounds = family_annotation.split(':')[-1].split('|')
                for compound in compounds:
                    splitted_compound = compound.split('>')

                    compound_score = None
                    if len(splitted_compound) > 1:
                        compound_id = splitted_compound[0]
                        compound_score = int(splitted_compound[-1])
                    
                    compound_list.append(Compound(
                        variant_id=compound_id,
                        combined_score=compound_score
                        )
                    )
        
        #Sort the compounds based on rank score
        compound_list.sort(key = operator.attrgetter('combined_score'), reverse=True)
        
        for compound in compound_list:
            variant_obj.add_compound(compound)
812738
private void moveIndexesToNextCombination()
    {
        for (int i = currentIndexes.length - 1, j = list.size() - 1; i >= 0; i--, j--)
        {
            if (currentIndexes[i] != j)
            {
                currentIndexes[i]++;
                for (int k = i + 1; k < currentIndexes.length; k++)
                {
                    currentIndexes[k] = currentIndexes[k - 1] + 1;
                }
                return;
            }
        }
        // otherwise, we are all done:
        currentIndexes = null;
    }
356902
def sort(ranked_records)
      ranked_records.sort { |a, b|
        a_score = a.last
        a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id

        b_score = b.last
        b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id

        if a_score == b_score
          a_id <=> b_id
        else
          b_score <=> a_score # We want the records with better relevance first.
        end

      }
    end
439271
private void makeCompounds(List<String> compoundList,
			List<String> sourceList) {
		//		System.out.println("[makeCompounds] making compounds from compoundLines");

		for (String line : compoundList) {
			if (compoundList.indexOf(line) + 1 == compoundList.size()) {
				//				System.out.println("[makeCompounds] Final line in compoundLines.");
				isLastCompndLine = true;
			}
			pdb_COMPND_Handler(line);

		}
		//		System.out.println("[makeCompounds] adding sources to compounds from sourceLines");
		// since we're starting again from the first compound, reset it here
		if ( entities.size() == 0){
			current_compound = new EntityInfo();
		} else {
			current_compound = entities.get(0);
		}
		for (String line : sourceList) {
			if (sourceList.indexOf(line) + 1 == sourceList.size()) {
				//				System.out.println("[makeCompounds] Final line in sourceLines.");
				isLastSourceLine = true;
			}
			pdb_SOURCE_Handler(line);
		}

	}
1062007
def apply(self, compound, orientation='', compound_port=''):
        
        compounds = list()
        if self.orientations.get(orientation):
            for port in self.orientations[orientation]:
                new_compound = clone(compound)
                new_port = new_compound.labels[compound_port]
                (new_compound, new_port['up'], port['up'])

                compounds.append(new_compound)
        else:
            for point in self.points:
                new_compound = clone(compound)
                new_compound.translate(point)

                compounds.append(new_compound)
        return compounds
733277
def __update_layer_density(self):
        """"""
        _stack = self.stack
        _density_lock = self.density_lock
        list_compound = _stack.keys()
        for _key in list_compound:
            if _density_lock[_key]:
                continue

            _list_ratio = _stack[_key]['stoichiometric_ratio']
            _list_density = []
            for _element in _stack[_key]['elements']:
                _list_density.append(_stack[_key][_element]['density']['value'])
                _compound_density = _utilities.get_compound_density(list_density=_list_density,
                                                                    list_ratio=_list_ratio)

            _stack[_key]['density']['value'] = _compound_density
        self.stack = _stack
375531
def get_compound_ids(self):
        
        cursor = self.conn.cursor()
        cursor.execute('SELECT inchikey_id FROM metab_compound')
        self.conn.commit()
        for row in cursor:
            if not row[0] in self.compound_ids:
                self.compound_ids.append(row[0])
1337395
function Compare () {

    var self = this;

    function compare (current, previous) {

        // all up/down properties are arrays of string.
        var build = {
                up: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                down: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                options: []
            },
            validAttrs = self.migConf.validAttributes,
            excludeAttrs = self.migConf.excludeAttributes,
            typeVariable = self.migConf.typeVariable || 'types',
            modelName = current.name,
            baseTabs = 2;

        function getTabs(int, addBase) {
            var tabs = '';
            if(addBase)
                int += baseTabs;
            while(int){
                tabs += '\t';
                --int;
            }
            return tabs;
        }

        function isValid(attr) {
            return validAttrs.indexOf(attr) !== -1;
        }

        function qwrap(str) {
            return "'" + str + "'";
        }

        function getActions(type) {
            var actions = [];
            _.forEach(type, function (v) {
                if(v.length) actions.push(v);
            });
            return actions;
        }

        function filterAttributes(obj) {
            var clone = _.clone(obj);
            _.forEach(clone, function (v,k) {
                if(!isValid(k))
                delete clone[k];
            });
            return clone;
        }

        function arrayToString(arr, def) {
            var val = '[';
            def = def || undefined;
            if(!arr || !arr.length)
                return def;
            if(!_.isString(arr[0])){
                val += arr.join(',');
            }else {
                _.forEach(arr, function (v) {
                    val += qwrap(v) + ',';
                });
                val = val.slice(0, val.length -1);
            }
            val += ']';
           return val;
        }

        function funcToString(func, level) {
            var split = func.split('\n'),
                tmp = [];
            _.forEach(split, function (v, k) {
                v = v.replace(/^\s+/, '').replace('\r', '');
                if(k +1 === split.length)
                    tmp.push(getTabs(level + 1, true) + v);
                else if(k > 0)
                    tmp.push(getTabs(level + 2, true) + v);
                else tmp.push(v);
            });
            return tmp.join('\n');
        }

        /**
         * Concats all up migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function upToString() {
            var upStr = '',
                ctr = 0,
                items = getActions(build.up),
                tab,
                suffix;
            // build the output string for up.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    upStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return upStr;
        }

        /**
         * Concats all down migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function downToString() {
            var dwnStr = '',
                ctr = 0,
                items = getActions(build.down),
                tab,
                suffix;
            // build the output string for down.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    dwnStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return dwnStr;
        }

        /**
         * Recurse child options concat to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the child object.
         * @returns {string}
         */
        function recurseChildOptions(obj, level){
            var child = '',
                len = Object.keys(obj).length,
                ctr = 0,
                prefix;
            level = level || 1;
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    var tab = getTabs(level +1, true),
                        val;
                    prefix = ctr > 0 ? ',\n' : '';
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var subChild = recurseChildOptions(obj[prop], level + 1);
                            if(subChild && subChild.length)
                                child += (tab + prop + ': { \n' + subChild + '\n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            val = arrayToString(obj[prop]);
                            if(val){
                                tab = ctr === 0 ? getTabs(level) : getTabs(level +1, true);
                                child += (prefix + tab + prop + ': ' + arrayToString(obj[prop]));
                            }
                        } else {
                            var isFunc;
                            val = obj[prop];
                            isFunc = _.isFunction(val);
                            if(_.isString(val)){
                                val = "'" + val.toString() + "'";
                            } else {
                                val = val.toString();
                                if(isFunc)
                                    val = funcToString(val, level);
                            }
                            child += (prefix + tab + prop + ': ' + val);
                        }
                    }
                    ctr +=1;
                }
            }
            return child;
        }

        /**
         * Parse options for create model migrations.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of options.
         */
        function parseOptions(obj) {
            var ctr = 0,
                tab = getTabs(1, true);
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var child = recurseChildOptions(obj[prop]);
                            if(child && child.length)
                                build.options.push(tab + prop + ': { \n' + child + ' \n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            build.options.push(tab + prop + ': ' + arrayToString(obj[prop]));
                        } else {
                            var val = obj[prop];
                            if(_.isString(val))
                                val = qwrap(val);
                            else
                                val = val.toString();
                            build.options.push(tab + prop + ': ' + val);
                        }
                    }
                }
                ctr +=1;
            }

        }

        /**
         * Converts a property's atttributes to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of attributes.
         * @param {object} prevObj - the previous object of attributes from last snapshot.
         * @returns {string}
         */
        function attributesToString(obj, prevObj, level) {
            var attrs = '',
                prefix,
                tab;
            level = level || 1;
            tab = getTabs(level, true);
            _.forEach(obj, function (v, k) {
                if(excludeAttrs.indexOf(k) === -1){
                    var prev = prevObj && prevObj[k] !== undefined ? prevObj[k] : undefined;
                    prefix = attrs.length ? ',\n' : '';
                    if(_.isPlainObject(v)){
                        var subAttr = attributesToString(v, prev, level +1);
                        if(subAttr && subAttr.length)
                            attrs += (prefix + tab + k + ': {\n' + subAttr + '\n' + tab + '}');
                    } else {
                        if(prev !== v){
                            var val = k === 'type' ? 'types.' + v : v;
                            if(_.isArray(val))
                                val = arrayToString(val);
                            if(_.isFunction(val)){
                                val = funcToString(val.toString(), 2);
                            }
                            attrs += (prefix + tab + k + ': ' + val);
                        }
                    }
                }
            });

            return attrs;
        }

        /**
         * Iterate table/model properties and compare or create new.
         * @private
         * @memberof Compare
         */
        function compareMigration(){

            var tab

            // the model/table already exists.
            if(previous){

                tab = getTabs(0, true),

                // compare to previous table checking for
                // any dropped columns.
                _.forEach(previous.attributes, function (v,k) {
                    if (v._modelAttribute) {
                        var curCol = current && current.attributes ? current.attributes[k] : undefined,
                            removeAttrs;
                        // if curCol is undefined it was removed.
                        if(!curCol){
                            removeAttrs = attributesToString(filterAttributes(v));
                            if(removeAttrs) {
                                build.up.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                                build.down.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n'+ removeAttrs + '\n' + tab + '});'
                                );
                            }
                        }
                    }

                });

                // iterate current defined attrs
                // looking for adds & changes.
                _.forEach(current.attributes, function (v,k) {

                    if(v._modelAttribute){
                        // check if is new column or existing.
                        var prevCol = previous.attributes ? previous.attributes[k] : undefined,
                            prevAttrs, curAttrs;

                        if(prevCol){

                            curAttrs = attributesToString(filterAttributes(v), filterAttributes(prevCol));
                            prevAttrs = attributesToString(filterAttributes(prevCol), filterAttributes(v));

                            if(curAttrs) {
                                build.up.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' + curAttrs + '\n' + tab + '});'
                                );
                            }

                            if(prevAttrs) {
                                build.down.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' +  prevAttrs + '\n' + tab +'});'
                                );
                            }

                        } else {

                            curAttrs = attributesToString(filterAttributes(v));
                            // column needs to be added.

                            if(curAttrs) {
                                build.up.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        '{\n' + curAttrs + '\n' + tab + '});'
                                );
                                build.down.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                            }

                        }
                    }

                    ctr += 1;

                });

            }

            // this is a new model/table.
            else {

                // this is a new table so we need to parse options.
                var newAttrs = [],
                    ctr = 0,
                    attrTab = getTabs(1, true),
                    newOpts;

                tab = getTabs(0, true);

                parseOptions(current.options);
                newOpts = build.options.join(',\n')

                _.forEach(current.attributes, function (v,k) {

                    //if (v._modelAttribute) {
                        var attrs = attributesToString(filterAttributes(v), null, 2);
                        if(attrs) newAttrs.push(attrTab + k + ': {\n' + attrs + '\n' + attrTab + '}');
                    //}
                    ctr +=1;
                });

                build.up.createTable.push(
                        'migration.createTable(' + qwrap(modelName) + ',\n' +
                        tab + '{\n' + newAttrs.join(',\n') + '\n' + tab + '},\n' +
                        tab + '{\n' + newOpts + '\n' + tab + '});'
                );
                build.down.dropTable.push('migration.dropTable(' + qwrap(modelName) + ');');

            }

            build.up.toString = upToString;
            build.down.toString = downToString;
        }

        // parse properties attributes & options.
        compareMigration();

        return build;

    };

    return compare;

}
452704
def _prepare_sort_by_score(self, values, sort_options):
        
        # create the keys
        base_tmp_key, tmp_keys = self._zset_to_keys(
                                    key=self._sort_by_sortedset['by'],
                                    values=values,
                                    )
        # ask to sort on our new keys
        sort_options['by'] = '%s:*' % base_tmp_key

        # retrieve original sort parameters
        for key in ('desc', 'alpha', 'get', 'store'):
            if key in self._sort_by_sortedset:
                sort_options[key] = self._sort_by_sortedset[key]

        # if we want to get the score with values/values_list
        if sort_options.get('get'):
            try:
                pos = sort_options['get'].index(SORTED_SCORE)
            except:
                pass
            else:
                sort_options['get'][pos] = '%s:*' % base_tmp_key

        return base_tmp_key, tmp_keys
1218958
private void diffClique(float[] weights, int p) {
		for (int t = 0; t < orders.length; t++) {
			if (data[p][t] == -1)
				continue;

			if (orders[t] == 0) {
				if (golds[p] != preds[p]) {
					int ts = data[p][t] + golds[p];
					int ps = data[p][t] + preds[p];
					adjust(weights, ts, ps);
				}
			}
			if (p > 0 && orders[t] == 1) {
				int ts = data[p][t] + (golds[p - 1] * ysize + golds[p]);
				int ps = data[p][t] + (preds[p - 1] * ysize + preds[p]);
				adjust(weights, ts, ps);
			}
		}
	}
753669
def remove_variants(self, variants):
        """"""
        chroms = set([i.chrom for i in variants])
        for chrom in chroms:
            if self.append_chromosome:
                chrom = 'chr%s' % chrom
            to_delete = [pos for pos in self.positions[chrom] if pos in variants]
            for pos in to_delete:
                del self.positions[chrom][pos]
535628
function grouped(array, groups, order) {
  if (!groups) { groups = [returnFalse]; }
  var sorted = [];
  var ordered = [];
  var remaining = array.slice();
  var unmatchedPosition = groups.indexOf('unmatched');
  groups.forEach(function(criteria, index) {
    if (index === unmatchedPosition) { return; }
    var tieBreakers = [];
    if (index !== groups.length - 1) {
      tieBreakers = groups.slice(index + 1);
      if (index < unmatchedPosition) {
        tieBreakers.splice(unmatchedPosition - index - 1, 1);
      }
    }
    var spliced = splice(remaining, criteria, tieBreakers);
    var matched = spliced.matched;
    var unmatched = spliced.unmatched;
    sorted[index] = matched;
    remaining = unmatched;
  });
  if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
  sorted[unmatchedPosition] = remaining;
  if (Array.isArray(order)) {
    order.forEach(function(position, index) {
      ordered[index] = sorted[position];
    });
  } else {
    ordered = sorted;
  }
  return ordered.reduce(function(flat, group) {
    return flat.concat(group);
  }, []);
}
1156843
def update(self, score_vals):
        ''''''
        add = self.add
        for score, value in score_vals:
            add(score, value)
267724
private static void addOrder(Criteria c, String sort, String order, boolean ignoreCase) {
        if (ORDER_DESC.equals(order)) {
            c.addOrder(ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
        }
        else {
            c.addOrder(ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort));
        }
    }
1277576
def run(self):
        """"""

        # Create solver
        solver = self._get_solver()

        # Load compound information
        def compound_name(id):
            if id not in self._model.compounds:
                return id
            return self._model.compounds[id].properties.get('name', id)

        # TODO: The exchange and transport reactions have tuple names. This
        # means that in Python 3 the reactions can no longer be directly
        # compared (e.g. while sorting) so define this helper function as a
        # workaround.
        def reaction_key(r):
            return r if isinstance(r, tuple) else (r,)

        # Calculate penalty if penalty file exists
        penalties = {}
        if self._args.penalty is not None:
            for line in self._args.penalty:
                line, _, comment = line.partition('#')
                line = line.strip()
                if line == '':
                    continue
                rxnid, penalty = line.split(None, 1)
                penalties[rxnid] = float(penalty)

        model_extended, weights = create_extended_model(
            self._model,
            db_penalty=self._args.db_penalty,
            ex_penalty=self._args.ex_penalty,
            tp_penalty=self._args.tp_penalty,
            penalties=penalties)

        epsilon = self._args.epsilon
        core = set()
        if self._args.subset is None:
            for r in self._mm.reactions:
                if not self._mm.is_exchange(r):
                    core.add(r)
        else:
            for line in self._args.subset:
                line = line.strip()
                if line == '':
                    continue
                core.add(line)
        induced = fastgapfill(model_extended, core, weights=weights,
                              epsilon=epsilon, solver=solver)

        for reaction_id in sorted(self._mm.reactions):
            rx = self._mm.get_reaction(reaction_id)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(reaction_id, 'Model', 0, rxt))

        for rxnid in sorted(induced, key=reaction_key):
            if self._mm.has_reaction(rxnid):
                continue
            rx = model_extended.get_reaction(rxnid)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(
                rxnid, 'Add', weights.get(rxnid, 1), rxt))
105020
function () {
      var doUniqueMemberIdsCheck = function (compound) {
        var duplicateMemberIds = [];
        compound.members.forEach(function (member) {
          var memberId = member.memberId;

          function filterByMemberId (member) {
            return member.memberId === memberId;
          }

          var arrayByMemberId = compound.members.filter(filterByMemberId);
          if (arrayByMemberId.length > 1 && duplicateMemberIds.indexOf(memberId) < 0) {
            duplicateMemberIds.push(memberId);
          }
        });
        duplicateMemberIds.forEach(function (memberId) {
          errors.push('RuleViolation identified: Artifact \'' + compound.artifactId +
            '\' contains multiple members with \'memberId\'=\'' + memberId + '\'');
        });
      };
      //
      if (doc.artifacts && doc.artifacts.compoundComponents) {
        doc.artifacts.compoundComponents.forEach(doUniqueMemberIdsCheck);
      }
    }
481253
private void fillTableWithMatches(VariantGraphRanking ranking, VariantGraph graph, Iterable<Token> witness, Comparator<Token> comparator) {
        Matches matches = Matches.between(graph.vertices(), witness, comparator);
        Set<Token> unique = matches.uniqueInWitness;
        Set<Token> ambiguous = matches.ambiguousInWitness;
        int rowIndex = 0;
        for (Token t : witness) {
            if (unique.contains(t) || ambiguous.contains(t)) {
                List<VariantGraph.Vertex> matchingVertices = matches.allMatches.getOrDefault(t, Collections.emptyList());
                for (VariantGraph.Vertex vgv : matchingVertices) {
                    set(rowIndex, ranking.apply(vgv) - 1, t, vgv);
                }
            }
            rowIndex++;
        }
    }