Beispiel #1
0
	def to_internal_value(self, data):
		question = self.get_question()
		polling  = question.polling

		now = _djtz.localtime(timezone=_djtz.get_default_timezone())

		if now < polling.start_time:
			self.fail('polling_not_started')

		if polling.start_time + polling.duration <= now:
			self.fail('polling_ended')

		data = super().to_internal_value(data)
		data['question'] = question

		data = F.select_values(F.complement(F.isnone), data)

		logger.debug('QuestionAnswerSerializer.to_internal_value(%r)', data)

		if isinstance(question, models.TextQuestion):
			kwargs = F.project(data, 'guest_id question text'.split())
			rest   = F.project(data, F.without(data, *kwargs.keys()))
		elif isinstance(question, models.ChoiceQuestion):
			kwargs = F.project(data, 'guest_id question choices'.split())
			rest   = F.project(data, F.without(data, *kwargs.keys()))
		else:
			self.fail('unknown_question', question=question)

		if rest:
			self.fail('unknown_fields', fields=dict(rest))

		return data
Beispiel #2
0
    def name(self):
        if self._name is None:
            if self._scorer is not None:
                # try from scorer
                if isinstance(self._scorer,
                              sklearn.metrics.scorer._BaseScorer):
                    scorers = sklearn.metrics.scorer.SCORERS
                    matches = select_values(
                        lambda x: x == self._scorer, scorers)
                    matches = list(matches.keys())
                    if len(matches) == 1:
                        self._name = matches[0]
                    elif len(matches) > 1:
                        # unexpected
                        logger.debug(
                            'Unexpectedly found multiple matches for scorer '
                            'name {name}: {matches!r}'
                            .format(name=self._name, matches=matches))
                    else:
                        # must be a custom scorer, try to get name
                        if hasattr(self._scorer, '__name__'):
                            self._name = self._scorer.__name__
            elif self._description is not None:
                # try from description
                mapper = flip(SCORING_NAME_MAPPER)
                if self._description in mapper:
                    self._name = mapper[self._description]
                else:
                    # default formatting
                    self._name = '_'.join(self._description.lower().split(' '))

        if self._name is not None:
            return self._name
        else:
            raise BalletError('Could not get name from scorer')
Beispiel #3
0
def _name_estimators(
        estimators: Sequence[BaseEstimator]
) -> List[Tuple[str, BaseEstimator]]:
    """Generate names for estimators.

    Adapted from sklearn.pipeline._name_estimators to use the name of the
    underlying transformer within a DelegatingRobustTransformer.
    """
    def get_name(estimator):
        if isinstance(estimator, DelegatingRobustTransformer):
            return get_name(estimator._transformer)

        return type(estimator).__name__.lower()

    names = list(map(get_name, estimators))
    counter = dict(Counter(names))
    counter = select_values(lambda x: x > 1, counter)

    for i in reversed(range(len(estimators))):
        name = names[i]
        if name in counter:
            names[i] += "-%d" % counter[name]
            counter[name] -= 1

    return list(zip(names, estimators))
Beispiel #4
0
    def load_search_settings(self, *_: Any, **kwargs: Any) -> None:
        self.display_disabled()

        active_func = lambda v: v == "down"
        name = first(select_values(active_func, kwargs))

        self.context.path_finder = self.path_finder_factory(name)
        self.bus.publish(SEARCH_LOADED_EVENT)
Beispiel #5
0
 def send(self, message_name, body=None):
     """Encode and send a message to client"""
     try:
         self.write_message(select_values(None, {
             'MESSAGE': message_name,
             'BODY': body,
         }))
     except WebSocketClosedError:
         logger.error('Error sending message', exc_info=True)
Beispiel #6
0
 def values(self, *fields, **expressions):
     """
     Extended version supporting renames:
         .values('id', 'name', author__name='author')
     """
     renames = select_values(isa(six.string_types), expressions)
     if not renames:
         return base.values(self, *fields, **expressions)
     elif django.VERSION >= (1, 11):
         rename_expressions = walk_values(F, renames)
         expressions.update(rename_expressions)
         return base.values(self, *fields, **expressions)
     else:
         f_to_name = flip(renames)
         rename = lambda d: {f_to_name.get(k, k): v for k, v in d.items()}
         return base.values(self, *chain(fields, f_to_name)).map(rename)
Beispiel #7
0
def monkey_mix(cls, mixin):
    """
    Mixes a mixin into existing class.
    Does not use actual multi-inheritance mixins, just monkey patches methods.
    Mixin methods can call copies of original ones stored in `_no_monkey` proxy:

    class SomeMixin(object):
        def do_smth(self, arg):
            ... do smth else before
            self._no_monkey.do_smth(self, arg)
            ... do smth else after
    """
    assert not hasattr(cls, '_no_monkey'), 'Multiple monkey mix not supported'
    cls._no_monkey = MonkeyProxy()

    test = any_fn(inspect.isfunction, inspect.ismethoddescriptor)
    methods = select_values(test, mixin.__dict__)

    for name, method in methods.items():
        if hasattr(cls, name):
            setattr(cls._no_monkey, name, getattr(cls, name))
        setattr(cls, name, method)
Beispiel #8
0
def _name_estimators(estimators):
    """Generate names for estimators.

    Adapted from sklearn.pipeline._name_estimators
    """
    def get_name(estimator):
        if isinstance(estimator, DelegatingRobustTransformer):
            return get_name(estimator._transformer)

        return type(estimator).__name__.lower()

    names = list(map(get_name, estimators))
    counter = dict(Counter(names))
    counter = select_values(lambda x: x > 1, counter)

    for i in reversed(range(len(estimators))):
        name = names[i]
        if name in counter:
            names[i] += "-%d" % counter[name]
            counter[name] -= 1

    return list(zip(names, estimators))
Beispiel #9
0
def monkey_mix(cls, mixin):
    """
    Mixes a mixin into existing class.
    Does not use actual multi-inheritance mixins, just monkey patches methods.
    Mixin methods can call copies of original ones stored in `_no_monkey` proxy:

    class SomeMixin(object):
        def do_smth(self, arg):
            ... do smth else before
            self._no_monkey.do_smth(self, arg)
            ... do smth else after
    """
    assert not hasattr(cls, '_no_monkey'), 'Multiple monkey mix not supported'
    cls._no_monkey = MonkeyProxy()

    test = any_fn(inspect.isfunction, inspect.ismethoddescriptor)
    methods = select_values(test, mixin.__dict__)

    for name, method in methods.items():
        if hasattr(cls, name):
            setattr(cls._no_monkey, name, getattr(cls, name))
        setattr(cls, name, method)
Beispiel #10
0
def filter_none(d):
    return select_values(lambda v: v is not None, d)
Beispiel #11
0
 def filter(self, pred):
     return self.evolve(data=fn.select_values(pred, self.data))
Beispiel #12
0
def filter_none(d):
    return select_values(lambda v: v is not None, d)
Beispiel #13
0
def remove_values(pred, col):
    return select_values(complement(pred), col)
Beispiel #14
0
 def find_multi_chars(cls, id_context_perm: Tuple[ContextChar]):
     count = defaultdict(list)
     for context_char in id_context_perm:
         count[context_char.char].append(context_char)
     return select_values(lambda lst: len(lst) > 1, count)