@classmethod
def delete(cls, name, namespace='default', **kwargs):
    """Delete the named resource"""
    url = cls._build_url(name=name, namespace=namespace)
    cls._client.delete(url, **kwargs)


@classmethod
def _fromset(cls, values, key=None):
    """Initialize sorted set from existing set.

        Used internally by set operations that return a new set.

        """
    sorted_set = object.__new__(cls)
    sorted_set._set = values
    sorted_set.__init__(key=key)
    return sorted_set


def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
    orig_answer_text):
    """Returns tokenized answer spans that better match the annotated answer."""
    tok_answer_text = ' '.join(tokenizer.tokenize(orig_answer_text))
    for new_start in range(input_start, input_end + 1):
        for new_end in range(input_end, new_start - 1, -1):
            text_span = ' '.join(doc_tokens[new_start:new_end + 1])
            if text_span == tok_answer_text:
                return new_start, new_end
    return input_start, input_end


@staticmethod
def _get_id(lookup, val):
    """Get the UUID object associated with the given name from the
        given lookup structure, None if no ID is found or the value isn't
        a string.
        """
    try:
        return lookup[val.lower()]
    except AttributeError:
        return None


def ad(df, high, low, close, volume, col):
    """
    Accumulation/distribution is a cumulative indicator that uses volume and price to assess whether a stock is being accumulated or distributed.
    The accumulation/distribution measure seeks to identify divergences between the stock price and volume flow.
    This provides insight into how strong a trend is. If the price is rising but the indicator is falling this
    indicates that buying or accumulation volume may not be enough to support the price rise and a price decline could be forthcoming.
    The CLV is based on the movement of the issue within a single bar and can be +1, -1 or zero.

    A/D=Previous A/D+Current Money Flow Value
    CMFV = ((Close - Low) - (high - close)//(high - Low)) * Volume

    Parameters:
        df (pd.DataFrame): DataFrame which contain the asset information.
        high (string): the column name for the period highest price  of the asset.
        low (string): the column name for the period lowest price of the asset.
        close (string): the column name for the closing price of the asset.
        volume (string): the column name for the volume of the asset.
        col (string): the column name for the ad values.

    Returns:
        df (pd.DataFrame): Dataframe with ad of the asset calculated.

    Sample Strategy:

    Bullish:

	AND [Daily SMA(60,Daily Volume) > 100000]
	AND [Daily SMA(60,Daily Close) > 10]

	AND [Daily Close < Daily SMA(65,Daily Close)]
	AND [Daily AccDist > Daily AccDist Signal (65)]
	AND [Daily OBV > Daily OBV Signal(65)]
	AND [Daily Close < Daily SMA(20,Daily Close)]
	AND [Daily AccDist > Daily AccDist Signal (20)]
	AND [Daily OBV > Daily OBV Signal(20)]

	Bearish:
	AND [Daily SMA(60,Daily Volume) > 100000]
	AND [Daily SMA(60,Daily Close) > 10]

	AND [Daily Close > Daily SMA(65,Daily Close)]
	AND [Daily AccDist < Daily AccDist Signal (65)]
	AND [Daily OBV < Daily OBV Signal(65)]
	AND [Daily Close > Daily SMA(20,Daily Close)]
	AND [Daily AccDist < Daily AccDist Signal (20)]
	AND [Daily OBV < Daily OBV Signal(20)]

	Citation: https://school.stockcharts.com/doku.php?id=technical_indicators:accumulation_distribution_line
    """
    money_flow_multiplier = (df[close] - df[low] - (df[high] - df[close])) / (
        df[high] - df[low])
    df[col + '_money_flow_volume'] = money_flow_multiplier * df[volume]
    prev_ad = df.loc[0, col + '_money_flow_volume']
    df.loc[0, col] = prev_ad
    ads = [0.0]
    for row in df.loc[1:, ([col + '_money_flow_volume'])].itertuples(index=
        False):
        ads.append(prev_ad + row[0])
        prev_ad = ads[-1]
    df = df.fillna(0)
    df[col] += ads
    df.drop([col + '_money_flow_volume'], axis=1, inplace=True)
    return df


def tzname(dt):
    """Return the time zone name corresponding to the datetime object as
        a string.
        """


def shorten_dataset(filename_in, filename_out, nlines=100000):
    """Reads first nlines lines of Combosaurus data from filename_in
       and writes shortened data to filename_out
    """
    with open(filename_in) as fin, open(filename_out, 'w') as fout:
        for line in fin.readlines():
            fout.write(line)
            nlines -= 1
            if nlines == 0:
                return


def p_compound_stmt_6(p):
    """compound_stmt : funcdef"""
    p[0] = [p[1]]


def _calculate_fill_sim(ri, rj, imsize):
    """
        Fill similarity measures how well ri and rj fit into each other.
        BBij is the bounding box around ri and rj.

        fill(ri, rj) = 1 − [size(BBij) − size(ri) − size(ri)] / size(image)
    """
    bbsize = (max(ri['box'][2], rj['box'][2]) - min(ri['box'][0], rj['box'][0])
        ) * (max(ri['box'][3], rj['box'][3]) - min(ri['box'][1], rj['box'][1]))
    return 1.0 - (bbsize - ri['size'] - rj['size']) / imsize


def p_values_list_many(p):
    """values_list : values_list ',' value"""
    if p[1] is None:
        p[0] = p[3]
    else:
        p[1].append(p[3])
        p[0] = p[1]


def is_slice(idx):
    """
    Check if `idx` is slice.
    """
    return type(idx) == slice


@staticmethod
def split_tokenize(text):
    """Splits tokens based on whitespace after adding whitespace around
        punctuation.
        Use re_tokenize if you want more robust handling of punctuation.
        """
    return text.replace('.', ' . ').replace(',', ' , ').replace(';', ' ; '
        ).replace(':', ' : ').replace('!', ' ! ').replace('?', ' ? ').split()


def options(opt):
    """
	Adds the ``--gsettingsschemadir`` command-line option
	"""
    gr = opt.add_option_group('Installation directories')
    gr.add_option('--gsettingsschemadir', help=
        'GSettings schema location [DATADIR/glib-2.0/schemas]', default='',
        dest='GSETTINGSSCHEMADIR')


def string_to_num(s: str):
    """Converts a string to an int/float

    Returns ``None`` if it can't be converted

    >>> string_to_num('5')
    5
    >>> string_to_num('5.2')
    5.2
    >>> string_to_num(10)
    10
    >>> string_to_num(10.1)
    10.1
    >>> string_to_num('this is not a string') is None
    True
    """
    if isinstance(s, (int, float)):
        return s
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None


@classmethod
def serialize(cls, data):
    """
        Serializes outgoing data

        :param data: Python data structure to be serialized
        :type data: dict, list, str
        :returns: serialized representation of the data
        :rtype: str
        """
    raise NotImplementedError


@staticmethod
def p_a2ml_enum_type_name(p):
    """a2ml_enum_type_name : enum a2ml_identifier_optional CURLY_OPEN a2ml_enumerator_list CURLY_CLOSE
                               | enum a2ml_identifier"""
    try:
        p[0] = [p[2]] + p[4]
    except IndexError:
        p[0] = [p[2]]


def resolve_tuple(value, default=None):
    """Resolve tuple (convert provided value if not tuple).

    :param value: Value
    :type value: any

    :param default: Default tuple function
    :type default: function
    """
    if value is None:
        return tuple()
    if default is None:
        default = lambda v: (v,)
    if not isinstance(value, tuple):
        return default(value)
    return value


def report_url_gen(starting_report_url):
    """
    Returns the original url followed by copies with the report id incremented by 1
    starting_report_url: 'https://canvas.csun.edu/api/v1/courses/85210/quizzes/165098/reports/92640'
    """
    r = starting_report_url.split('/')
    url_stub = '/'.join(r[:-1])
    rid = int(r[-1:][0])
    while True:
        yield '{}/{}?include[]=progress&include[]=file'.format(url_stub, rid)
        rid += 1


def start(method):
    """Decorator for specifying the start step.

    Must decorate a single method from the crawler class"""
    method._crawlster_start_step = True
    return method


def is_single_unit_truck(df):
    """Return if vehicle is a single unit truck, per NHTSA convention."""
    yr = df['YEAR']
    body = df['BODY_TYP']
    tow_veh = df['TOW_VEH']
    return yr.between(1975, 1981) & body.isin([53, 54, 55, 56, 60]) & (tow_veh
         == 0) | yr.between(1982, 1990) & body.isin([70, 71, 72, 75, 76, 78,
        79]) & tow_veh.isin([0, 9]) | (1991 <= yr) & body.isin([60, 61, 62,
        63, 64, 67, 71, 72, 78, 79]) & tow_veh.isin([0, 5, 6, 9])


def transform_attrs(obj, keys, container, func, extras=None):
    """
    Allows to apply one function to set of keys cheching if key is in container,
    also trasform ccs key to report lab keys.

    extras = Are extra params for func, it will be call like func(*[param1, param2])

    obj = frag
    keys = [(reportlab, css), ... ]
    container = cssAttr
    """
    cpextras = extras
    for reportlab, css in keys:
        extras = cpextras
        if extras is None:
            extras = []
        elif not isinstance(extras, list):
            extras = [extras]
        if css in container:
            extras.insert(0, container[css])
            setattr(obj, reportlab, func(*extras))


def _filter_annotations_list(annotations_list, image,
    small_object_area_threshold, foreground_class_of_interest_id):
    """Filters COCO annotations_list to visual wakewords annotations_list.

  Each image is assigned a label 1 or 0. The label 1 is assigned as long
  as it has at least one foreground_class_of_interest (e.g. person)
  bounding box greater than 5% of the image area.

  Args:
    annotations_list: list of dicts with keys: [ u'id', u'image_id',
    u'category_id', u'segmentation', u'area', u'bbox' : [x,y,width,height],
      u'iscrowd']. Notice that bounding box coordinates in the official COCO
      dataset are given as [x, y, width, height] tuples using absolute
      coordinates where x, y represent the top-left (0-indexed) corner.
    image: dict with keys: [u'license', u'file_name', u'coco_url', u'height',
      u'width', u'date_captured', u'flickr_url', u'id']
    small_object_area_threshold: threshold on fraction of image area below which
      small objects are filtered
    foreground_class_of_interest_id: category of COCO dataset which visual
      wakewords filters

  Returns:
    filtered_annotations_list: list of dicts with keys: [ u'image_id',
    u'label', u'category_id', u'count',
    u'object':[{"category_id", "area", "bbox" : [x,y,width,height],}]
  """
    category_ids = []
    area = []
    flag_small_object = []
    num_ann = 0
    image_height = image['height']
    image_width = image['width']
    image_area = image_height * image_width
    bbox = []
    count = 0
    for object_annotations in annotations_list:
        x, y, width, height = tuple(object_annotations['bbox'])
        category_id = int(object_annotations['category_id'])
        category_ids.append(category_id)
        obj_area = object_annotations['area']
        normalized_object_area = obj_area / image_area
        if category_id == foreground_class_of_interest_id:
            if normalized_object_area < small_object_area_threshold:
                flag_small_object.append(True)
            else:
                flag_small_object.append(False)
                bbox.append({u'bbox': [x, y, width, height], u'area':
                    obj_area, u'category_id': category_id})
                count = count + 1
        area.append(obj_area)
        num_ann = num_ann + 1
    if (foreground_class_of_interest_id in category_ids and False in
        flag_small_object):
        return {u'image_id': image['id'], u'label': 1, u'object': bbox,
            u'count': count}
    else:
        return {u'image_id': image['id'], u'label': 0, u'object': [],
            u'count': 0}


def glGetPolygonStipple(mask: 'bpy.context.object'):
    """Return the polygon stipple pattern

    :param mask: Returns the stipple pattern. The initial value is all 1’s.
    :type mask: 'bpy.context.object'
    """
    pass


def create_package(project, name, sourcefolder=None):
    """Creates a package and returns a `rope.base.resources.Folder`"""
    if sourcefolder is None:
        sourcefolder = project.root
    packages = name.split('.')
    parent = sourcefolder
    for package in packages[:-1]:
        parent = parent.get_child(package)
    made_packages = parent.create_folder(packages[-1])
    made_packages.create_file('__init__.py')
    return made_packages


def keylist2str(keylist):
    """Convert keylist to a string representation.

    :param keylist: keylist to be converted
    :type keylist: list
    :return: string representation
    :rtype: str
    """
    return ''.join(map(lambda x: "['" + str(x) + "']", keylist))


def rolling_std(df, window, shift=1):
    """Calculate rolling std of all numeric columns of a pandas dataframe

    Function can be used by ApplyFunc module.

    :param pd.DataFrame df: input pandas dataframe
    :param int shift: size of shift. default is 1.
    :param int window: size of rolling window.
    :return: df with rolling std of columns
    """
    return df.shift(shift).rolling(window).std()


def parameters_ui(layout, params):
    """ Create the ui for the rig parameters."""
    r = layout.row()
    r.prop(params, 'limb_type')
    r = layout.row()
    r.prop(params, 'rotation_axis')
    if 'auto' not in params.rotation_axis.lower():
        r = layout.row()
        etremities = {'arm': 'Hand', 'leg': 'Foot', 'paw': 'Claw'}
        text = 'Auto align ' + etremities[params.limb_type]
        r.prop(params, 'auto_align_extremity', text=text)
    r = layout.row()
    r.prop(params, 'segments')
    r = layout.row()
    r.prop(params, 'bbones')
    for layer in ['fk', 'tweak']:
        r = layout.row()
        r.prop(params, layer + '_extra_layers')
        r.active = params.tweak_extra_layers
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(16, 24):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8, 16):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(24, 32):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')


def wedge_integration(src_data, center, theta_start, delta_theta, r_inner,
    delta_r):
    """
    Implementation of caking.

    Parameters
    ----------
    scr_data : ndarray
        The source-data to be integrated

    center : ndarray
        The center of the ring in pixels

    theta_start : float
        The angle of the start of the wedge from the
        image y-axis in degrees

    delta_theta : float
        The angular width of the wedge in degrees.  Positive
        angles go clockwise, negative go counter-clockwise.

    r_inner : float
        The inner radius in pixel units, Must be non-negative

    delta_r : float
        The length of the wedge in the radial direction
        in pixel units. Must be non-negative

    Returns
    -------
    float
        The integrated intensity under the wedge
    """
    raise NotImplementedError()


def convert_single_to_list(val):
    """If a single object is provided, replace with a list containing only that object"""
    if val is None:
        return []
    if not isinstance(val, list):
        return [val]
    return val


def get_author_email(repo, use_git_config):
    """Get author and email from git configuration"""
    author = email = None
    if use_git_config:
        try:
            author = repo.get_config('user.name')
        except KeyError:
            pass
        try:
            email = repo.get_config('user.email')
        except KeyError:
            pass
    return author, email


def _get_result_value(result_dict, key, default_value=''):
    """
    Get the value of the result dictionary or a default value if the key does not exists.
    :param result_dict: result dictionary
    :param key: the key to use
    :param default_value: the default value
    :return: the value of key in the dictionary or the default value if the key does not exists in the dictionary
    """
    if key in result_dict:
        return result_dict[key]
    else:
        return default_value


def call_vtk(obj, method, args=None):
    """ Invoke a method on a vtk object.

    Parameters
    ----------
    obj : object
        VTK object.
    method : str
        Method name.
    args : None ot tuple or list
        Arguments to be passed to the method.
        If None, the method is called with no arguments.

    Returns
    -------
    result : Any
        Return the results of invoking `method` with `args` on `obj`.

    Notes
    -----
    Use a tuple to pass a None to the method: (None,).

    Examples
    --------
    >>> import vtk
    >>> from brainspace.vtk_interface.wrappers.base import call_vtk
    >>> m = vtk.vtkPolyDataMapper()

    Get array id of the mapper:

    >>> call_vtk(m, 'GetArrayId', args=None)
    -1
    >>> m.GetArrayId()
    -1

    Set array id of the mapper to 2:

    >>> call_vtk(m, 'SetArrayId', args=(2,)) # same as m.SetArrayId(2)
    >>> m.GetArrayId()
    2

    """
    if args is None:
        try:
            return getattr(obj, method)()
        except:
            return getattr(obj, method)(None)
    if isinstance(args, dict):
        return getattr(obj, method)(**args)
    if isinstance(args, (tuple, list)):
        try:
            return getattr(obj, method)(*args)
        except TypeError:
            pass
    return getattr(obj, method)(args)


def get_option(option):
    """ get_option returns the type of option (if any) applied
    to that year's salary

    @param **option** (*str*): Sting of color indicators that
        correspond to yearly options.

    Returns:

        **option** (*list*): One of '', 'Team',
        'Qualifying', 'Two-Way', 'Player'
    """
    if option == 'color:black':
        option = ''
    elif option == 'color:rgb(255, 0, 0)':
        option = 'Team'
    elif option == 'color:rgb(0, 153, 0)':
        option = 'Qualifying'
    elif option == 'color:rgb(168, 0, 212)':
        option = 'Two-Way'
    elif option == 'color:rgb(4, 134, 176)':
        option = 'Player'
    else:
        option = ''
    return option


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def get_ip_address(request):
    """
    Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
    """
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
    elif 'REMOTE_ADDR' in request.META:
        return request.META['REMOTE_ADDR']


@staticmethod
def _image_size(image_config, type_, target_size):
    """Find the closest available size for specified image type.

        Arguments:
          image_config (:py:class:`dict`): The image config data.
          type_ (:py:class:`str`): The type of image to create a URL
            for, (``'poster'`` or ``'profile'``).
          target_size (:py:class:`int`): The size of image to aim for (used
            as either width or height).

        """
    return min(image_config['{}_sizes'.format(type_)], key=lambda size: abs
        (target_size - int(size[1:])) if size.startswith('w') or size.
        startswith('h') else 999)


@classmethod
def get_by_filter(cls, context, filters):
    """Get an attribute by specified filters"""
    db_attr = cls.dbapi.attribute_get_by_filter(context, filters)
    return cls._from_db_object_list(db_attr, context)


def split_model_kwargs(kw):
    """
    django_any birds language parser
    """
    from collections import defaultdict
    model_fields = {}
    fields_agrs = defaultdict(lambda : {})
    for key in kw.keys():
        if '__' in key:
            field, _, subfield = key.partition('__')
            fields_agrs[field][subfield] = kw[key]
        else:
            model_fields[key] = kw[key]
    return model_fields, fields_agrs


@classmethod
def shared_folder_create_details(cls, val):
    """
        Create an instance of this class set to the
        ``shared_folder_create_details`` tag with value ``val``.

        :param SharedFolderCreateDetails val:
        :rtype: EventDetails
        """
    return cls('shared_folder_create_details', val)


def add_tags_to_stream(StreamName=None, Tags=None):
    """
    Adds or updates tags for the specified Amazon Kinesis stream. Each stream can have up to 10 tags.
    If tags have already been assigned to the stream, AddTagsToStream overwrites any existing tags that correspond to the specified tag keys.
    See also: AWS API Documentation

    :example: response = client.add_tags_to_stream(
        StreamName='string',
        Tags={
            'string': 'string'
        }
    )

    :type StreamName: string
    :param StreamName: [REQUIRED]
            The name of the stream.

    :type Tags: dict
    :param Tags: [REQUIRED]
            The set of key-value pairs to use to create the tags.
            (string) --
            (string) --

    """
    pass


@classmethod
def _from_dict(cls, _dict):
    """Initialize a AcousticModel object from a json dictionary."""
    args = {}
    if 'customization_id' in _dict:
        args['customization_id'] = _dict.get('customization_id')
    else:
        raise ValueError(
            "Required property 'customization_id' not present in AcousticModel JSON"
            )
    if 'created' in _dict:
        args['created'] = _dict.get('created')
    if 'language' in _dict:
        args['language'] = _dict.get('language')
    if 'versions' in _dict:
        args['versions'] = _dict.get('versions')
    if 'owner' in _dict:
        args['owner'] = _dict.get('owner')
    if 'name' in _dict:
        args['name'] = _dict.get('name')
    if 'description' in _dict:
        args['description'] = _dict.get('description')
    if 'base_model_name' in _dict:
        args['base_model_name'] = _dict.get('base_model_name')
    if 'status' in _dict:
        args['status'] = _dict.get('status')
    if 'progress' in _dict:
        args['progress'] = _dict.get('progress')
    if 'warnings' in _dict:
        args['warnings'] = _dict.get('warnings')
    return cls(**args)


@classmethod
def smarter_smart_sync_policy_changed_details(cls, val):
    """
        Create an instance of this class set to the
        ``smarter_smart_sync_policy_changed_details`` tag with value ``val``.

        :param SmarterSmartSyncPolicyChangedDetails val:
        :rtype: EventDetails
        """
    return cls('smarter_smart_sync_policy_changed_details', val)


def _show_progress_bar(downloaded, total):
    """
    progress bar for command line
    """
    htlen = 33
    percent = downloaded / total * 100
    hashtags = int(percent / 100 * htlen)
    print('|' + '#' * hashtags + ' ' * (htlen - hashtags) + '|' +
        '  {0}/{1} '.format(downloaded, total) + ' {:.1f}'.format(percent).
        ljust(5) + ' %', end='\r', flush=True)


def pfactors(n):
    """
  Finds the prime factors of 'n'
  https://stackoverflow.com/questions/14550794/python-integer-factorization-into-primes
  """
    from math import sqrt
    pFact, limit, check, num = [], int(sqrt(n)) + 1, 2, n
    if n == 1:
        return [1]
    for check in range(2, limit):
        while num % check == 0:
            pFact.append(check)
            num /= check
    if num > 1:
        pFact.append(num)
    return pFact


def get_metadata(name):
    """The named metadata resource as a string"""


def force_cpu():
    """Force CPU on a GPU system
    """
    import keras.backend as K
    import tensorflow as tf
    config = tf.ConfigProto(device_count={'GPU': 0})
    session = tf.Session(config=config)
    K.set_session(session)


def p_define_expansion(p):
    """
    macro_expansion : code_expressions
    """
    p[0] = p[1]


def write_params_to_yml(kwargs, output_file='grizli.auto_script.yml',
    verbose=True):
    """
    Write grizli parameters to a file
    """
    import time
    import yaml
    import grizli
    try:
        phot_apertures = kwargs['multiband_catalog_args']['phot_apertures']
        kwargs['multiband_catalog_args']['phot_apertures'] = None
    except:
        phot_apertures = None
    try:
        filter_kernel = kwargs['multiband_catalog_args']['detection_params'][
            'filter_kernel']
        kwargs['multiband_catalog_args']['detection_params']['filter_kernel'
            ] = None
    except:
        filter_kernel = None
    fp = open(output_file, 'w')
    fp.write('# {0}\n'.format(time.ctime()))
    fp.write('# Grizli version = {0}\n'.format(grizli.__version__))
    for k in kwargs:
        try:
            d = {k: kwargs[k].copy()}
        except:
            d = {k: kwargs[k]}
        yaml.dump(d, stream=fp, default_flow_style=False)
    fp.close()
    if phot_apertures is not None:
        kwargs['multiband_catalog_args']['phot_apertures'] = phot_apertures
    if filter_kernel is not None:
        kwargs['multiband_catalog_args']['detection_params']['filter_kernel'
            ] = filter_kernel
    if verbose:
        print('\n# Write parameters to {0}\n'.format(output_file))


def dbh__binary(path, contenttype, extension, roottag, nsurl):
    """ Generic Binary Handler - Returns binary_generic for all text files """
    if not (contenttype.startswith('inode/directory') or contenttype.
        startswith('application/x-directory') or contenttype.startswith(
        'directory')) and len(contenttype) > 14 and contenttype[-14:
        ] == 'charset=binary':
        return 'db_generic_binary_file'
    else:
        return False


@classmethod
def one(cls, *args):
    """Fetch an instance of the model by its key.

        Returns:
            An instance of the model.
        """
    col = cls._key()
    if len(col) != len(args):
        raise ValueError('Invalid key')
    query = cls._session().query(cls)
    if getattr(cls, '__key__', None) is None and len(col) == 1:
        return query.get(*args)
    query = query.filter_by(**dict(zip(col, args)))
    if query.count() > 1:
        msg = 'The keys does not ensure the uniqueness of an instance.'
        raise NotImplementedError(msg)
    return query.first()


def nearest(items, pivot):
    """Find nearest value in array, including datetimes

    Args
    ----
    items: iterable
        List of values from which to find nearest value to `pivot`
    pivot: int or float
        Value to find nearest of in `items`

    Returns
    -------
    nearest: int or float
        Value in items nearest to `pivot`
    """
    return min(items, key=lambda x: abs(x - pivot))


@classmethod
def biggest(cls) ->int:
    """Get the biggest prime."""
    return cls.get(bits=cls.max_bits())


def rate2height(rain_flow_rate, duration):
    """
    convert the rain flow rate to the height of rainfall in [mm]
    if 2 array-like parameters are give, a element-wise calculation will be made.
    So the length of the array must be the same.

    Args:
        rain_flow_rate (float | np.ndarray | pd.Series): in [l/(s*ha)]
        duration (float | np.ndarray | pd.Series): in minutes

    Returns:
        float | np.ndarray | pd.Series: height of rainfall in [mm]
    """
    return rain_flow_rate * duration / (1000 / 6)


def isintriangle(tri_x, tri_y, point_x, point_y):
    """
    Returns a boolean as to whether the point (point_x, point_y) is within the triangle (tri_x, tri_y)

    Parameters
    ----------
    tri_x, tri_y : np.ndarray
        Coordinates of the triangle vertices.
    point_x, point_y : float
        Position to test.

    Returns
    -------
    isin : bool
        True if the position (point_x, point_y) is in the triangle defined by (tri_x, tri_y).

    Notes
    -----
    Method from http://totologic.blogspot.co.uk/2014/01/accurate-point-in-triangle-test.html without edge test used
    in getcrossectiontriangles.

    """
    x1 = tri_x[0]
    x2 = tri_x[1]
    x3 = tri_x[2]
    y1 = tri_y[0]
    y2 = tri_y[1]
    y3 = tri_y[2]
    a = ((y2 - y3) * (point_x - x3) + (x3 - x2) * (point_y - y3)) / ((y2 -
        y3) * (x1 - x3) + (x3 - x2) * (y1 - y3))
    b = ((y3 - y1) * (point_x - x3) + (x1 - x3) * (point_y - y3)) / ((y2 -
        y3) * (x1 - x3) + (x3 - x2) * (y1 - y3))
    c = 1 - a - b
    is_in = 0 <= a <= 1 and 0 <= b <= 1 and 0 <= c <= 1
    return is_in


def to_list(val):
    """
	Converts a string argument to a list by splitting it by spaces.
	Returns the object if not a string::

		from waflib.Utils import to_list
		lst = to_list('a b c d')

	:param val: list of string or space-separated string
	:rtype: list
	:return: Argument converted to list
	"""
    if isinstance(val, str):
        return val.split()
    else:
        return val


@staticmethod
def _run(waterbody, datetime_time_step, logger, time_gap_sec, r_in_temp,
    r_in_c_no3, r_in_c_nh4, r_in_c_dph, r_in_c_pph, r_in_c_sed, r_p_att_no3,
    r_p_att_nh4, r_p_att_dph, r_p_att_pph, r_p_att_sed, r_s_m_no3,
    r_s_m_nh4, r_s_m_dph, r_s_m_pph, r_s_m_sed, r_cst_c_dn, r_cst_c_ni,
    r_cst_flow_tolerance, r_cst_vol_tolerance, r_in_q_h2o, r_s_v_h2o_old,
    r_s_v_h2o, r_out_q_h2o):
    """
        This function was written by Thibault Hallouin but is largely inspired by the work of Eva Mockler and
        Michael Bruen, namely for the work published in: Mockler, E., Bruen, M., Desta, M., Misstear, B., Environmental
        Protection Agency, Ireland, 2014. Pathways Project Final Report Volume 4: Catchment Modelling Tool
        (STRIVE Report). Dublin.

        The INCA model was developed by researchers at the Department of Geography and Environmental Science of the
        University of Reading, United Kingdom: http://www.reading.ac.uk/geographyandenvironmentalscience/research/INCA/

        Wade, A.J., Durand, P., Beaujouan, V., Wessel, W.W., Raat, K.J., Whitehead, P.G., Butterfield, D., Rankinen, K.
        and Lepisto, A. (2002) A nitrogen model for European catchments: INCA, new model structure and equations,
        Hydrology and Earth System Sciences, 6, 559-582.

        Wade, A. J., Whitehead, P. G. and Butterfield, D. (2002) The Integrated Catchments model of Phosphorus dynamics
        (INCA-P), a new approach for multiple source assessment in heterogeneous river systems: model structure and
        equations, Hydrology and Earth Systems Sciences, 6, 583-606.

        River Constants
        _ time_gap_sec        time gap between two simulation time steps [seconds]

        River Model * r_ *
        _ Water Quality
        ___ Inputs * in_ *
        _____ r_in_temp       water temperature [degree celsius]
        _____ r_in_c_no3      nitrate concentration at inlet [kg/m3]
        _____ r_in_c_nh4      ammonia concentration at inlet [kg/m3]
        _____ r_in_c_dph      dissolved phosphorus concentration at inlet [kg/m3]
        _____ r_in_c_pph      particulate phosphorus concentration at inlet [kg/m3]
        _____ r_in_c_sed      sediment concentration at inlet [kg/m3]
        ___ Parameters * p_ *
        _____ r_p_att_no3     daily attenuation factor for nitrate [-]
        _____ r_p_att_nh4     daily attenuation factor for ammonia [-]
        _____ r_p_att_dph     daily attenuation factor for dissolved phosphorus [-]
        _____ r_p_att_pph     daily attenuation factor for particulate phosphorus [-]
        _____ r_p_att_sed     daily attenuation factor for sediment [-]
        ___ States * s_ *
        _____ r_s_m_no3       quantity of nitrate in store [kg]
        _____ r_s_m_nh4       quantity of ammonia in store [kg]
        _____ r_s_m_dph       quantity of dissolved phosphorus in store [kg]
        _____ r_s_m_pph       quantity of particulate phosphorus in store [kg]
        _____ r_s_m_sed       quantity of sediment in store [kg]
        ___ Constants * cst_ *
        _____ r_cst_c_dn      denitrification rate constant [-]
        _____ r_cst_c_ni      nitrification rate constant [-]
        _____ r_cst_flow_tolerance      minimum flow to consider equal to no flow [m3/s]
        _____ r_cst_vol_tolerance       minimum volume to consider equal to empty [m3]
        ___ Outputs * out_ *
        _____ r_out_c_no3     nitrate concentration at outlet [kg/m3]
        _____ r_out_c_nh4     ammonia concentration at outlet [kg/m3]
        _____ r_out_c_dph     dissolved phosphorus concentration at outlet [kg/m3]
        _____ r_out_c_pph     particulate phosphorus concentration at outlet [kg/m3]
        _____ r_out_c_sed     sediment concentration at outlet [kg/m3]
        """
    if r_in_q_h2o < r_cst_flow_tolerance:
        logger.debug(''.join(['INCAS # ', waterbody, ': ',
            datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
            ' - Inflow to River Store too low, inflow concentrations set to zero.'
            ]))
        r_in_c_no3 = 0.0
        r_in_c_nh4 = 0.0
        r_in_c_dph = 0.0
        r_in_c_pph = 0.0
        r_in_c_sed = 0.0
    if r_s_v_h2o_old < r_cst_vol_tolerance:
        logger.debug(''.join(['INCAS # ', waterbody, ': ',
            datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
            ' - Volume in River Store too low, in-store contaminant quantities and outflow concentrations set to zero.'
            ]))
        r_s_m_no3 = 0.0
        r_s_m_nh4 = 0.0
        r_s_m_dph = 0.0
        r_s_m_pph = 0.0
        r_s_m_sed = 0.0
        r_out_c_no3 = 0.0
        r_out_c_nh4 = 0.0
        r_out_c_dph = 0.0
        r_out_c_pph = 0.0
        r_out_c_sed = 0.0
    else:
        r_s_m_no3_old = r_s_m_no3
        concentration_no3 = r_s_m_no3_old / r_s_v_h2o_old
        if r_in_temp < 0.0:
            c10 = 0.0
            c11 = 0.0
        else:
            c10 = r_cst_c_ni * 1.047 ** (r_in_temp - 20.0)
            c11 = r_cst_c_dn * 1.047 ** (r_in_temp - 20.0)
            if c10 < 0.0:
                c10 = 0.0
            elif c10 > 1.0:
                c10 = 1.0
            if c11 < 0.0:
                c11 = 0.0
            elif c11 > 1.0:
                c11 = 1.0
        rni = c10 * r_s_m_nh4
        rdn = c11 * r_s_m_no3
        r_s_m_no3 = r_s_m_no3_old + rni - rdn + (r_in_c_no3 * r_in_q_h2o -
            concentration_no3 * r_out_q_h2o) * time_gap_sec
        if r_s_m_no3 < 0.0:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - NO3 Quantity has gone negative in River Store, quantity reset to zero.'
                ]))
            r_s_m_no3 = 0.0
        if (r_s_v_h2o > r_cst_vol_tolerance and r_out_q_h2o >
            r_cst_flow_tolerance):
            r_out_c_no3 = r_s_m_no3 / r_s_v_h2o
        else:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - Volume/Flow in River Store too low, outflow NO3 concentration set to zero.'
                ]))
            r_out_c_no3 = 0.0
        r_s_m_nh4_old = r_s_m_nh4
        concentration_nh4 = r_s_m_nh4_old / r_s_v_h2o_old
        r_s_m_nh4 = r_s_m_nh4_old - rni + (r_in_c_nh4 * r_in_q_h2o -
            concentration_nh4 * r_out_q_h2o) * time_gap_sec
        if r_s_m_nh4 < 0.0:
            r_s_m_nh4 = 0.0
        if (r_s_v_h2o > r_cst_vol_tolerance and r_out_q_h2o >
            r_cst_flow_tolerance):
            r_out_c_nh4 = r_s_m_nh4 / r_s_v_h2o
        else:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - Volume/Flow in River Store too low, outflow NH4 concentration set to zero.'
                ]))
            r_out_c_nh4 = 0.0
        r_s_m_dph_old = r_s_m_dph
        concentration_dph = r_s_m_dph_old / r_s_v_h2o_old
        r_s_m_dph = r_s_m_dph_old + (r_in_c_dph * r_in_q_h2o -
            concentration_dph * r_out_q_h2o) * time_gap_sec
        if r_s_m_dph < 0.0:
            r_s_m_dph = 0.0
        r_s_m_dph = r_s_m_dph * r_p_att_dph
        if (r_s_v_h2o > r_cst_vol_tolerance and r_out_q_h2o >
            r_cst_flow_tolerance):
            r_out_c_dph = r_s_m_dph / r_s_v_h2o
        else:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - Volume/Flow in River Store too low, outflow DPH concentration set to zero.'
                ]))
            r_out_c_dph = 0.0
        r_s_m_pph_old = r_s_m_pph
        concentration_pph = r_s_m_pph_old / r_s_v_h2o_old
        r_s_m_pph = r_s_m_pph_old + (r_in_c_pph * r_in_q_h2o -
            concentration_pph * r_out_q_h2o) * time_gap_sec
        if r_s_m_pph < 0.0:
            r_s_m_pph = 0.0
        r_s_m_pph = r_s_m_pph * r_p_att_pph
        if (r_s_v_h2o > r_cst_vol_tolerance and r_out_q_h2o >
            r_cst_flow_tolerance):
            r_out_c_pph = r_s_m_pph / r_s_v_h2o
        else:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - Volume/Flow in River Store too low, outflow PPH concentration set to zero.'
                ]))
            r_out_c_pph = 0.0
        r_s_m_sed_old = r_s_m_sed
        concentration_sed = r_s_m_sed_old / r_s_v_h2o_old
        r_s_m_sed = r_s_m_sed_old + (r_in_c_sed * r_in_q_h2o -
            concentration_sed * r_out_q_h2o) * time_gap_sec
        if r_s_m_sed < 0.0:
            r_s_m_sed = 0.0
        r_s_m_sed = r_s_m_sed * r_p_att_sed
        if (r_s_v_h2o > r_cst_vol_tolerance and r_out_q_h2o >
            r_cst_flow_tolerance):
            r_out_c_sed = r_s_m_sed / r_s_v_h2o
        else:
            logger.debug(''.join(['INCAS # ', waterbody, ': ',
                datetime_time_step.strftime('%d/%m/%Y %H:%M:%S'),
                ' - Volume/Flow in River Store too low, outflow SED concentration set to zero.'
                ]))
            r_out_c_sed = 0.0
    return (r_out_c_no3, r_out_c_nh4, r_out_c_dph, r_out_c_pph, r_out_c_sed,
        r_s_m_no3, r_s_m_nh4, r_s_m_dph, r_s_m_pph, r_s_m_sed)


@classmethod
def blue(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x3498db``."""
    return cls(3447003)


@staticmethod
def initialLower(key_name):
    """
        First character to lower case
        :return:
        """
    first_character = str(key_name)[:1]
    remaining_characters = str(key_name)[1:]
    new_property_name = str(first_character.lower()) + str(remaining_characters
        )
    return new_property_name


def __setattr__(name, value):
    """ Handle activating ghosts before setting an attribute value.

        "Special" attributes and '_p_*' attributes don't require activation.
        """


def merge(a, b):
    """
    Merge all attributes and metadata from I{a} to I{b}.
    @param a: A I{source} object
    @type a: L{Object}
    @param b: A I{destination} object
    @type b: L{Object}
    """
    for item in a:
        setattr(b, item[0], item[1])
        b.__metadata__ = b.__metadata__
    return b


def getXJpath(voc_root, data):
    """
    voc_root: '...../'
    data: [(2007, 'trainval'), (2012, 'trainval')]
    """
    xml_path = voc_root + 'VOC{}/Annotations/{}.xml'
    jpg_path = voc_root + 'VOC{}/JPEGImages/{}.jpg'
    set_path = voc_root + 'VOC{}/ImageSets/Main/{}.txt'
    for year, dataset in data:
        with open(set_path.format(year, dataset), 'r') as fp:
            for line in fp:
                xpath = xml_path.format(year, line.strip())
                jpath = jpg_path.format(year, line.strip())
                yield xpath, jpath


def to_unicode(data_str, encoding):
    """Convert a str object to unicode using the encoding given

    Characters that cannot be converted will be converted to '�' (the
    unicode replacement character).
    """
    return data_str.decode(encoding, 'w3lib_replace')


def _so_version_num(libname):
    """Extracts the version number from an .so filename as a list of ints."""
    return list(map(int, libname.split('.so.')[1].split('.')))


def p_from_a(sep, m1, m2):
    """ Computes separation from orbital period with kepler III

    Parameters
    ----------
    sep : float/array
        separation [rsun]
    m1 : float/array
        primary mass [msun]
    m2 : float/array
        secondary mass [msun]

    Returns
    -------
    p : float/array
        orbital period [day]
    """
    sep_au = sep / 215.032
    p_2 = sep_au ** 3 / (m1 + m2)
    p_day = p_2 ** 0.5 * 365.25
    return p_day


def xstr(s):
    """If ``s`` is None return empty string.

    :param s: string
    :return: s or an empty string if s is None
    :rtype: str

    :Example:
        >>> xstr(None)
        ''
    """
    return '' if s is None else str(s)


@classmethod
def convert_code(cls, code, redirect_uri=
    'http://local.mellowmorning.com:8000/facebook/connect/'):
    """
        Turns a code into an access token

        **Example**::

            FacebookAuthorization.convert_code(code)

        :param code:
            The code to convert

        :param redirect_uri:
            The redirect uri with which the code was requested

        :returns: dict

        """
    kwargs = cls._client_info()
    kwargs['code'] = code
    kwargs['redirect_uri'] = redirect_uri
    response = cls.request('oauth/access_token', **kwargs)
    return response


def handle_notes_merge(args, configs):
    """Handle `merge` subcommand of `notes` subcommand

    :param args: parsed arguments
    :type args: :py:class:`argparse.Namespace`
    :param configs: configurations object
    :type configs: :py:class:`sfftk.core.configs.Configs`
    :return exit_status: exit status
    :rtype exit_status: int
    """
    from sfftk.notes.modify import merge
    return merge(args, configs)


def is_complex_expr(expr):
    """Check if expression in complex

    :param expr: expression to parse
    :type expr: str
    :return: True if '(', ')', '&', '|', '!' or '*' are in expr
    :rtype: bool
    """
    for char in '()&|!*':
        if char in expr:
            return True
    return False


def parse_player_version(data: dict) ->str:
    """Parse the player version from the data payload."""
    return data.get('version')


@classmethod
def initialize_reactor(cls):
    """
        Called once by Cluster.connect().  This should be used by implementations
        to set up any resources that will be shared across connections.
        """
    pass


def show_message(configurator):
    """
    If you want to display a message to the user when rendering is complete, you
    can use this function as :ref:`post-render-hook`:

    .. code-block:: ini

        [template]
        post_render = mrbob.hooks:show_message
        message = Well done, %(author.name)s, your code is ready!

    As shown above, you can use standard Python formatting in ``post_render_msg``.
    """
    message = configurator.templateconfig.get('message', '')
    if not configurator.quiet and message:
        print(message % configurator.variables)


def set_source_info(directive, node):
    """
    copied from sphinx.util.nodes import set_source_info
    """
    node.source, node.line = directive.state_machine.get_source_and_line(
        directive.lineno)


def order_plan_queryset(plans, field, asc=False):
    """
    Annotate the TestPlan queryset by calling order_by on it.
    """
    orderable_fields = ('plan_id', 'name', 'author__username',
        'owner__username', 'create_date', 'product__name', 'type',
        'num_cases', 'num_runs', 'num_children')
    if field in orderable_fields:
        order_by = field
        if not asc:
            order_by = '-%s' % order_by
        plans = plans.order_by(order_by)
    return plans


def dbh_xlg_limatix(path, contenttype, extension, roottag, nsurl):
    """ Generic XLG Handler - Returns xlg_viewer for all XLG files """
    if (extension == 'xlg' or extension == 'xlp') and nsurl.startswith(
        'http://limatix.org'):
        return 'db_limatix_viewer'
    else:
        return False


def remove_str_from_keys(dct, key_str):
    """ convert dictionary keys by removing key_str"""
    new_dct = {}
    for key, value in dct.iteritems():
        if key_str in key:
            new_key = key.replace(key_str, '')
            new_dct[new_key] = value
        else:
            new_dct[key] = value
    return new_dct


@classmethod
def from_dendropy(cls, tree, config={}, **kwargs):
    """Read from DendroPy Tree."""
    try:
        import phylopandas as pd
        df = pd.read_dendropy(tree)
        data = df.to_dict(orient='records')
        return cls(data=data, config={}, **kwargs)
    except ImportError:
        Exception('DendroPy and Phylopandas must be installed.')


def config_identifier(python_identifier):
    """For vanity, keep keys and section names in the config file with dashes instead of underscores and
    all-lowercase"""
    return python_identifier.lower().replace('_', '-')


@staticmethod
def sort_key(field):
    """ Get a key to sort a field

        Args:
            field (:obj:`ChartDataField`): field

        Returns:
            :obj:`tuple`
        """
    return (field.name, field.shape.value if field.shape else None, field.
        type.value if field.type else None)


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def game_start():
    """Start game engine

    """
    pass


def calc_tick_coords(u, f, g, dx_unit, dy_unit, distance):
    """
    helper func to calculate tick start and stop coords
    """
    x1, y1 = f(u), g(u)
    x2 = x1 + distance * dy_unit
    y2 = y1 - distance * dx_unit
    return x1, y1, x2, y2


def escape_char(c):
    """
    Return the special character that `c` encodes.

        >>> escape_char("n")
        "
"
    """
    if c == 'n':
        return '\n'
    elif c == 't':
        return '\t'
    elif c == '\\':
        return '\\'
    elif c == '"':
        return '"'
    else:
        return '\\' + c


def trim_trailing_lines(lines):
    """
    Trim trailing blank lines.
    """
    lines = list(lines)
    while lines and not lines[-1]:
        lines.pop(-1)
    return lines


def rendersize():
    """Set render size and aspect from active sequence

    """
    pass


def mixin(obj, *mixins):
    """
    Function adding one or more mixin class to the list of parent classes of the current object.
    This is done by dynamically changing the class hierarchy of the current object,
    not only by adding the mixin methods to the object.

    :param obj: the object on which to apply the mixins.
    :param mixins: the list of mixin classes to add to the object.
    :return: the extended object.
    """
    obj.__class__ = type(obj.__class__.__name__, (obj.__class__,) + tuple(
        mixins), dict())
    return obj


def organize_by_values(dict_list, key):
    """
    dict_list -- a list of dicts
    key -- a key shared by all the dicts in dict_list
    Returns a dict of dicts keyed by the value of the specified key
    in each dictionary.
    If two dictionaries fall under the same key an error is thrown.
    If a dictionary is doesn't have the specified key it is omitted
    """
    result = {}
    for dicty in dict_list:
        if key in dicty:
            dicty_copy = dicty.copy()
            val = dicty_copy.pop(key)
            if val in result:
                raise Exception('Duplicate key: ' + val)
            result[val] = dicty_copy
    return result


def find_property(id):
    """ Trys to find and return the property having the specified id
        """


def lovasz_grad(gt_sorted):
    """
    Computes gradient of the Lovasz extension w.r.t sorted errors
    See Alg. 1 in paper
    """
    p = len(gt_sorted)
    gts = gt_sorted.sum()
    intersection = gts - gt_sorted.float().cumsum(0)
    union = gts + (1 - gt_sorted).float().cumsum(0)
    jaccard = 1.0 - intersection / union
    if p > 1:
        jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
    return jaccard


def default_jwt_headers_callback(default_headers):
    """
    By default header typically consists of two parts: the type of the token,
    which is JWT, and the signing algorithm being used, such as HMAC SHA256
    or RSA. But we don't set the default header here we set it as empty which
    further by default set while encoding the token
    :return: default we set None here
    """
    return None


def get_decisive_snr(snrs):
    """Return the SNR for the trigger that decides if an event is detectable.

    If there are two or more detectors, then the decisive SNR is the SNR of the
    second loudest detector (since a coincidence of two or more events is
    required). If there is only one detector, then the decisive SNR is just the
    SNR of that detector. If there are no detectors, then 0 is returned.

    Parameters
    ----------
    snrs : list
        List of SNRs (floats).

    Returns
    -------
    decisive_snr : float

    """
    if len(snrs) > 1:
        return sorted(snrs)[-2]
    elif len(snrs) == 1:
        return snrs[0]
    else:
        return 0.0


@classmethod
def from_box(cls, box):
    """Creates a `SolidPrimitive` from a :class:`compas.geometry.Box`.

        Parameters
        ----------
        box: `compas.geometry.Box`

        Returns
        -------
        SolidPrimitive
        """
    return cls(type=cls.BOX, dimensions=[box.xsize, box.ysize, box.zsize])


def make_imapdict(mapdict):
    """ make inverse mapping dict """
    result = dict()
    for k, v in mapdict.items():
        for _ in v:
            result[_] = k
    return result


def __call__(request):
    """ Handle single request
        """


@classmethod
def team_folder_change_status_details(cls, val):
    """
        Create an instance of this class set to the
        ``team_folder_change_status_details`` tag with value ``val``.

        :param TeamFolderChangeStatusDetails val:
        :rtype: EventDetails
        """
    return cls('team_folder_change_status_details', val)


def pretty_print(chain_data):
    """Pretty print on terminal.

    :param list chain_data: List of `deps.Node`
    """
    lines = ''
    for node in chain_data:
        lines += '{0} -> {1}\n'.format(node, node.targets)
    return lines.rstrip()


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


@classmethod
def member_transfer_account_contents(cls, val):
    """
        Create an instance of this class set to the
        ``member_transfer_account_contents`` tag with value ``val``.

        :param MemberTransferAccountContentsType val:
        :rtype: EventType
        """
    return cls('member_transfer_account_contents', val)


def has_annotations(doc):
    """ Check if document has any mutation mention saved. """
    for part in doc.values():
        if len(part['annotations']) > 0:
            return True
    return False


def is_db_connection_error(args):
    """Return True if error in connecting to db."""
    conn_err_codes = '2002', '2003', '2006'
    for err_code in conn_err_codes:
        if args.find(err_code) != -1:
            return True
    return False


def check_cols2regi(constant_regi, cols2regi, x, yend=None, add_cons=True):
    """ Checks if dimensions of list cols2regi match number of variables. """
    if add_cons:
        is_cons = 1
        if constant_regi == 'many':
            regi_cons = [True]
        elif constant_regi == 'one':
            regi_cons = [False]
    else:
        is_cons = 0
        regi_cons = []
    try:
        tot_k = x.shape[1] + yend.shape[1]
    except:
        tot_k = x.shape[1]
    if cols2regi == 'all':
        cols2regi = regi_cons + [True] * tot_k
    else:
        cols2regi = regi_cons + cols2regi
    if len(cols2regi) - is_cons != tot_k:
        raise Exception(
            "The lenght of list 'cols2regi' must be equal to the amount of variables (exogenous + endogenous) when not using cols2regi=='all'."
            )
    return cols2regi


def parse_AcceptLanguage(acceptLanguage):
    """en-US,en;q=0.8,pt;q=0.6"""
    if not acceptLanguage:
        return [('en', '1')]
    languages_with_weigths = acceptLanguage.strip().split(',')
    map(lambda s: s.strip, languages_with_weigths)
    locale_q_pairs = []
    for language in languages_with_weigths:
        try:
            if language.split(';')[0].strip() == language:
                locale_q_pairs.append((language.strip(), '1'))
            else:
                locale = language.split(';')[0].strip()
                q = language.split(';')[1].split('=')[1]
                locale_q_pairs.append((locale, q))
        except IndexError:
            pass
    if locale_q_pairs:
        return sorted(locale_q_pairs, key=lambda v: v[1], reverse=True)
    else:
        return [('en', '1')]


@staticmethod
def is_multivalue(field_name):
    """
        Check, if given form field is a multivalue field.

        :param str field_name: Name of the form field.
        :return: ``True``, if the field can contain multiple values, ``False`` otherwise.
        :rtype: bool
        """
    if field_name in ('groups',):
        return True
    return False


@classmethod
def from_excellon(cls, line, **kwargs):
    """ Create a ZAxisInfeedRate from an excellon file line.

        Parameters
        ----------
        line : string
            Line from an Excellon file

        Returns
        -------
        z_axis_infeed_rate : ToolSelectionStmt
            ToolSelectionStmt representation of `line.`
        """
    rate = int(line[1:])
    return cls(rate, **kwargs)


@classmethod
def fromFile(cls, filePath, ramAddress):
    """
        Load a main code file from a filesystem file.
        """
    with open(filePath, 'rb') as f:
        return cls(f.read(), ramAddress)


@property
def xls():
    """A Legacy Excel Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

        .. note::

            XLS files are limited to a maximum of 65,000 rows. Use :class:`Dataset.xlsx` to avoid this limitation.

         .. admonition:: Binary Warning

             :class:`Dataset.xls` contains binary data, so make sure to write in binary mode::

                with open('output.xls', 'wb') as f:
                    f.write(data.xls)'
        """
    pass


@classmethod
def create_batch(cls, nb_record, **kwargs):
    """Create n records in elastic, using bulk.

    nb_record: int
    """
    model_class = cls.Meta.model
    ids = []
    if hasattr(cls.Meta, 'max_bulk_size'):
        max_bulk_size = cls.Meta.max_bulk_size
    else:
        max_bulk_size = cls.MAX_BULK_SIZE
    bulk = ''
    if nb_record > max_bulk_size:
        nb_record = max_bulk_size
    for x in range(0, nb_record):
        bulk += model_class.bulk_data(cls.build(**kwargs))
    bulk_result = model_class.send(bulk)
    for one_record in bulk_result['items']:
        ids.append(one_record['index']['_id'])
    model_class.refresh()
    query = {'_source': '*', 'query': {'terms': {'_id': ids}}}
    return model_class.scan(query, limit=len(ids))


@classmethod
def createRange(cls, min_value, max_value, delta):
    """
        Will create new vector and initialize a range.
        """
    vector = cls()
    vector.initRange(min_value, max_value, delta)
    return vector


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a Launchpad item."""
    return str(item['bug_data']['id'])


@classmethod
def stub_batch(cls, size, **kwargs):
    """Stub a batch of instances of the given class, with overriden attrs.

        Args:
            size (int): the number of instances to stub

        Returns:
            object list: the stubbed instances
        """
    return [cls.stub(**kwargs) for _ in range(size)]


def HR(hit_trades_int, total_trades_int):
    """
    Hit Rate / Win Rate
    Returns: float = jhta.HR(hit_trades_int, total_trades_int)
    Source: http://traderskillset.com/hit-rate-stock-trading/
    """
    return float(hit_trades_int / total_trades_int)


def setTaggedValue(tag, value):
    """Associates `value` with `key`."""


def docstring_summary(docstring):
    """Return summary of docstring."""
    return docstring.split('\n')[0] if docstring else ''


def location_prompt(location, msg='WEAthER'):
    """
    Prompt user to display weather or forecast.
    """
    from x84.bbs import getterminal, echo
    term = getterminal()
    echo(u''.join((u'\r\n\r\n', term.yellow(u'Display %s for ' % (msg,)),
        term.bold('%(city)s, %(state)s' % location), term.yellow(' ? '),
        term.bold_yellow(u'['), term.underline_yellow(u'yn'), term.
        bold_yellow(u']'), u': ')))
    while True:
        inp = term.inkey()
        if inp.lower() in (u'n', 'q', '\x1b'):
            return False
        elif inp.lower() in (u'y', u' ', u'\r', u'\n'):
            return True


def items_iterator(dictionary):
    """Add support for python2 or 3 dictionary iterators."""
    try:
        gen = dictionary.iteritems()
    except:
        gen = dictionary.items()
    return gen


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


@staticmethod
def verify_condition(_data, _collection_name, _caller_name):
    """
        Validates the conditions' structure and the collection it queries.

        :param _data: The data to check.
        :param _collection_name: Name of the collection that it should be checked against
        :param _caller_name: The name of the calling function for logging

        """
    if 'conditions' not in _data:
        raise Exception(_caller_name +
            ': Error - Not a valid condition, "conditions"-property missing')
    if 'collection' in _data and _data['collection'] != _collection_name:
        raise Exception(_caller_name +
            ': Error - collection omitted or wrong, only queries against the '
             + _collection_name + ' collection is permitted.')


def _get_col_that_is_primary(common_cols, featuregroups):
    """
    Helper method that returns the column among a shared column between featuregroups that is most often marked as
    'primary' in the hive schema.

    Args:
        :common_cols: the list of columns shared between all featuregroups
        :featuregroups: the list of featuregroups

    Returns:
        the column among a shared column between featuregroups that is most often marked as 'primary' in the hive schema
    """
    primary_counts = []
    for col in common_cols:
        primary_count = 0
        for fg in featuregroups:
            for feature in fg.features:
                if feature.name == col and feature.primary:
                    primary_count = primary_count + 1
        primary_counts.append(primary_count)
    max_no_primary = max(primary_counts)
    if max(primary_counts) == 0:
        return common_cols[0]
    else:
        return common_cols[primary_counts.index(max_no_primary)]


def get_resource_string(manager, resource_name):
    """Return a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``"""


def star_chain_str(star_chain_index_mean):
    """
    Arbitry choices to associate star-chain index with geometry
    """
    if star_chain_index_mean <= 1 / 3:
        return 'chain'
    elif star_chain_index_mean <= 2 / 3:
        return 'mixed'
    else:
        return 'star'


@classmethod
def create_floatingip(cls, external_network_id=None, port=None, client=None,
    **kwargs):
    """Creates a floating IP.

        Create a floating IP and schedule it for later deletion.
        If a client is passed, then it is used for deleting the IP too.

        :param external_network_id: network ID where to create
        By default this is 'CONF.network.public_network_id'.

        :param port: port to bind floating IP to
        This is translated to 'port_id=port['id']'
        By default it is None.

        :param client: network client to be used for creating and cleaning up
        the floating IP.

        :param **kwargs: additional creation parameters to be forwarded to
        networking server.
        """
    client = client or cls.client
    external_network_id = external_network_id or cls.external_network_id
    if port:
        port_id = kwargs.setdefault('port_id', port['id'])
        if port_id != port['id']:
            message = 'Port ID specified twice: {!s} != {!s}'.format(port_id,
                port['id'])
            raise ValueError(message)
    fip = client.create_floatingip(external_network_id, **kwargs)['floatingip']
    fip['client'] = client
    cls.floating_ips.append(fip)
    return fip


def get_post_repair_results():
    """Return an ICheckResults instance that describes the state of the
        file/dir after any repair was attempted. If no repair was attempted,
        the pre-repair and post-repair results will be identical."""


def szrange(charge, nsingle):
    """
    Make a list giving :math:`S_{z}` values for given charge.

    Parameters
    ----------
    charge : int
        Value of the charge.
    nsingle : int
        Number of single particle states.

    Returns
    -------
    list
        List containing :math:`S_{z}` values for given charge.
    """
    szmax = min(charge, nsingle - charge)
    return list(range(-szmax, szmax + 1, +2))


def response_callback(resp, *args, **kwargs):
    """ Don't do anything with the response """
    pass


def size16(parent=None, new_value=None, **kwargs):
    """
    Size getter for rsa key data where the byte size
    of the integer is (parent.parent.bitlen + 15) // 16
    (the + 15 is to round up to the nearest multiple of 16)

    We dont want to have this be a setter since bitlen
    is used by more than one attribute and while it may
    work for some bigints, it may be too small for others.
    """
    if new_value is None:
        return (parent.parent.bitlen + 15) // 16


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


@staticmethod
def evaluate(x, factor):
    """One dimensional multiply model function"""
    return factor * x


def _overload_dummy(*args, **kwds):
    """Helper for @overload to raise when called."""
    raise NotImplementedError(
        'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.'
        )


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def round_channels(channels, divisor=8):
    """
    Round weighted channel number (make divisible operation).

    Parameters:
    ----------
    channels : int or float
        Original number of channels.
    divisor : int, default 8
        Alignment value.

    Returns
    -------
    int
        Weighted number of channels.
    """
    rounded_channels = max(int(channels + divisor / 2.0) // divisor *
        divisor, divisor)
    if float(rounded_channels) < 0.9 * channels:
        rounded_channels += divisor
    return rounded_channels


def distance_matrix(client, locations, profile='driving-car', sources=None,
    destinations=None, metrics=None, resolve_locations=None, units=None,
    optimized=None, validate=True, dry_run=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param locations: One or more pairs of lng/lat values.
    :type locations: a single location, or a list of locations, where a
        location is a list or tuple of lng,lat values

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road",
        "cycling-safe", "cycling-mountain", "cycling-tour",
        "cycling-electric",]. Default "driving-car".
    :type profile: string

    :param sources: A list of indices that refer to the list of locations
        (starting with 0). If not passed, all indices are considered.
    :type sources: list or tuple

    :param destinations: A list of indices that refer to the list of locations
        (starting with 0). If not passed, all indices are considered.
    :type destinations: list or tuple

    :param metrics: Specifies a list of returned metrics. One or more of ["distance",
        "duration"]. Default ['duration'].
    :type metrics: list of strings

    :param resolve_locations: Specifies whether given locations are resolved or
        not. If set 'true', every element in destinations and sources will
        contain the name element that identifies the name of the closest street.
        Default False.
    :type resolve_locations: boolean

    :param units: Specifies the unit system to use when displaying results.
        One of ["m", "km", "m"]. Default "m".
    :type units: string

    :param optimized: Specifies whether Dijkstra algorithm ('false') or any
        available technique to speed up shortest-path routing ('true') is used.
        For normal Dijkstra the number of visited nodes is limited to 100000.
        Default True
    :type optimized: boolean

    :param validate: Specifies whether parameters should be validated before sending the request. Default True.
    :type validate: bool

    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When profile parameter has wrong value.

    :rtype: call to Client.request()
    """
    params = {'locations': locations}
    if sources:
        params['sources'] = sources
    if destinations:
        params['destinations'] = destinations
    if profile:
        params['profile'] = profile
    if sources:
        params['sources'] = sources
    if destinations:
        params['destinations'] = destinations
    if metrics:
        params['metrics'] = metrics
    if resolve_locations is not None:
        params['resolve_locations'] = resolve_locations
    if units:
        params['units'] = units
    if optimized is not None:
        params['optimized'] = optimized
    return client.request('/v2/matrix/' + profile + '/json', {}, post_json=
        params, dry_run=dry_run)


def list():
    """Return a list with the messages in the queue. Each message is a dict
        which must have a 'name' key (with the spider name), and other optional
        keys that will be used as spider arguments, to create the spider.

        This method can return a deferred. """


def duplicate_move_keep_inputs(NODE_OT_duplicate=None,
    NODE_OT_translate_attach=None):
    """Duplicate selected nodes keeping input links and move them

    :param NODE_OT_duplicate: Duplicate Nodes, Duplicate selected nodes
    :param NODE_OT_translate_attach: Move and Attach, Move nodes and attach to frame
    """
    pass


@staticmethod
def get_instance(provider):
    """
        This is a method that is used to instantiate the provider class.
        """
    classname = provider + 'CloudProvider'
    providerModule = __import__('ec2spotmanager.CloudProvider.%s' %
        classname, fromlist=[classname])
    providerClass = getattr(providerModule, classname)
    return providerClass()


@staticmethod
def isUnixsockLocation(location):
    """determine if a location string is for a Unix domain socket"""
    return location.startswith('./u:')


def flip(bbox, size, flip_x=False, flip_y=False):
    """Flip bounding boxes according to image flipping directions.

    Parameters
    ----------
    bbox : numpy.ndarray
        Numpy.ndarray with shape (N, 4+) where N is the number of bounding boxes.
        The second axis represents attributes of the bounding box.
        Specifically, these are :math:`(x_{min}, y_{min}, x_{max}, y_{max})`,
        we allow additional attributes other than coordinates, which stay intact
        during bounding box transformations.
    size : tuple
        Tuple of length 2: (width, height).
    flip_x : bool
        Whether flip horizontally.
    flip_y : bool
        Whether flip vertically.

    Returns
    -------
    numpy.ndarray
        Flipped bounding boxes with original shape.
    """
    if not len(size) == 2:
        raise ValueError('size requires length 2 tuple, given {}'.format(
            len(size)))
    width, height = size
    bbox = bbox.copy()
    if flip_y:
        ymax = height - bbox[:, (1)]
        ymin = height - bbox[:, (3)]
        bbox[:, (1)] = ymin
        bbox[:, (3)] = ymax
    if flip_x:
        xmax = width - bbox[:, (0)]
        xmin = width - bbox[:, (2)]
        bbox[:, (0)] = xmin
        bbox[:, (2)] = xmax
    return bbox


def blanknone(v):
    """
    Return a value, or empty string if it's None.
    """
    return '' if v is None else v


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def CO2LOGSERVER_OSEM_COL_REDIRECT(col):
    """
    This function is called with the column name as argument to determine
    whether this column should be considered for OpenSenseMap upload. By
    default, this function returns ``True`` for any column, so any column will
    be redirected to the OpenSenseMap.
    """
    return True


def model_params(model):
    """
    Create string of alphabetically sorted parameters of the model
    obtained with get_params or string contaning result of __repr__ call
    """
    s = ''
    if hasattr(model, 'get_params'):
        params_dict = model.get_params()
        max_len = 0
        for key in params_dict:
            if len(key) > max_len:
                max_len = len(key)
        sorted_keys = sorted(params_dict.keys())
        for key in sorted_keys:
            s += '%-*s %s\n' % (max_len, key, params_dict[key])
    elif hasattr(model, '__repr__'):
        s = model.__repr__()
        s += '\n'
    else:
        s = (
            'Model has no ability to show parameters (has no <get_params> or <__repr__>)\n'
            )
    s += '\n'
    return s


def UJ_to_UdJH(U, J):
    """
    Given Kanamori :math:`U` and :math:`J`, return :math:`U_d` and :math:`J_H`,
    for :math:`t2g`-orbitals.

    Parameters
    ----------
    U: float
        Coulomb interaction :math:`U`.
    J: float
        Hund's coupling :math:`J`.

    Returns
    -------
    Ud: float
        Coulomb interaction :math:`U_d`.
    JH: float
        Hund's coupling :math:`J_{H}`.
    """
    F2 = J / (3.0 / 49.0 + 20 * 0.625 / 441.0)
    F4 = 0.625 * F2
    JH = (F2 + F4) / 14.0
    Ud = U - 4.0 / 49.0 * (F2 + F4)
    return Ud, JH


def sign(number):
    """Returns the sign of a number: +1 or -1.
    """
    return int(int(number > 0) - int(number < 0))


def obj_box_coord_centroid_to_upleft(coord):
    """Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
    It is the reverse process of ``obj_box_coord_upleft_to_centroid``.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.

    Returns
    -------
    list of 4 numbers
        New bounding box.

    """
    if len(coord) != 4:
        raise AssertionError('coordinate should be 4 values : [x, y, w, h]')
    x_center, y_center, w, h = coord
    x = x_center - w / 2.0
    y = y_center - h / 2.0
    return [x, y, w, h]


def std(series, n):
    """
    标准差: 求series序列每n个周期的标准差

        注意: n为0的情况下, 或当n为有效值但当前的series序列元素个数不足n个, 函数返回 NaN 序列

    Args:
        series (pandas.Series): 数据序列

        n (int): 标准差的周期

    Returns:
        pandas.Series: 标准差序列

    Example::

        from tqsdk import TqApi, TqSim, tafunc

        api = TqApi(TqSim())
        klines = api.get_kline_serial("CFFEX.IF1908", 24 * 60 * 60)
        std = tafunc.std(klines.close, 5)  # 收盘价序列每5项计算一个标准差
        print(list(std))
    """
    m = series.rolling(n).std()
    return m


@classmethod
def willAllowParent(cls, parent):
    """Is the parent of an allowed type to have this type as a child?"""
    ap = cls.allowedParentTypes()
    if parent is None and len(ap) > 0 and ap[0] is None:
        return True
    for p in ap:
        if isinstance(parent, p):
            return True
    return False


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str)


def split_virtual_offset(virtual_offset):
    """Divides a 64-bit BGZF virtual offset into block start & within block offsets.

    >>> (100000, 0) == split_virtual_offset(6553600000)
    True
    >>> (100000, 10) == split_virtual_offset(6553600010)
    True

    """
    start = virtual_offset >> 16
    return start, virtual_offset ^ start << 16


def nest_toc_tokens(toc_list):
    """Given an unsorted list with errors and skips, return a nested one.
    [{'level': 1}, {'level': 2}]
    =>
    [{'level': 1, 'children': [{'level': 2, 'children': []}]}]

    A wrong list is also converted:
    [{'level': 2}, {'level': 1}]
    =>
    [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
    """
    ordered_list = []
    if len(toc_list):
        last = toc_list.pop(0)
        last['children'] = []
        levels = [last['level']]
        ordered_list.append(last)
        parents = []
        while toc_list:
            t = toc_list.pop(0)
            current_level = t['level']
            t['children'] = []
            if current_level < levels[-1]:
                levels.pop()
                to_pop = 0
                for p in reversed(parents):
                    if current_level <= p['level']:
                        to_pop += 1
                    else:
                        break
                if to_pop:
                    levels = levels[:-to_pop]
                    parents = parents[:-to_pop]
                levels.append(current_level)
            if current_level == levels[-1]:
                (parents[-1]['children'] if parents else ordered_list).append(t
                    )
            else:
                last['children'].append(t)
                parents.append(last)
                levels.append(current_level)
            last = t
    return ordered_list


def post_hook():
    """A plugin hook called in the second initialization step.

        This is called after the database is initialized.
        """


def p_field_id(p):
    """field_id : INTCONSTANT ':' """
    p[0] = p[1]


def allYears():
    """ get all the years """


@classmethod
def enabled_domain_invites(cls, val):
    """
        Create an instance of this class set to the ``enabled_domain_invites``
        tag with value ``val``.

        :param EnabledDomainInvitesType val:
        :rtype: EventType
        """
    return cls('enabled_domain_invites', val)


def set_streamlining(streamline):
    """Sets whether `acorn` logging logic should be disabled temporarily.
    """
    global streamlining
    streamlining = streamline


def mean_samples(data, xcol, ycollist):
    """Create a sample list that contains
    the mean of the original list.

>>> chart_data.mean_samples([ [1, 10, 15], [2, 5, 10], [3, 8, 33] ], 0, (1, 2))
[(1, 12.5), (2, 7.5), (3, 20.5)]
"""
    out = []
    numcol = len(ycollist)
    try:
        for elem in data:
            v = 0
            for col in ycollist:
                v += elem[col]
            out.append((elem[xcol], float(v) / numcol))
    except IndexError:
        raise IndexError('bad data: %s,xcol=%d,ycollist=%s' % (data, xcol,
            ycollist))
    return out


def list_to_rst_modules(list_):
    """
    Combina los nombres de los módulos para formatearlos
    e incluirlos en un fichero ``.rst``

    :param list[str] list_: lista con los nombres de los módulos
    :return: string formateada para ``.rst``
    :rtype: str

    .. code-block:: python

        >> list_to_rst_modules(['generators', 'identify', 'utils'])
        "generators \\n identify \\n utils"

    """
    result = ''
    for element in list_:
        result = result + '   ' + element + '\n'
    return result


@classmethod
def start(cls, options=None):
    """Starts a docker container

        Usage::

            hammer docker container start [OPTIONS]

        Options::

            --compute-resource COMPUTE_RESOURCE_NAME  Compute resource name
            --compute-resource-id COMPUTE_RESOURCE_ID
            --id ID
            --name NAME                               Name to search by

        """
    cls.command_sub = 'start'
    return cls.execute(cls._construct_command(options))


@classmethod
def parse_string(cls, string):
    """Key-value string parser.

        Replaces a string containing a placeholder with it's stored value.

        Args:
            string (str): String to scan and update.

        Returns:
            str: Updated string.
        """
    for k, v in cls.storage.iteritems():
        string = string.replace('<%s>' % k, v)
    return string


def get_journal_from_entry(entry):
    """get journal from entry (keys: journal, eprint)"""
    if 'journal' in entry and entry['journal'] != '':
        return entry['journal']
    elif 'eprint' in entry:
        return entry['eprint']
    else:
        return ''


def nucleotides_to_integers(seq):
    """Converts a nucleotide sequence to an interger representation.

    The base characters in the nucleotide string (A, C, G and T) are converted to the following: A -> 0, C -> 1, G -> 2
    and T -> 3. The combined uppercase string is returned.

    Parameters
    ----------
    seq : str
        A nucleotide sequence string.

    Returns
    -------
    str
        The interger representation string for the given nucleotide sequence.

    """
    int_sequence = []
    for i in seq.upper():
        if i == 'A':
            int_sequence.append(str(0))
        elif i == 'C':
            int_sequence.append(str(1))
        elif i == 'G':
            int_sequence.append(str(2))
        elif i == 'T':
            int_sequence.append(str(3))
    return ''.join(int_sequence)


def degminsec2dec(degrees, minutes, seconds):
    """
    convert a triple (int degrees, int minutes, float seconds) to
    a floating point number of degrees

    >>> assert dec2degminsec(degminsec2dec(30,30,0.0)) == (30,30,0.0)
    """
    dec = float(degrees)
    if minutes:
        dec += float(minutes) / 60
    if seconds:
        dec += float(seconds) / 3600
    return dec


@classmethod
def showcase_untrashed_deprecated_details(cls, val):
    """
        Create an instance of this class set to the
        ``showcase_untrashed_deprecated_details`` tag with value ``val``.

        :param ShowcaseUntrashedDeprecatedDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_untrashed_deprecated_details', val)


def bake():
    """Bake selected F-Curves to a set of sampled points defining a similar curve

    """
    pass


@classmethod
def preload_SAM(cls, h5_file, sites, tech, **kwargs):
    """
        Placeholder for classmethod that will pre-load project_points for SAM

        Parameters
        ----------
        h5_file : str
            h5_file to extract resource from
        sites : list
            List of sites to be provided to SAM
        tech : str
            Technology to be run by SAM
        kwargs : dict
            kwargs to init resource class
        """


def calc_wv_mixing_ratio(sounding, vapor_pressure):
    """
    Calculate water vapor mixing ratio
    """
    wv_mix_ratio = 1000.0 * (0.622 * vapor_pressure / (100.0 * sounding.
        pressure - vapor_pressure))
    return wv_mix_ratio


def make_loss(data=None, name=None, attr=None, out=None, **kwargs):
    """Make your own loss function in network construction.

    This operator accepts a customized loss function symbol as a terminal loss and
    the symbol should be an operator with no backward dependency.
    The output of this function is the gradient of loss with respect to the input data.

    For example, if you are a making a cross entropy loss function. Assume ``out`` is the
    predicted output and ``label`` is the true label, then the cross entropy can be defined as::

      cross_entropy = label * log(out) + (1 - label) * log(1 - out)
      loss = make_loss(cross_entropy)

    We will need to use ``make_loss`` when we are creating our own loss function or we want to
    combine multiple loss functions. Also we may want to stop some variables' gradients
    from backpropagation. See more detail in ``BlockGrad`` or ``stop_gradient``.

    The storage type of ``make_loss`` output depends upon the input storage type:

       - make_loss(default) = default
       - make_loss(row_sparse) = row_sparse

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L360

    Parameters
    ----------
    data : Symbol
        The input array.

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def differential_phase_filter(sdp, thresh_sdp=12):
    """
    Filter out gates with large standard deviations of differential phase.
    Note: thresh_sdp can be an array the same size as sdp.
    """
    return sdp > thresh_sdp


@staticmethod
def get_user_identifier(user_id=None, update=None):
    """Get telegram id of user given an update.

        Result itself may be passed as either parameter (for backward
            compatibility).
        """
    identifier = user_id or update
    assert identifier is not None, 'Provide a user_id or update object to get a user identifier.'
    if isinstance(identifier, dict
        ) and 'message' in identifier and 'from' not in identifier:
        identifier = identifier['message']
    if isinstance(identifier, dict) and 'from' in identifier:
        identifier = identifier['from']['id']
    assert type(identifier
        ) is int, f'Unable to find a user identifier. Got `{identifier}`'
    return identifier


def write(transaction, linkrev, p1node, p2node, added, removed, match=None):
    """Add this revision to storage.

        Takes a transaction object, the changeset revision number it will
        be associated with, its parent nodes, and lists of added and
        removed paths.

        If match is provided, storage can choose not to inspect or write out
        items that do not match. Storage is still required to be able to provide
        the full manifest in the future for any directories written (these
        manifests should not be "narrowed on disk").

        Returns the binary node of the created revision.
        """


def attach_object(DirectoryArn=None, ParentReference=None, ChildReference=
    None, LinkName=None):
    """
    Attaches an existing object to another object. An object can be accessed in two ways:
    See also: AWS API Documentation

    :example: response = client.attach_object(
        DirectoryArn='string',
        ParentReference={
            'Selector': 'string'
        },
        ChildReference={
            'Selector': 'string'
        },
        LinkName='string'
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more information, see arns .

    :type ParentReference: dict
    :param ParentReference: [REQUIRED]
            The parent object reference.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type ChildReference: dict
    :param ChildReference: [REQUIRED]
            The child object reference to be attached to the object.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type LinkName: string
    :param LinkName: [REQUIRED]
            The link name with which the child object is attached to the parent.

    :rtype: dict
    :return: {
        'AttachedObjectIdentifier': 'string'
    }

    :returns:
    DirectoryArn (string) -- [REQUIRED]
    Amazon Resource Name (ARN) that is associated with the  Directory where both objects reside. For more information, see  arns .

    ParentReference (dict) -- [REQUIRED]
    The parent object reference.

    Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:

    $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An objects identifier is immutable and no two objects will ever share the same object identifier
    /some/path - Identifies the object based on path
    #SomeBatchReference - Identifies the object in a batch call

    ChildReference (dict) -- [REQUIRED]
    The child object reference to be attached to the object.

    Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:

    $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An objects identifier is immutable and no two objects will ever share the same object identifier
    /some/path - Identifies the object based on path
    #SomeBatchReference - Identifies the object in a batch call

    LinkName (string) -- [REQUIRED]
    The link name with which the child object is attached to the parent.

    """
    pass


def first_of_year(date):
    """
    Returns a date representing the first day of whichever year ``date`` falls in.
    """
    return date.replace(month=1, day=1)


def add_double_page(writer, page_size, print_page):
    """ Adds a double page """
    width, height = page_size
    page = writer.insertBlankPage(width=width, height=height, index=writer.
        getNumPages())
    l_page = print_page.left.page
    if l_page is not None:
        page.mergePage(l_page)
    r_page = print_page.right.page
    if r_page is not None:
        page.mergeTranslatedPage(r_page, width / 2, 0)


def joinitems(itemiter, sep):
    """Join items with the separator; Returns generator of bytes"""
    first = True
    for x in itemiter:
        if first:
            first = False
        elif sep:
            yield sep
        yield x


@staticmethod
def run_ndctl_list_val(json_op, field):
    """
        Get the value of a field in given json

        :param json_op: Input Json object
        :param field: Field to find the value from json_op object

        :rtype: Found value type, None if not found
        """
    for key, value in json_op.items():
        if key == field:
            return value
    return None


def keyframe_insert_by_name(type='Type', confirm_success: bool=True):
    """Alternate access to ‘Insert Keyframe’ for keymaps to use

    :param confirm_success: Confirm Successful Insert, Show a popup when the keyframes get successfully added
    :type confirm_success: bool
    """
    pass


def identify_nested_items(complete_list):
    """Identify nested and non-nested two-element tuples in a list.

    :param complete_list: List of tuples that will be evaluated.
    :type complete_list: list
    :returns:
        tuple (not_nested_set, nested_set)
        WHERE
        not_nested_set(set) is a set of non-nested tuples.
        nested_set(set) is a set of nested tuples.
    :rtype: tuple
    """
    not_nested_set = set()
    nested_set = set()
    return not_nested_set, nested_set


def schedule(project, spider_name, **spider_args):
    """Schedule a spider for the given project"""


@classmethod
def check_type(cls, typestr):
    """
        Returns True if the typestr represents the class
        """
    return typestr == cls.MESSAGE_TYPE_ALIAS


@staticmethod
def delete_local_session(callback=None):
    """
        Deletes the local session.
        """
    if callback is not None:
        callback()


def _round_multiple(x: int, mult: int=None) ->int:
    """Calc `x` to nearest multiple of `mult`."""
    return int(x / mult + 0.5) * mult if mult is not None else x


@staticmethod
def _draw_graph_node(module, tpl):
    """Generates a Graphviz node named `module`."""
    import pydot
    return pydot.Node(module, margin='0', shape='none', label=tpl)


def FWHMeff2FWHMgeom(FWHMeff):
    """
    Convert FWHMeff to FWHMgeom.
    This conversion was calculated by Bo Xin and Zeljko Ivezic (and will be in an update on the LSE-40 and overview papers).
    @param [in] FWHMeff (the single-gaussian equivalent FWHM value, appropriate for calcNeff) in arcseconds
    @param [out] FWHMgeom (the geometric FWHM value, as measured from a typical PSF profile) in arcseconds
    """
    FWHMgeom = 0.822 * FWHMeff + 0.052
    return FWHMgeom


def bake_from_cache():
    """Bake from cache

    """
    pass


def ema(series, n):
    """
    指数加权移动平均线: 求series序列n周期的指数加权移动平均

        计算公式:
            ema(x, n) = 2 * x / (n + 1) + (n - 1) * ema(x, n).shift(1) / (n + 1)

        注意:
            1. n 需大于等于1
            2. 对距离当前较近的k线赋予了较大的权重

    Args:
        series (pandas.Series): 数据序列

        n (int): 周期

    Returns:
        pandas.Series: 指数加权移动平均线序列

    Example::

        from tqsdk import TqApi, TqSim, tafunc

        api = TqApi(TqSim())
        klines = api.get_kline_serial("CFFEX.IF1908", 24 * 60 * 60)
        ema = tafunc.ema(klines.close, 5)
        print(list(ema))
    """
    ema_data = series.ewm(span=n, adjust=False).mean()
    return ema_data


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def register_handler(handler):
    """
    Install application-specific WMF image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


@classmethod
def file_transfers_transfer_send_details(cls, val):
    """
        Create an instance of this class set to the
        ``file_transfers_transfer_send_details`` tag with value ``val``.

        :param FileTransfersTransferSendDetails val:
        :rtype: EventDetails
        """
    return cls('file_transfers_transfer_send_details', val)


def _to_public_key(obj):
    """Convert obj a PublicKey object."""
    from .keys import PublicKey
    if isinstance(obj, PublicKey):
        return obj
    if isinstance(obj, str):
        return PublicKey.from_hex(obj)
    return PublicKey.from_bytes(obj)


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
            "properties": {
                "data": {
                    "properties": {
                        "user": {
                            "properties": {
                                "entities": {
                                    "dynamic":false,
                                    "properties": {}
                                }
                            }
                        },
                        "hashtags": {
                            "properties": {
                                "indices": {
                                    "dynamic":false,
                                    "properties": {}
                                }
                            }
                        },
                        "metadata": {
                            "dynamic":false,
                            "properties": {}
                        },
                        "entities": {
                            "properties": {
                                "media": {
                                    "dynamic":false,
                                    "properties": {}
                                },
                                "symbols": {
                                    "dynamic":false,
                                    "properties": {}
                                },
                                "urls": {
                                    "dynamic":false,
                                    "properties": {}
                                },
                                "user_mentions": {
                                    "dynamic":false,
                                    "properties": {}
                                }
                            }
                        },
                        "extended_entities": {
                            "dynamic":false,
                            "properties": {}
                        },
                        "extended_tweet": {
                            "dynamic":false,
                            "properties": {}
                        },
                        "quoted_status": {
                            "dynamic":false,
                            "properties": {}
                        },
                        "retweeted_status": {
                            "dynamic":false,
                            "properties": {}
                        }
                    }
                }
            }
        }
        """
    return {'items': mapping}


def is_aware(timestamp):
    """
    Check whether timestamp is timezone aware

    :param timestamp: :py:class:`datetime.datetime`
    :return: ``True``, if timestamp is tz-aware
    """
    return timestamp.tzinfo is not None and timestamp.tzinfo.utcoffset(
        timestamp) is not None


def green(text):
    """ Return this text formatted green """
    return '\x0303%s\x03' % text


def decode_key(key):
    """return a tuple containing the field and the wire type"""
    return key >> 3, key & 7