decorator to translate the purposes field.

    translate the values of the purposes field of the API response into
    translated values.
342140
def translate_purposes(f):
    
    @wraps(f)
    def wr(r, pc):
        tmp = []
        for P in r["purposes"]:
            try:
                tmp.append(POSTCODE_API_TYPEDEFS_PURPOSES[P])
            except:
                logger.warning("Warning: {}: "
                               "cannot translate 'purpose': {}".format(pc, P))
                tmp.append(P)

        r.update({"purposes": tmp})
        return f(r, pc)

    return wr
958637
def translate(self, exc):
        
        # Find actual class.
        for key in self.translations.keys():
            if isinstance(exc, key):
                # pylint: disable=unsubscriptable-object
                return self.translations[key](str(exc))

        return None
796096
def translate(self, exc):
        """"""
        from boto.exception import StorageResponseError

        if isinstance(exc, StorageResponseError):
            if exc.status == 404:
                return self.error_cls(str(exc))

        return None
1227632
def transform_specialfield(jsonify,f,v):
  ""
  raw = f.ser(v) if is_serdes(f) else v
  return ujson.dumps(raw) if not isinstance(f,basestring) and jsonify else raw
668668
def get_serializer_fields(self, path, method, view, version=None, method_func=None):
        
        if method in ('PUT', 'PATCH', 'POST'):
            location = 'form'
        else:
            location = 'query'

        serializer_class = self.get_serializer_class(view, method_func)
        if not serializer_class:
            return []

        serializer = serializer_class()
        if isinstance(serializer, serializers.ListSerializer):
            return [
                Field(
                    name='data',
                    location=location,
                    required=True,
                    schema=coreschema.Array()
                )
            ]

        if not isinstance(serializer, serializers.Serializer):
            return []

        fields = []
        for field in serializer.fields.values():
            if field.read_only or isinstance(field, serializers.HiddenField):
                continue

            required = field.required and method != 'PATCH'
            # if the attribute ('help_text') of this field is a lazy translation object, force it to generate a string
            description = str(field.help_text) if isinstance(field.help_text, Promise) else field.help_text
            fallback_schema = self.fallback_schema_from_field(field)
            field = Field(
                name=field.field_name,
                location=location,
                required=required,
                schema=fallback_schema if fallback_schema else field_to_schema(field),
                description=description,
            )
            fields.append(field)

        return fields
32556
def update_translations(request):
	
	FieldTranslation.delete_orphan_translations()
	num_translations = FieldTranslation.update_translations()
	return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request))
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
1261009
function translateMessagesToBundle(src, translationsSrc) {
    var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

    var _ref$inputFormat = _ref.inputFormat;
    var inputFormat = _ref$inputFormat === undefined ? 'po' : _ref$inputFormat;

    var options = _objectWithoutProperties(_ref, ['inputFormat']);

    var bundle = {};
    var missing = {};
    var translations = _io2.default[inputFormat].in(translationsSrc, options);

    function attemptToCreateRenderer(node, message) {
        if (translations[message]) {
            bundle[message] = (0, _translation2.default)(node, translations[message], message);
        } else {
            missing[message] = message;
        }
    }

    var plugin = function plugin() {
        return {
            visitor: {
                CallExpression: function CallExpression(_ref2) {
                    var node = _ref2.node;

                    if ((0, _ast.isFunctionMarker)(node)) {
                        var message = (0, _extract.extractFunctionMessage)(node);
                        attemptToCreateRenderer(node, message);
                    }
                },
                JSXElement: function JSXElement(_ref3) {
                    var node = _ref3.node;

                    if ((0, _ast.isElementMarker)(node)) {
                        var message = (0, _extract.extractElementMessageWithoutSideEffects)(node);
                        attemptToCreateRenderer(node, message);
                    }
                }
            }
        };
    };

    _parsing2.default.transform(src, [plugin]);

    return { bundle: bundle, missing: missing };
}
1083724
def translate(cls, val):
        """"""
        if val is None:
            return cls.translate_none(val)
        elif isinstance(val, string_types):
            return cls.translate_str(val)
        # Needs to be before integer checks
        elif isinstance(val, bool):
            return cls.translate_bool(val)
        elif isinstance(val, integer_types):
            return cls.translate_int(val)
        elif isinstance(val, float):
            return cls.translate_float(val)
        elif isinstance(val, dict):
            return cls.translate_dict(val)
        elif isinstance(val, list):
            return cls.translate_list(val)
        # Use this generic translation as a last resort
        return cls.translate_escaped_str(val)
833152
def usage(text):
    

    def decorator(func):
        adaptor = ScriptAdaptor._get_adaptor(func)
        adaptor.usage = text
        return func
    return decorator
756663
function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText) {
          if (translationId) {
            $translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText)
              .then(function (translation) {
                applyTranslation(translation, scope, true, translateAttr);
              }, function (translationId) {
                applyTranslation(translationId, scope, false, translateAttr);
              });
          } else {
            // as an empty string cannot be translated, we can solve this using successful=false
            applyTranslation(translationId, scope, false, translateAttr);
          }
        }
498327
def translate(self, node):
        
        _translate = self._translate_functions.get(node.operator)
        return _translate(node)
393196
def translated_value(self):
        
        if self.typeof in self:
            return NATValue(self.get(self.typeof, {}).get(
                'translated_value'))
1272351
def getter_generator(field_name, short_description):
    
    def get_translation_field(cls, language_code=None, fallback=False):
        try:
            return cls.get_translation(language_code,
                                       fallback=fallback,
                                       field=field_name)
        except TranslationDoesNotExist:
            return None
    get_translation_field.short_description = short_description
    return get_translation_field
321302
def translation_save_translated_fields(instance, **kwargs):
    
    if not hasattr(instance, '_translation_cache'):
        return
    for l_id, translation in instance._translation_cache.iteritems():
        # set the translation ID just in case the translation was
        # created while instance was not stored in the DB yet

        # note: we're using _get_pk_val here even though it is
        # private, since that's the most reliable way to get the value
        # on older Django (pk property did not exist yet)
        translation.master_id = instance._get_pk_val()
        translation.save()
1278756
def translate(value):
    
    if isinstance(value, BaseValidator):
        return value

    if value is None:
        return Anything()

    if isinstance(value, type):
        return IsA(value)

    if type(value) in compat.func_types:
        real_value = value()
        return IsA(type(real_value), default=real_value)

    if isinstance(value, list):
        if value == []:
            # no inner spec, just an empty list as the default value
            return IsA(list)
        elif len(value) == 1:
            # the only item as spec for each item of the collection
            return ListOf(translate(value[0]))
        else:
            raise StructureSpecificationError(
                'Expected a list containing exactly 1 item; '
                'got {cnt}: {spec}'.format(cnt=len(value), spec=value))

    if isinstance(value, dict):
        if not value:
            return IsA(dict)
        items = []
        for k, v in value.items():
            if isinstance(k, BaseValidator):
                k_validator = k
            else:
                k_validator = translate(k)
                default = k_validator.get_default_for(None)
                if default is not None:
                    k_validator = Equals(default)
            v_validator = translate(v)
            items.append((k_validator, v_validator))
        return DictOf(items)

    return IsA(type(value), default=value)
740741
def validate_fields(func):
    """"""
    @functools.wraps(func)
    def decorated(instance, *args, **kwargs):
        """The decorator function."""
        data = request.get_json(force=True, silent=True)
        if not data:
            raise BadRequestException('No data received from request')
        for key in data:
            if key not in (
                    instance.__model__.required() +
                    instance.__model__.optional()):
                raise BadRequestException('Unknown field [{}]'.format(key))
        missing = set(instance.__model__.required()) - set(data)
        if missing:
            message = 'The following required fields are missing: ' + ', '.join(missing)
            raise BadRequestException(message)
        return func(instance, *args, **kwargs)
    return decorated