def get_mag_ff(atomic_number, q, ion=0, j=0):
    """Returns the j0 magnetic form factor for a given atomic number,
    radiation and q values

    :param atomic_number: atomic number
    :type atomic_number: int
    :param q: value or values of q for which to get form factors
    :type q: float, list, :class:`numpy.ndarray`
    :param ion: charge of selected atom
    :type ion: int
    :param j: order of spherical Bessel function (0, 2, 4 or 6)
    :type j: int
    :return: magnetic form factor for given q
    :rtype: float, :class:`numpy.ndarray`

    :Examples:

    >>> get_mag_ff(8, q=2, ion=1)
    0.58510426376585045

    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=2)
    array([ 1.        ,  0.49729671,  0.09979243])

    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4)
    array([ 0.9997    ,  0.58273549,  0.13948496])

    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4, j=4)
    array([ 0.       ,  0.0149604,  0.0759222])
    """
    import periodictable
    return getattr(periodictable.elements[atomic_number].magnetic_ff[ion],
        'j' + str(j) + '_Q')(q)


@classmethod
def from_yaml(cls, s, **kwargs):
    """
        Load and decode YAML data from url, filepath or data-string.
        Decoder specific options can be passed using kwargs:
        https://pyyaml.org/wiki/PyYAMLDocumentation
        Return a new dict instance. A ValueError is raised in case of failure.
        """
    return cls(s, format='yaml', **kwargs)


def _load_model(name):
    """Load a model class from the SDK in order to inspect for
    parameter names and whether they're required.
    :param str name: The model class name to load.
    :returns: Model class
    """
    if name.startswith('azure.'):
        namespace = name.split('.')
    else:
        namespace = ['azure', 'batch', 'models', name]
    model = __import__(namespace[0])
    for level in namespace[1:]:
        model = getattr(model, level)
    return model


def _validate_list(s, accept_none=False):
    """
	A validation method to convert input s to a list or raise error if it is not convertable
	"""
    if s is None and accept_none:
        return None
    try:
        return list(s)
    except ValueError:
        raise ValueError('Could not convert input to list')


@classmethod
def get_oauthlib_core(cls):
    """
        Cache and return `OAuthlibCore` instance so it will be created only on first request
        """
    if not hasattr(cls, '_oauthlib_core'):
        server = cls.get_server()
        core_class = cls.get_oauthlib_backend_class()
        cls._oauthlib_core = core_class(server)
    return cls._oauthlib_core


def _install_file(name_in, name_out, patches):
    """ Install a file and return a copy of its contents. """
    with open(name_in) as f:
        data = f.read()
    for patch_name, patch in patches.items():
        data = data.replace(patch_name, patch)
    with open(name_out, 'w') as f:
        f.write(data)
    return data


@classmethod
def taropen(cls, name, mode='r', fileobj=None, **kwargs):
    """Open uncompressed tar archive name for reading or writing.
        """
    if len(mode) > 1 or mode not in 'raw':
        raise ValueError("mode must be 'r', 'a' or 'w'")
    return cls(name, mode, fileobj, **kwargs)


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 parse_debug_value(value):
    """Resolve the given string value to a debug option.

    Can be used to deal with os environment variables, for example.
    """
    if value is None:
        return value
    value = value.lower()
    if value in ('true', '1'):
        return True
    elif value in ('false', '0'):
        return False
    elif value in ('merge',):
        return 'merge'
    else:
        raise ValueError()


def __delitem__(oid):
    """ Remove the persistent object for OID.

        o 'oid' must be a string, else raise ValueError.

        o Raise KeyError if not found.
        """


def convertbits(data, frombits, tobits, pad=True):
    """General power-of-2 base conversion."""
    acc = 0
    bits = 0
    ret = []
    maxv = (1 << tobits) - 1
    max_acc = (1 << frombits + tobits - 1) - 1
    for value in data:
        if value < 0 or value >> frombits:
            return None
        acc = (acc << frombits | value) & max_acc
        bits += frombits
        while bits >= tobits:
            bits -= tobits
            ret.append(acc >> bits & maxv)
    if pad:
        if bits:
            ret.append(acc << tobits - bits & maxv)
    elif bits >= frombits or acc << tobits - bits & maxv:
        return None
    return ret


def tile_region(rname, start, end, step):
    """ Make non-overlapping tiled windows from the specified region in
    the UCSC-style string format.

    >>> list(tile_region('chr1', 1, 250, 100))
    ['chr1:1-100', 'chr1:101-200', 'chr1:201-250']
    >>> list(tile_region('chr1', 1, 200, 100))
    ['chr1:1-100', 'chr1:101-200']
    """
    while start + step <= end:
        yield '%s:%d-%d' % (rname, start, start + step - 1)
        start += step
    if start < end:
        yield '%s:%d-%d' % (rname, start, end)


def read_yaml_config(path):
    """Read file content from path"""
    try:
        with open(path) as f:
            return f.read()
    except IOError:
        pass


def _get_is_hypothesis(stmt):
    """Returns true if there is evidence that the statement is only
    hypothetical. If all of the evidences associated with the statement
    indicate a hypothetical interaction then we assume the interaction
    is hypothetical."""
    for ev in stmt.evidence:
        if not ev.epistemics.get('hypothesis') is True:
            return True
    return False


def model_with_weights(model, weights, skip_mismatch):
    """ Load weights for model.

    Args
        model         : The model to load weights for.
        weights       : The weights to load.
        skip_mismatch : If True, skips layers whose shape of weights doesn't match with the model.
    """
    if weights is not None:
        model.load_weights(weights, by_name=True, skip_mismatch=skip_mismatch)
    return model


def first(predicate_or_None, iterable, default=None):
    """
    Returns the first item of iterable for which predicate(item) is true.
    If predicate is None, matches the first item that is true.
    Returns value of default in case of no matching items.
    """
    return next(filter(predicate_or_None, iterable), default)


@classmethod
def from_code_and_minor(cls, currency_code, value):
    """
        Initialises the amount with a currency code and an integer value
        of minor units
        """
    from .currency import currencies
    try:
        return cls(currencies[currency_code.upper()], value)
    except KeyError:
        raise ValueError('Invalid currency code %s' % currency_code)


def yes_no(message):
    """ Simple prompt parser"""
    yes = set(['yes', 'ye', 'y', ''])
    no = set(['no', 'n'])
    print(message)
    while True:
        answer = input('Would you like to continue? [y/n] ').lower()
        if answer in yes:
            return True
        elif answer in no:
            return False
        else:
            print('Please answer "Yes" or "No"')


@staticmethod
def prime_product_from_hand(card_ints):
    """
        Expects a list of cards in integer form.
        """
    product = 1
    for c in card_ints:
        product *= c & 255
    return product


def getBuild(number):
    """Return an IBuildStatus object for a historical build. Each build
        is numbered (starting at 0 when the Builder is first added),
        getBuild(n) will retrieve the Nth such build. getBuild(-n) will
        retrieve a recent build, with -1 being the most recent build
        started. If the Builder is idle, this will be the same as
        getLastFinishedBuild(). If the Builder is active, it will be an
        unfinished build. This method will return None if the build is no
        longer available. Older builds are likely to have less information
        stored: Logs are the first to go, then Steps."""


def antenna_metrics_hourly_query(table_name='%(table_name)s'):
    """
    Further aggregate user event counts by the hour of the day, therefore
    ignoring the day and week. Most importantly aggregate up to the
    antenna level for all users who are predicted to live inside an
    antennas coverage (home antenna).

    Inputs
    ------
    table_name : name of the table the query is supposed to run on,
                 defaulting to '%(table_name)s', i.e. no substitution

    Output
    ------
    Hourly antenna level aggregates of event counts,
    no more user ids.
    """
    query = """
        SELECT
          antenna_id,
          hour,
          SUM(og_sms) as og_sms,
          SUM(ic_sms) as ic_sms,
          SUM(og_calls) as og_calls,
          SUM(ic_calls) as ic_calls,
          SUM(og_vol) as og_vol,
          SUM(ic_vol) as ic_vol
        FROM %(table_name)s um
        JOIN table_user_home_antenna_df uha
        ON um.user_id = uha.user_id
        GROUP BY antenna_id, hour
    """
    return query % {'table_name': table_name}


def list_exploded(client, file_=None, name=None):
    """List views that match criteria and are exploded.

    Args:
        client (obj):
            creopyson Client.
        `file_` (str, optional):
            Model name. Defaults is current active model.
        name (str, optional):
            View name (wildcards allowed: True).
            Defaults is None: all views are listed.

    Returns:
        (list:str): List of view names.

    """
    data = {}
    if name is not None:
        data['name'] = name
    if file_ is not None:
        data['file'] = file_
    else:
        active_file = client.file_get_active()
        if active_file is not None:
            data['file'] = active_file['file']
    return client._creoson_post('view', 'list_exploded', data, 'viewlist')


def update_campaign(ApplicationId=None, CampaignId=None,
    WriteCampaignRequest=None):
    """
    Use to update a campaign.

    :example: response = client.update_campaign(
        ApplicationId='string',
        CampaignId='string',
        WriteCampaignRequest={
            'AdditionalTreatments': [
                {
                    'MessageConfiguration': {
                        'APNSMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'DefaultMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'GCMMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        }
                    },
                    'Schedule': {
                        'EndTime': 'string',
                        'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                        'IsLocalTime': True|False,
                        'QuietTime': {
                            'End': 'string',
                            'Start': 'string'
                        },
                        'StartTime': 'string',
                        'Timezone': 'string'
                    },
                    'SizePercent': 123,
                    'TreatmentDescription': 'string',
                    'TreatmentName': 'string'
                },
            ],
            'Description': 'string',
            'HoldoutPercent': 123,
            'IsPaused': True|False,
            'Limits': {
                'Daily': 123,
                'Total': 123
            },
            'MessageConfiguration': {
                'APNSMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'DefaultMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'GCMMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                }
            },
            'Name': 'string',
            'Schedule': {
                'EndTime': 'string',
                'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                'IsLocalTime': True|False,
                'QuietTime': {
                    'End': 'string',
                    'Start': 'string'
                },
                'StartTime': 'string',
                'Timezone': 'string'
            },
            'SegmentId': 'string',
            'SegmentVersion': 123,
            'TreatmentDescription': 'string',
            'TreatmentName': 'string'
        }
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :type CampaignId: string
    :param CampaignId: [REQUIRED]

    :type WriteCampaignRequest: dict
    :param WriteCampaignRequest: [REQUIRED] Used to create a campaign.
            AdditionalTreatments (list) -- Treatments that are defined in addition to the default treatment.
            (dict) -- Used to create a campaign treatment.
            MessageConfiguration (dict) -- The message configuration settings.
            APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.
            DefaultMessage (dict) -- The default message for all channels.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.
            GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

            Schedule (dict) -- The campaign schedule.
            EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
            Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
            IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
            QuietTime (dict) -- The time during which the campaign sends no messages.
            End (string) -- The default end time for quiet time in ISO 8601 format.
            Start (string) -- The default start time for quiet time in ISO 8601 format.
            StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
            Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11
            SizePercent (integer) -- The allocated percentage of users for this treatment.
            TreatmentDescription (string) -- A custom description for the treatment.
            TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.

            Description (string) -- A description of the campaign.
            HoldoutPercent (integer) -- The allocated percentage of end users who will not receive messages from this campaign.
            IsPaused (boolean) -- Indicates whether the campaign is paused. A paused campaign does not send messages unless you resume it by setting IsPaused to false.
            Limits (dict) -- The campaign limits settings.
            Daily (integer) -- The maximum number of messages that the campaign can send daily.
            Total (integer) -- The maximum total number of messages that the campaign can send.
            MessageConfiguration (dict) -- The message configuration settings.
            APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.
            DefaultMessage (dict) -- The default message for all channels.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.
            GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
            Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP   Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK   Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL   The default mobile browser on the user's device launches and opens a web page at the URL you specify.
            Body (string) -- The message body. Can include up to 140 characters.
            ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
            ImageUrl (string) -- The URL that points to an image used in the push notification.
            JsonBody (string) -- The JSON payload used for a silent push.
            MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
            SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
            Title (string) -- The message title that displays above the message on the user's device.
            Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

            Name (string) -- The custom name of the campaign.
            Schedule (dict) -- The campaign schedule.
            EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
            Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
            IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
            QuietTime (dict) -- The time during which the campaign sends no messages.
            End (string) -- The default end time for quiet time in ISO 8601 format.
            Start (string) -- The default start time for quiet time in ISO 8601 format.
            StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
            Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11
            SegmentId (string) -- The ID of the segment to which the campaign sends messages.
            SegmentVersion (integer) -- The version of the segment to which the campaign sends messages.
            TreatmentDescription (string) -- A custom description for the treatment.
            TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.

    :rtype: dict
    :return: {
        'CampaignResponse': {
            'AdditionalTreatments': [
                {
                    'Id': 'string',
                    'MessageConfiguration': {
                        'APNSMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'DefaultMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        },
                        'GCMMessage': {
                            'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                            'Body': 'string',
                            'ImageIconUrl': 'string',
                            'ImageUrl': 'string',
                            'JsonBody': 'string',
                            'MediaUrl': 'string',
                            'SilentPush': True|False,
                            'Title': 'string',
                            'Url': 'string'
                        }
                    },
                    'Schedule': {
                        'EndTime': 'string',
                        'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                        'IsLocalTime': True|False,
                        'QuietTime': {
                            'End': 'string',
                            'Start': 'string'
                        },
                        'StartTime': 'string',
                        'Timezone': 'string'
                    },
                    'SizePercent': 123,
                    'State': {
                        'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
                    },
                    'TreatmentDescription': 'string',
                    'TreatmentName': 'string'
                },
            ],
            'ApplicationId': 'string',
            'CreationDate': 'string',
            'DefaultState': {
                'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
            },
            'Description': 'string',
            'HoldoutPercent': 123,
            'Id': 'string',
            'IsPaused': True|False,
            'LastModifiedDate': 'string',
            'Limits': {
                'Daily': 123,
                'Total': 123
            },
            'MessageConfiguration': {
                'APNSMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'DefaultMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                },
                'GCMMessage': {
                    'Action': 'OPEN_APP'|'DEEP_LINK'|'URL',
                    'Body': 'string',
                    'ImageIconUrl': 'string',
                    'ImageUrl': 'string',
                    'JsonBody': 'string',
                    'MediaUrl': 'string',
                    'SilentPush': True|False,
                    'Title': 'string',
                    'Url': 'string'
                }
            },
            'Name': 'string',
            'Schedule': {
                'EndTime': 'string',
                'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY',
                'IsLocalTime': True|False,
                'QuietTime': {
                    'End': 'string',
                    'Start': 'string'
                },
                'StartTime': 'string',
                'Timezone': 'string'
            },
            'SegmentId': 'string',
            'SegmentVersion': 123,
            'State': {
                'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED'
            },
            'TreatmentDescription': 'string',
            'TreatmentName': 'string',
            'Version': 123
        }
    }

    :returns:
    (dict) -- 200 response
    CampaignResponse (dict) -- Campaign definition
    AdditionalTreatments (list) -- Treatments that are defined in addition to the default treatment.
    (dict) -- Treatment resource
    Id (string) -- The unique treatment ID.
    MessageConfiguration (dict) -- The message configuration settings.
    APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    DefaultMessage (dict) -- The default message for all channels.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    Schedule (dict) -- The campaign schedule.
    EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
    Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
    IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
    QuietTime (dict) -- The time during which the campaign sends no messages.
    End (string) -- The default end time for quiet time in ISO 8601 format.
    Start (string) -- The default start time for quiet time in ISO 8601 format.

    StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
    Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11

    SizePercent (integer) -- The allocated percentage of users for this treatment.
    State (dict) -- The treatment status.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    TreatmentDescription (string) -- A custom description for the treatment.
    TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.

    ApplicationId (string) -- The ID of the application to which the campaign applies.
    CreationDate (string) -- The date the campaign was created in ISO 8601 format.
    DefaultState (dict) -- The status of the campaign's default treatment. Only present for A/B test campaigns.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    Description (string) -- A description of the campaign.
    HoldoutPercent (integer) -- The allocated percentage of end users who will not receive messages from this campaign.
    Id (string) -- The unique campaign ID.
    IsPaused (boolean) -- Indicates whether the campaign is paused. A paused campaign does not send messages unless you resume it by setting IsPaused to false.
    LastModifiedDate (string) -- The date the campaign was last updated in ISO 8601 format.
    Limits (dict) -- The campaign limits settings.
    Daily (integer) -- The maximum number of messages that the campaign can send daily.
    Total (integer) -- The maximum total number of messages that the campaign can send.

    MessageConfiguration (dict) -- The message configuration settings.
    APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    DefaultMessage (dict) -- The default message for all channels.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message.
    Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP  Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK  Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL  The default mobile browser on the user's device launches and opens a web page at the URL you specify.
    Body (string) -- The message body. Can include up to 140 characters.
    ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon.
    ImageUrl (string) -- The URL that points to an image used in the push notification.
    JsonBody (string) -- The JSON payload used for a silent push.
    MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file.
    SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases.
    Title (string) -- The message title that displays above the message on the user's device.
    Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL.

    Name (string) -- The custom name of the campaign.
    Schedule (dict) -- The campaign schedule.
    EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format.
    Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY
    IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time.
    QuietTime (dict) -- The time during which the campaign sends no messages.
    End (string) -- The default end time for quiet time in ISO 8601 format.
    Start (string) -- The default start time for quiet time in ISO 8601 format.

    StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format.
    Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11

    SegmentId (string) -- The ID of the segment to which the campaign sends messages.
    SegmentVersion (integer) -- The version of the segment to which the campaign sends messages.
    State (dict) -- The campaign status. An A/B test campaign will have a status of COMPLETED only when all treatments have a status of COMPLETED.
    CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED

    TreatmentDescription (string) -- A custom description for the treatment.
    TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing.
    Version (integer) -- The campaign version number.

    """
    pass


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


@classmethod
def _from_version_string(cls, s):
    """
        Parse *s* and return a _VersionInfo.
        """
    v = s.split('.')
    if len(v) == 3:
        v.append('final')
    return cls(year=int(v[0]), minor=int(v[1]), micro=int(v[2]),
        releaselevel=v[3])


@staticmethod
def dva2ret(xdva):
    """Convert degrees of visual angle (dva) to retinal eccentricity (um)

        Assumes that one degree of visual angle is equal to 280 um on the
        retina [Curcio1990]_.
        """
    return 280.0 * xdva


def wrap_list(list_, idx):
    """Return value at index, wrapping if necessary.

    Parameters
    ----------
    list_ : :class:`list`
        List to wrap around.
    idx : :class:`int`
        Index of item to return in list.

    Returns
    -------
    :class:`list` element
        Item at given index, index will be wrapped if necessary.
    """
    return list_[idx % len(list_)]


def getlocals(back=2):
    """Get the local variables some levels back (-1 is top)."""
    import inspect
    fr = inspect.currentframe()
    try:
        while fr and back != 0:
            fr1 = fr
            fr = fr.f_back
            back -= 1
    except:
        pass
    return fr1.f_locals


@classmethod
def set_validlocations(cls, locations):
    """
        Set valid locations using list of dictionaries of form {'name': 'zmb', 'title', 'Zambia'}

        Args:
            locations (List[Dict]): List of dictionaries of form {'name': 'zmb', 'title', 'Zambia'}

        Returns:
            None
        """
    cls._validlocations = locations


@classmethod
def from_array(cls, array, **kwargs):
    """
        Construct a Kernel weights from an array. Supports all the same options
        as :class:`libpysal.weights.Kernel`

        See Also
        --------
        :class:`libpysal.weights.weights.W`
        """
    return cls(array, **kwargs)


def recategorise(_df, _cat_type, _cols, _map=None):
    """
    A Convenience function to re-categorise the columns in the dataframe: the operation is performed in place. Note that
    the function allows mapping of categorical type with no overlaps through the _map construct.

    :param _df:         Data-Frame to recategorise
    :param _cat_type:   Categorical DType to set
    :param _cols:       The columns to change
    :param _map:        If need be, map certain values to others before recategorising: values which are not mapped
                        and which appear in the data but not in the new label-set (CDType) will be turned into NaN
    :return:            None (operation done in place)
    """
    if _map is not None:
        for col in _cols:
            _df.loc[:, (col)] = _df[col].map(_map)
            _df.loc[:, (col)] = _df[col].astype(float, copy=False).astype(
                _cat_type)
    else:
        for col in _cols:
            _df.loc[:, (col)] = _df[col].astype(float, copy=False).astype(
                _cat_type)


def getdeepattr(d, keys, default_value=None):
    """
    Similar to the built-in `getattr`, this function accepts a list/tuple of keys to get a value deep in a `dict`

    Given the following dict structure

    .. code-block:: python

        d = {
          'A': {
            '0': {
              'a': 1,
              'b': 2,
            }
          },
        }

    Calling `getdeepattr` with a key path to a value deep in the structure will return that value. If the value or any
    of the objects in the key path do not exist, then the default value is returned.

    .. code-block:: python

        assert 1 == getdeepattr(d, ('A', '0', 'a'))
        assert 2 == getdeepattr(d, ('A', '0', 'b'))
        assert 0 == getdeepattr(d, ('A', '0', 'c'), default_value=0)
        assert 0 == getdeepattr(d, ('X', '0', 'a'), default_value=0)

    :param d:
        A dict value with nested dict attributes.
    :param keys:
        A list/tuple path of keys in `d` to the desired value
    :param default_value:
        A default value that will be returned if the path `keys` does not yield a value.
    :return:
        The value following the path `keys` or `default_value`
    """
    d_level = d
    for key in keys:
        if isinstance(d_level, dict) and key not in d_level or not hasattr(
            d_level, key):
            return default_value
        d_level = d_level[key]
    return d_level


@staticmethod
def generate_notes(notes):
    """
        Generate the notes list

        :param dict notes: A dict of converted notes from the old topology
        :return: List of notes for the the topology
        :rtype: list
        """
    new_notes = []
    for note in notes:
        tmp_note = {}
        for note_item in notes[note]:
            tmp_note[note_item] = notes[note][note_item]
        new_notes.append(tmp_note)
    return new_notes


def region_quadview():
    """Split selected area into camera, front, right & top views

    """
    pass


@classmethod
def _more_events(cls, series, date_data):
    """Returns True if more events exist in this series after ``date_data``.

        :Example:

        If the series included a recurrence for an event five times, and
        ``series.events`` contained only three events, this would return True.

        :Example:

        If the series started on Jan 1 and recurred weekly until Feb 1, and
        date_data represented Jan 29, this would return False, because the next
        event in the series would be after the end of the recurrence.

        :param series: The event series in question
        :type series: :class:`EventSeries`
        :param dict date_data: The reference date.

        :returns: True if there are more events in the series.
        :rtype: bool.
        """
    if series.ends_after and len(series.events
        ) >= series.num_occurrences or series.ends_on and date_data[
        'start_date'] > series.recurrence_end_date:
        return False
    return True


def kill_process(process) ->None:
    """
    Simply kills the process passed as a parameter
    :param process: executing process
    """
    process.kill()


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


@classmethod
def from_dict(cls, connector, ip_dict):
    """Build dict fields as SubObjects if needed.

        Checks if lambda for building object from dict exists.
        _global_field_processing and _custom_field_processing rules
        are checked.
        """
    mapping = cls._global_field_processing.copy()
    mapping.update(cls._custom_field_processing)
    for field in mapping:
        if field in ip_dict:
            ip_dict[field] = mapping[field](ip_dict[field])
    return cls(connector, **ip_dict)


def number(token):
    """
        Convert string number to Python integer
        """
    return int(token, 0)


def ohms2mV_km_nT(zs):
    """Convert imp. tensor(s) from ohms to mV/km/nT."""
    return zs * 796.0


def filter_output(output, filtered):
    """ Filters out characters from output """
    for char in filtered:
        output = output.replace(char, '')
    return output


def list_hierarchy_object(obj):
    """Returns objet list of hierarchy."""


def squish(r, axis):
    """
    Squish array along an axis.

    Determine the sum along all but one axis for an array.

    Parameters
    ----------
    r : ndarray
        Array to squish.
    axis : int
        Axis of r to squish along.

    Returns
    -------
    s : 1D ndarray
        Array r squished into a single dimension.

    """
    N = int(r.ndim)
    r = r.swapaxes(axis, N - 1)
    for i in range(N - 1):
        r = r.sum(0)
    return r


@staticmethod
def kruskal_time_complexity():
    """
        Return time complexity of kruskal
        :return: string
        """
    return (
        'Worst case: O(E log(V)) where E in the number of edges and V the number of vertexes'
        )


def axis_to_dispaxis(axis):
    """Obtain the dispersion axis from the spatial axis."""
    if axis == 0:
        dispaxis = 1
    elif axis == 1:
        dispaxis = 0
    else:
        raise ValueError("'axis' must be 0 or 1")
    return dispaxis


@classmethod
def get_html_template(cls):
    """Create a generic angular HTML template for configuring the
        vendor's login from the settings information.
        """
    template = """
        	<fieldset>
            """
    sinfo = cls.info.get('angular', {})
    settings = cls.info.get('settings', [])
    for setting in settings:
        info = sinfo.get(setting, {})
        label = info.get('label', setting)
        placeholder = info.get('placeholder', label)
        htype = info.get('type', 'text')
        template += (
            """

        			%s

        			  <input required type="%s" class="form-control"
        			  		id="username" placeholder="%s"
        					ng-model="v.settings.%s">

            """
             % (setting, label, htype, placeholder, setting))
    template += """
        	</fieldset>
        """
    return template


@staticmethod
def unpack_subitems(value):
    """Yields None, cannot unpack subitems"""
    yield None


def _donothing_func(*args, **kwargs):
    """Perform no good and no bad"""
    pass


def extract_x_y(message):
    """
    Extracts features & target from `message['data']` with expected structure such as :
        1. tuple - (x,y)
        2. dict - {'x':x_data,'y':y_data}

    Handle data structures of dictionary to extract features & target
    """
    if type(message['data']) == tuple:
        x = message['data'][0]
        y = message['data'][1]
    elif type(message['data']) == dict:
        x = message['data']['x']
        y = message['data']['y']
    else:
        return -1
    return x, y


def get_dataset_hashtags(client, dataset):
    """Get dataset information.

	Args:
	    :client: the pyAMI client [ pyAMI.client.Client ]
	    :dataset: the dataset [ str ]

	Returns:
	    a python dictionnaries.
	"""
    command = ['DatasetWBListHashtags', '-ldn="%s"' % dataset]
    return client.execute(command, format='dom_object').get_rows()


def _cached_call(cache, estimator, method, *args, **kwargs):
    """Call estimator with method and args and kwargs."""
    if cache is None:
        return getattr(estimator, method)(*args, **kwargs)
    try:
        return cache[method]
    except KeyError:
        result = getattr(estimator, method)(*args, **kwargs)
        cache[method] = result
        return result


def remove_states(sys, dE):
    """
    Remove the states with energy dE larger than the ground state
    for the transport calculations.

    Parameters
    ----------
    sys : Approach, Approach2vN, or Builder
        The system given as Approach, Approach2vN, or Builder object.
    dE : float
        Energy above the ground state.

    Modifies:
    sys.si.statesdm : list
        List containing indices of many-body state under consideration.
    """
    Emax = min(sys.qd.Ea) + dE
    statesdm = [[] for i in range(sys.si.nsingle + 1)]
    for charge in range(sys.si.ncharge):
        for b in sys.si.chargelst[charge]:
            if sys.qd.Ea[b] < Emax:
                statesdm[charge].append(b)
    sys.si.set_statesdm(statesdm)


def url_join(*fragments):
    """ Join fragments of a URL, dealing with slashes."""
    if len(fragments) == 0:
        return ''
    buff = []
    for fragment in fragments:
        stripped = fragment.strip('/')
        if len(stripped) > 0:
            buff.append(stripped)
            buff.append('/')
    last = fragments[-1]
    if len(last) > 0 and last[-1] != '/':
        buff.pop()
    return ''.join(buff)


def dump(obj, prefix=''):
    """Utility function to print to standard output a generic object with all its attributes."""
    print('{} {}.{} : {}'.format(prefix, obj.__module__, obj.__class__.
        __name__, obj.__dict__))


def instance(cls):
    """Create a new instance of a class.

    Parameters
    ----------
    cls : type
        The class to create an instance of.

    Returns
    -------
    instance : cls
        A new instance of ``cls``.
    """
    return cls()


def _sum_piece(wavelength, compound):
    """
    Helper for neutron_composite_sld which precomputes quantities of interest
    for material fragments in a composite formula.
    """
    molar_mass = num_atoms = 0
    sigma_a = sigma_s = b_c = 0
    is_energy_dependent = False
    for element, quantity in compound.atoms.items():
        molar_mass += element.mass * quantity
        num_atoms += quantity
        sigma_a += quantity * element.neutron.absorption
        sigma_s += quantity * element.neutron.total
        b_c += quantity * element.neutron.b_c
        is_energy_dependent |= element.neutron.is_energy_dependent
    return num_atoms, molar_mass, b_c, sigma_s, sigma_a


@staticmethod
def compress(data, compresslevel=0):
    """Get two params, data, and compresslevel. Method only return data."""
    return data


def cat_arrays(vector_arrays):
    """Return a new |VectorArray| which is a concatenation of the arrays in `vector_arrays`."""
    vector_arrays = list(vector_arrays)
    total_length = sum(map(len, vector_arrays))
    cated_arrays = vector_arrays[0].empty(reserve=total_length)
    for a in vector_arrays:
        cated_arrays.append(a)
    return cated_arrays


def VShadowPathSpecGetStoreIndex(path_spec):
    """Retrieves the store index from the path specification.

  Args:
    path_spec (PathSpec): path specification.

  Returns:
    int: store index or None if not available.
  """
    store_index = getattr(path_spec, 'store_index', None)
    if store_index is None:
        location = getattr(path_spec, 'location', None)
        if location is None or not location.startswith('/vss'):
            return None
        store_index = None
        try:
            store_index = int(location[4:], 10) - 1
        except (TypeError, ValueError):
            pass
        if store_index is None or store_index < 0:
            return None
    return store_index


def is_closed(socket_):
    """Determine if a socket is closed.

    This uses the associated file descriptor as a proxy for "closed".

    Args:
        socket_ (socket.socket): The socket to check.

    Returns:
        bool: Indicates if closed or open.
    """
    return socket_.fileno() == -1


def get_iface_name(enode, netname):
    """
    Get interface name inside a container

    This function will figure out the interface name inside the container for
    a given docker network.

    :param enode: The platform ("engine") node to get the iface name from.
    :param str netname: The name of the docker network to which the interface
                        we're looking for is connected.
    """
    docker_netconf = enode._client.inspect_container(enode.container_id)[
        'NetworkSettings']['Networks'][netname]
    ifaces_conf = enode._docker_exec('ip -o link list').strip().split('\n')
    for iface_conf in ifaces_conf:
        if docker_netconf['MacAddress'] in iface_conf:
            iface = iface_conf.split(': ')[1].split('@')[0]
            break
    else:
        raise RuntimeError(
            'Unable to find interface with MAC address {docker_netconf[MacAddress]} in netns {netns} in container {enode._container_id} with name {enode._container_name}'
            .format(**locals()))
    return iface


def run_script(script_name, namespace):
    """Execute the named script in the supplied namespace dictionary"""


def hidedot():
    """Toggle hide hidden dot files

    """
    pass


def create_alias(FunctionName=None, Name=None, FunctionVersion=None,
    Description=None):
    """
    Creates an alias that points to the specified Lambda function version. For more information, see Introduction to AWS Lambda Aliases .
    Alias names are unique for a given function. This requires permission for the lambda:CreateAlias action.
    See also: AWS API Documentation

    :example: response = client.create_alias(
        FunctionName='string',
        Name='string',
        FunctionVersion='string',
        Description='string'
    )

    :type FunctionName: string
    :param FunctionName: [REQUIRED]
            Name of the Lambda function for which you want to create an alias. Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length.

    :type Name: string
    :param Name: [REQUIRED]
            Name for the alias you are creating.

    :type FunctionVersion: string
    :param FunctionVersion: [REQUIRED]
            Lambda function version for which you are creating the alias.

    :type Description: string
    :param Description: Description of the alias.

    :rtype: dict
    :return: {
        'AliasArn': 'string',
        'Name': 'string',
        'FunctionVersion': 'string',
        'Description': 'string'
    }

    """
    pass


def get_domain(request):
    """
    Get the domain name parsed from a hostname:port string

    >>> class FakeRequest(object):
    ...     def __init__(self, url):
    ...         self.url = url
    ...     def get_host(self):
    ...         return self.url
    >>> req = FakeRequest("example.com:5984")
    >>> get_domain(req)
    'example.com'
    """
    return request.get_host().split(':')[0]


def log(text, array=None):
    """Prints a text message. And, optionally, if a Numpy array is provided it
    prints it's shape, min, and max values.
    """
    if array is not None:
        text = text.ljust(25)
        text += 'shape: {:20}  '.format(str(array.shape))
        if array.size:
            text += 'min: {:10.5f}  max: {:10.5f}'.format(array.min(),
                array.max())
        else:
            text += 'min: {:10}  max: {:10}'.format('', '')
        text += '  {}'.format(array.dtype)
    print(text)


def check_cutoff_value(criterion, cutoff_value):
    """Validate single cutoff value from config file."""
    if criterion == 'lognorm':
        if cutoff_value > 0 and cutoff_value < 1:
            pass
        else:
            exit(
                'Invalid lognorm quantile cutoff value "{}". The cutoffs must be numbers greater than 0 and less than 1.'
                .format(cutoff_value))
    elif criterion == 'mean':
        if cutoff_value > 1:
            pass
        elif cutoff_value > 0 and cutoff_value < 1:
            print(
                'WARNING: cutoff value "{}" is less than 1 mean. Did you intend to specify "lognorm" as criterion?'
                .format(cutoff_value))
        elif cutoff_value < 0:
            exit(
                'Invalid mean cutoff value "{}". Cutoffs must be greater than 0.'
                )


def highlightSubsequence(sequence, x1, x2, start=' [', stop='] '):
    """returns a sequence where the subsequence in [x1, x2[ is placed
	in bewteen 'start' and 'stop'"""
    seq = list(sequence)
    print(x1, x2 - 1, len(seq))
    seq[x1] = start + seq[x1]
    seq[x2 - 1] = seq[x2 - 1] + stop
    return ''.join(seq)


def trailing_whitespace(physical_line):
    """Trailing whitespace is superfluous.

    The warning returned varies on whether the line itself is blank, for easier
    filtering for those who want to indent their blank lines.

    Okay: spam(1)\\n#
    W291: spam(1) \\n#
    W293: class Foo(object):\\n    \\n    bang = 12
    """
    physical_line = physical_line.rstrip('\n')
    physical_line = physical_line.rstrip('\r')
    physical_line = physical_line.rstrip('\x0c')
    stripped = physical_line.rstrip(' \t\x0b')
    if physical_line != stripped:
        if stripped:
            return len(stripped), 'W291 trailing whitespace'
        else:
            return 0, 'W293 blank line contains whitespace'


@staticmethod
def p_ecu_address_extension(p):
    """ecu_address_extension : ECU_ADDRESS_EXTENSION NUMERIC"""
    p[0] = p[2]


def reciprocal_rank(recommendations, relevant_recommendation, k=None):
    """Reciprocal Rank at k
    Example calls:
    >>> reciprocal_rank([1,2,3], 1) == 1.0
    >>> reciprocal_rank([1,2,3], 2) == 0.5
    >>> reciprocal_rank([1,2,3], 3) == 0.3333333333333333
    >>> reciprocal_rank([1,2,3], 4) == 0
    >>> reciprocal_rank([1,2,3], 3, k=2) == 0
    >>> reciprocal_rank([1,2,3], 2, k=2) == 0.5
    :param recommendations:
    :param relevant_recommendation:
    :param k:
    :return:
    """
    if k is not None:
        recommendations = recommendations[:k]
    if relevant_recommendation in recommendations:
        return 1 / (recommendations.index(relevant_recommendation) + 1)
    return 0


def get_parser():
    """Build parser object"""
    from argparse import ArgumentParser
    from argparse import RawTextHelpFormatter
    parser = ArgumentParser(description=
        "OpenfMRI participants sampler, for FMRIPREP's testing purposes",
        formatter_class=RawTextHelpFormatter)
    parser.add_argument('openfmri_dir', action='store', help=
        'the root folder of a the openfmri dataset')
    parser.add_argument('-D', '--datalad_fetch', action='store_true',
        default=False, help='download sampled subjects')
    parser.add_argument('-o', '--output-file', action='store', help=
        'write output file')
    parser.add_argument('-n', '--num-participants', action='store', type=
        int, default=4, help=
        'number of participants randomly selected per dataset')
    parser.add_argument('--njobs', action='store', type=int, help=
        'parallel downloads')
    parser.add_argument('--seed', action='store', type=int, default=
        20170914, help='seed for random number generation')
    return parser


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 positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


def prepare_arg(argument):
    """Prepend dashes to conform with cli standards on arguments if necessary"""
    keyword, arg = argument.split('=')
    if len(keyword) == 1:
        keyword = '-' + keyword
    elif len(keyword) == 2 and keyword[0] == '-':
        pass
    elif keyword[:2] != '--':
        keyword = '--' + keyword
    return [keyword, arg]


def _decode_line(line, encoding=None):
    """Decode bytes from binary input streams.

    Defaults to decoding from 'latin1'. That differs from the behavior of
    np.compat.asunicode that decodes from 'ascii'.

    Parameters
    ----------
    line : str or bytes
         Line to be decoded.

    Returns
    -------
    decoded_line : unicode
         Unicode in Python 2, a str (unicode) in Python 3.

    """
    if type(line) is bytes:
        if encoding is None:
            line = line.decode('latin1')
        else:
            line = line.decode(encoding)
    return line


def _process_string_exps(str_list):
    """
    common.hosts._process_string_exps accepts pre-parsed string data
    from the common.expressions library and pulls address, tcp port, and type
    information from the list of lists based on position.
    """
    if len(str_list) == 1:
        htype = None
    else:
        htype = str_list[1][0]
    if len(str_list[0]) == 1:
        return {'address': str_list[0][0], 'port': None, 'type': htype}
    elif len(str_list[0]) > 1:
        return {'address': str_list[0][0], 'port': str_list[0][1], 'type':
            htype}


def p0mode_is_smart(p0mode_value) ->bool:
    """
    Is the p0mode value a "smart value".  See calcp0 for more info on p0mode values.

    :param p0mode_value:  If it is an int, this p0mode value represents doing
        smart p0 making the node of that index (i.e.p0mode's value) smooth

    :return: True | False
    """
    return isinstance(p0mode_value, int)


@staticmethod
def _get_major_version(version):
    """Return the 'major' component of the version."""
    return version[:version.find('.')]


def box_fit_2d(points: list) ->float:
    """Returns an angle that best fits the points to an axis aligned rectangle

    :param points: list of 2d points.
    :type points: list
    :return:  angle
    """
    pass


def find_object(mylist, error=None, **kwargs):
    """
    Very simple tools to return an object with the matching parameters in
    kwargs.
    """
    for a in mylist:
        for key, value in kwargs.items():
            if getattr(a, key) != value:
                break
        else:
            return a
    if error is not None:
        raise error()
    return None


def parseAddressRange(text):
    """parse a single address or an address range and return a tuple."""
    if '-' in text:
        adr1, adr2 = text.split('-', 1)
        try:
            adr1 = int(adr1, 0)
        except ValueError:
            raise ValueError(
                'Address range start address must be a valid number in dec, hex or octal'
                )
        try:
            adr2 = int(adr2, 0)
        except ValueError:
            raise ValueError(
                'Address range end address must be a valid number in dec, hex or octal'
                )
        return adr1, adr2
    elif '/' in text:
        adr1, size = text.split('/', 1)
        try:
            adr1 = int(adr1, 0)
        except ValueError:
            raise ValueError(
                'Address range start address must be a valid number in dec, hex or octal'
                )
        multiplier = 1
        if size.endswith('k'):
            size = size[:-1]
            multiplier = 1024
        try:
            size = int(size, 0) * multiplier
        except ValueError:
            raise ValueError(
                'Address range size must be a valid number in dec, hex or octal'
                )
        return adr1, adr1 + size - 1
    else:
        try:
            adr = int(text, 0)
            return adr, None
        except ValueError:
            raise ValueError(
                'Address must be a valid number in dec, hex or octal or a range adr1-adr2'
                )


def softmax(input, dim=-1):
    """Apply the softmax function on given dimension.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The dimension along which to compute softmax.

    Returns
    -------
    Tensor
        The output tensor.
    """
    pass


@staticmethod
def is_doc(obj):
    """Is `BeautifulSoup` object."""
    import bs4
    return isinstance(obj, bs4.BeautifulSoup)


def format_dict(dict_in):
    """
    Format the dictionary to use upper-case keys.

    Parameters
    ----------
    dict_in : dict
        input dictionary
    """
    dict_out = {}
    for key in dict_in:
        new_key = str(key).upper()
        if new_key != key and new_key in dict_in:
            print('Your given OGS-keywords are not unique: ' + new_key)
            print('  --> DATA WILL BE LOST')
        dict_out[new_key] = dict_in[key]
    return dict_out


def vertex_color_remove():
    """Remove vertex color layer

    """
    pass


def read_file(filename):
    """ Given a filename, read the entire thing into a string """
    with open(filename, encoding='utf-8') as file:
        return file.read()


@classmethod
def CreateScale(cls, x=1, y=1, z=1):
    """
        Scales this matrix (in-place) by the given amount

        :param x: x-coordinate of the scale (default 1)
        :type x:  ``int`` or ``float``

        :param y: y-coordinate of the scale (default 1)
        :type Y:  ``int`` or ``float``

        :param z: z-coordinate of the scale (default 1)
        :type Z:  ``int`` or ``float``
        """
    result = cls()
    result.scale(x, y, z)
    return result


def argparse_args(cmd_parser):
    """initialize argparse arguments that the main() function expects"""
    cmd_parser.add_argument('-n', dest='name_filter', nargs='+', metavar='',
        help='Instance tag value filter for the tag key "Name".')
    cmd_parser.add_argument('-r', dest='region_filter', nargs='+', metavar=
        '', help=
        'AWS region(s) to probe for instances. If not set, all whitelisted regions will be probed.'
        )
    cmd_parser.add_argument('-t', dest='tag_filters', nargs='+', action=
        'append', metavar='', help=
        'Instance tag value filter. First value is the tag key, with proceeding value(s) as the tag value(s). If only 1 value given, the tag key itself will be filtered for instead.'
        )
    cmd_parser.add_argument('-i', dest='id_filter', nargs='+', metavar='',
        help='Instance ID filter.')


def from_helioviewer_project(meta):
    """
    Test determining if the MapMeta object contains Helioviewer Project sourced
    data.

    Parameters
    ----------
    meta : `~sunpy.map.MapMeta`

    Returns
    -------
    If the data of the map comes from the Helioviewer Project, then True is
    returned.  If not, False is returned.

    """
    return 'helioviewer' in meta.keys()


def slide_marker(offset: float=(0.0, 0.0)):
    """Slide marker areas

    :param offset: Offset, Offset in floating point units, 1.0 is the width and height of the image
    :type offset: float
    """
    pass


@classmethod
def create(cls, **kwargs):
    """Create a new record and save it the database."""
    instance = cls(**kwargs)
    return instance.save()


@staticmethod
def _dummy(*args, **kwargs):
    """Dummy event handler."""
    pass


def _format(msg, left_margin=0, right_margin=78):
    """ Format a message by inserting line breaks at appropriate places.  msg
    is the text of the message.  left_margin is the position of the left
    margin.  right_margin is the position of the right margin.  Returns the
    formatted message.
    """
    curs = left_margin
    fmsg = ' ' * left_margin
    for w in msg.split():
        l = len(w)
        if curs != left_margin and curs + l > right_margin:
            fmsg = fmsg + '\n' + ' ' * left_margin
            curs = left_margin
        if curs > left_margin:
            fmsg = fmsg + ' '
            curs = curs + 1
        fmsg = fmsg + w
        curs = curs + l
    return fmsg


def unsorted_1d_segment_sum(input, seg_id, n_segs, dim):
    """Computes the sum along segments of a tensor.

    Equivalent to tf.unsorted_segment_sum, but seg_id is required to be a
    1D tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor
    seg_id : 1D Tensor
        The segment IDs whose values are between 0 and n_segs - 1.  Should
        have the same length as input.
    n_segs : int
        Number of distinct segments
    dim : int
        Dimension to sum on

    Returns
    -------
    Tensor
        The result
    """
    pass


def intrinsic(fsm, func, *args, **kwargs):
    """ function call as an intrinsic """
    func(fsm, *args, **kwargs)


def p_track_flag_no_pre_emphasis(t):
    """track_flag : NO PRE_EMPHASIS"""
    from audiotools.toc import TOCFlag_PRE_EMPHASIS
    t[0] = TOCFlag_PRE_EMPHASIS(False)


def write_text_files(dictionary: dict, text_folder: str):
    """Write info to text files.

    The dictionary key will become the filename and the values will    be the content of the files.

    :param dictionary: The dictionary with items to output.
    :param text_folder: The directory to write the text files.
    """
    for filename, text in dictionary.items():
        f = open(f'{text_folder}/{filename}.txt', 'w', encoding='utf8')
        f.write(text)
        f.close


@staticmethod
def translate_indexes(triangle_list, lut):
    """Translate the values of the list of 3-tuples according to the provided look-up table

        Is a generator.

        :param list triangle_list: a list of 3-tuples of integers
        :param dict lut: a dictionary mapping current to new values
        """
    for t0, t1, t2 in triangle_list:
        yield lut[t0], lut[t1], lut[t2]


def timedelta_to_seconds(td):
    """Convert a timedelta to seconds.

    The returned seconds will be rounded to the nearest whole number.
    """
    return round(td.total_seconds())


def lessThan(t):
    """Compare this DateTime object to another DateTime object OR
        a floating point number such as that which is returned by the
        python time module. Returns true if the object represents a
        date/time less than the specified DateTime or time module
        style time.  Revised to give more correct results through
        comparison of long integer milliseconds."""


def IsCppString(line):
    """Does line terminate so, that the next symbol is in string constant.

  This function does not consider single-line nor multi-line comments.

  Args:
    line: is a partial line of code starting from the 0..n.

  Returns:
    True, if next character appended to 'line' is inside a
    string constant.
  """
    line = line.replace('\\\\', 'XX')
    return line.count('"') - line.count('\\"') - line.count('\'"\'') & 1 == 1


def can_change_due_date(payment):
    """If it's possible to change the due date of a payment

        :param payment: the payment to change due date
        """


@classmethod
def get_all(cls, return_type):
    """
        Return list of (suffix, return_type, post_processor)
        """
    default = cls.get_default(return_type)
    alternate = cls.get_alternate_post_processor(return_type)
    result = [('', return_type, default)]
    if alternate:
        result.append(alternate)
    return result


def to_exchange(exchange):
    """转换成正确的交易市场. 如果不存在, 则返回None"""
    exchange_set = {'SHSE', 'SZSE', 'CFFEX', 'SHFE', 'DCE', 'CZCE'}
    if not exchange:
        return None
    s = str(exchange).upper().strip()
    return s if s in exchange_set else None


def detach_role_policy(RoleName=None, PolicyArn=None):
    """
    Removes the specified managed policy from the specified role.
    A role can also have inline policies embedded with it. To delete an inline policy, use the  DeleteRolePolicy API. For information about policies, see Managed Policies and Inline Policies in the IAM User Guide .
    See also: AWS API Documentation

    :example: response = client.detach_role_policy(
        RoleName='string',
        PolicyArn='string'
    )

    :type RoleName: string
    :param RoleName: [REQUIRED]
            The name (friendly name, not ARN) of the IAM role to detach the policy from.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-

    :type PolicyArn: string
    :param PolicyArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the IAM policy you want to detach.
            For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    """
    pass


def normalize_expasy_id(expasy_id: str) ->str:
    """Return a standardized ExPASy identifier string.

    :param expasy_id: A possibly non-normalized ExPASy identifier
    """
    return expasy_id.replace(' ', '')


def construct_sslv2_client_hello():
    """
    Returns a SSLv2 ClientHello message in bytes.

    This is a quick and dirty function to return a SSLv2 ClientHello with all
    7 specified cipher suites. I don't really want to enumerate the supported
    SSLv2 cipher suites so this doesn't have to be flexible...

    This function does not require test coverage because I am simply returning
    bytes constructed from a fix list.

    """
    return bytes([128, 46, 1, 0, 2, 0, 21, 0, 0, 0, 16, 1, 0, 128, 2, 0,
        128, 3, 0, 128, 4, 0, 128, 5, 0, 128, 6, 0, 64, 7, 0, 192, 83, 67,
        91, 144, 157, 155, 114, 11, 188, 12, 188, 43, 146, 168, 72, 151])


def hide():
    """Hide selected objects and collections

    """
    pass


def slice_to_range(sl: slice, n):
    """
    Turn a slice into a range
    :param sl: slice object
    :param n: total number of items
    :return: range object, if the slice is not supported an exception is raised
    """
    if sl.start is None and sl.step is None and sl.start is None:
        return range(n)
    elif sl.start is not None and sl.step is None and sl.start is None:
        return range(sl.start, n)
    elif sl.start is not None and sl.step is not None and sl.start is None:
        raise Exception('Invalid slice')
    elif sl.start is not None and sl.step is None and sl.start is not None:
        return range(sl.start, sl.stop)
    elif sl.start is not None and sl.step is not None and sl.start is not None:
        return range(sl.start, sl.stop, sl.step)
    elif sl.start is None and sl.step is None and sl.start is not None:
        return range(sl.stop)
    else:
        raise Exception('Invalid slice')


def has_party_results(item):
    """ Returns True, if the item has party results. """
    if getattr(item, 'type', 'proporz') == 'proporz':
        if item.party_results.first():
            return True
    return False


def to_base(base, num):
    """Encode a positive integer as a big-endian list of digits in the given
    base.
    """
    if num < 0:
        raise ValueError('only works on positive integers')
    out = []
    while num > 0:
        out.insert(0, num % base)
        num //= base
    return out


def is_android_raw(raw):
    """
        Returns a string that describes the type of file, for common Android
        specific formats
    """
    val = None
    if raw[0:2] == b'PK' and b'AndroidManifest.xml' in raw:
        val = 'APK'
    elif raw[0:3] == b'dex':
        val = 'DEX'
    elif raw[0:3] == b'dey':
        val = 'DEY'
    elif raw[0:4] == b'\x03\x00\x08\x00':
        val = 'AXML'
    elif raw[0:4] == b'\x02\x00\x0c\x00':
        val = b'ARSC'
    return val


def _split_tokens(tokens, token, value):
    """Split a list of tokens on the specified token pair (token, value),
    where *token* is the token type (i.e. its code) and *value* its actual
    value in the code.
    """
    res = [[]]
    for token_values in tokens:
        if (token, value) == token_values[:2]:
            res.append([])
            continue
        res[-1].append(token_values)
    return res


def __getitem__(index):
    """Return the element at the given offset."""


def _decompose_bytes_to_bit_arr(arr):
    """
    Unpack bytes to bits

    :param arr: list
        Byte Stream, as a list of uint8 values

    Returns
    -------
    bit_arr: list
        Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
    """
    bit_arr = []
    for idx in range(len(arr)):
        for i in reversed(range(8)):
            bit_arr.append(arr[idx] >> i & 1 << 0)
    return bit_arr


@classmethod
def from_lists(cls, data, fields, types=None):
    """Create a list of MonaryParams from lists of arguments. These three
        lists will be repeated passed to __init__ as array, field, and mtype.

        :Parameters:
         - `data`: List of numpy masked arrays.
         - `fields`: List of field name.
         - `types` (optional): List of corresponding types.
        """
    if types is None:
        if not len(data) == len(fields):
            raise ValueError('Data and fields must be of equal length.')
        return cls.from_groups(zip(data, fields))
    else:
        if not len(data) == len(fields) == len(types):
            raise ValueError('Data, fields, and types must be of equal length.'
                )
        return cls.from_groups(zip(data, fields, types))


def getfieldindex(data, commdct, objkey, fname):
    """given objkey and fieldname, return its index"""
    objindex = data.dtls.index(objkey)
    objcomm = commdct[objindex]
    for i_index, item in enumerate(objcomm):
        try:
            if item['field'] == [fname]:
                break
        except KeyError as err:
            pass
    return i_index


def encode_root(v):
    """encodes a trie root into serialization"""
    return v


def possible_frobenius_trace_range(field):
    """
    Return the interval in which the trace of the Frobenius endomorphism
    must reside.

    This is the naive estimation: a curve has at least one point (at infinity),
    and at most @f$ 2q + 1 @f$ points, where @f$ q @f$ is the field size.

    @return    The interval that must contain the trace of the Frobenius
               endomorphism.
    """
    return range(-field.size(), field.size() + 1)


def format_kernel(variables, name, screen_width):
    """ Format regular variables """
    max_width = int(screen_width / 5)
    typ = '[' + variables[name]['type'] + ']'
    val = variables[name]['value']
    if len(val) > 3 * max_width:
        val = val[0:3 * max_width - 4] + '... '
    if len(name) > max_width:
        name = name[0:max_width - 4] + '... '
    if len(typ) > max_width:
        typ = typ[0:max_width - 4] + '... '
    s1 = '{:{wname}} {:{wval}}'.format(name, val, wname=max_width, wval=3 *
        max_width)
    s2 = '{:{wtype}}'.format(typ, wtype=screen_width - len(s1))
    return s1, s2


@classmethod
def is_placeholder(cls, code):
    """省直辖县级行政区划/自治区直辖县级行政区划。不属于正常地区，占位连接直辖县"""
    if code in ('156419000000000', '156429000000000', '156469000000000',
        '156659000000000'):
        return True
    return False


def properties():
    """Toggle the properties region visibility

    """
    pass


def generator(lines):
    """
	>>> lines = ['Question: 1', 'Option: 1', 'Question: 2', 'Option: 3', "Question: 3", "Option: 4"]
	>>> questions = list(generator(lines))
	>>> len(questions)
	3
	>>> len(questions[0])
	2
	>>> len(questions[1])
	2
	"""
    lst = []
    for line in lines:
        if line.startswith('Question:'):
            if lst:
                yield lst
            lst = [line.replace('Question:', '', 1)]
        elif line.strip():
            lst.append(line.replace('Option:', '', 1))
    if lst:
        yield lst


def unread():
    """ Number of unread notifications for the current user
        """


def to_list(obj):
    """Convert an object to a list if it is not already one"""
    if not isinstance(obj, (list, tuple)):
        obj = [obj]
    return obj


def getMonthNames():
    """Return a list of month names."""


def list_value_renderer(value, **options):
    """Render list value"""
    return ', '.join(map(str, value))


def _get_value_as_int(dict_obj, key):
    """
    Return the value associated with a key in a dictionary, converted to an
    int.

    :param dict dict_obj: Dictionary to retrieve the value from
    :param str key: Key associated with the value to return
    :return The value, as an integer. Returns 'None' if the key cannot be found
        in the dictionary.
    :rtype: int
    :raises ValueError: If the key is present in the dictionary but the value
        cannot be converted to an int.
    """
    return_value = None
    if key in dict_obj:
        try:
            return_value = int(dict_obj.get(key))
        except ValueError:
            raise ValueError("'{}' of '{}' could not be converted to an int"
                .format(key, return_value))
    return return_value


def use_exc_ipdb():
    """ Set unhandled exception handler to automatically start ipdb """
    import pyaux.exc_ipdb as exc_ipdb
    exc_ipdb.init()


def removeSortCriterion():
    """remove the Sort criterion.
        """


def _polarized_nonmagnetic(r):
    """Convert nonmagnetic data to polarized representation.

    Polarized non-magnetic data repeats the reflectivity in the non spin flip
    channels and sets the spin flip channels to zero.
    """
    nsf = r
    sf = 0 * r
    return [nsf, sf, sf, nsf]


@classmethod
def clear_expired(cls):
    """
        Remove expired sessions from the session store.

        If this operation isn't possible on a given backend, it should raise
        NotImplementedError. If it isn't necessary, because the backend has
        a built-in expiration mechanism, it should be a no-op.
        """
    raise NotImplementedError('This backend does not support clear_expired().')


@classmethod
def _from_dict(cls, _dict):
    """Initialize a AnalyticsEngineLoggingNodeSpec object from a json dictionary."""
    return cls.from_dict(_dict)


def copy_attributes(source, target, attribute_names, overwrite=True):
    """
    Copies attributes from source object to target object, overwriting if already exists.

    :param source: the source object (dataset, variable, etc)
    :param target: the target object
    :param attribute_names: tuple / list of attribute names to copy across
    """
    for attribute_name in attribute_names:
        if attribute_name in '_FillValue':
            continue
        if hasattr(target, attribute_name) and not overwrite:
            raise Exception(
                'Attribute already exists in target, but overwrite is false')
        setattr(target, attribute_name, getattr(source, attribute_name))


def _anisotropy(haeb_evals, reduced=False):
    """Calculate anisotropy given eigenvalues sorted with Haeberlen
    convention"""
    f = 2.0 / 3.0 if reduced else 1.0
    return (haeb_evals[:, (2)] - (haeb_evals[:, (0)] + haeb_evals[:, (1)]) /
        2.0) * f


def size_of_pointer_fn():
    """
    Return pointer size for current Redis connection
    :return int:
    """
    return 8


def feature_scale_or_normalize(dataframe, col_names, norm_type='StandardScaler'
    ):
    """
    Basically converts floating point or integer valued columns to fit into the range of 0 to 1
    """
    from sklearn.preprocessing import StandardScaler, MinMaxScaler
    if norm_type == 'StandardScaler':
        return StandardScaler().fit_transform(dataframe[col_names])
    elif norm_type == 'MinMaxScaler':
        return MinMaxScaler().fit_transform(dataframe[col_names])
    else:
        return None


def all_indexes_same(indexes):
    """
    Determine if all indexes contain the same elements.

    Parameters
    ----------
    indexes : list of Index objects

    Returns
    -------
    bool
        True if all indexes contain the same elements, False otherwise.
    """
    first = indexes[0]
    for index in indexes[1:]:
        if not first.equals(index):
            return False
    return True


@classmethod
def unregister(cls, dotpath):
    """ Unregister a previously-registered ExporterBase instance,
            specified by the dotted path (née “dotpath”) of the module
            in which it is ensconced.

            Returns the successfully unregistered instance in question.
        """
    return cls.instances.pop(dotpath, None)


def _sort_list_int(elem):
    """Get the first element of the array as int. for sorting.

    Args:
        elem: The 2d list

    Returns:
        The a int value of the first list element.
    """
    return int(elem[0])


def DbndFunctionalOperator_1_10_0(task_id, dbnd_task_type,
    dbnd_task_params_fields, **ctor_kwargs):
    """
    Workaround for backwards compatibility with Airflow 1.10.0,
    dynamically creating new operator class (that inherits AirflowDagDbndOperator).
    This is used because XCom templates for each operator are found in a class attribute
    and we have different XCom templates for each INSTANCE of the operator.
    Also, the template_fields attribute has a different value for each task, so we must ensure that they
    don't get mixed up.
    """
    template_fields = dbnd_task_params_fields
    from dbnd_airflow_operator.dbnd_functional_operator import DbndFunctionalOperator
    new_op = type(dbnd_task_type, (DbndFunctionalOperator,), {
        'template_fields': template_fields})
    op = new_op(task_id=task_id, dbnd_task_type=dbnd_task_type,
        dbnd_task_params_fields=dbnd_task_params_fields, **ctor_kwargs)
    return op


def fix_column_name(val):
    """
    Fixes column names so that they are compatible with Numpy on
    Python 2.  Raises a ValueError exception if the column name
    contains Unicode characters, which can not reasonably be used as a
    column name.
    """
    if val is not None:
        try:
            val = str(val)
        except UnicodeEncodeError:
            raise
    return val


def _gbd(n):
    """Compute second greatest base-2 divisor"""
    i = 1
    if n <= 0:
        return 0
    while not n % i:
        i <<= 1
    return i >> 2


def text_stripper(txt: str) ->str:
    """This is a stdout/stderr processor that strips the given text.

    :param str txt: The text to be stripped
    :rtype: str
    """
    return txt.strip()


def purify_kwargs(kwargs):
    """If type or metavar are set to None, they are removed from kwargs."""
    for key, value in kwargs.copy().items():
        if key in set(['type', 'metavar']) and value is None:
            del kwargs[key]
    return kwargs


@classmethod
def DeregisterMountPoint(cls, mount_point):
    """Deregisters a path specification mount point.

    Args:
      mount_point (str): mount point identifier.

    Raises:
      KeyError: if the corresponding mount point is not set.
    """
    if mount_point not in cls._mount_points:
        raise KeyError('Mount point: {0:s} not set.'.format(mount_point))
    del cls._mount_points[mount_point]


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['configSourceType']
    if type == 'ZIP_UPLOAD':
        return 'ZipUploadConfigSource'
    else:
        return 'ConfigSource'


def get_local_word_count(bot, _nick, _count_key):
    """ Returns the word count for a given nick for the specific channel"""
    try:
        word_count = int(bot.db.get_nick_value(_nick, _count_key))
    except:
        word_count = 0
    return word_count


@classmethod
def get_visible_name_from_scope(cls, scope):
    """ Generate visible name based on host scope """
    return ('%s-%s' % (scope.uuid.hex, scope.name))[:64]


@staticmethod
def bytes_to_readable(num):
    """Converts bytes to a human readable format."""
    if num < 512:
        return '0 Kb'
    elif num < 1024:
        return '1 Kb'
    for unit in ['', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb']:
        if abs(num) < 1024.0:
            return '%3.1f%s' % (num, unit)
        num /= 1024.0
    return '%.1f%s' % (num, 'Yb')


def is_even(number):
    """ Return True if a number is even, False if odd. """
    return not number % 2


def optimizeAngle(angle):
    """
    Because any rotation can be expressed within 360 degrees
    of any given number, and since negative angles sometimes
    are one character longer than corresponding positive angle,
    we shorten the number to one in the range to [-90, 270[.
    """
    if angle < 0:
        angle %= -360
    else:
        angle %= 360
    if angle >= 270:
        angle -= 360
    elif angle < -90:
        angle += 360
    return angle


def add_arg(func, *args, **kwargs):
    """Bind CLI arguments to a shell.py `do_foo` function."""
    if not hasattr(func, 'arguments'):
        func.arguments = []
    if (args, kwargs) not in func.arguments:
        func.arguments.insert(0, (args, kwargs))


def reject_request(message):
    """Reject a request for approval.
        """


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'