def apply_padders(cls):
    """ Decorator for generating useful padding methods
    Loops through and generates methods like:
      Padding.push_1(Widget)
      Sets the left padding attribute by 1
      Padding.pull_24(Widget)
      Sets right padding attribute by 24.
      Padding.center_50(Widget)
      Provides center padding with a relative width of 50
    """
    padding_count = 100

    for i in range(1, padding_count):
        setattr(cls, 'push_{}'.format(i), partialmethod(_Padding, left=i))
        setattr(cls, 'pull_{}'.format(i), partialmethod(_Padding, right=i))
        setattr(cls, 'center_{}'.format(i),
                partialmethod(_Padding, align='center',
                              width=('relative', i)))
        setattr(cls, 'left_{}'.format(i),
                partialmethod(_Padding, align='left',
                              width=('relative', i)))
        setattr(cls, 'right_{}'.format(i),
                partialmethod(_Padding, align='right',
                              width=('relative', i)))
    return cls
Example #2
0
    def _op(argname, arg=None, *, _pseudop=pseudop):
        # this is a temportary helper to shrink the declarations of
        # the simpler operators. These operators all either take no
        # arguments, or take a single constant argument. this helper
        # is deleted after the operators are all defined.

        if arg is None:
            return partialmethod(_pseudop, Pseudop[argname])
        else:
            return partialmethod(_pseudop, Pseudop[argname], arg)
Example #3
0
 def test_serialize_functools_partialmethod(self):
     value = functools.partialmethod(datetime.timedelta, 1, seconds=2)
     result = self.serialize_round_trip(value)
     self.assertIsInstance(result, functools.partialmethod)
     self.assertEqual(result.func, value.func)
     self.assertEqual(result.args, value.args)
     self.assertEqual(result.keywords, value.keywords)
Example #4
0
 def on(self, command, func=None, **kwargs):
     
     if func is None:
         return functools.partialmethod(command, **kwargs)
     
     plugin = structures.Plugin(func, command, **kwargs)
     self.register(plugin)
     
     return plugin
def apply_style_map(cls):
    """ Applies AttrMap attributes to Color class
    Eg:
      Color.frame_header(Text("I'm text in the Orange frame header"))
      Color.body(Text("Im text in wrapped with the body color"))
    """
    for k in STYLES:
        setattr(cls, k[0], partialmethod(AttrMap, attr_map=k[0]))
    return cls
def override(cls, name, method):
    """Injects a method into a class.

    This will inject the given method into the given class, overriding a member
    of the given name. The new method will receive the same arguments as the old
    variant, with the original member passed in as second argument right after self.
    If the class previously had no member of this name, this argument will be None.
    """
    setattr(cls, name, partialmethod(method, getattr(cls, name, None)))
    return method
Example #7
0
    def __new__(cls, name, bases, attrs):
        newClass = super().__new__(cls, name, bases, attrs)

        if hasattr(newClass, 'add'):
            add = getattr(newClass, 'add')
            for m in HTTP_METHODS:
                method = partialmethod(add, methods=m)
                setattr(newClass, m, method)
                setattr(newClass, m.lower(), method)

        return newClass
Example #8
0
def admininline_factory(Model, Inline):
    classname = "{}{}".format(Model.__name__, "AdminInline")
    class_attributes = {"model": Model, "formset": OneFormFormSet, "min_num": 1, "max_num": 1, "can_delete": False}
    #{"model": Model, "extra": 2, "max_num": 1, "formset": inlineformset_factory(Release, Model,
    #  formset=DebugBaseInlineFormSet, fields="__all__", max_num=1, validate_max=True)}

    if hasattr(Model, "form_callback"):
        SpecificFormSet = type("{}SpecificFormSet".format(Model.__name__), (OneFormFormSet,),
                               {"collecster_instance_callback": functools.partialmethod(specific_instance_callback, Model=Model)})
        class_attributes["formset"] = SpecificFormSet

    return type(classname, (Inline,), class_attributes)
Example #9
0
def register_tests(test_class, method_name, test_func, exclude=None):
    """
    Dynamically create serializer tests to ensure that all registered
    serializers are automatically tested.
    """
    formats = [
        f for f in serializers.get_serializer_formats()
        if (not isinstance(serializers.get_serializer(f), serializers.BadSerializer) and
            f != 'geojson' and
            (exclude is None or f not in exclude))
    ]
    for format_ in formats:
        setattr(test_class, method_name % format_, partialmethod(test_func, format_))
Example #10
0
    def _create_go_to_method(cls, path, class_name=None):
        go_to_method = Navigation.GoToMethodFactory(path, class_name)
        inst_method = six.create_unbound_method(go_to_method, Navigation)

        # TODO(e0ne): remove python2 support once all integration jobs
        # will be switched to python3.
        if six.PY3:
            def _go_to_page(self, path):
                return Navigation._go_to_page(self, path)

            wrapped_go_to = functools.partialmethod(_go_to_page, path)
            setattr(Navigation, inst_method.name, wrapped_go_to)
        else:
            setattr(Navigation, inst_method.name, inst_method)
Example #11
0
 def __init__(cls, name, bases, dct):
     func_names_to_proxy = dct.get('_proxyfunc_func_set_') or set(['__setitem__', '__getitem__', '__delitem__',
                                                                   '__contains__', '__iter__', '__len__'])
     for attr in func_names_to_proxy:
         if not hasattr(cls, attr):
             if sys.version_info[0] > 2:
                 # Python 3+
                 func = functools.partialmethod(dct['_proxyfunc_'], attr)
                 setattr(cls, attr, func)
             else:
                 # Python 2
                 func = (lambda attr:
                         lambda self, *args, **kwargs: dct['_proxyfunc_'](self, attr, *args, **kwargs))(attr)
                 setattr(cls, attr, new.instancemethod(func, None, cls))
     return super(ProxyContainerMethodsMetaClass, cls).__init__(name, bases, dct)
Example #12
0
    def calculate(self, indices: list, n=None, parallel=True, cores=0) -> MutExResult:
        """
        :param indices: A list of indices for which to test the MutEx. The indices refer the the background-data row-ids.
        :return: MutExResult
        """

        if not all([x in self.background.index for x in indices]):
            raise Exception("Not all indices found in background")

        target = self.background.loc[indices]

        coverage = target.apply(max).pipe(sum)
        observation_signal = target.apply(sum, axis=1)
        signal = sum(observation_signal)

        if n == None:
            n = self.permutations

        logging.info("running {} permutations".format(n))

        if not parallel:
            cores = 1
        pool = mp.Pool(processes=mp.cpu_count() if cores < 1 else cores)
        logging.info('permutation with {} cores'.format(pool._processes))
        partial_simul = partialmethod(self._one_permutation)
        simulated_results = pool.starmap(partial_simul.func,
                                         zip(itertools.repeat(coverage, n), itertools.repeat(observation_signal, n)))
        pool.close()  # we are not adding any more processes
        pool.join()  # tell it to wait until all threads are done before going on

        logging.info('calculate result')
        sim_coverages = [x[0] for x in simulated_results]
        higher_coverage = [x[1] for x in simulated_results]
        lower_coverage = [x[2] for x in simulated_results]

        return MutExResult(coverage=coverage, signal=signal,
                           higher_coverage_count=np.sum(higher_coverage),
                           lower_coverage_count=np.sum(lower_coverage), permutations=n,
                           mean_sim_coverage=np.mean(sim_coverages),
                           stdev_sim_coverage=np.std(sim_coverages),
                           sample_size=len(self.sample_weights),
                           items=indices
                           )
Example #13
0
	def __new__(mcs, name, bases, members):
		"""
		Defines a new TestCase class.

		This intercepts all tests that are parametrised and duplicates them for
		each of the sets of parameters they need to be called with.
		:param name: The name of the TestCase class.
		:param bases: The superclasses of the TestCase class.
		:param members: The members of the TestCase class, including functions.
		:return: A new TestCase class, modified for parametrised tests.
		"""
		members_copy = dict(members)
		for member in members_copy:
			if callable(members_copy[member]) and hasattr(members_copy[member], "parameters"): #It's a function that's marked with the @parametrise annotation.
				for test_name, parameters in members_copy[member].parameters.items(): #Copy the function for each set of parameters.
					new_function = functools.partialmethod(members_copy[member], **parameters) #Fill in only the parameters. The rest is filled in at calling (such as "self").
					members[member + "_" + test_name] = new_function #Store the filled-in function along with the test name to make it unique.
				del members[member] #Delete the original parametrised function.
		return type.__new__(mcs, name, bases, members)
Example #14
0
    'uncon_vars',
    'tagsin_mask',
    'tagsout_mask',
    'tagsin_lhs_vars',
    'tagsout_lhs_vars',
    'should_filter',
    'filter_needs_preds',
    'functionally_determines',
    'get_priority',
    'get_code',
    'rename_lhs_vars',
    'rename_rhs_rel',
    'singletonize',
    'subtract',
    ]:
    setattr(ClauseVisitor, op, partialmethod(ClauseVisitor.visit, op))


def assert_unique(vars):
    """Given a tuple of LHS vars, raise AssertionError if there are
    repeated vars (representing an equality pattern).
    """
    counts = Counter(vars)
    if not all(c == 1 for c in counts.values()):
        dups = [x for x, c in counts.items() if c > 1]
        raise AssertionError('LHS vars appear multiple times in same '
                             'clause: ' + ', '.join(dups))


class RelMemberHandler(ClauseHandler):
    
Example #15
0
        """
        result = challenge_f()

        if result is not None:
            self.assertTrue(result)


"""
Automatically add test methods from each challenge.
"""
excluded = {"challenge", "main"}  # manually exclude some functions.
# exclude slow tests by default
slows = {
    "twentytwo", "twentyfour", "twenty",
    "thirtyeight", "thirtytwo", "thirtyone",
    "fortyseven", "fortyeight", "fiftysix"
}
for f_name, f in inspect.getmembers(matasano.challenges, inspect.isfunction):
    if not f_name.startswith("_") and f_name not in excluded:
        test_challenge = functools.partialmethod(ChallengeTestCase.challenge, challenge_f=f)
        if f_name in slows:
            test_challenge = unittest.skip("Slow test")
        setattr(
            ChallengeTestCase,
            "test_{}".format(f_name),
            test_challenge
        )

if __name__ == '__main__':
    unittest.main()
Example #16
0
    def setup_initializer(self, initializer=None):
        if initializer is None:
            def initializer(self, *args, **kwargs):
                self.instance = self.subject(*args, **kwargs)

        self.factory.methods['__init__'] = partialmethod(initializer)
Example #17
0
    def decorate(class_):
        for method in method_names:
            setattr(class_, method, partialmethod(call_attribute_method, method))

        return class_
Example #18
0
from functools import partialmethod
from requests import Session

class T:
    def test(self, msg=''):
        print(msg)

    test = partialmethod(test, msg='4444')

Session.get = partialmethod(Session.get, timeout=5)

T().test()
print(Session().get('http://www.baidu.com'))


from client import client
client._session.get('http://10.255.255.1')
Example #19
0
            return normalize.get_degraded_scores([str(self)], as_lv, ui)[str(self)]

    def apostrophe(self, as_lv=None):
        if not as_lv: as_lv = self.lv
        apos_char = normalize.apostrophe(as_lv)
        return self.sub(r"'", apos_char)

    def dict(self):
        return {'langvar' : self.lv, 'txt' : str(self)}

    @classmethod
    def undict(cls, d):
        return cls(d['txt'], d['langvar'])

for i in ['__getitem__', '__mul__', '__rmul__', '__mod__', '__rmod__']:
    setattr(Ex, i, partialmethod(Ex.__special_obj__, i))

for i in ['__eq__', '__lt__', '__gt__', '__le__', '__ge__', '__ne__', '__contains__']:
    setattr(Ex, i, partialmethod(Ex.__special_cmp__, i))


class Df(Ex):
    def pretty(self, indent=0):
        ind = '  ' * indent
        out = ""
        out += ind + self.__class__.__name__.lower() + '\n'
        out += ind + '  ' + self.lv + '\n'
        out += ind + '  ' + self.text + '\n'
        return out

    @classmethod
Example #20
0
File: data.py Project: bjarkig/holo
                return curnode

def get_pairs(self, names):
        t = []
        for n in names:
                fine = n
                n = n.lower()
                n = n.replace('-', '')
                if n == 'description':
                        n = 'desc'
                value = getattr(self, n)
                if isinstance(value, list):
                        value = ", ".join(value)
                t.append((fine, value))
        return t


Person = collections.namedtuple('Person', ['name', 'desc', 'profile', 'joke'])
Person.get_pairs = partialmethod(get_pairs, ['Name', 'Description', 'Profile', 'Joke'])

Role = collections.namedtuple('Role', ['name', 'desc'])
Role.get_pairs = partialmethod(get_pairs, ['Name', 'Description'])

Circle = collections.namedtuple('Circle', \
                ['name', 'desc', 'domain', 'coremembers', 'tree'])
Circle.get_pairs = partialmethod(get_pairs, ['Name', 'Description', 'Domain', 'Core-members'])

Circle.__str__ = lambda self: str(self.name)
Project.get_pairs = get_pairs = partialmethod(get_pairs, ['Owner', 'Name', 'Description'])

Example #21
0
        if desc.get('masks'):
            fast_result = fast_func(im=image, mask=desc['masks'][idx] if len(desc['masks']) > 1 else desc['masks'][0])
            slow_result = slow_func(im=image, mask=desc['masks'][idx] if len(desc['masks']) > 1 else desc['masks'][0])
        else:
            fast_result = fast_func(im=image)
            slow_result = slow_func(im=image)
    if desc.get('validator_takes_desc_and_flavor_args'):
        desc['validator'](self, fast_result, slow_result, desc=desc, flavor=flavor)
    else:
        desc['validator'](self, fast_result, slow_result)

for desc in TARGET_FUNC_DESCS:
    for flavor in IMAGE_FLAVORS:
        if 'accepted_dtypes' not in desc or any(numpy.issubdtype(flavor.dtype, accepted_dtype) for accepted_dtype in desc['accepted_dtypes']):
            if 'slow_func' in desc and 'fast_func' in desc and 'validator' in desc:
                 setattr(NDImageStatisticsTestCase, 'test_{}_{}'.format(desc['name'], flavor.name), functools.partialmethod(_test, desc=desc, flavor=flavor))
            # def test(self):
            #     if desc.
            benchmarks.append(functools.partial(_benchmark, desc, flavor))

if __name__ == '__main__':
    import sys
    if len(sys.argv) == 1 or sys.argv[1] not in ('test', 'benchmark', 'test_and_benchmark'):
        print("***Defaulting to running tests.  Supply benchmark or test_and_benchmark as an argument to do otherwise.***")
        unittest.main(argv=sys.argv)
    elif sys.argv[1] == 'test':
        unittest.main(argv=sys.argv[0:1] + sys.argv[2:])
    elif sys.argv[1] == 'benchmark':
        print("All results in milliseconds.  Running benchmarks...")
        for benchmark in benchmarks:
            benchmark()
Example #22
0
 def pass_args(*args, **kwargs):
     return functools.partialmethod(method, *args, **kwargs)
Example #23
0
def setup_generic_relations(model_actor, relation_methods):
    """
    注册过的 actor_model_class 实例可以如此操作:
        actor.METHOD(target) # 建立 target 的特定 RELATION
        actor.dont_METHOD(target) # 或 no_METHOD 取消 target 的特定 RELATION
        #
        actor.actor_relations.filter(...)
        actor.METHOD_relations(...) # AS actor 的特定 RELATION filter
        actor.has_METHOD(target) # 与 target 是否存在特定 RELATION
    target_model_instance 可以有如下操作:
        target.target_relations.filter(...)
        target.METHOD_related(...) # AS target 的特定 RELATION filter
        target.was_METHOD(actor) # 与 actor 是否存在特定 RELATION
    owner_model_instance 可以有如下操作:
        owner.owner_relations.filter(...)
        owner.METHOD_related(...) # AS owner 的特定 RELATION filter
    """
    from qrelation import models
    #
    rel = GenericRelation(models.Relation,
        content_type_field='actor_type',
        object_id_field='actor_id',
        related_query_name='relations_with_%s_as_%s' % (label(model_actor), 'actor'))
    rel.contribute_to_class(model_actor, 'actor_relations')
    #
    actor_type = get_contenttype(model_actor)
    for method, kwargs in relation_methods.items():
        # 'follow': {
        #     'relation': models.REL_USER_FOLLOW,
        #     'target': 'quser.User',
        # }
        model_target = validate(kwargs.pop('target'))
        if not hasattr(model_target, 'target_relations'):
            rel = GenericRelation(models.Relation,
                content_type_field='target_type',
                object_id_field='target_id',
                related_query_name='relations_with_%s_as_%s' % (label(model_target), 'target'))
            rel.contribute_to_class(model_target, 'target_relations')
        model_owner = kwargs.pop('owner', None)
        if model_owner:
            model_owner = validate(model_owner)
            owner_type = get_contenttype(model_owner)
        if model_owner and not hasattr(model_owner, 'owner_relations'):
            rel = GenericRelation(models.Relation,
                content_type_field='owner_type',
                object_id_field='owner_id',
                related_query_name='relations_with_%s_as_%s' % (label(model_owner), 'owner'))
            rel.contribute_to_class(model_owner, 'owner_relations')
        #
        target_type = get_contenttype(model_target)
        relation, owner_field = kwargs.pop('relation'), kwargs.pop('owner_field', None)
        # 建立 relation
        setattr(model_actor, method, functools.partialmethod(
            relate, relation=relation, target_type=target_type, model_target=model_target, actor_type=actor_type, owner_field=owner_field))
        cancel_method = functools.partialmethod(
            relate, relation=relation, target_type=target_type, model_target=model_target, actor_type=actor_type, deleted=True)
        # 取消 relation
        setattr(model_actor, 'dont_%s' % method, cancel_method)
        setattr(model_actor, 'no_%s' % method, cancel_method)
        # 给 actor_model 增加类方法 METHOD_relations
        setattr(model_actor, '%s_relations' % method, functools.partialmethod(
            filter_relations, relation=relation))
        # 给 actor_model 增加类方法 has_METHOD
        setattr(model_actor, 'has_%s' % method, functools.partialmethod(
            check_relation, relation=relation, target_type=target_type, model_target=model_target))
        # 给 target_model 增加类方法 METHOD_related
        setattr(model_target, '%s_related' % method, functools.partialmethod(
            filter_related, relation=relation))
        # 给 target_model 增加类方法 was_METHOD
        setattr(model_target, 'was_%s' % method, functools.partialmethod(
            check_related, relation=relation, actor_type=actor_type, model_actor=model_actor))
        if not model_owner:
            continue
        # 给 owner_model 增加类方法 
        setattr(model_owner, '%s_related' % method, functools.partialmethod(
            filter_owner, relation=relation))
Example #24
0
 def __getattr__(self, name):
     if name.strip('_') in self.errs:
         f = functools.partialmethod(self.propagate, name=name)
         return f
     else:
         raise AttributeError
Example #25
0
def _inject_numeric_testing_methods(cls):
    def test_binop_name(suffix):
        return 'test_binop_{}_{}'.format(name, suffix)

    def test_ibinop_name(suffix):
        return 'test_ibinop_{}_{}'.format(name, suffix)

    def test_unaryop_name(suffix):
        return 'test_unaryop_{}_{}'.format(name, suffix)

    # inject testing methods for each binary operation
    for name, binop in _BINOPS:

        setattr(cls, test_binop_name('invalid_unknown'), partialmethod(_TestNumericField._test_binop_invalid_unknown, op=binop))
        setattr(cls, test_binop_name('invalid_none'), partialmethod(_TestNumericField._test_binop_invalid_none, op=binop))
        setattr(cls, test_binop_name('type_true'), partialmethod(_TestNumericField._test_binop_type_true, op=binop))
        setattr(cls, test_binop_name('type_pos_int'), partialmethod(_TestNumericField._test_binop_type_pos_int, op=binop))
        setattr(cls, test_binop_name('type_pos_vint'), partialmethod(_TestNumericField._test_binop_type_pos_vint, op=binop))
        setattr(cls, test_binop_name('value_true'), partialmethod(_TestNumericField._test_binop_value_true, op=binop))
        setattr(cls, test_binop_name('value_pos_int'), partialmethod(_TestNumericField._test_binop_value_pos_int, op=binop))
        setattr(cls, test_binop_name('value_pos_vint'), partialmethod(_TestNumericField._test_binop_value_pos_vint, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_true'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_true, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_pos_int'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_pos_int, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_pos_vint'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_pos_vint, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_true'), partialmethod(_TestNumericField._test_binop_lhs_value_same_true, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_pos_int'), partialmethod(_TestNumericField._test_binop_lhs_value_same_pos_int, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_pos_vint'), partialmethod(_TestNumericField._test_binop_lhs_value_same_pos_vint, op=binop))
        setattr(cls, test_binop_name('type_neg_int'), partialmethod(_TestNumericField._test_binop_type_neg_int, op=binop))
        setattr(cls, test_binop_name('type_neg_vint'), partialmethod(_TestNumericField._test_binop_type_neg_vint, op=binop))
        setattr(cls, test_binop_name('value_neg_int'), partialmethod(_TestNumericField._test_binop_value_neg_int, op=binop))
        setattr(cls, test_binop_name('value_neg_vint'), partialmethod(_TestNumericField._test_binop_value_neg_vint, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_neg_int'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_neg_int, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_neg_vint'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_neg_vint, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_neg_int'), partialmethod(_TestNumericField._test_binop_lhs_value_same_neg_int, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_neg_vint'), partialmethod(_TestNumericField._test_binop_lhs_value_same_neg_vint, op=binop))
        setattr(cls, test_binop_name('type_false'), partialmethod(_TestNumericField._test_binop_type_false, op=binop))
        setattr(cls, test_binop_name('type_zero_int'), partialmethod(_TestNumericField._test_binop_type_zero_int, op=binop))
        setattr(cls, test_binop_name('type_zero_vint'), partialmethod(_TestNumericField._test_binop_type_zero_vint, op=binop))
        setattr(cls, test_binop_name('value_false'), partialmethod(_TestNumericField._test_binop_value_false, op=binop))
        setattr(cls, test_binop_name('value_zero_int'), partialmethod(_TestNumericField._test_binop_value_zero_int, op=binop))
        setattr(cls, test_binop_name('value_zero_vint'), partialmethod(_TestNumericField._test_binop_value_zero_vint, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_false'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_false, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_zero_int'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_zero_int, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_zero_vint'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_zero_vint, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_false'), partialmethod(_TestNumericField._test_binop_lhs_value_same_false, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_zero_int'), partialmethod(_TestNumericField._test_binop_lhs_value_same_zero_int, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_zero_vint'), partialmethod(_TestNumericField._test_binop_lhs_value_same_zero_vint, op=binop))
        setattr(cls, test_binop_name('type_pos_float'), partialmethod(_TestNumericField._test_binop_type_pos_float, op=binop))
        setattr(cls, test_binop_name('type_neg_float'), partialmethod(_TestNumericField._test_binop_type_neg_float, op=binop))
        setattr(cls, test_binop_name('type_pos_vfloat'), partialmethod(_TestNumericField._test_binop_type_pos_vfloat, op=binop))
        setattr(cls, test_binop_name('type_neg_vfloat'), partialmethod(_TestNumericField._test_binop_type_neg_vfloat, op=binop))
        setattr(cls, test_binop_name('value_pos_float'), partialmethod(_TestNumericField._test_binop_value_pos_float, op=binop))
        setattr(cls, test_binop_name('value_neg_float'), partialmethod(_TestNumericField._test_binop_value_neg_float, op=binop))
        setattr(cls, test_binop_name('value_pos_vfloat'), partialmethod(_TestNumericField._test_binop_value_pos_vfloat, op=binop))
        setattr(cls, test_binop_name('value_neg_vfloat'), partialmethod(_TestNumericField._test_binop_value_neg_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_pos_float'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_pos_float, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_neg_float'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_neg_float, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_pos_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_pos_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_neg_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_neg_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_pos_float'), partialmethod(_TestNumericField._test_binop_lhs_value_same_pos_float, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_neg_float'), partialmethod(_TestNumericField._test_binop_lhs_value_same_neg_float, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_pos_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_value_same_pos_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_neg_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_value_same_neg_vfloat, op=binop))
        setattr(cls, test_binop_name('type_zero_float'), partialmethod(_TestNumericField._test_binop_type_zero_float, op=binop))
        setattr(cls, test_binop_name('type_zero_vfloat'), partialmethod(_TestNumericField._test_binop_type_zero_vfloat, op=binop))
        setattr(cls, test_binop_name('value_zero_float'), partialmethod(_TestNumericField._test_binop_value_zero_float, op=binop))
        setattr(cls, test_binop_name('value_zero_vfloat'), partialmethod(_TestNumericField._test_binop_value_zero_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_zero_float'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_zero_float, op=binop))
        setattr(cls, test_binop_name('lhs_addr_same_zero_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_addr_same_zero_vfloat, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_zero_float'), partialmethod(_TestNumericField._test_binop_lhs_value_same_zero_float, op=binop))
        setattr(cls, test_binop_name('lhs_value_same_zero_vfloat'), partialmethod(_TestNumericField._test_binop_lhs_value_same_zero_vfloat, op=binop))

    # inject testing methods for each unary operation
    for name, unaryop in _UNARYOPS:
        setattr(cls, test_unaryop_name('type'), partialmethod(_TestNumericField._test_unaryop_type, op=unaryop))
        setattr(cls, test_unaryop_name('value'), partialmethod(_TestNumericField._test_unaryop_value, op=unaryop))
        setattr(cls, test_unaryop_name('addr_same'), partialmethod(_TestNumericField._test_unaryop_addr_same, op=unaryop))
        setattr(cls, test_unaryop_name('value_same'), partialmethod(_TestNumericField._test_unaryop_value_same, op=unaryop))

    # inject testing methods for each inplace binary operation
    for name, ibinop in _IBINOPS:
        setattr(cls, test_ibinop_name('invalid_unknown'), partialmethod(_TestNumericField._test_ibinop_invalid_unknown, op=ibinop))
        setattr(cls, test_ibinop_name('invalid_none'), partialmethod(_TestNumericField._test_ibinop_invalid_none, op=ibinop))
        setattr(cls, test_ibinop_name('type_true'), partialmethod(_TestNumericField._test_ibinop_type_true, op=ibinop))
        setattr(cls, test_ibinop_name('value_true'), partialmethod(_TestNumericField._test_ibinop_value_true, op=ibinop))
        setattr(cls, test_ibinop_name('type_pos_int'), partialmethod(_TestNumericField._test_ibinop_type_pos_int, op=ibinop))
        setattr(cls, test_ibinop_name('type_pos_vint'), partialmethod(_TestNumericField._test_ibinop_type_pos_vint, op=ibinop))
        setattr(cls, test_ibinop_name('value_pos_int'), partialmethod(_TestNumericField._test_ibinop_value_pos_int, op=ibinop))
        setattr(cls, test_ibinop_name('value_pos_vint'), partialmethod(_TestNumericField._test_ibinop_value_pos_vint, op=ibinop))
        setattr(cls, test_ibinop_name('type_neg_int'), partialmethod(_TestNumericField._test_ibinop_type_neg_int, op=ibinop))
        setattr(cls, test_ibinop_name('type_neg_vint'), partialmethod(_TestNumericField._test_ibinop_type_neg_vint, op=ibinop))
        setattr(cls, test_ibinop_name('value_neg_int'), partialmethod(_TestNumericField._test_ibinop_value_neg_int, op=ibinop))
        setattr(cls, test_ibinop_name('value_neg_vint'), partialmethod(_TestNumericField._test_ibinop_value_neg_vint, op=ibinop))
        setattr(cls, test_ibinop_name('type_false'), partialmethod(_TestNumericField._test_ibinop_type_false, op=ibinop))
        setattr(cls, test_ibinop_name('value_false'), partialmethod(_TestNumericField._test_ibinop_value_false, op=ibinop))
        setattr(cls, test_ibinop_name('type_zero_int'), partialmethod(_TestNumericField._test_ibinop_type_zero_int, op=ibinop))
        setattr(cls, test_ibinop_name('type_zero_vint'), partialmethod(_TestNumericField._test_ibinop_type_zero_vint, op=ibinop))
        setattr(cls, test_ibinop_name('value_zero_int'), partialmethod(_TestNumericField._test_ibinop_value_zero_int, op=ibinop))
        setattr(cls, test_ibinop_name('value_zero_vint'), partialmethod(_TestNumericField._test_ibinop_value_zero_vint, op=ibinop))
        setattr(cls, test_ibinop_name('type_pos_float'), partialmethod(_TestNumericField._test_ibinop_type_pos_float, op=ibinop))
        setattr(cls, test_ibinop_name('type_neg_float'), partialmethod(_TestNumericField._test_ibinop_type_neg_float, op=ibinop))
        setattr(cls, test_ibinop_name('type_pos_vfloat'), partialmethod(_TestNumericField._test_ibinop_type_pos_vfloat, op=ibinop))
        setattr(cls, test_ibinop_name('type_neg_vfloat'), partialmethod(_TestNumericField._test_ibinop_type_neg_vfloat, op=ibinop))
        setattr(cls, test_ibinop_name('value_pos_float'), partialmethod(_TestNumericField._test_ibinop_value_pos_float, op=ibinop))
        setattr(cls, test_ibinop_name('value_neg_float'), partialmethod(_TestNumericField._test_ibinop_value_neg_float, op=ibinop))
        setattr(cls, test_ibinop_name('value_pos_vfloat'), partialmethod(_TestNumericField._test_ibinop_value_pos_vfloat, op=ibinop))
        setattr(cls, test_ibinop_name('value_neg_vfloat'), partialmethod(_TestNumericField._test_ibinop_value_neg_vfloat, op=ibinop))
        setattr(cls, test_ibinop_name('type_zero_float'), partialmethod(_TestNumericField._test_ibinop_type_zero_float, op=ibinop))
        setattr(cls, test_ibinop_name('type_zero_vfloat'), partialmethod(_TestNumericField._test_ibinop_type_zero_vfloat, op=ibinop))
        setattr(cls, test_ibinop_name('value_zero_float'), partialmethod(_TestNumericField._test_ibinop_value_zero_float, op=ibinop))
        setattr(cls, test_ibinop_name('value_zero_vfloat'), partialmethod(_TestNumericField._test_ibinop_value_zero_vfloat, op=ibinop))
Example #26
0
    #print("METHOD", name)
    method = self._get_special(name)
    if method is NotImplemented:
        return NotImplemented
    return method()

unary_special_method_names = (
    "__len__",
    "__neg__", "__pos__", "__abs__",
    "__invert__", "__complex__",
    "__int__", "__float__",
    "__round__",
)

for name in unary_special_method_names:
    m = partialmethod(silk_unary_method, name=name)
    setattr(SilkBase, name, m)


def silk_unary_method_optional(self, name):
    #print("METHOD", name)
    try:
        method = self._get_special(name)
    except AttributeError:
        return NotImplementedError
    return method()

unary_special_method_names_optional = (
    "__length_hint__", "__index__",
    "__iter__", "__reversed__", "__bool__"
)
Example #27
0
from pymongo.errors import OperationFailure

import src
from controller import MSGHandler
from backend_modules import router
from src import messages as msg
from src.db import User, Code, NoObjectReturnedFromDB, \
    ConditionNotMetError, Course, Room
from src.pub_sub import MalformedMessageError
from src.wsclass import subscribe

_path = msg.join_path('panels', 'user')

MSGHandler.send_user_not_loaded_error = partialmethod(
    MSGHandler.send_error,
    'userNotLoaded',
    description='There was no loaded user when '
                'this message arrived.'
)

MSGHandler.send_room_not_loaded_error = partialmethod(
    MSGHandler.send_error,
    'roomNotLoaded',
    description='There was no loaded room when '
    'this message arrived.'
)


def _logout_and_close(self, reason):
    """Send a logout message and close the connection."""
    self.write_message({'type': 'logout'})
    self.close(1000, reason)
Example #28
0
    return getattr(self.value,name)(other)

def mixed_scalar_binary_method_inplace(self, other, name2):
    result = getattr(self.value,name2)(other)
    if result is NotImplemented:
        return NotImplemented
    self._monitor.set_path(self._path, result)
    return result

class MixedScalar(MixedBase):
    def __getitem__(self, item):
        value = self.value
        if not isinstance(value, (str, np.ndarray)):
            raise TypeError(type(value))
        return value[item]

for name in binary_special_method_names:
    if name.startswith("__i"):
        name2 = "__" + name[3:]
        m = partialmethod(mixed_scalar_binary_method_inplace, name2=name2)
    else:
        m = partialmethod(mixed_scalar_binary_method, name=name)
    setattr(MixedScalar, name, m)


from .MixedDict import MixedDict
from .MixedObject import MixedObject
from .Monitor import Monitor
from .Backend import Backend, DefaultBackend, CellBackend
from .get_form import is_contiguous, is_unsigned
Example #29
0
 def __new__(cls, name, bases, dict):
     method = dict.get('run_test', BaseUnitTest.run_test)
     for name, args in dict['tests'].items():
         dict['test_%s' % (name, )] = partialmethod(method, dict['func'], args['output'], **args['kwargs'])
     return type(name, bases, dict)