Return a tuple of functions that will provide the usage of the
    JSON egginfo based around the provided field.
763589
def build_helpers_egginfo_json(
        json_field, json_key_registry, json_filename=None):
    

    json_filename = (
        json_field + '.json' if json_filename is None else json_filename)

    # Default calmjs core implementation specific functions, to be used by
    # integrators intended to use this as a distribution.

    def get_extras_json(pkg_names, working_set=None):
        """
        Only extract the extras_json information for the given packages
        'pkg_names'.
        """

        working_set = working_set or default_working_set
        dep_keys = set(get(json_key_registry).iter_records())
        dists = pkg_names_to_dists(pkg_names, working_set=working_set)
        return flatten_dist_egginfo_json(
            dists, filename=json_filename,
            dep_keys=dep_keys, working_set=working_set
        )

    def _flatten_extras_json(pkg_names, find_dists, working_set):
        # registry key must be explicit here as it was designed for this.
        dep_keys = set(get(json_key_registry).iter_records())
        dists = find_dists(pkg_names, working_set=working_set)
        return flatten_dist_egginfo_json(
            dists, filename=json_filename,
            dep_keys=dep_keys, working_set=working_set
        )

    def flatten_extras_json(pkg_names, working_set=None):
        """
        Traverses through the dependency graph of packages 'pkg_names'
        and flattens all the egg_info json information
        """

        working_set = working_set or default_working_set
        return _flatten_extras_json(
            pkg_names, find_packages_requirements_dists, working_set)

    def flatten_parents_extras_json(pkg_names, working_set=None):
        """
        Traverses through the dependency graph of packages 'pkg_names'
        and flattens all the egg_info json information for parents of
        the specified packages.
        """

        working_set = working_set or default_working_set
        return _flatten_extras_json(
            pkg_names, find_packages_parents_requirements_dists, working_set)

    write_extras_json = partial(write_json_file, json_field)

    return (
        get_extras_json,
        flatten_extras_json,
        flatten_parents_extras_json,
        write_extras_json,
    )
1064853
def abstract_json(soup):
    """"""
    abstract_tags = raw_parser.abstract(soup)
    abstract_json = None
    for tag in abstract_tags:
        if tag.get("abstract-type") is None:
            abstract_json = render_abstract_json(tag)
    return abstract_json
928637
def asjsonld(
    inst,
    recurse=True,
    filter=None,
    dict_factory=dict,
    retain_collection_types=False,
    export_context=True,
    basedir=None,
):
    """"""
    jsonld_fields = inst.__class__._jsonld_fields
    attrs = tuple(
        field
        for field in fields(inst.__class__) if field.name in jsonld_fields
    )
    rv = dict_factory()

    def convert_value(v):
        """Convert special types."""
        if isinstance(v, Path):
            v = str(v)
            return os.path.relpath(v, str(basedir)) if basedir else v
        return v

    for a in attrs:
        v = getattr(inst, a.name)

        # skip proxies
        if isinstance(v, weakref.ReferenceType):
            continue

        # do not export context for containers
        ec = export_context and KEY_CLS not in a.metadata

        if filter is not None and not filter(a, v):
            continue
        if recurse is True:
            if has(v.__class__):
                rv[a.name] = asjsonld(
                    v,
                    recurse=True,
                    filter=filter,
                    dict_factory=dict_factory,
                    basedir=basedir,
                )
            elif isinstance(v, (tuple, list, set)):
                cf = v.__class__ if retain_collection_types is True else list
                rv[a.name] = cf([
                    asjsonld(
                        i,
                        recurse=True,
                        filter=filter,
                        dict_factory=dict_factory,
                        export_context=ec,
                        basedir=basedir,
                    ) if has(i.__class__) else i for i in v
                ])
            elif isinstance(v, dict):
                df = dict_factory
                rv[a.name] = df((
                    asjsonld(
                        kk,
                        dict_factory=df,
                        basedir=basedir,
                    ) if has(kk.__class__) else convert_value(kk),
                    asjsonld(
                        vv,
                        dict_factory=df,
                        export_context=ec,
                        basedir=basedir,
                    ) if has(vv.__class__) else vv
                ) for kk, vv in iteritems(v))
            else:
                rv[a.name] = convert_value(v)
        else:
            rv[a.name] = convert_value(v)

    inst_cls = type(inst)

    if export_context:
        rv['@context'] = deepcopy(inst_cls._jsonld_context)

    if inst_cls._jsonld_type:
        rv['@type'] = inst_cls._jsonld_type
    return rv
496896
def _dict_of_funcs(self, funcs: list) -> pd.Series:
        """"""
        return {func.__name__: func for func in funcs}
73394
def required_fields(self):
        """"""
        return {f:v for f, v in self.normal_fields.items() if v.required}
194384
def parse_json(path):
    # type: (str) -> List[FunctionInfo]
    
    with open(path) as f:
        data = json.load(f)  # type: List[RawEntry]
    result = []

    def assert_type(value, typ):
        # type: (object, type) -> None
        assert isinstance(value, typ), '%s: Unexpected type %r' % (path, type(value).__name__)

    def assert_dict_item(dictionary, key, typ):
        # type: (Mapping[Any, Any], str, type) -> None
        assert key in dictionary, '%s: Missing dictionary key %r' % (path, key)
        value = dictionary[key]
        assert isinstance(value, typ), '%s: Unexpected type %r for key %r' % (
            path, type(value).__name__, key)

    assert_type(data, list)
    for item in data:
        assert_type(item, dict)
        assert_dict_item(item, 'path', Text)
        assert_dict_item(item, 'line', int)
        assert_dict_item(item, 'func_name', Text)
        assert_dict_item(item, 'type_comments', list)
        for comment in item['type_comments']:
            assert_type(comment, Text)
        assert_type(item['samples'], int)
        info = FunctionInfo(encode(item['path']),
                            item['line'],
                            encode(item['func_name']),
                            [encode(comment) for comment in item['type_comments']],
                            item['samples'])
        result.append(info)
    return result
300309
def get_functions_map(self):
        """"""
        return dict([(column, DATA_TYPE_FUNCTIONS[data_type]) for column, data_type in self.columns.values_list('name', 'data_type')])
905998
def _make_field_info(self, field_name, field):
        
        supported_field_types = (
            (Integer, 'integer'),
            (Float, 'float'),
            (Boolean, 'boolean'),
            (String, 'string'),
            (List, 'list'),
            (DateTime, 'datepicker'),
            (JSONField, 'generic'),  # This is last so as a last resort we display a text field w/ the JSON string
        )
        if self.service_declaration("i18n"):
            ugettext = self.ugettext
        else:

            def ugettext(text):
                """ Dummy ugettext method that doesn't do anything """
                return text

        info = {
            'name': field_name,
            'display_name': ugettext(field.display_name) if field.display_name else "",
            'is_set': field.is_set_on(self),
            'default': field.default,
            'value': field.read_from(self),
            'has_values': False,
            'help': ugettext(field.help) if field.help else "",
            'allow_reset': field.runtime_options.get('resettable_editor', True),
            'list_values': None,  # Only available for List fields
            'has_list_values': False,  # True if list_values_provider exists, even if it returned no available options
        }
        for type_class, type_name in supported_field_types:
            if isinstance(field, type_class):
                info['type'] = type_name
                # If String fields are declared like String(..., multiline_editor=True), then call them "text" type:
                editor_type = field.runtime_options.get('multiline_editor')
                if type_class is String and editor_type:
                    if editor_type == "html":
                        info['type'] = 'html'
                    else:
                        info['type'] = 'text'
                if type_class is List and field.runtime_options.get('list_style') == "set":
                    # List represents unordered, unique items, optionally drawn from list_values_provider()
                    info['type'] = 'set'
                elif type_class is List:
                    info['type'] = "generic"  # disable other types of list for now until properly implemented
                break
        if "type" not in info:
            raise NotImplementedError("StudioEditableXBlockMixin currently only supports fields derived from JSONField")
        if info["type"] in ("list", "set"):
            info["value"] = [json.dumps(val) for val in info["value"]]
            info["default"] = json.dumps(info["default"])
        elif info["type"] == "generic":
            # Convert value to JSON string if we're treating this field generically:
            info["value"] = json.dumps(info["value"])
            info["default"] = json.dumps(info["default"])
        elif info["type"] == "datepicker":
            if info["value"]:
                info["value"] = info["value"].strftime("%m/%d/%Y")
            if info["default"]:
                info["default"] = info["default"].strftime("%m/%d/%Y")

        if 'values_provider' in field.runtime_options:
            values = field.runtime_options["values_provider"](self)
        else:
            values = field.values
        if values and not isinstance(field, Boolean):
            # This field has only a limited number of pre-defined options.
            # Protip: when defining the field, values= can be a callable.
            if isinstance(field.values, dict) and isinstance(field, (Float, Integer)):
                # e.g. {"min": 0 , "max": 10, "step": .1}
                for option in field.values:
                    if option in ("min", "max", "step"):
                        info[option] = field.values.get(option)
                    else:
                        raise KeyError("Invalid 'values' key. Should be like values={'min': 1, 'max': 10, 'step': 1}")
            elif isinstance(values[0], dict) and "display_name" in values[0] and "value" in values[0]:
                # e.g. [ {"display_name": "Always", "value": "always"}, ... ]
                for value in values:
                    assert "display_name" in value and "value" in value
                info['values'] = values
            else:
                # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format
                info['values'] = [{"display_name": text_type(val), "value": val} for val in values]
            info['has_values'] = 'values' in info
        if info["type"] in ("list", "set") and field.runtime_options.get('list_values_provider'):
            list_values = field.runtime_options['list_values_provider'](self)
            # list_values must be a list of values or {"display_name": x, "value": y} objects
            # Furthermore, we need to convert all values to JSON since they could be of any type
            if list_values and isinstance(list_values[0], dict) and "display_name" in list_values[0]:
                # e.g. [ {"display_name": "Always", "value": "always"}, ... ]
                for entry in list_values:
                    assert "display_name" in entry and "value" in entry
                    entry["value"] = json.dumps(entry["value"])
            else:
                # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format
                list_values = [json.dumps(val) for val in list_values]
                list_values = [{"display_name": text_type(val), "value": val} for val in list_values]
            info['list_values'] = list_values
            info['has_list_values'] = True
        return info
557864
def json_response(func):
    

    @wraps(func)
    def wrapper(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        request.setHeader('Content-Type', 'application/json')
        return json.dumps(res)

    return wrapper
653881
def json_output(f):
    

    @wraps(f)
    def json_output_decorator(*args, **kwargs):
        @inject(config=Config)
        def get_config(config):
            return config

        config = get_config()

        rv = f(*args, **kwargs)
        indent = None
        if config.get('DEBUG', False):
            logging.getLogger(__name__).debug("Formatting JSON nicely.")
            indent = 2
        rv = json.dumps(rv, cls=AppModelJSONEncoder, indent=indent)
        _set_json_response_content_type()
        return rv

    return json_output_decorator
61669
def get_fun(fun):
    '''
    
    '''
    with _get_serv(ret=None, commit=True) as cur:

        sql = '''SELECT s.id,s.jid, s.full_ret
                FROM `salt_returns` s
                JOIN ( SELECT MAX(`jid`) as jid
                    from `salt_returns` GROUP BY fun, id) max
                ON s.jid = max.jid
                WHERE s.fun = %s
                '''

        cur.execute(sql, (fun,))
        data = cur.fetchall()

        ret = {}
        if data:
            for minion, _, full_ret in data:
                ret[minion] = salt.utils.json.loads(full_ret)
        return ret
779776
def field_from_json(self, key_and_type, json_value):
        """"""
        assert ':' in key_and_type
        key, type_code = key_and_type.split(':', 1)
        from_json = self.field_function(type_code, 'from_json')
        value = from_json(json_value)
        return key, value
430835
def f(field: str, kwargs: Dict[str, Any],
      default: Optional[Any] = None) -> str:
    
    if default is not None:
        return str(kwargs.get(field, default))
    return str(kwargs[field])
100516
def _list_function_infos(jvm):
    

    jinfos = jvm.org.apache.spark.sql.api.python.PythonSQLUtils.listBuiltinFunctionInfos()
    infos = []
    for jinfo in jinfos:
        name = jinfo.getName()
        usage = jinfo.getUsage()
        usage = usage.replace("_FUNC_", name) if usage is not None else usage
        infos.append(ExpressionInfo(
            className=jinfo.getClassName(),
            name=name,
            usage=usage,
            arguments=jinfo.getArguments().replace("_FUNC_", name),
            examples=jinfo.getExamples().replace("_FUNC_", name),
            note=jinfo.getNote(),
            since=jinfo.getSince(),
            deprecated=jinfo.getDeprecated()))
    return sorted(infos, key=lambda i: i.name)
1330127
def _feature_to_fields(f, jsonify=True):
    
    x = []
    for k in constants._keys:
        v = getattr(f, k)
        if jsonify and (k in ('attributes', 'extra')):
            x.append(_jsonify(v))
        else:
            x.append(v)
    return tuple(x)
321742
def get_json(self):
        
        port = self.get_basic_json()
        port['Functions'] = {
            'Function': [f.get_json() for f in self.functions.values()]
        }
        return port
888301
def json_repr(self, minimal=False):
        
        if self.value:
            return [self.field, self.operator, self.value]
        else:
            return [self.field, self.operator]