Python functools.cmp_to_key() Examples

The following are code examples for showing how to use functools.cmp_to_key(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def _sorted_unique_jdk_configs(configs):
    path_seen = set()
    unique_configs = [c for c in configs if c.home not in path_seen and not path_seen.add(c.home)]

    def _compare_configs(c1, c2):
        if c1 == _default_java_home:
            if c2 != _default_java_home:
                return 1
        elif c2 == _default_java_home:
            return -1
        if c1 in _extra_java_homes:
            if c2 not in _extra_java_homes:
                return 1
        elif c2 in _extra_java_homes:
            return -1
        return VersionSpec.__cmp__(c1.version, c2.version)
    return sorted(unique_configs, key=cmp_to_key(_compare_configs), reverse=True) 
Example 2
Project: Repobot   Author: Desgard   File: misc.py    MIT License 6 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: loader.py    GNU General Public License v3.0 6 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def shouldIncludeMethod(attrname):
            if not attrname.startswith(self.testMethodPrefix):
                return False
            testFunc = getattr(testCaseClass, attrname)
            if not callable(testFunc):
                return False
            fullName = '%s.%s' % (testCaseClass.__module__, testFunc.__qualname__)
            return self.testNamePatterns is None or \
                any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)
        testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        return testFnNames 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_sort.py    GNU General Public License v3.0 6 votes vote down vote up
def test_undetected_mutation(self):
        # Python 2.4a1 did not always detect mutation
        memorywaster = []
        for i in range(20):
            def mutating_cmp(x, y):
                L.append(3)
                L.pop()
                return (x > y) - (x < y)
            L = [1,2]
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            def mutating_cmp(x, y):
                L.append(3)
                del L[:]
                return (x > y) - (x < y)
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            memorywaster = [memorywaster]

#============================================================================== 
Example 5
Project: JWTConnect-Python-CryptoJWT   Author: openid   File: key_bundle.py    Apache License 2.0 6 votes vote down vote up
def order_key_defs(key_def):
    """
    Sort a set of key definitions. A key definition that defines more then
    one usage type are splitted into as many definitions as the number of
    usage types specified. One key definition per usage type.

    :param key_def: A set of key definitions
    :return: The set of definitions as a sorted list
    """
    _int = []
    # First make sure all defs only reference one usage
    for _def in key_def:
        if len(_def['use']) > 1:
            for _use in _def['use']:
                _kd = _def.copy()
                _kd['use'] = _use
                _int.append(_kd)
        else:
            _int.append(_def)

    _int.sort(key=cmp_to_key(sort_func))

    return _int 
Example 6
Project: avocado-vt   Author: avocado-framework   File: utils_disk.py    GNU General Public License v2.0 6 votes vote down vote up
def mount_all(self):
        def compare(a, b):
            if len(a[0]) > len(b[0]):
                return 1
            elif len(a[0]) == len(b[0]):
                return 0
            else:
                return -1

        roots = self.os_inspects()
        if roots:
            for root in roots:
                mps = self.g.inspect_get_mountpoints(root)
                mps.sort(key=cmp_to_key(compare))
                for mp_dev in mps:
                    try:
                        msg = "Mount dev '%s' partitions '%s' to '%s'"
                        logging.info(msg % (root, mp_dev[1], mp_dev[0]))
                        self.g.mount(mp_dev[1], mp_dev[0])
                    except RuntimeError as err_msg:
                        logging.info("%s (ignored)" % err_msg)
        else:
            raise exceptions.TestError(
                "inspect_vm: no operating systems found") 
Example 7
Project: MaruMaru.bundle   Author: hojel   File: jsarray.py    MIT License 6 votes vote down vote up
def sort(cmpfn):
        if not this.Class in {'Array', 'Arguments'}:
            return this.to_object() # do nothing
        arr = []
        for i in xrange(len(this)):
            arr.append(this.get(six.text_type(i)))

        if not arr:
            return this
        if not cmpfn.is_callable():
            cmpfn = None
        cmp = lambda a,b: sort_compare(a, b, cmpfn)
        if six.PY3:
            key = functools.cmp_to_key(cmp)
            arr.sort(key=key)
        else:
            arr.sort(cmp=cmp)
        for i in xrange(len(arr)):
            this.put(six.text_type(i), arr[i])

        return this 
Example 8
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_sort.py    GNU General Public License v3.0 6 votes vote down vote up
def test_undetected_mutation(self):
        # Python 2.4a1 did not always detect mutation
        memorywaster = []
        for i in range(20):
            def mutating_cmp(x, y):
                L.append(3)
                L.pop()
                return (x > y) - (x < y)
            L = [1,2]
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            def mutating_cmp(x, y):
                L.append(3)
                del L[:]
                return (x > y) - (x < y)
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            memorywaster = [memorywaster]

#============================================================================== 
Example 9
Project: ble5-nrf52-mac   Author: tomasero   File: misc.py    MIT License 6 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example 10
Project: genielibs   Author: CiscoTestAutomation   File: topology_mapper.py    Apache License 2.0 6 votes vote down vote up
def link_names(self):
        '''OrderedSet of link names (L#).'''
        try:
            from ats.tcl.internal import DictionaryCompare
            topo_devices = list(self.devices.values())
            topo_links = set()
            for topo_dev in topo_devices:
                topo_links |= set(topo_dev.links)
            sLs = [topo_link.link_name for topo_link in topo_links]
            sLs = OrderedSet(sorted(sLs, key=functools.cmp_to_key(DictionaryCompare)))
            return sLs
        except ImportError:
            # Considering users with no sourced tcl environment
            pass
        except Exception:
            return 
Example 11
Project: pyblish-win   Author: pyblish   File: loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
        testFnNames = filter(isTestMethod, dir(testCaseClass))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
        return testFnNames 
Example 12
Project: pyblish-win   Author: pyblish   File: pstats.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example 13
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cmp_to_key(self):
        def mycmp(x, y):
            return y - x
        self.assertEqual(sorted(range(5), key=functools.cmp_to_key(mycmp)),
                         [4, 3, 2, 1, 0]) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_hash(self):
        def mycmp(x, y):
            return y - x
        key = functools.cmp_to_key(mycmp)
        k = key(10)
        self.assertRaises(TypeError, hash(k)) 
Example 15
Project: relay-bench   Author: uwsampl   File: plot_util.py    Apache License 2.0 5 votes vote down vote up
def to_dataframe(self, data):
        outer_ordering = list(list(data['raw'].values())[0].keys())
        def _cmp_func(a, b):
            return outer_ordering.index(a[0]) - outer_ordering.index(b[0])

        def _unzip(lst):
            a_lst = []
            b_lst = []
            c_lst = []
            for (a, b, c) in lst:
                a_lst.append(a)
                b_lst.append(b)
                c_lst.append(c)
            return (a_lst, b_lst, c_lst)

        raw_data = data['raw']
        metadata = data['meta']
        df_data = []
        for path, val in _traverse_dict(raw_data):
            df_data.append((path[1], path[0], val))
        df_data.sort(key=functools.cmp_to_key(_cmp_func))
        a_lst, b_lst, c_lst = _unzip(df_data)
        return pd.DataFrame({
            metadata[1]: a_lst,
            metadata[0]: b_lst,
            metadata[2]: c_lst
        }) 
Example 16
Project: jawfish   Author: war-and-code   File: loader.py    MIT License 5 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                callable(getattr(testCaseClass, attrname))
        testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        return testFnNames 
Example 17
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def __init__(self,separator = None,escape = None,endOfLine = None):
		self.sep = None
		self.esc = None
		self.eol = None
		self.inp = None
		self.eolsize = None
		self.buffer = None
		self.pos = None
		self.bufferOffset = None
		self.cachedToken = None
		self.cachedPos = None
		_g = self
		if (separator is not None):
			self.sep = separator
		else:
			self.sep = ","
		if (self.stringLength(self.sep) != 1):
			raise _HxException((("Separator string \"" + HxOverrides.stringOrNull(self.sep)) + "\" not allowed, only single char"))
		if (escape is not None):
			self.esc = escape
		else:
			self.esc = "\""
		if (self.stringLength(self.esc) != 1):
			raise _HxException((("Escape string \"" + HxOverrides.stringOrNull(self.esc)) + "\" not allowed, only single char"))
		if (endOfLine is not None):
			self.eol = endOfLine
		else:
			self.eol = ["\r\n", "\n"]
		if (Lambda.has(self.eol,None) or Lambda.has(self.eol,"")):
			raise _HxException("EOL sequences can't be empty")
		def _hx_local_0(a,b):
			return (_g.stringLength(b) - _g.stringLength(a))
		self.eol.sort(key= python_lib_Functools.cmp_to_key(_hx_local_0))
		self.eolsize = list(map(self.stringLength,self.eol))
		self.open(None,None) 
Example 18
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 19
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 20
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def __init__(self,separator = None,escape = None,endOfLine = None):
		self.sep = None
		self.esc = None
		self.eol = None
		self.inp = None
		self.eolsize = None
		self.buffer = None
		self.pos = None
		self.bufferOffset = None
		self.cachedToken = None
		self.cachedPos = None
		_g = self
		if (separator is not None):
			self.sep = separator
		else:
			self.sep = ","
		if (self.stringLength(self.sep) != 1):
			raise _HxException((("Separator string \"" + HxOverrides.stringOrNull(self.sep)) + "\" not allowed, only single char"))
		if (escape is not None):
			self.esc = escape
		else:
			self.esc = "\""
		if (self.stringLength(self.esc) != 1):
			raise _HxException((("Escape string \"" + HxOverrides.stringOrNull(self.esc)) + "\" not allowed, only single char"))
		if (endOfLine is not None):
			self.eol = endOfLine
		else:
			self.eol = ["\r\n", "\n"]
		if (Lambda.has(self.eol,None) or Lambda.has(self.eol,"")):
			raise _HxException("EOL sequences can't be empty")
		def _hx_local_0(a,b):
			return (_g.stringLength(b) - _g.stringLength(a))
		self.eol.sort(key= python_lib_Functools.cmp_to_key(_hx_local_0))
		self.eolsize = list(map(self.stringLength,self.eol))
		self.open(None,None) 
Example 21
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def __init__(self,separator = None,escape = None,endOfLine = None):
		self.sep = None
		self.esc = None
		self.eol = None
		self.inp = None
		self.eolsize = None
		self.buffer = None
		self.pos = None
		self.bufferOffset = None
		self.cachedToken = None
		self.cachedPos = None
		_g = self
		if (separator is not None):
			self.sep = separator
		else:
			self.sep = ","
		if (self.stringLength(self.sep) != 1):
			raise _HxException((("Separator string \"" + HxOverrides.stringOrNull(self.sep)) + "\" not allowed, only single char"))
		if (escape is not None):
			self.esc = escape
		else:
			self.esc = "\""
		if (self.stringLength(self.esc) != 1):
			raise _HxException((("Escape string \"" + HxOverrides.stringOrNull(self.esc)) + "\" not allowed, only single char"))
		if (endOfLine is not None):
			self.eol = endOfLine
		else:
			self.eol = ["\r\n", "\n"]
		if (Lambda.has(self.eol,None) or Lambda.has(self.eol,"")):
			raise _HxException("EOL sequences can't be empty")
		def _hx_local_0(a,b):
			return (_g.stringLength(b) - _g.stringLength(a))
		self.eol.sort(key= python_lib_Functools.cmp_to_key(_hx_local_0))
		self.eolsize = list(map(self.stringLength,self.eol))
		self.open(None,None) 
Example 22
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 23
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def __init__(self,separator = None,escape = None,endOfLine = None):
		self.sep = None
		self.esc = None
		self.eol = None
		self.inp = None
		self.eolsize = None
		self.buffer = None
		self.pos = None
		self.bufferOffset = None
		self.cachedToken = None
		self.cachedPos = None
		_g = self
		if (separator is not None):
			self.sep = separator
		else:
			self.sep = ","
		if (self.stringLength(self.sep) != 1):
			raise _HxException((("Separator string \"" + HxOverrides.stringOrNull(self.sep)) + "\" not allowed, only single char"))
		if (escape is not None):
			self.esc = escape
		else:
			self.esc = "\""
		if (self.stringLength(self.esc) != 1):
			raise _HxException((("Escape string \"" + HxOverrides.stringOrNull(self.esc)) + "\" not allowed, only single char"))
		if (endOfLine is not None):
			self.eol = endOfLine
		else:
			self.eol = ["\r\n", "\n"]
		if (Lambda.has(self.eol,None) or Lambda.has(self.eol,"")):
			raise _HxException("EOL sequences can't be empty")
		def _hx_local_0(a,b):
			return (_g.stringLength(b) - _g.stringLength(a))
		self.eol.sort(key= python_lib_Functools.cmp_to_key(_hx_local_0))
		self.eolsize = list(map(self.stringLength,self.eol))
		self.open(None,None) 
Example 24
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
		x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 25
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 26
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 27
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 28
Project: Dataquest   Author: ustutz   File: script.py    MIT License 5 votes vote down vote up
def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f)) 
Example 29
Project: gftools   Author: googlefonts   File: gftools-add-font.py    Apache License 2.0 5 votes vote down vote up
def _FileFamilyStyleWeights(fontdir):
  """Extracts file, family, style, weight 4-tuples for each font in dir.

  Args:
    fontdir: Directory that supposedly contains font files for a family.
  Returns:
    List of fonts.FileFamilyStyleWeightTuple ordered by weight, style
    (normal first).
  Raises:
    OSError: If the font directory doesn't exist (errno.ENOTDIR) or has no font
    files (errno.ENOENT) in it.
    RuntimeError: If the font directory appears to contain files from multiple
    families.
  """
  if not os.path.isdir(fontdir):
    raise OSError(errno.ENOTDIR, 'No such directory', fontdir)

  files = glob.glob(os.path.join(fontdir, '*.[ot]tf'))
  if not files:
    raise OSError(errno.ENOENT, 'no font files found')

  result = [fonts.FamilyStyleWeight(f) for f in files]
  def _Cmp(r1, r2):
    return cmp(r1.weight, r2.weight) or -cmp(r1.style, r2.style)
  result = sorted(result, key=cmp_to_key(_Cmp))

  family_names = {i.family for i in result}
  if len(family_names) > 1:
    raise RuntimeError('Ambiguous family name; possibilities: %s'
                       % family_names)

  return result 
Example 30
Project: NiujiaoDebugger   Author: MrSrc   File: pstats.py    GNU General Public License v3.0 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], int):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]
        elif len(field) >= 2:
            for arg in field[1:]:
                if type(arg) != type(field[0]):
                    raise TypeError("Can't have mixed argument type")

        sort_arg_defs = self.get_sort_arg_defs()

        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            if isinstance(word, SortKey):
                word = word.value
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: test_sort.py    GNU General Public License v3.0 5 votes vote down vote up
def check(tag, expected, raw, compare=None):
    global nerrors

    if verbose:
        print("    checking", tag)

    orig = raw[:]   # save input in case of error
    if compare:
        raw.sort(key=cmp_to_key(compare))
    else:
        raw.sort()

    if len(expected) != len(raw):
        print("error in", tag)
        print("length mismatch;", len(expected), len(raw))
        print(expected)
        print(orig)
        print(raw)
        nerrors += 1
        return

    for i, good in enumerate(expected):
        maybe = raw[i]
        if good is not maybe:
            print("error in", tag)
            print("out of order at index", i, good, maybe)
            print(expected)
            print(orig)
            print(raw)
            nerrors += 1
            return 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: test_sort.py    GNU General Public License v3.0 5 votes vote down vote up
def test_decorated(self):
        data = 'The quick Brown fox Jumped over The lazy Dog'.split()
        copy = data[:]
        random.shuffle(data)
        data.sort(key=str.lower)
        def my_cmp(x, y):
            xlower, ylower = x.lower(), y.lower()
            return (xlower > ylower) - (xlower < ylower)
        copy.sort(key=cmp_to_key(my_cmp)) 
Example 33
Project: WavesGatewayLTCExample   Author: jansenmarc   File: litecoin_transaction_service.py    MIT License 5 votes vote down vote up
def _fast_optimize_unspents(self, unspents: List[dict], dst_amount: Decimal) -> Optional[List]:
        res = list()  # type: List[dict]
        unspents = list(unspents)

        if sum_unspents(unspents) < dst_amount:
            return None

        for i in range(0, len(unspents)):

            diff_dst_amount = dst_amount - sum_unspents(res)

            def comparator(value: dict, other: dict) -> int:
                """
                Compares two unspents by their absolute difference to
                the required amount.
                """
                distance_a = value['amount'] - diff_dst_amount
                distance_b = other['amount'] - diff_dst_amount

                if abs(distance_a) != abs(distance_b):
                    return abs(distance_a) - abs(distance_b)
                else:
                    return distance_a - distance_b

            sorted_unspents = sorted(unspents, key=cmp_to_key(comparator))

            best_fit = sorted_unspents[0]

            res.append(best_fit)
            unspents.remove(best_fit)

            if sum_unspents(res) >= dst_amount:
                return res

        return None 
Example 34
Project: OpenTDA   Author: outlace   File: persistent_homology.py    Apache License 2.0 5 votes vote down vote up
def sortComplex(filterComplex, filterValues):
    pairedList = zip(filterComplex, filterValues)
    sortedComplex = sorted(pairedList, key=functools.cmp_to_key(compare))
    sortedComplex = [list(t) for t in zip(*sortedComplex)]

    return sortedComplex 
Example 35
Project: BiLatticeRNN-data-processing   Author: alecokas   File: posterior.py    MIT License 5 votes vote down vote up
def sort_nodes_forward(self):
        # Sort nodes by starting point
        self.nodes.sort(key=functools.cmp_to_key(lambda x, y: cmp(x.entry, y.entry)))
        # Sort edges by ending point
        for n in self.nodes:
            n.exits.sort(key=functools.cmp_to_key(lambda x, y: cmp(x.dest.entry, y.dest.entry))) 
Example 36
Project: PyTools   Author: taige   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def to_str(mlist, prefix='[', suffix=']', empty='', newest=None, sort_by_tm=False, sort_by_count=True):
        if len(mlist) == 0:
            return '%s%s%s' % (prefix, empty, suffix)
        _counter_ = {} if sort_by_tm or sort_by_count else OrderedDict()
        for key in mlist:
            key = key.cn_name if isinstance(key, Material) else key
            if key.find('#') > 0:
                key = key.split('#')[1]
            if key in _counter_:
                _counter_[key] += 1
            else:
                _counter_[key] = 1
        if newest is None:
            _str_ = ''
        else:
            _str_ = '%d*%s' % (_counter_[newest], newest)

        if not isinstance(_counter_, OrderedDict):

            def _counter_sort_(k1, k2):
                m1 = MaterialDict.get(k1)
                m2 = MaterialDict.get(k2)
                if sort_by_tm:
                    rc = m2.time_consuming - m1.time_consuming
                else:
                    rc = _counter_[k2] - _counter_[k1]
                if rc == 0:
                    rc = -1 if m1.seq < m2.seq else 0 if m1.seq == m2.seq else 1
                return rc

        for key in (_counter_ if isinstance(_counter_, OrderedDict) else sorted(_counter_, key=functools.cmp_to_key(_counter_sort_))):
            if newest is not None and key == newest:
                continue
            if _str_ != '':
                _str_ += ', '
            _str_ += '%d*%s' % (_counter_[key], key)
        return '%s%s%s' % (prefix, _str_, suffix) 
Example 37
Project: PyTools   Author: taige   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def refresh_status(self, index=None, done_percent_changed=False):
        status = self._status
        pos = yx = 0
        if index is None:
            self._win.move(0, 0)
            for idx in sorted(status, key=functools.cmp_to_key(self.progress_cmp)):
                if not isinstance(status[idx], Progress):
                    continue
                prog = status[idx]
                if prog.start0 > pos:
                    yx = self.mark_progress(yx, pos, prog.start0-1) + 1
                elif prog.start0 < pos:
                    logger.debug('error status[%d]: %s', idx, prog)
                    continue
                self._segments[idx] = yx
                yx = self.mark_progress(yx, prog=prog) + 1
                pos = prog.end+1
            if pos < self._con_len:
                self.mark_progress(yx, pos, self._con_len - 1)
        else:
            yx = self._segments[index]
            self.move(yx)
            self.mark_progress(yx, prog=status[index])
            self._win.move(self._height, 0)
            # logger.debug("only refresh status[%d]: %s %d%%", index, status[index], status[index].done_percent())
        self._win.noutrefresh()
        if status.done_percent_changed() or done_percent_changed:
            # self._pwin.border(0)
            p_str = "[ %s %3d%% ]" % (self._out_file, status.done_percent())
            # logger.debug("self._pwin.p_str=%s", p_str)
            self._pwin.addstr(0, int((SCR_COLS - len(p_str)) / 2), p_str)
            self._pwin.noutrefresh() 
Example 38
Project: katana-sdk-python2   Author: kusanagi   File: versions.py    MIT License 5 votes vote down vote up
def resolve(self, versions):
        valid_versions = [ver for ver in versions if self.match(ver)]
        if not valid_versions:
            raise VersionNotFound(self.pattern)

        valid_versions.sort(key=cmp_to_key(self.compare))
        return valid_versions[0] 
Example 39
Project: DropSynth   Author: KosuriLab   File: Primerselectiontools_py3.py    MIT License 5 votes vote down vote up
def evaluateOverlaps(seq, overlapseqs, overlaptemps, deltaGThreshold, selfDimersThreshold):
    overlapseqs = secondaryStructure(overlapseqs, deltaGThreshold)
    overlapseqs = selfDimers(overlapseqs, selfDimersThreshold)
    overlapseqs = meltingTemperature(overlapseqs, overlaptemps[0], overlaptemps[1])
    if len(overlapseqs) > 0:
        #py2: overlapseqs.sort(lambda x, y: cmp(abs(x[2]), abs(y[2])))
        overlapseqs.sort(key=functools.cmp_to_key(lambda x, y: cmp(abs(x[2]), abs(y[2]))))
        finaloverlap = overlapseqs[0]
        return finaloverlap
    else:
        return [] 
Example 40
Project: DropSynth   Author: KosuriLab   File: Primerselectiontools_py3.py    MIT License 5 votes vote down vote up
def optimizeOverlap(overlap, seq, lengthleeway, positionleeway, overlaptemps, deltaGThreshold, selfDimersThreshold):
    #First Check Characteristics of all oligos at the same positions with different lengths
    
    newoverlap = overlap[:]
    poslees = list(range(positionleeway*-1,(positionleeway)+1))
    #py2: poslees.sort(lambda x, y: cmp(abs(x), abs(y)))
    poslees.sort(key=functools.cmp_to_key(lambda x, y: cmp(abs(x), abs(y))))
    #print(poslees)
    for pl in poslees:
        for ll in range(lengthleeway+1):
            #print("ll=" + str(ll))
            newoverlap = [overlap[0]+pl, overlap[1]+pl]
            ##print(overlap[0])
            ##print(overlap[1])
            ##print(pl)
            testseqcoords = []
            for i in range(ll+1):
                #print("i="+str(i))
                testseqcoords.append([i,ll-i])
                if not ll==0:
                    testseqcoords.append([i*-1,(ll-i)*-1])
            overlapseqs = []
            #print(testseqcoords)
            for coord in testseqcoords:
                newcoords = [newoverlap[0]+coord[0], newoverlap[1]+coord[1]]
                ##print(newoverlap[0])
                ##print(newoverlap[1])
                #print(str(newcoords) + '\t' + str(overlap[2]))
                if newcoords[1]<=overlap[2]:
                    ##print(newcoords[0])
                    ##print(newcoords[1])
                    overlapseq = seq[newcoords[0]:newcoords[1]]
                    overlapseqs.append([overlapseq, newcoords])
                #print(overlapseqs)
            finaloverlap = evaluateOverlaps(seq, overlapseqs, overlaptemps, deltaGThreshold, selfDimersThreshold)
            if finaloverlap:
                return finaloverlap[1]
        #print("position change") 
Example 41
Project: leetcode   Author: tedye   File: leetcode.179.largest-number.py    MIT License 5 votes vote down vote up
def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        import functools
        if not nums:
            return ''
        
        res= ''.join(sorted([str(x) for x in nums], key = functools.cmp_to_key(self.compare))).lstrip('0')
        if not res:
            return '0'
        else:
            return res 
Example 42
Project: sawtooth-core   Author: hyperledger   File: client_handlers.py    Apache License 2.0 5 votes vote down vote up
def sort_resources(cls, request, resources, fail_enum, header_proto=None):
        """Sorts a list of resources based on a list of sort controls

        Args:
            request (object): The parsed protobuf request object
            resources (list of objects): The resources to be sorted
            fail_enum (int, enum): The enum status to raise with invalid keys
            header_proto(class): Class to decode a resources header

        Returns:
            list: The sorted list of resources
        """
        if not request.sorting:
            return resources

        value_handlers = cls._get_handler_set(request, fail_enum, header_proto)

        def sorter(resource_a, resource_b):
            for handler in value_handlers:
                val_a, val_b = handler.get_sort_values(resource_a, resource_b)

                if val_a < val_b:
                    return handler.xform_result(-1)
                if val_a > val_b:
                    return handler.xform_result(1)

            return 0

        return sorted(resources, key=cmp_to_key(sorter)) 
Example 43
Project: cosinnus-core   Author: wechange-eg   File: functions.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def sort_key_strcoll_attr(attr_name):
    """ Returns a function usable as key for the py3 sorted() function,
        that will sort objects using strcoll() on their given attributes. """
    def strcoll_cmp_attr(obj1, obj2):
        return locale.strcoll(getattr(obj1, attr_name, ''), getattr(obj2, attr_name, ''))
    return functools.cmp_to_key(strcoll_cmp_attr) 
Example 44
Project: cosinnus-core   Author: wechange-eg   File: functions.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def sort_key_strcoll_lambda(lambda_func):
    """ Returns a function usable as key for the py3 sorted() function,
        that will sort objects using strcoll() the attribute accessed by a given lambda function. """
    def strcoll_cmp_attr(obj1, obj2):
        return locale.strcoll(lambda_func(obj1), lambda_func(obj2))
    return functools.cmp_to_key(strcoll_cmp_attr) 
Example 45
Project: grep-linux-patch-statistics   Author: klockeph   File: get_patch_data.py    Apache License 2.0 5 votes vote down vote up
def get_commits_dot_zero(grep_filter, sha_lookup, start_zero):
    return get_commits_ordered(sorted(
                get_dot_zero_versions(),
                key=functools.cmp_to_key(kernel_version_comparator)),
            grep_filter, sha_lookup, start_zero) 
Example 46
Project: grep-linux-patch-statistics   Author: klockeph   File: get_patch_data.py    Apache License 2.0 5 votes vote down vote up
def get_commits_lts(version, grep_filter, sha_lookup, start_zero):
    versions = sorted(
            [v for v in get_versions() if v == version or v.startswith(version+".")],
            key=functools.cmp_to_key(kernel_version_comparator))

    return get_commits_ordered(versions, grep_filter, sha_lookup, start_zero) 
Example 47
Project: SempoBlockchain   Author: teamsempo   File: user.py    GNU General Public License v3.0 5 votes vote down vote up
def transfer_usages_for_user(user: User) -> List[TransferUsage]:
    most_common_uses = user.get_most_relevant_transfer_usages()

    def usage_sort(a, b):
        ma = most_common_uses.get(a.name)
        mb = most_common_uses.get(b.name)

        # return most used, then default, then everything else
        if ma is not None and mb is not None:
            if ma >= mb:
                return -1
            else:
                return 1
        elif ma is not None:
            return -1
        elif mb is not None:
            return 1
        elif a.default or b.default:
            if a.default:
                return -1
            else:
                return 1
        else:
            return -1

    ordered_transfer_usages = sorted(TransferUsage.query.all(), key=cmp_to_key(usage_sort))
    return ordered_transfer_usages 
Example 48
Project: ironpython2   Author: IronLanguages   File: loader.py    Apache License 2.0 5 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
        testFnNames = filter(isTestMethod, dir(testCaseClass))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
        return testFnNames 
Example 49
Project: ironpython2   Author: IronLanguages   File: pstats.py    Apache License 2.0 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example 50
Project: ironpython2   Author: IronLanguages   File: test_functools.py    Apache License 2.0 5 votes vote down vote up
def test_cmp_to_key(self):
        def mycmp(x, y):
            return y - x
        self.assertEqual(sorted(range(5), key=functools.cmp_to_key(mycmp)),
                         [4, 3, 2, 1, 0])