Wraps Django Model __getattribute__ method making translation in templates less painful
425067
def get_translated_attribute(instance, attr):
	
	
	# If its class has no translatable fields, returns attribute
	try:
		if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_fields"))==0:
			return getattr(instance, attr)
	except AttributeError:
		return instance
	
	# Translatable fields of this instance
	translatable_fields = instance._meta.translatable_fields

	# Current language
	cur_language = get_language()
	lang = cur_language.title().lower()

	# If current language is default language, returns attribute
	if lang == settings.LANGUAGE_CODE:
		return getattr(instance, attr)
	
	# Otherwise, if a translation is NOT needed for attr atribute, get attribute
	if not attr in translatable_fields:
		return getattr(instance, attr)

	# Gets field translations of this instance and return the translated attribute
	field_translation = _get_fieldtranslations(instance, field=attr, lang=lang)
	if field_translation:
		if not field_translation.is_fuzzy:
			return field_translation.translation
	return getattr(instance, attr)
969166
def get_field_kwargs(field_name, model_field):
    
    kwargs = {}
    validator_kwarg = list(model_field.validators)

    # The following will only be used by ModelField classes.
    # Gets removed for everything else.
    kwargs['model_field'] = model_field

    if model_field.verbose_name and needs_label(model_field, field_name):
        kwargs['label'] = capfirst(model_field.verbose_name)

    if model_field.help_text:
        kwargs['help_text'] = model_field.help_text

    max_digits = getattr(model_field, 'max_digits', None)
    if max_digits is not None:
        kwargs['max_digits'] = max_digits

    decimal_places = getattr(model_field, 'decimal_places', None)
    if decimal_places is not None:
        kwargs['decimal_places'] = decimal_places

    if isinstance(model_field, models.TextField):
        kwargs['style'] = {'base_template': 'textarea.html'}

    if isinstance(model_field, models.AutoField) or not model_field.editable:
        # If this field is read-only, then return early.
        # Further keyword arguments are not valid.
        kwargs['read_only'] = True
        return kwargs

    if model_field.has_default() or model_field.blank or model_field.null:
        kwargs['required'] = False

    if model_field.null and not isinstance(model_field, models.NullBooleanField):
        kwargs['allow_null'] = True

    if model_field.blank and (isinstance(model_field, models.CharField) or
                              isinstance(model_field, models.TextField)):
        kwargs['allow_blank'] = True

    if isinstance(model_field, models.FilePathField):
        kwargs['path'] = model_field.path

        if model_field.match is not None:
            kwargs['match'] = model_field.match

        if model_field.recursive is not False:
            kwargs['recursive'] = model_field.recursive

        if model_field.allow_files is not True:
            kwargs['allow_files'] = model_field.allow_files

        if model_field.allow_folders is not False:
            kwargs['allow_folders'] = model_field.allow_folders

    if model_field.choices:
        # If this model field contains choices, then return early.
        # Further keyword arguments are not valid.
        kwargs['choices'] = model_field.choices
        return kwargs

    # Our decimal validation is handled in the field code, not validator code.
    # (In Django 1.9+ this differs from previous style)
    if isinstance(model_field, models.DecimalField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if DecimalValidator and not isinstance(validator, DecimalValidator)
        ]

    # Ensure that max_length is passed explicitly as a keyword arg,
    # rather than as a validator.
    max_length = getattr(model_field, 'max_length', None)
    if max_length is not None and (isinstance(model_field, models.CharField) or
                                   isinstance(model_field, models.TextField)):
        kwargs['max_length'] = max_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MaxLengthValidator)
        ]

    # Ensure that min_length is passed explicitly as a keyword arg,
    # rather than as a validator.
    min_length = next((
        validator.limit_value for validator in validator_kwarg
        if isinstance(validator, validators.MinLengthValidator)
    ), None)
    if min_length is not None and isinstance(model_field, models.CharField):
        kwargs['min_length'] = min_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MinLengthValidator)
        ]

    # Ensure that max_value is passed explicitly as a keyword arg,
    # rather than as a validator.
    max_value = next((
        validator.limit_value for validator in validator_kwarg
        if isinstance(validator, validators.MaxValueValidator)
    ), None)
    if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['max_value'] = max_value
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MaxValueValidator)
        ]

    # Ensure that max_value is passed explicitly as a keyword arg,
    # rather than as a validator.
    min_value = next((
        validator.limit_value for validator in validator_kwarg
        if isinstance(validator, validators.MinValueValidator)
    ), None)
    if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['min_value'] = min_value
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MinValueValidator)
        ]

    # URLField does not need to include the URLValidator argument,
    # as it is explicitly added in.
    if isinstance(model_field, models.URLField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.URLValidator)
        ]

    # EmailField does not need to include the validate_email argument,
    # as it is explicitly added in.
    if isinstance(model_field, models.EmailField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_email
        ]

    # SlugField do not need to include the 'validate_slug' argument,
    if isinstance(model_field, models.SlugField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_slug
        ]

    # IPAddressField do not need to include the 'validate_ipv46_address' argument,
    if isinstance(model_field, models.GenericIPAddressField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_ipv46_address
        ]

    if getattr(model_field, 'unique', False):
        unique_error_message = model_field.error_messages.get('unique', None)
        if unique_error_message:
            unique_error_message = unique_error_message % {
                'model_name': model_field.model._meta.object_name,
                'field_label': model_field.verbose_name
            }
        validator = UniqueValidator(
            queryset=model_field.model._default_manager,
            message=unique_error_message)
        validator_kwarg.append(validator)

    if validator_kwarg:
        kwargs['validators'] = validator_kwarg

    return kwargs
999965
def get_templates(model):
    
    for template_name, template in templates.items():
        if issubclass(template.model, model):
            yield (template_name, template.layout._meta.verbose_name)
167425
def _original_attr(self, attr_name):
        
        try:
            return getattr(
                getattr(self.obj.__class__, attr_name), '_doubles_target_method', None
            )
        except AttributeError:
            return None
1130935
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
    

    def wrapper(func):
        @functools.wraps(func)
        async def wrapped(*args, **kwargs):
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)
            context = await coro(*args, **kwargs)
            if isinstance(context, web.StreamResponse):
                return context

            if 'request' in kwargs:
                request = kwargs['request']
            elif not args:
                request = None
                warnings.warn("Request not detected")
            elif isinstance(args[0], AbstractView):
                request = args[0].request
            else:
                request = args[-1]

            response = render_template(template_name, request, context,
                                       app_key=app_key, encoding=encoding)
            response.set_status(status)
            return response
        return wrapped
    return wrapper
593988
def attributes(atts = {}, for_definition = false)
      wrapped_attributes atts, for_definition
      attributes_assignments atts, false, for_definition
      atts
    end
1295682
function getAttributeType (name, isDirective) {
  if (isDirective) {
    if (name === 'for') {
      return 'LIST_RENDERING'
    } else if (name === 'if' || name === 'else-if' || name === 'else' || name === 'show' || name === 'cloak') {
      return 'CONDITIONALS'
    } else if (name === 'pre' || name === 'once') {
      return 'RENDER_MODIFIERS'
    } else if (name === 'model') {
      return 'TWO_WAY_BINDING'
    } else if (name === 'on') {
      return 'EVENTS'
    } else if (name === 'html' || name === 'text') {
      return 'CONTENT'
    } else {
      return 'OTHER_ATTR'
    }
  } else {
    if (name === 'is') {
      return 'DEFINITION'
    } else if (name === 'id') {
      return 'GLOBAL'
    } else if (name === 'ref' || name === 'key' || name === 'slot') {
      return 'UNIQUE'
    } else {
      return 'OTHER_ATTR'
    }
  }
}
882456
def attr(cls, iterable, attr_name):
    

    return cls(getattr(x, attr_name) for x in iterable)
589930
def delegate(attribute_name, method_names):
    """"""
    # hack for python 2.7 as nonlocal is not available
    info = {
        'attribute': attribute_name,
        'methods': method_names
    }

    def decorator(cls):
        """Decorate class."""
        attribute = info['attribute']
        if attribute.startswith("__"):
            attribute = "_" + cls.__name__ + attribute
        for name in info['methods']:
            setattr(cls, name, eval("lambda self, *a, **kw: "
                                    "self.{0}.{1}(*a, **kw)".format(attribute, name)))
        return cls
    return decorator
496187
def translate_resource_args(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        """
        :type args: *Any
        :type kwargs: **Any
        :return: Any
        """
        arg_list = []
        for arg in args:
            if isinstance(arg, (Issue, Project)):
                arg_list.append(arg.key)
            else:
                arg_list.append(arg)
        result = func(*arg_list, **kwargs)
        return result

    return wrapper
424083
def _wrap_public_method(self, attr):
        
        def wrapper(*args, **kwargs):
            return getattr(self.connection, attr)(*args, **kwargs)
        return wrapper
1204026
def append_translated(model, fields):
    ""
    fields = set(fields)
    from modeltranslation.translator import translator
    opts = translator.get_options_for_model(model)
    for key, translated in opts.fields.items():
        if key in fields:
            fields = fields.union(f.name for f in translated)
    return fields
151563
def view_getattr():
    

    def view_getattr(_value, context, **_params):
        value = getattr(context["view"], context["key"])
        return _attr(value)

    return view_getattr
1185581
def get_and_setattr(cls, id, **kwargs):
        
        model = cls.get(id)
        for k, v in cls._preprocess_params(kwargs).items():
            setattr(model, k, v)
        return model
94761
def _attr_to_method(self, attr):
        

        if attr in codes['fore']:
            # Fore method
            return partial(self.chained, fore=attr)
        elif attr in codes['style']:
            # Style method
            return partial(self.chained, style=attr)
        elif attr.startswith('bg'):
            # Back method
            name = attr[2:].lstrip('_')
            if name in codes['back']:
                return partial(self.chained, back=name)
        elif attr.startswith(('b256_', 'b_')):
            # Back 256 method
            # Remove the b256_ portion.
            name = attr.partition('_')[2]
            return self._ext_attr_to_partial(name, 'back')
        elif attr.startswith(('f256_', 'f_')):
            # Fore 256 method
            name = attr.partition('_')[2]
            return self._ext_attr_to_partial(name, 'fore')

        return None
653336
def getAttributeName(self, name):
        '''
        '''
        if self.func_aname is None:
            return name
        assert callable(self.func_aname), \
            'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
        f = self.func_aname
        return f(name)
539497
def source_attr(attr_name):
    

    def source_attr(_value, context, **_params):
        value = getattr(context["model"].source, attr_name)
        return _attr(value)

    return source_attr