Lexicographic order for triples.
430878
private static boolean leq(int a1, int a2, int a3, int b1, int b2, int b3) {
        return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3)));
    }
604352
def entityTriples(rdfGraph, anEntity, excludeProps=False, excludeBNodes=False,
                  orderProps=[RDF, RDFS, OWL.OWLNS, DC.DCNS]):
    
    temp = []
    if not excludeProps:
        excludeProps = []

    # extract predicate/object
    for x, y, z in rdfGraph.triples((anEntity, None, None)):
        if excludeBNodes and isBlankNode(z):
            continue
        if y not in excludeProps:
            temp += [(y, z)]

    # sorting
    if type(orderProps) == type([]):
        orderedUris = sortByNamespacePrefix([y for y, z in temp], orderProps)  # order props only
        orderedUris = [(n + 1, x) for n, x in
                       enumerate(orderedUris)]  # create form: [(1, 'something'),(2,'bobby'),(3,'suzy'),(4,'crab')]
        rank = dict((key, rank) for (rank, key) in orderedUris)  # create dict to pass to sorted procedure
        temp = sorted(temp, key=lambda tup: rank.get(tup[0]))
    elif orderProps:  # default to alpha sorting unless False
        temp = sorted(temp, key=lambda tup: tup[0])

    # if niceURI:
    #	temp = [(uri2niceString(ontology, y), z) for y,z in temp]

    return temp
1165159
def multiplicity(keys, axis=semantics.axis_default):
    
    index = as_index(keys, axis)
    return index.count[index.inverse]
316944
function getter_THREE_Euler(inst) {
	return [
		inst._x,
		inst._y,
		inst._z,
		inst._order];
}
1273049
public static <T1, T2, T3> TriPredicate<T1, T2, T3> and(TriPredicate<T1, T2, T3>... predicates) {
        dbc.precondition(predicates != null, "predicates is null");
        return Logic.Ternary.and(Iterations.iterable(predicates));
    }
1075214
def wc_dict2lha(wc, skip_redundant=True, skip_zero=True):
    """"""
    d = OrderedDict()
    for name, (block, i) in WC_dict_0f.items():
        if block not in d:
            d[block] = defaultdict(list)
        if wc[name] != 0:
            d[block]['values'].append([i, wc[name].real])
    for name in definitions.WC_keys_2f:
        reblock = 'WC'+name.upper()
        imblock = 'IMWC'+name.upper()
        if reblock not in d:
            d[reblock] = defaultdict(list)
        if imblock not in d:
            d[imblock] = defaultdict(list)
        for i in range(3):
            for j in range(3):
                if (i, j) in definitions.redundant_elements[name] and skip_redundant:
                    # skip redundant elements
                    continue
                if wc[name][i, j].real != 0 or not skip_zero:
                    d[reblock]['values'].append([i+1, j+1, float(wc[name][i, j].real)])
                if wc[name][i, j].imag != 0 or not skip_zero:
                    # omit Im parts that have to vanish by symmetry
                    if (i, j) not in definitions.vanishing_im_parts[name]:
                        d[imblock]['values'].append([i+1, j+1, float(wc[name][i, j].imag)])
    for name in definitions.WC_keys_4f:
        reblock = 'WC'+name.upper()
        imblock = 'IMWC'+name.upper()
        if reblock not in d:
            d[reblock] = defaultdict(list)
        if imblock not in d:
            d[imblock] = defaultdict(list)
        for i in range(3):
            for j in range(3):
                for k in range(3):
                    for l in range(3):
                        if (i, j, k, l) in definitions.redundant_elements[name] and skip_redundant:
                            # skip redundant elements
                            continue
                        if wc[name][i, j, k, l].real != 0 or not skip_zero:
                            d[reblock]['values'].append([i+1, j+1, k+1, l+1, float(wc[name][i, j, k, l].real)])
                        if wc[name][i, j, k, l].imag != 0 or not skip_zero:
                            # omit Im parts that have to vanish by symmetry
                            if (i, j, k, l) not in definitions.vanishing_im_parts[name]:
                                d[imblock]['values'].append([i+1, j+1, k+1, l+1, float(wc[name][i, j, k, l].imag)])
    # remove empty blocks
    empty = []
    for block in d:
        if d[block] == {}:
            empty.append(block)
    for block in empty:
        del d[block]
    return {'BLOCK': d}
1162442
function(word)
		{
			var c = word[0];
			for (var i = 0; i < 3; i++)
				word[i] = word[i+1];
			word[3] = c;
			
			return word;
		}
1155465
function permutations(iterable, r) {
    // (ABCD, 2) -> AB AC AD BA BC BD CA CB CD DA DB DC
    // (012,  3) -> 012 021 102 120 201 210
/*
    0 1 2 3, 3
    ______
    (0, 1, 2)
    (0, 1, 3)
    (0, 2, 1)
    (0, 2, 3)
    (0, 3, 1)
    (0, 3, 2)
    (1, 0, 2)
    (1, 0, 3)
    (1, 2, 0)
    (1, 2, 3)
    (1, 3, 0)
    (1, 3, 2)
    (2, 0, 1)
    (2, 0, 3)
    (2, 1, 0)
    (2, 1, 3)
    (2, 3, 0)
    (2, 3, 1)
    (3, 0, 1)
    (3, 0, 2)
    (3, 1, 0)
    (3, 1, 2)
    (3, 2, 0)
    (3, 2, 1)
*/

    var pool = tools.toArray(tools.ensureIter(iterable));
    var n = pool.length;
    r = r || n;
    if (r > n) {
        throw new Error(
            'Parameter r cannot be greater than amount of elements in the iterable [' + n + ']'
        );
    }
    var indices = tools.newArray(r, 0, 1);

    function fromIndices() {
        state.current = indices.map(function(idx) {
            state.used[idx] = true;
            return pool[idx];
        });
    }

    function next() {
        // 0. indices: 0, 1, 2
        // 1. indices: 0, 1, 3
        // 2. indices: 0, 1, 4 -> carry = t 0, 1, -1 -> 0, 1, 0 -> 0, 1, 1 -> 0, 1, 2
        var backtrack = null;
        var i = indices.length - 1;
        for (; i >= 0; i--) {
            indices[i]++;
            if (indices[i] === n) {
                // Time to reset current index and increase previous one.
                if (i === 0) {
                    // There is no previous index, so it's the end of generation.
                    continue;
                }

                delete state.used[indices[i - 1]]; // Release previous index
                backtrack = indices[i] - 1;        // Pre-save current index to be able to release it in future.
                indices[i] = -1;                   // Reset current index
                i++;
                continue;
            }

            if (state.used[indices[i]]) {
                // Trying to increase current index until find the
                // lowest free value or reach the end of the range.
                i++;
                continue;
            }

            // First free value found. Release previous one.
            if (backtrack !== null) {
                // If we need to backtrack, doing it!
                delete state.used[backtrack];
                backtrack = null;
                continue;
            }

            // Otherwise exiting from the generation.
            break;
        }

        if (i < 0) {
            state.finished = true;
        } else {
            fromIndices();
        }
    }

    var state = {current: null, finished: false, used: {}};
    var permutIter = {
        next: function() {
            state.current
                ? next()
                : fromIndices();

            return {
                done: state.finished,
                value: state.finished
                    ? undefined
                    : state.current
            };
        }
    };
    return tools.fuseIter(permutIter, function() { return permutIter; });
}
52925
def C_array2dict(C):
    """"""
    d = OrderedDict()
    i=0
    for k in C_keys:
        s = C_keys_shape[k]
        if s == 1:
            j = i+1
            d[k] = C[i]
        else:
            j = i \
      + reduce(operator.mul, s, 1)
            d[k] = C[i:j].reshape(s)
        i = j
    return d
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);
			}
		}
	}
139138
def _conv_general_permutations(self, dimension_numbers):
    """"""
    lhs_spec, rhs_spec, out_spec = dimension_numbers
    lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
    charpairs = (lhs_char, rhs_char, out_char)
    for i, (a, b) in enumerate(charpairs):
      if not (dimension_numbers[i].count(a) == 1 and
              dimension_numbers[i].count(b) == 1):
        msg = ('convolution dimension_numbers[{}] must contain the characters '
               '"{}" and "{}" exatly once, got {}.')
        raise TypeError(msg.format(i, a, b, dimension_numbers[i]))
      if len(dimension_numbers[i]) != len(set(dimension_numbers[i])):
        msg = ('convolution dimension_numbers[{}] cannot have duplicate '
               'characters, got {}.')
        raise TypeError(msg.format(i, dimension_numbers[i]))
    if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) ==
            set(out_spec) - set(out_char)):
      msg = ('convolution dimension_numbers elements must each have the same '
             'set of spatial characters, got {}.')
      raise TypeError(msg.format(dimension_numbers))

    def getperm(spec, charpair):
      spatial = (i for i, c in enumerate(spec) if c not in charpair)
      if spec is not rhs_spec:
        spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i]))
      return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial)

    lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs)
    return lhs_perm, rhs_perm, out_perm
155613
def predicatesIn(G: Graph, n: Node) -> Set[TriplePredicate]:
    
    return {p for _, p in G.subject_predicates(n)}
916957
def sm_lha2dict(lha):
    """"""
    d = OrderedDict()
    v = dict(lha['BLOCK']['GAUGE']['values'])
    d['g'] = v[1]
    d['gp'] = v[2]
    d['gs'] = v[3]
    v = dict(lha['BLOCK']['SCALAR']['values'])
    d['Lambda'] = v[1]
    d['m2'] = v[2]
    d['Gu'] = lha2matrix(lha['BLOCK']['GU']['values'], (3,3))
    if 'IMGU' in lha['BLOCK']:
        d['Gu'] = d['Gu'] + 1j*lha2matrix(lha['BLOCK']['IMGU']['values'], (3,3))
    d['Gd'] = lha2matrix(lha['BLOCK']['GD']['values'], (3,3))
    if 'IMGD' in lha['BLOCK']:
        d['Gd'] = d['Gd'] + 1j*lha2matrix(lha['BLOCK']['IMGD']['values'], (3,3))
    d['Ge'] = lha2matrix(lha['BLOCK']['GE']['values'], (3,3))
    if 'IMGE' in lha['BLOCK']:
        d['Ge'] = d['Ge'] + 1j*lha2matrix(lha['BLOCK']['IMGE']['values'], (3,3))
    # thetas default to 0
    if 'THETA' in lha['BLOCK']:
        v = dict(lha['BLOCK']['THETA']['values'])
        d['Theta'] = v.get(1, 0)
        d['Thetap'] = v.get(2, 0)
        d['Thetas'] = v.get(3, 0)
    else:
        d['Theta'] = 0
        d['Thetap'] = 0
        d['Thetas'] = 0
    return d
589944
function zOrder(x, y, minX, minY, size) {
        // coords are transformed into non-negative 15-bit integer range
        x = 32767 * (x - minX) / size;
        y = 32767 * (y - minY) / size;
        x = (x | (x << 8)) & 0x00FF00FF;
        x = (x | (x << 4)) & 0x0F0F0F0F;
        x = (x | (x << 2)) & 0x33333333;
        x = (x | (x << 1)) & 0x55555555;
        y = (y | (y << 8)) & 0x00FF00FF;
        y = (y | (y << 4)) & 0x0F0F0F0F;
        y = (y | (y << 2)) & 0x33333333;
        y = (y | (y << 1)) & 0x55555555;
        return x | (y << 1);
    }
1010849
def _core_semantics(self, lex_chains, concept_weights):
        
        chain_scores = [self._score_chain(lex_chain, adj_submat, concept_weights) for lex_chain, adj_submat in lex_chains]
        scored_chains = zip(lex_chains, chain_scores)
        scored_chains = sorted(scored_chains, key=lambda x: x[1], reverse=True)

        thresh = (self.alpha/len(lex_chains)) * sum(chain_scores)
        return [chain for (chain, adj_mat), score in scored_chains if score >= thresh][:self.n_chains]
157095
private int median3(PagesIndex pagesIndex, int a, int b, int c)
    {
        int ab = comparator.compareTo(pagesIndex, a, b);
        int ac = comparator.compareTo(pagesIndex, a, c);
        int bc = comparator.compareTo(pagesIndex, b, c);
        return (ab < 0 ?
                (bc < 0 ? b : ac < 0 ? c : a) :
                (bc > 0 ? b : ac > 0 ? c : a));
    }
395770
def from_triples(cls, triples, remap_nodeids=True):
        
        top_nid = str(LTOP_NODEID)
        top = lnk = surface = identifier = None
        nids, nd, edges = [], {}, []
        for src, rel, tgt in triples:
            src, tgt = str(src), str(tgt)  # hack for int-converted src/tgt
            if src == top_nid and rel == 'top':
                top = tgt
                continue
            elif src not in nd:
                if top is None:
                    top=src
                nids.append(src)
                nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
            if rel == 'predicate':
                nd[src]['pred'] = Pred.surface_or_abstract(tgt)
            elif rel == 'lnk':
                cfrom, cto = tgt.strip('"<>').split(':')
                nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
            elif rel == 'carg':
                if (tgt[0], tgt[-1]) == ('"', '"'):
                    tgt = tgt[1:-1]
                nd[src]['carg'] = tgt
            elif rel.islower():
                nd[src]['si'].append((rel, tgt))
            else:
                rargname, post = rel.rsplit('-', 1)
                edges.append((src, tgt, rargname, post))
        if remap_nodeids:
            nidmap = dict((nid, FIRST_NODEID+i) for i, nid in enumerate(nids))
        else:
            nidmap = dict((nid, nid) for nid in nids)
        nodes = [
            Node(
                nodeid=nidmap[nid],
                pred=nd[nid]['pred'],
                sortinfo=nd[nid]['si'],
                lnk=nd[nid]['lnk'],
                carg=nd[nid]['carg']
            ) for i, nid in enumerate(nids)
        ]
        links = [Link(nidmap[s], nidmap[t], r, p) for s, t, r, p in edges]
        if top:
            links.append(Link(LTOP_NODEID, nidmap[top], None, H_POST))
        return cls(
            nodes=nodes,
            links=links,
            lnk=lnk,
            surface=surface,
            identifier=identifier
        )