def
Func
(
arg_0
,
arg_1
=
True
,
arg_2
=
)
:
if
not
arg_1
:
raise
ValueError
(
'Nice try ;-)'
)
for
arg_3
in
list
(
arg_0
.
_children
.
keys
(
)
)
:
arg_0
.
Func_child
(
arg_3
,
arg_1
=
True
,
arg_2
=
arg_2
)

def Func(arg_0, arg_1=True, arg_2=None):
        """Recursively removes all children of the trajectory

        :param recursive:

            Only here for consistency with signature of parent method. Cannot be set
            to `False` because the trajectory root node cannot be removed.

        :param predicate:

            Predicate which can evaluate for each node to ``True`` in order to remove the node or
            ``False`` if the node should be kept. Leave ``None`` if you want to remove all nodes.

        """
        if not arg_1:
            raise ValueError('Nice try ;-)')

        for arg_3 in list(arg_0._children.keys()):
            arg_0.Func_child(arg_3, arg_1=True, arg_2=arg_2)


def
Func
(
arg_0
,
arg_1
)
:
try
:
arg_2
,
arg_1
=
arg_0
.
session
.
feed_identities
(
arg_1
)
except
ValueError
:
arg_2
=
[
]
if
not
arg_2
:
arg_0
.
log
.
error
(
"Bad Query Message: %r"
,
arg_1
)
return
arg_3
=
arg_2
[
0
]
try
:
arg_1
=
arg_0
.
session
.
unserialize
(
arg_1
,
arg_4
=
True
)
except
Exception
:
arg_4
=
error
.
wrap_exception
(
)
arg_0
.
log
.
error
(
"Bad Query Message: %r"
,
arg_1
,
exc_info
=
True
)
arg_0
.
session
.
send
(
arg_0
.
query
,
"hub_error"
,
ident
=
arg_3
,
arg_4
=
arg_4
)
return
arg_5
=
arg_1
[
'header'
]
[
'msg_type'
]
arg_0
.
log
.
info
(
"client::client %r requested %r"
,
arg_3
,
arg_5
)
arg_6
=
arg_0
.
query_handlers
.
get
(
arg_5
,
)
try
:
assert
arg_6
is
not
,
"Bad Message Type: %r"
%
arg_5
except
:
arg_4
=
error
.
wrap_exception
(
)
arg_0
.
log
.
error
(
"Bad Message Type: %r"
,
arg_5
,
exc_info
=
True
)
arg_0
.
session
.
send
(
arg_0
.
query
,
"hub_error"
,
ident
=
arg_3
,
arg_4
=
arg_4
)
return
else
:
arg_6
(
arg_2
,
arg_1
)

def Func(arg_0, arg_1):
        """Route registration requests and queries from clients."""
        try:
            arg_2, arg_1 = arg_0.session.feed_identities(arg_1)
        except ValueError:
            arg_2 = []
        if not arg_2:
            arg_0.log.error("Bad Query Message: %r", arg_1)
            return
        arg_3 = arg_2[0]
        try:
            arg_1 = arg_0.session.unserialize(arg_1, arg_4=True)
        except Exception:
            arg_4 = error.wrap_exception()
            arg_0.log.error("Bad Query Message: %r", arg_1, exc_info=True)
            arg_0.session.send(arg_0.query, "hub_error", ident=arg_3,
                    arg_4=arg_4)
            return
        # print client_id, header, parent, content
        #switch on message type:
        arg_5 = arg_1['header']['msg_type']
        arg_0.log.info("client::client %r requested %r", arg_3, arg_5)
        arg_6 = arg_0.query_handlers.get(arg_5, None)
        try:
            assert arg_6 is not None, "Bad Message Type: %r" % arg_5
        except:
            arg_4 = error.wrap_exception()
            arg_0.log.error("Bad Message Type: %r", arg_5, exc_info=True)
            arg_0.session.send(arg_0.query, "hub_error", ident=arg_3,
                    arg_4=arg_4)
            return

        else:
            arg_6(arg_2, arg_1)

Route registration requests and queries from clients .


(circuits, qobj_header=None,
                     qobj_id=None, backend_name=None,
                     config=None, shots=None, max_credits=None,
                     basis_gates=None,
                     coupling_map=None, seed=None, memory=None)

def Func(arg_0, arg_1=None,
                     arg_2=None, arg_3=None,
                     arg_4=None, arg_5=None, arg_6=None,
                     arg_7=None,
                     arg_8=None, arg_9=None, arg_10=None):
    """Convert a list of circuits into a qobj.

    Args:
        circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
        qobj_header (QobjHeader): header to pass to the results
        qobj_id (int): TODO: delete after qiskit-terra 0.8
        backend_name (str): TODO: delete after qiskit-terra 0.8
        config (dict): TODO: delete after qiskit-terra 0.8
        shots (int): TODO: delete after qiskit-terra 0.8
        max_credits (int): TODO: delete after qiskit-terra 0.8
        basis_gates (str): TODO: delete after qiskit-terra 0.8
        coupling_map (list): TODO: delete after qiskit-terra 0.8
        seed (int): TODO: delete after qiskit-terra 0.8
        memory (bool): TODO: delete after qiskit-terra 0.8

    Returns:
        Qobj: the Qobj to be run on the backends
    """
    warnings.warn('Func is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Use qiskit.compiler.assemble() to serialize circuits into a qobj.',
                  DeprecationWarning)

    arg_1 = arg_1 or QobjHeader()

    if arg_3:
        arg_1.backend_name = arg_3
    if arg_7:
        warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning)
    if arg_8:
        warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning)

    arg_11 = assemble(experiments=arg_0,
                    arg_2=arg_2,
                    arg_1=arg_1,
                    arg_5=arg_5,
                    arg_10=arg_10,
                    arg_6=arg_6,
                    seed_simulator=arg_9,
                    arg_4=arg_4)

    return arg_11

Convert a list of circuits into a qobj .


def Func(arg_0, arg_1):
        """Delete a key if it exists.
        """
        arg_0._assert_valid_stash()

        if arg_1 == 'stored_passphrase':
            raise GhostError(
                '`stored_passphrase` is a reserved ghost key name '
                'which cannot be Funcd')

        # TODO: Optimize. We get from the storage twice here for no reason
        if not arg_0.get(arg_1):
            raise GhostError('Key `{0}` not found'.format(arg_1))
        arg_2 = arg_0._storage.get(arg_1)
        if arg_2.get('lock'):
            raise GhostError(
                'Key `{0}` is locked and therefore cannot be Funcd '
                'Please unlock the key and try again'.format(arg_1))

        arg_3 = arg_0._storage.Func(arg_1)

        audit(
            storage=arg_0._storage.db_path,
            action='DELETE',
            message=json.dumps(dict(arg_1=arg_1)))

        if not arg_3:
            raise GhostError('Failed to Func {0}'.format(arg_1))


(store, institute_obj, case_obj, variants_query, page=1, per_page=50)

return variants(store, institute_obj, case_obj, variants_query, page, per_page)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4=1, arg_5=50):
    """Pre-process list of STR variants."""
    # Nothing unique to STRs on this level. Inheritance?
    return variants(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5)


def Func ( arg_0 , arg_1 ) : arg_2 = 1.5 arg_3 = arg_1 * arg_0 . timestep / arg_0 . scale arg_4 = int ( round ( float ( arg_3 ) / 2 * arg_2 ) ) arg_5 = int ( math . ceil ( ( math . sqrt ( arg_0 . w ) - 1 ) / 2 ) ) return max ( arg_4 , arg_5 )

def Func(arg_0, arg_1):
    """
    Returns radius for given speed.

    Tries to get the encodings of consecutive readings to be
    adjacent with some overlap.

    :param: speed (float) Speed (in meters per second)
    :returns: (int) Radius for given speed
    """
    arg_2 = 1.5
    arg_3 = arg_1 * arg_0.timestep / arg_0.scale
    arg_4 = int(round(float(arg_3) / 2 * arg_2))
    arg_5 = int(math.ceil((math.sqrt(arg_0.w) - 1) / 2))
    return max(arg_4, arg_5)


def Func(arg_0, arg_1):
  """potential_scale_reduction for one single state `Tensor`."""
  with tf.compat.v1.name_scope(
      'potential_scale_reduction_single_state',
      values=[arg_0, arg_1]):
    # We assume exactly one leading dimension indexes e.g. correlated samples
    # from each Markov chain.
    arg_0 = tf.convert_to_tensor(value=arg_0, name='state')
    arg_2 = 1

    arg_3 = tf.range(0, arg_2)
    arg_4 = tf.range(arg_2,
                          arg_2 + arg_1)
    arg_5 = tf.range(
        0, arg_2 + arg_1)

    arg_6 = _axis_size(arg_0, arg_3)
    arg_7 = _axis_size(arg_0, arg_4)

    # In the language of Brooks and Gelman (1998),
    # B / n is the between chain variance, the variance of the chain means.
    # W is the within sequence variance, the mean of the chain variances.
    arg_8 = _reduce_variance(
        tf.reduce_mean(input_tensor=arg_0, axis=arg_3, keepdims=True),
        arg_5,
        biased=False)
    arg_9 = tf.reduce_mean(
        input_tensor=_reduce_variance(
            arg_0, arg_3, keepdims=True, biased=True),
        axis=arg_5)

    # sigma^2_+ is an estimate of the true variance, which would be unbiased if
    # each chain was drawn from the target.  c.f. "law of total variance."
    arg_10 = arg_9 + arg_8

    return ((arg_7 + 1.) / arg_7) * arg_10 / arg_9 - (arg_6 - 1.) / (arg_7 * arg_6)

potential_scale_reduction for one single state Tensor .


def Func(arg_0, arg_1=None):
        """
        Updates the status of the file clusters comparing the cluster
        key files with a levenshtein weighted measure using either the
        header_fields or self.header_fields.

        Parameters
        ----------
        field_weights: dict of strings with floats
            A dict with header field names to float scalar values, that indicate a distance measure
            ratio for the levenshtein distance averaging of all the header field names in it.
            e.g., {'PatientID': 1}
        """
        if arg_1 is None:
            if not isinstance(arg_0.field_weights, dict):
                raise ValueError('Expected a dict for `field_weights` parameter, '
                                 'got {}'.format(type(arg_0.field_weights)))

        arg_2 = list(arg_0.dicom_groups.keys())
        arg_3 = calculate_file_distances(arg_2, arg_1, arg_0._dist_method_cls)
        return arg_3

Updates the status of the file clusters comparing the cluster key files with a levenshtein weighted measure using either the header_fields or self . header_fields .


def Func(arg_0, arg_1, arg_2):
    """invoke task hooks for every time spout fails a tuple

    :type message_id: str
    :param message_id: message id to which a failed tuple was anchored
    :type fail_latency_ns: float
    :param fail_latency_ns: fail latency in nano seconds
    """
    if len(arg_0.task_hooks) > 0:
      arg_3 = SpoutFailInfo(arg_1=arg_1,
                                      spout_task_id=arg_0.get_task_id(),
                                      fail_latency_ms=arg_2 * system_constants.NS_TO_MS)
      for arg_4 in arg_0.task_hooks:
        arg_4.spout_fail(arg_3)


(session, member_ids, project_id, message)

return create_thread(session, member_ids, 'project', project_id, message)

def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Create a project thread
    """
    return create_thread(arg_0, arg_1, 'project', arg_2, arg_3)


def Func ( ) -> int : arg_0 = getattr ( os , "sched_getaffinity" , None ) if arg_0 : return len ( arg_0 ( 0 ) ) if multiprocessing : return multiprocessing . cpu_count ( ) return 1

def Func() -> int:
    """Use sched_affinity if available for virtualized or containerized environments."""
    arg_0 = getattr(os, "sched_getaffinity", None)
    # pylint: disable=not-callable,using-constant-test
    if arg_0:
        return len(arg_0(0))
    if multiprocessing:
        return multiprocessing.cpu_count()
    return 1

Use sched_affinity if available for virtualized or containerized environments .


return [l1 for l1,count in iitems(exit_counts) if count > 1]

def Func ( arg_0 ) : arg_1 = arg_0 . parser . exit_counts ( ) return [ arg_2 for arg_2 , arg_3 in iitems ( arg_1 ) if arg_3 > 1 ]

def Func(arg_0):
        """Returns a list of line numbers that have more than one exit."""
        arg_1 = arg_0.parser.exit_counts()
        return [arg_2 for arg_2,arg_3 in iitems(arg_1) if arg_3 > 1]

Returns a list of line numbers that have more than one exit .


def Func ( arg_0 , arg_1 ) : arg_1 . value = int ( arg_1 . value ) arg_1 . type = 'NUMBER' return arg_1

def Func(arg_0, arg_1):
        r'-?\d+'
        arg_1.value = int(arg_1.value)
        arg_1.type = 'NUMBER'
        return arg_1


def Func(arg_0) -> None:
        """
        Apply stashed values to signals
        """
        assert not arg_0._applyValPlaned, arg_0.now
        arg_0._add_process(arg_0._applyValues(), PRIORITY_APPLY_COMB)
        arg_0._applyValPlaned = True

        if arg_0._runSeqProcessesPlaned:
            # if runSeqProcesses is already scheduled
            return

        assert not arg_0._seqProcsToRun and not arg_0._runSeqProcessesPlaned, arg_0.now
        arg_0._add_process(arg_0._runSeqProcesses(), PRIORITY_APPLY_SEQ)
        arg_0._runSeqProcessesPlaned = True


def Func ( arg_0 , arg_1 ) : arg_2 = libaio . io_Func ( arg_0 . _ctx , len ( arg_1 ) , ( libaio . iocb_p * len ( arg_1 ) ) ( * [ pointer ( x . _iocb ) for x in arg_1 ] ) , ) arg_3 = arg_0 . _Functed for arg_4 in arg_1 [ : arg_2 ] : arg_3 [ arg_5 ( arg_4 . _iocb ) ] = ( arg_4 , arg_4 . _getSubmissionState ( ) ) return arg_2

def Func(arg_0, arg_1):
        """
        Submits transfers.

        block_list (list of AIOBlock)
            The IO blocks to hand off to kernel.

        Returns the number of successfully Functed blocks.
        """
        # io_Func ioctl will only return an error for issues with the first
        # transfer block. If there are issues with a later block, it will stop
        # submission and return the number of Functed blocks. So it is safe
        # to only update self._Functed once io_Func returned.
        arg_2 = libaio.io_Func(
            arg_0._ctx,
            len(arg_1),
            (libaio.iocb_p * len(arg_1))(*[
                # pylint: disable=protected-access
                pointer(x._iocb)
                # pylint: enable=protected-access
                for x in arg_1
            ]),
        )
        arg_3 = arg_0._Functed
        for arg_4 in arg_1[:arg_2]:
            # pylint: disable=protected-access
            arg_3[arg_5(arg_4._iocb)] = (arg_4, arg_4._getSubmissionState())
            # pylint: enable=protected-access
        return arg_2

Submits transfers.

        block_list (list of AIOBlock)
            The IO blocks to hand off to kernel.

        Returns the number of successfully submitted blocks.


(
            self, application_definition_id, parameters, custom_headers=None, raw=False, polling=True, **operation_config)

return LROPoller(self._client, raw_result, get_long_running_output, polling_method)

def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=False, arg_5=True, **arg_6):
        """Creates a new managed application definition.

        :param application_definition_id: The fully qualified ID of the
         managed application definition, including the managed application name
         and the managed application definition resource type. Use the format,
         /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applicationDefinitions/{applicationDefinition-name}
        :type application_definition_id: str
        :param parameters: Parameters supplied to the create or update a
         managed application definition.
        :type parameters:
         ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns ApplicationDefinition
         or ClientRawResponse<ApplicationDefinition> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.resource.managedapplications.models.ErrorResponseException>`
        """
        arg_7 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=True,
            **arg_6
        )

        def get_long_running_output(arg_8):
            arg_9 = arg_0._deserialize('ApplicationDefinition', arg_8)

            if arg_4:
                arg_10 = ClientRawResponse(arg_9, arg_8)
                return arg_10

            return arg_9

        arg_11 = arg_6.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_5 is True: arg_12 = ARMPolling(arg_11, **arg_6)
        elif arg_5 is False: arg_12 = NoPolling()
        else: arg_12 = arg_5
        return LROPoller(arg_0._client, arg_7, get_long_running_output, arg_12)

Creates a new managed application definition .


def Func ( arg_0 , arg_1 = None ) : arg_1 = arg_1 if arg_1 is not None else arg_0 . _last_result arg_2 = False if arg_1 is not None : arg_2 = True if arg_1 [ 'type' ] > 0 else False return arg_2

def Func(arg_0, arg_1=None):
        """
        Check if IP is suspicious

        :param result: httpBL results; if None, then results from last check_ip() used (optional)
        :return: True or False
        """

        arg_1 = arg_1 if arg_1 is not None else arg_0._last_result
        arg_2 = False
        if arg_1 is not None:
            arg_2 = True if arg_1['type'] > 0 else False
        return arg_2


def
Func
(
arg_0
,
arg_1
=
'ped'
)
:
arg_2
=
FamilyParser
(
arg_0
,
arg_1
=
arg_1
)
if
len
(
arg_2
.
families
)
!=
1
:
raise
PedigreeError
(
"Only one case per ped file is allowed"
)
arg_3
=
list
(
arg_2
.
families
.
keys
(
)
)
[
0
]
arg_4
=
arg_2
.
families
[
arg_3
]
arg_5
=
[
{
'sample_id'
:
ind_id
,
'father'
:
individual
.
father
,
'mother'
:
individual
.
mother
,
'sex'
:
SEX_MAP
[
individual
.
sex
]
,
'phenotype'
:
PHENOTYPE_MAP
[
int
(
individual
.
phenotype
)
]
,
}
for
ind_id
,
individual
in
arg_4
.
individuals
.
items
(
)
]
return
arg_3
,
arg_5

def Func(arg_0, arg_1='ped'):
    """Parse out minimal family information from a PED file.

    Args:
        ped_stream(iterable(str))
        family_type(str): Format of the pedigree information

    Returns:
        family_id(str), samples(list[dict])
    """
    arg_2 = FamilyParser(arg_0, arg_1=arg_1)

    if len(arg_2.families) != 1:
        raise PedigreeError("Only one case per ped file is allowed")

    arg_3 = list(arg_2.families.keys())[0]
    arg_4 = arg_2.families[arg_3]

    arg_5 = [{
        'sample_id': ind_id,
        'father': individual.father,
        'mother': individual.mother,
        # Convert sex to human readable
        'sex': SEX_MAP[individual.sex],
        'phenotype': PHENOTYPE_MAP[int(individual.phenotype)],
    } for ind_id, individual in arg_4.individuals.items()]

    return arg_3, arg_5

Parse out minimal family information from a PED file .


Asserts that val is callable and that when called raises the given error.

return AssertionBuilder(self.val, self.description, self.kind, ex)

def
Func
(
arg_0
,
arg_1
)
:
if
not
callable
(
arg_0
.
val
)
:
raise
TypeError
(
'val must be callable'
)
if
not
issubclass
(
arg_1
,
BaseException
)
:
raise
TypeError
(
'given arg must be exception'
)
return
AssertionBuilder
(
arg_0
.
val
,
arg_0
.
description
,
arg_0
.
kind
,
arg_1
)

def Func(arg_0, arg_1):
        """Asserts that val is callable and that when called Func the given error."""
        if not callable(arg_0.val):
            raise TypeError('val must be callable')
        if not issubclass(arg_1, BaseException):
            raise TypeError('given arg must be exception')
        return AssertionBuilder(arg_0.val, arg_0.description, arg_0.kind, arg_1)

Asserts that val is callable and that when called raises the given error .


def Func ( arg_0 , ** arg_1 ) : arg_0 [ '_version' ] = 1 arg_0 . update ( get_group_api ( arg_0 [ 'GroupName' ] , users = False , ** arg_1 ) [ 'Group' ] ) arg_0 [ 'CreateDate' ] = get_iso_string ( arg_0 [ 'CreateDate' ] ) return arg_0

def Func(arg_0, **arg_1):
    """Fetch the base IAM Group."""
    arg_0['_version'] = 1

    # Get the initial group details (only needed if we didn't grab the users):
    arg_0.update(get_group_api(arg_0['GroupName'], users=False, **arg_1)['Group'])

    # Cast CreateDate from a datetime to something JSON serializable.
    arg_0['CreateDate'] = get_iso_string(arg_0['CreateDate'])
    return arg_0


(self, slug, name, chart_obj, filepath=None,
             html_before="", html_after="")

def Func ( arg_0 , arg_1 , arg_2 , arg_3 , arg_4 = None , arg_5 = "" , arg_6 = "" ) : try : Func = "" if arg_2 : Func = "<h3>" + arg_2 + "</h3>" arg_8 = arg_3 . to_json ( ) arg_8 = arg_0 . _patch_json ( arg_8 ) Func = arg_5 + Func + arg_0 . _json_to_html ( arg_1 , arg_8 ) + arg_6 except Exception as e : tr . new ( e ) tr . check ( ) if arg_4 is not None : arg_0 . _write_file ( arg_1 , arg_4 , Func ) return None else : return Func

def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None,
             arg_5="", arg_6=""):
        """
        Generate html from an Altair chart object and optionally write it to a file
        """
        try:
            Func = ""
            if arg_2:
                Func = "<h3>" + arg_2 + "</h3>"
            arg_8 = arg_3.to_json()
            arg_8 = arg_0._patch_json(arg_8)
            Func = arg_5 + Func +\
                arg_0._json_to_html(arg_1, arg_8) + arg_6
        except Exception as e:
            tr.new(e)
            tr.check()
        # generate file
        if arg_4 is not None:
            arg_0._write_file(arg_1, arg_4, Func)
            return None
        else:
            return Func


def Func ( arg_0 , arg_1 , arg_2 ) : arg_1 = PATTERN . sub ( '' , arg_1 ) arg_1 = re . sub ( r'\b(?:ago|in)\b' , '' , arg_1 ) try : return time_parser ( arg_1 ) except : pass

def Func(arg_0, arg_1, arg_2):
        """Attemps to parse time part of date strings like '1 day ago, 2 PM' """
        arg_1 = PATTERN.sub('', arg_1)
        arg_1 = re.sub(r'\b(?:ago|in)\b', '', arg_1)
        try:
            return time_parser(arg_1)
        except:
            pass

Attemps to parse time part of date strings like 1 day ago 2 PM


return "{data[installer][name]}/{data[installer][version]} {json}".format(
        data=data,
        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
    )

def Func():
    """
    Return a string representing the user agent.
    """
    arg_0 = {
        "installer": {"name": "pip", "version": pip.__version__},
        "python": platform.python_version(),
        "implementation": {
            "name": platform.python_implementation(),
        },
    }

    if arg_0["implementation"]["name"] == 'CPython':
        arg_0["implementation"]["version"] = platform.python_version()
    elif arg_0["implementation"]["name"] == 'PyPy':
        if sys.pypy_version_info.releaselevel == 'final':
            arg_1 = sys.pypy_version_info[:3]
        else:
            arg_1 = sys.pypy_version_info
        arg_0["implementation"]["version"] = ".".join(
            [str(x) for x in arg_1]
        )
    elif arg_0["implementation"]["name"] == 'Jython':
        # Complete Guess
        arg_0["implementation"]["version"] = platform.python_version()
    elif arg_0["implementation"]["name"] == 'IronPython':
        # Complete Guess
        arg_0["implementation"]["version"] = platform.python_version()

    if sys.platform.startswith("linux"):
        arg_2 = dict(filter(
            lambda x: x[1],
            zip(["name", "version", "id"], platform.linux_distribution()),
        ))
        arg_3 = dict(filter(
            lambda x: x[1],
            zip(["lib", "version"], platform.libc_ver()),
        ))
        if arg_3:
            arg_2["libc"] = arg_3
        if arg_2:
            arg_0["distro"] = arg_2

    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
        arg_0["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]}

    if platform.system():
        arg_0.setdefault("system", {})["name"] = platform.system()

    if platform.release():
        arg_0.setdefault("system", {})["release"] = platform.release()

    if platform.machine():
        arg_0["cpu"] = platform.machine()

    return "{data[installer][name]}/{data[installer][version]} {json}".format(
        arg_0=arg_0,
        json=json.dumps(arg_0, separators=(",", ":"), sort_keys=True),
    )

Return a string representing the user agent .


def
Func
(
arg_0
)
:
arg_0
.
log
.
debug
(
"Reading cached stepper info: %s"
,
arg_0
.
__si_filename
(
)
)
with
open
(
arg_0
.
__si_filename
(
)
,
'r'
)
as
si_file
:
arg_1
=
info
.
StepperInfo
(
**
json
.
load
(
si_file
)
)
return
arg_1

def Func(arg_0):
        '''
        Read stepper info from json
        '''
        arg_0.log.debug("Reading cached stepper info: %s", arg_0.__si_filename())
        with open(arg_0.__si_filename(), 'r') as si_file:
            arg_1 = info.StepperInfo(**json.load(si_file))
        return arg_1


def Func(arg_0):
    """
    Gets two classifiers for each type of algorithm, and returns them.  First for predicting, second for cv error.
    type - one of util_functions.AlgorithmTypes
    """
    if arg_0 == util_functions.AlgorithmTypes.classification:
        arg_1 = sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,
            max_depth=4, random_state=1,min_samples_leaf=3)
        arg_2=sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,
            max_depth=4, random_state=1,min_samples_leaf=3)
    else:
        arg_1 = sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,
            max_depth=4, random_state=1,min_samples_leaf=3)
        arg_2=sklearn.ensemble.GradientBoostingRegressor(n_estimators=100, learn_rate=.05,
            max_depth=4, random_state=1,min_samples_leaf=3)
    return arg_1, arg_2

Gets two classifiers for each type of algorithm and returns them . First for predicting second for cv error . type - one of util_functions . AlgorithmTypes


def
Func
(
arg_0
,
**
arg_1
)
:
assert
len
(
arg_0
)
>
0
arg_2
=
time
.
time
(
)
arg_3
=
AsyncProcess
(
arg_0
,
**
arg_1
)
arg_3
.
wait
(
)
arg_4
=
time
.
time
(
)
arg_2
logger
.
info
(
"%s took %0.4f seconds"
,
arg_0
[
0
]
,
arg_4
)

def Func(arg_0, **arg_1):
    """
    Given a list whose first element is a command name, followed by arguments,
    execute it and show timing info.
    """
    assert len(arg_0) > 0
    arg_2 = time.time()
    arg_3 = AsyncProcess(arg_0, **arg_1)
    arg_3.wait()
    arg_4 = time.time() - arg_2
    logger.info("%s took %0.4f seconds", arg_0[0], arg_4)

Given a list whose first element is a command name followed by arguments execute it and show timing info .


return self.reduce(f, value, flat=flat, all=True)

def Func ( arg_0 , arg_1 , arg_2 , arg_3 = True ) : return arg_0 . reduce ( arg_1 , arg_2 , arg_3 = arg_3 , all = True )

def Func(arg_0, arg_1, arg_2, arg_3=True):
        """parallel reduce followed by broadcast of the result"""
        return arg_0.reduce(arg_1, arg_2, arg_3=arg_3, all=True)


def Func(**arg_0):
    """Bind an Engine's Kernel to be used as a full IPython kernel.

    This allows a running Engine to be used simultaneously as a full IPython kernel
    with the QtConsole or other frontends.

    This function returns immediately.
    """
    from IPython.zmq.ipkernel import IPKernelApp
    from IPython.parallel.apps.ipengineapp import IPEngineApp

    # first check for IPKernelApp, in which case this should be a no-op
    # because there is already a bound kernel
    if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
        return

    if IPEngineApp.initialized():
        try:
            arg_1 = IPEngineApp.instance()
        except MultipleInstanceError:
            pass
        else:
            return arg_1.Func(**arg_0)

    raise RuntimeError("Func be called from an IPEngineApp instance")

Bind an Engine s Kernel to be used as a full IPython kernel . This allows a running Engine to be used simultaneously as a full IPython kernel with the QtConsole or other frontends . This function returns immediately .


def Func ( arg_0 , arg_1 ) : arg_2 = subprocess . Popen ( [ arg_1 , arg_0 . filename ] ) arg_2 . communicate ( )

def Func(arg_0, arg_1):
    """Open the vcard file for a contact in an external editor.

    :param selected_vcard: the contact to edit
    :type selected_vcard: carddav_object.CarddavObject
    :param editor: the eitor command to use
    :type editor: str
    :returns: None
    :rtype: None

    """
    arg_2 = subprocess.Popen([arg_1, arg_0.filename])
    arg_2.communicate()

Open the vcard file for a contact in an external editor .


(circuit,
                               scale=0.7,
                               filename=None,
                               style=None,
                               plot_barriers=True,
                               reverse_bits=False,
                               justify=None)

def Func(arg_0,
                               arg_1=0.7,
                               arg_2=None,
                               arg_3=None,
                               arg_4=True,
                               arg_5=False,
                               arg_6=None):
    """Draw a quantum circuit based on matplotlib.
    If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
    We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.

    Args:
        circuit (QuantumCircuit): a quantum circuit
        scale (float): scaling factor
        filename (str): file path to save image to
        style (dict or str): dictionary of style or file name of style file
        reverse_bits (bool): When set to True reverse the bit order inside
            registers for the output visualization.
        plot_barriers (bool): Enable/disable drawing barriers in the output
            circuit. Defaults to True.
        justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
            the circuit should be justified.

    Returns:
        matplotlib.figure: a matplotlib figure object for the circuit diagram
    """

    arg_7, arg_8, arg_9 = utils._get_layered_instructions(arg_0,
                                                        arg_5=arg_5,
                                                        arg_6=arg_6)
    arg_10 = _matplotlib.MatplotlibDrawer(arg_7, arg_8, arg_9, arg_1=arg_1, arg_3=arg_3,
                                       arg_4=arg_4,
                                       arg_5=arg_5)
    return arg_10.draw(arg_2)

Draw a quantum circuit based on matplotlib . If %matplotlib inline is invoked in a Jupyter notebook it visualizes a circuit inline . We recommend %config InlineBackend . figure_format = svg for the inline visualization .


(self, url, response_code=200, headers={}, follow=False)

def Func ( arg_0 , arg_1 , arg_2 = 200 , arg_3 = { } , arg_4 = False ) : if not arg_0 . authed : arg_0 . authorize ( ) arg_5 = arg_0 . client . get ( arg_1 , arg_4 = arg_4 , ** arg_3 ) arg_0 . assertEqual ( arg_2 , arg_5 . status_code ) return arg_5

def Func(arg_0, arg_1, arg_2=200, arg_3={}, arg_4=False):
        """Does a django test client ``get`` against the given url after
        logging in the admin first.

        :param url:
            URL to fetch
        :param response_code:
            Expected response code from the URL fetch.  This value is
            asserted.  Defaults to 200
        :param headers:
            Optional dictionary of headers to send in the request
        :param follow:
            When True, the get call will follow any redirect requests.
            Defaults to False.
        :returns:
            Django testing ``Response`` object
        """
        if not arg_0.authed:
            arg_0.authorize()

        arg_5 = arg_0.client.get(arg_1, arg_4=arg_4, **arg_3)
        arg_0.assertEqual(arg_2, arg_5.status_code)
        return arg_5

Does a django test client get against the given url after logging in the admin first .


(self, service_name, deployment_name, role_name, lun)

return self._perform_get(
            self._get_data_disk_path(
                service_name, deployment_name, role_name, lun),
            DataVirtualHardDisk)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        '''
        Retrieves the specified data disk from a virtual machine.

        service_name:
            The name of the service.
        deployment_name:
            The name of the deployment.
        role_name:
            The name of the role.
        lun:
            The Logical Unit Number (LUN) for the disk.
        '''
        _validate_not_none('service_name', arg_1)
        _validate_not_none('deployment_name', arg_2)
        _validate_not_none('role_name', arg_3)
        _validate_not_none('lun', arg_4)
        return arg_0._perform_get(
            arg_0._Func_path(
                arg_1, arg_2, arg_3, arg_4),
            DataVirtualHardDisk)

Retrieves the specified data disk from a virtual machine .


def Func(arg_0, arg_1):
        """
        Iterate over each learner data record and transmit it to the integrated channel.
        """
        arg_2 = arg_0.get_learner_data_exporter(arg_1)
        arg_3 = arg_0.get_learner_data_transmitter()
        arg_3.transmit(arg_2)

Iterate over each learner data record and transmit it to the integrated channel .


def Func ( arg_0 , arg_1 = None ) : arg_2 = set ( AUTO_GENERATE_AVATAR_SIZES ) if arg_1 is not None : arg_2 . add ( arg_1 ) for arg_3 in cached_funcs : for arg_1 in arg_2 : cache . delete ( get_cache_key ( arg_0 , arg_1 , arg_3 ) )

def Func(arg_0, arg_1=None):
    """
    Function to be called when saving or changing an user's avatars.
    """
    arg_2 = set(AUTO_GENERATE_AVATAR_SIZES)
    if arg_1 is not None:
        arg_2.add(arg_1)
    for arg_3 in cached_funcs:
        for arg_1 in arg_2:
            cache.delete(get_cache_key(arg_0, arg_1, arg_3))

Function to be called when saving or changing an user s avatars .


def Func ( arg_0 , arg_1 ) : arg_0 . wbtn_ok = button . Button ( "btn_ok" , arg_0 , arg_0 . window , arg_0 . peng , pos = lambda sw , sh , bw , bh : ( sw / 2 - bw / 2 , sh / 2 - bh / 2 - bh * 2 ) , arg_3 = [ 0 , 0 ] , label = arg_1 , borderstyle = arg_0 . borderstyle ) arg_0 . wbtn_ok . size = lambda sw , sh : ( arg_0 . wbtn_ok . _label . font_size * 8 , arg_0 . wbtn_ok . _label . font_size * 2 ) arg_0 . addWidget ( arg_0 . wbtn_ok ) def f ( ) : arg_0 . doAction ( "click_ok" ) arg_0 . exitDialog ( ) arg_0 . wbtn_ok . addAction ( "click" , f )

def Func(arg_0,arg_1):
        """
        Adds an OK button to allow the user to exit the dialog.

        This widget can be triggered by setting the label ``label_ok`` to a string.

        This widget will be mostly centered on the screen, but below the main label
        by the double of its height.
        """
        # OK Button
        arg_0.wbtn_ok = button.Button("btn_ok",arg_0,arg_0.window,arg_0.peng,
                        pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2-bh*2),
                        arg_3=[0,0],
                        label=arg_1,
                        borderstyle=arg_0.borderstyle
                        )
        arg_0.wbtn_ok.size = lambda sw,sh: (arg_0.wbtn_ok._label.font_size*8,arg_0.wbtn_ok._label.font_size*2)
        arg_0.addWidget(arg_0.wbtn_ok)

        def f():
            arg_0.doAction("click_ok")
            arg_0.exitDialog()
        arg_0.wbtn_ok.addAction("click",f)

Adds an OK button to allow the user to exit the dialog . This widget can be triggered by setting the label label_ok to a string . This widget will be mostly centered on the screen but below the main label by the double of its height .


return [compress_user(p, tilde_expand, tilde_val) for p in found]

def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
get_ipython
(
)
arg_3
=
arg_1
.
symbol
if
arg_1
.
line
.
endswith
(
'-b'
)
or
' -b '
in
arg_1
.
line
:
arg_4
=
arg_0
.
db
.
get
(
'bookmarks'
,
)
if
arg_4
:
return
arg_4
.
keys
(
)
else
:
return
[
]
if
arg_1
.
symbol
==
'-'
:
arg_5
=
str
(
len
(
str
(
len
(
arg_2
.
user_ns
[
'_dh'
]
)
+
1
)
)
)
arg_6
=
'-%0'
+
arg_5
+
'd [%s]'
arg_7
=
[
arg_6
%
(
i
,
s
)
for
i
,
s
in
enumerate
(
arg_2
.
user_ns
[
'_dh'
]
)
]
if
len
(
arg_7
)
>
1
:
return
arg_7
return
[
]
if
arg_1
.
symbol
.
startswith
(
'--'
)
:
return
[
"--"
+
os
.
path
.
basename
(
arg_8
)
for
arg_8
in
arg_2
.
user_ns
[
'_dh'
]
]
arg_3
,
arg_9
,
arg_10
=
expand_user
(
arg_3
)
arg_3
=
arg_3
.
replace
(
'\\'
,
'/'
)
arg_11
=
[
]
for
arg_8
in
[
f
.
replace
(
'\\'
,
'/'
)
+
'/'
for
f
in
glob
.
glob
(
arg_3
+
'*'
)
if
os
.
path
.
isdir
(
f
)
]
:
if
' '
in
arg_8
:
raise
TryNext
arg_11
.
append
(
arg_8
)
if
not
arg_11
:
if
os
.
path
.
isdir
(
arg_3
)
:
return
[
compress_user
(
arg_3
,
arg_9
,
arg_10
)
]
arg_12
=
arg_0
.
db
.
get
(
'bookmarks'
,
{
}
)
.
iterkeys
(
)
arg_13
=
[
s
for
s
in
arg_12
if
s
.
startswith
(
arg_1
.
symbol
)
]
if
arg_13
:
return
arg_13
raise
TryNext
return
[
compress_user
(
arg_14
,
arg_9
,
arg_10
)
for
arg_14
in
arg_11
]

def Func(arg_0, arg_1):
    """Completer function for cd, which only returns directories."""
    arg_2 = get_ipython()
    arg_3 = arg_1.symbol

    #print(event) # dbg
    if arg_1.line.endswith('-b') or ' -b ' in arg_1.line:
        # return only bookmark completions
        arg_4 = arg_0.db.get('bookmarks', None)
        if arg_4:
            return arg_4.keys()
        else:
            return []

    if arg_1.symbol == '-':
        arg_5 = str(len(str(len(arg_2.user_ns['_dh']) + 1)))
        # jump in directory history by number
        arg_6 = '-%0' + arg_5 +'d [%s]'
        arg_7 = [ arg_6 % (i,s) for i,s in enumerate(arg_2.user_ns['_dh'])]
        if len(arg_7) > 1:
            return arg_7
        return []

    if arg_1.symbol.startswith('--'):
        return ["--" + os.path.basename(arg_8) for arg_8 in arg_2.user_ns['_dh']]

    # Expand ~ in path and normalize directory separators.
    arg_3, arg_9, arg_10 = expand_user(arg_3)
    arg_3 = arg_3.replace('\\','/')

    arg_11 = []
    for arg_8 in [f.replace('\\','/') + '/' for f in glob.glob(arg_3+'*')
              if os.path.isdir(f)]:
        if ' ' in arg_8:
            # we don't want to deal with any of that, complex code
            # for this is elsewhere
            raise TryNext

        arg_11.append(arg_8)

    if not arg_11:
        if os.path.isdir(arg_3):
            return [compress_user(arg_3, arg_9, arg_10)]

        # if no completions so far, try bookmarks
        arg_12 = arg_0.db.get('bookmarks',{}).iterkeys()
        arg_13 = [s for s in arg_12 if s.startswith(arg_1.symbol)]
        if arg_13:
            return arg_13

        raise TryNext

    return [compress_user(arg_14, arg_9, arg_10) for arg_14 in arg_11]

Completer function for cd which only returns directories .


def Func ( arg_0 ) : arg_1 = None if arg_0 . _settings [ "user" ] or arg_0 . _settings [ "authorization" ] : if arg_0 . _settings [ "url" ] : arg_1 = arg_0 . _settings [ "url" ] elif arg_0 . _settings [ "base_url" ] : arg_1 = arg_0 . _settings [ "base_url" ] return arg_1

def Func(arg_0):
        """ Get URL used for authentication

        Returns:
            string: URL
        """
        arg_1 = None
        if arg_0._settings["user"] or arg_0._settings["authorization"]:
            if arg_0._settings["url"]:
                arg_1 = arg_0._settings["url"]
            elif arg_0._settings["base_url"]:
                arg_1 = arg_0._settings["base_url"]
        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Handles the behaviour of visible bolts flying toward Marauders."""
    # Disappear if we've hit a Marauder or a bunker.
    if (arg_0.character in arg_4['bunker_hitters'] or
        arg_0.character in arg_4['marauder_hitters']):
      return arg_0._teleport((-1, -1))
    # Otherwise, northward!
    arg_0._north(arg_1, arg_4)

Handles the behaviour of visible bolts flying toward Marauders .


Is the store unlocked so that I can decrypt the content?

def
Func
(
arg_0
)
:
if
arg_0
.
password
is
not
:
return
bool
(
arg_0
.
password
)
else
:
if
(
"UNLOCK"
in
os
.
environ
and
os
.
environ
[
"UNLOCK"
]
and
arg_0
.
config_key
in
arg_0
.
config
and
arg_0
.
config
[
arg_0
.
config_key
]
)
:
log
.
debug
(
"Trying to use environmental "
"variable to unlock wallet"
)
arg_0
.
unlock
(
os
.
environ
.
get
(
"UNLOCK"
)
)
return
bool
(
arg_0
.
password
)
return
False

def Func(arg_0):
        """ Is the store Func so that I can decrypt the content?
        """
        if arg_0.password is not None:
            return bool(arg_0.password)
        else:
            if (
                "UNLOCK" in os.environ
                and os.environ["UNLOCK"]
                and arg_0.config_key in arg_0.config
                and arg_0.config[arg_0.config_key]
            ):
                log.debug("Trying to use environmental " "variable to unlock wallet")
                arg_0.unlock(os.environ.get("UNLOCK"))
                return bool(arg_0.password)
        return False


(self, admin_login, admin_password, location)

return _SqlManagementXmlSerializer.xml_to_create_server_response(
            response.body)

def Func(arg_0, arg_1, arg_2, arg_3):
        '''
        Create a new Azure SQL Database server.

        admin_login:
            The administrator login name for the new server.
        admin_password:
            The administrator login password for the new server.
        location:
            The region to deploy the new server.
        '''
        _validate_not_none('admin_login', arg_1)
        _validate_not_none('admin_password', arg_2)
        _validate_not_none('location', arg_3)
        arg_4 = arg_0.perform_post(
            arg_0._get_servers_path(),
            _SqlManagementXmlSerializer.Func_to_xml(
                arg_1,
                arg_2,
                arg_3
            )
        )

        return _SqlManagementXmlSerializer.xml_to_Func_response(
            arg_4.body)

Create a new Azure SQL Database server .


return [element for element in (line.strip() for line in value.split('\n'))
            if element]

def Func ( arg_0 ) : return [ arg_1 for arg_1 in ( arg_2 . strip ( ) for arg_2 in arg_0 . split ( '\n' ) ) if arg_1 ]

def Func(arg_0):
    """Split a multiline string into a list, excluding blank lines."""
    return [arg_1 for arg_1 in (arg_2.strip() for arg_2 in arg_0.split('\n'))
            if arg_1]

Split a multiline string into a list excluding blank lines .


def
Func
(
arg_0
,
arg_1
,
arg_2
=
"="
,
arg_3
=
)
:
if
arg_3
==
:
arg_3
=
arg_0
.
_key
try
:
arg_1
=
unicode
(
arg_1
)
except
:
pass
arg_4
=
"delete from "
+
arg_0
.
_name
+
" where "
+
arg_3
+
" "
+
arg_2
+
" ?"
arg_0
.
_db
.
_cur
.
execute
(
arg_4
,
(
arg_1
,
)
)

def Func(arg_0, arg_1, arg_2="=", arg_3=None):

        """ Deletes the row with given id.
        """

        if arg_3 == None: arg_3 = arg_0._key
        try: arg_1 = unicode(arg_1)
        except: pass
        arg_4 = "delete from "+arg_0._name+" where "+arg_3+" "+arg_2+" ?"
        arg_0._db._cur.execute(arg_4, (arg_1,))


return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)

def Func ( arg_0 ) : if len ( arg_0 ) == 0 : return np . array ( [ ] , dtype = np . int64 ) return np . stack ( list ( map ( _transform_triple_numpy , arg_0 ) ) , axis = 0 )

def Func(arg_0):
    """Packs a list of triple indexes into a 2D numpy array."""
    if len(arg_0) == 0:
        return np.array([], dtype=np.int64)
    return np.stack(list(map(_transform_triple_numpy, arg_0)), axis=0)

Packs a list of triple indexes into a 2D numpy array .


def
Func
(
arg_0
)
:
def
node_to_dict
(
arg_1
)
:
arg_2
=
{
}
arg_2
.
update
(
arg_1
.
items
(
)
)
arg_3
=
getattr
(
arg_1
,
'text'
,
)
if
arg_3
is
not
:
arg_2
[
'__text__'
]
=
arg_3
arg_4
=
{
}
for
arg_5
in
arg_1
:
arg_4
.
setdefault
(
arg_5
.
tag
,
[
]
)
.
append
(
node_to_dict
(
arg_5
)
)
arg_2
.
update
(
arg_4
.
items
(
)
)
return
arg_2
arg_6
=
remove_invalid_xml_chars
(
arg_0
)
try
:
arg_7
=
xml
.
etree
.
ElementTree
.
fromstring
(
arg_6
)
except
xml
.
etree
.
ElementTree
.
ParseError
as
e
:
arg_8
=
"XML stream %s"
%
(
str
(
e
)
)
raise
ParseError
(
arg_8
=
arg_8
)
arg_2
=
node_to_dict
(
arg_7
)
return
arg_2

def Func(arg_0):
    """Convert a XML stream into a dictionary.

    This function transforms a xml stream into a dictionary. The
    attributes are stored as single elements while child nodes are
    stored into lists. The text node is stored using the special
    key '__text__'.

    This code is based on Winston Ewert's solution to this problem.
    See http://codereview.stackexchange.com/questions/10400/convert-elementtree-to-dict
    for more info. The code was licensed as cc by-sa 3.0.

    :param raw_xml: XML stream

    :returns: a dict with the XML data

    :raises ParseError: raised when an error occurs parsing the given
        XML stream
    """
    def node_to_dict(arg_1):
        arg_2 = {}
        arg_2.update(arg_1.items())

        arg_3 = getattr(arg_1, 'text', None)

        if arg_3 is not None:
            arg_2['__text__'] = arg_3

        arg_4 = {}
        for arg_5 in arg_1:
            arg_4.setdefault(arg_5.tag, []).append(node_to_dict(arg_5))

        arg_2.update(arg_4.items())

        return arg_2

    arg_6 = remove_invalid_xml_chars(arg_0)

    try:
        arg_7 = xml.etree.ElementTree.fromstring(arg_6)
    except xml.etree.ElementTree.ParseError as e:
        arg_8 = "XML stream %s" % (str(e))
        raise ParseError(arg_8=arg_8)

    arg_2 = node_to_dict(arg_7)

    return arg_2

Convert a XML stream into a dictionary .


def Func(arg_0, arg_1):
        """Break covalent bonds between metals and organic atoms under certain conditions.

        The algorithm works as follows:

        - Disconnect N, O, F from any metal.
        - Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po).
        - For every bond broken, adjust the charges of the begin and end atoms accordingly.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The molecule with metals Funced.
        :rtype: rdkit.Chem.rdchem.Mol
        """
        log.debug('Running MetalDisconnector')
        # Remove bonds that match SMARTS
        for arg_2 in [arg_0._metal_nof, arg_0._metal_non]:
            arg_3 = arg_1.GetSubstructMatches(arg_2)
            arg_4 = Chem.RWMol(arg_1)
            arg_5 = []
            for arg_6, arg_7 in arg_3:
                # TODO: Could get the valence contributions of the bond instead of GetBondTypeAsDouble?
                arg_5.append(int(arg_1.GetBondBetweenAtoms(arg_6, arg_7).GetBondTypeAsDouble()))
                arg_4.RemoveBond(arg_6, arg_7)
            # Adjust neighbouring charges accordingly
            arg_1 = arg_4.GetMol()
            for arg_8, (arg_6, arg_7) in enumerate(arg_3):
                arg_9 = arg_5[arg_8]
                arg_10 = arg_1.GetAtomWithIdx(arg_6)
                arg_10.SetFormalCharge(arg_10.GetFormalCharge() + arg_9)
                arg_11 = arg_1.GetAtomWithIdx(arg_7)
                arg_11.SetFormalCharge(arg_11.GetFormalCharge() - arg_9)
                log.info('Removed covalent bond between %s and %s', arg_10.GetSymbol(), arg_11.GetSymbol())
        Chem.SanitizeMol(arg_1)
        return arg_1

Break covalent bonds between metals and organic atoms under certain conditions.

        The algorithm works as follows:

        - Disconnect N, O, F from any metal.
        - Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po).
        - For every bond broken, adjust the charges of the begin and end atoms accordingly.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The molecule with metals disconnected.
        :rtype: rdkit.Chem.rdchem.Mol

Break covalent bonds between metals and organic atoms under certain conditions .


def Func ( arg_0 ) : arg_1 = "," . join ( str ( v ) for v in arg_0 ) arg_2 = int ( int ( hashlib . md5 ( arg_1 ) . hexdigest ( ) , 16 ) % ( 2 ** 64 ) ) return arg_2

def Func(arg_0):
    """Hash a coordinate to a 64 bit integer."""
    arg_1 = ",".join(str(v) for v in arg_0)
    # Compute the hash and convert to 64 bit int.
    arg_2 = int(int(hashlib.md5(arg_1).hexdigest(), 16) % (2 ** 64))
    return arg_2


def Func ( * arg_0 , ** arg_1 ) : arg_2 = cherrypy . serving . request . _json_inner_handler ( * arg_0 , ** arg_1 ) for arg_3 in JSONEncoder ( ) . iterencode ( arg_2 ) : yield arg_3 . encode ( 'utf-8' )

def Func(*arg_0, **arg_1):
    """Custom JSON encoder handler"""

    arg_2 = cherrypy.serving.request._json_inner_handler(*arg_0, **arg_1)

    for arg_3 in JSONEncoder().iterencode(arg_2):
        yield arg_3.encode('utf-8')


def Func ( arg_0 , Func , arg_2 = False ) : arg_0 . push ( Func , arg_2 ) yield arg_0 . current arg_0 . pop ( )

def Func(arg_0, Func, arg_2=False):
        """
        Allows temporarily pushing an additional context, yields the new context
        into the following block.
        """
        arg_0.push(Func, arg_2)
        yield arg_0.current
        arg_0.pop()

Allows temporarily pushing an additional context yields the new context into the following block .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . _protocols . pop ( arg_1 ) arg_2 . transport = None return { }

def Func(arg_0, arg_1):
        """
        Disconnects the given protocol.
        """
        arg_2 = arg_0._protocols.pop(arg_1)
        arg_2.transport = None
        return {}


def Func ( arg_0 , arg_1 = None , ** arg_2 ) : if arg_1 != None : for arg_3 in arg_1 : arg_0 . fields . append ( arg_3 )

def Func(arg_0, arg_1 = None, **arg_2):
    """
    Add the fields into the list of fields.
    """
    if arg_1 != None:
      for arg_3 in arg_1:
        arg_0.fields.append(arg_3)

Add the fields into the list of fields .


def Func ( arg_0 , arg_1 = arg_2 ) : arg_3 = { } arg_4 = super ( ) . Func ( arg_1 , ** arg_3 ) return arg_4

def Func(arg_0, arg_1=arg_2):
        """Fetch events from the MozillaClub URL.

        The method retrieves, from a MozillaClub URL, the
        events. The data is a Google spreadsheet retrieved using
        the feed API REST.

        :param category: the category of items to Func

        :returns: a generator of events
        """
        arg_3 = {}
        arg_4 = super().Func(arg_1, **arg_3)

        return arg_4

Fetch events from the MozillaClub URL.

        The method retrieves, from a MozillaClub URL, the
        events. The data is a Google spreadsheet retrieved using
        the feed API REST.

        :param category: the category of items to fetch

        :returns: a generator of events


return JobDescriptor.get_complete_descriptor(
        job_metadata, job_params, job_resources, task_descriptors)

def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
{
}
for
arg_3
in
[
'job-id'
,
'job-name'
,
'create-time'
]
:
arg_2
[
arg_3
]
=
arg_1
.
get
(
arg_3
)
arg_2
[
'create-time'
]
=
dsub_util
.
replace_timezone
(
datetime
.
datetime
.
strptime
(
arg_1
[
'create-time'
]
,
'%Y-%m-%d %H:%M:%S.%f'
)
,
tzlocal
(
)
)
arg_4
=
Resources
(
)
arg_5
=
{
}
arg_6
=
arg_1
.
get
(
'labels'
,
{
}
)
if
'dsub-version'
in
arg_6
:
arg_2
[
'dsub-version'
]
=
arg_6
[
'dsub-version'
]
del
arg_6
[
'dsub-version'
]
arg_5
[
'labels'
]
=
arg_0
.
_label_params_from_dict
(
arg_6
)
arg_5
[
'envs'
]
=
arg_0
.
_env_params_from_dict
(
arg_1
.
get
(
'envs'
,
{
}
)
)
arg_5
[
'inputs'
]
=
arg_0
.
_input_file_params_from_dict
(
arg_1
.
get
(
'inputs'
,
{
}
)
,
False
)
arg_5
[
'outputs'
]
=
arg_0
.
_output_file_params_from_dict
(
arg_1
.
get
(
'outputs'
,
{
}
)
,
False
)
if
arg_1
.
get
(
'task-id'
)
is
:
arg_7
=
arg_5
arg_8
=
{
'task-id'
:
}
arg_9
=
{
}
else
:
arg_7
=
{
}
arg_8
=
{
'task-id'
:
str
(
arg_1
.
get
(
'task-id'
)
)
}
arg_9
=
arg_5
arg_10
=
Resources
(
logging_path
=
arg_1
.
get
(
'logging'
)
)
arg_11
=
[
TaskDescriptor
.
get_complete_descriptor
(
arg_8
,
arg_9
,
arg_10
)
]
return
JobDescriptor
.
get_complete_descriptor
(
arg_2
,
arg_7
,
arg_4
,
arg_11
)

def Func(arg_0, arg_1):
    """Populate a JobDescriptor from the local provider's original meta.yaml.

    The local job provider had the first incarnation of a YAML file for each
    task. That idea was extended here in the JobDescriptor and the local
    provider adopted the JobDescriptor.to_yaml() call to write its meta.yaml.

    The JobDescriptor.from_yaml() detects if it receives a local provider's
    "v0" meta.yaml and calls this function.

    Args:
      job: an object produced from decoding meta.yaml.

    Returns:
      A JobDescriptor populated as best we can from the old meta.yaml.
    """

    # The v0 meta.yaml only contained:
    #   create-time, job-id, job-name, logging, task-id
    #   labels, envs, inputs, outputs
    # It did NOT contain user-id.
    # dsub-version might be there as a label.

    arg_2 = {}
    for arg_3 in ['job-id', 'job-name', 'create-time']:
      arg_2[arg_3] = arg_1.get(arg_3)

    # Make sure that create-time string is turned into a datetime
    arg_2['create-time'] = dsub_util.replace_timezone(
        datetime.datetime.strptime(arg_1['create-time'], '%Y-%m-%d %H:%M:%S.%f'),
        tzlocal())

    # The v0 meta.yaml contained a "logging" field which was the task-specific
    # logging path. It did not include the actual "--logging" value the user
    # specified.
    arg_4 = Resources()

    # The v0 meta.yaml represented a single task.
    # It did not distinguish whether params were job params or task params.
    # We will treat them as either all job params or all task params, based on
    # whether the task-id is empty or an integer value.
    #
    # We also cannot distinguish whether inputs/outputs were recursive or not.
    # Just treat them all as non-recursive.
    arg_5 = {}

    # The dsub-version may be in the meta.yaml as a label. If so remove it
    # and set it as a top-level job metadata value.
    arg_6 = arg_1.get('labels', {})
    if 'dsub-version' in arg_6:
      arg_2['dsub-version'] = arg_6['dsub-version']
      del arg_6['dsub-version']
    arg_5['labels'] = arg_0._label_params_from_dict(arg_6)

    arg_5['envs'] = arg_0._env_params_from_dict(arg_1.get('envs', {}))
    arg_5['inputs'] = arg_0._input_file_params_from_dict(
        arg_1.get('inputs', {}), False)
    arg_5['outputs'] = arg_0._output_file_params_from_dict(
        arg_1.get('outputs', {}), False)

    if arg_1.get('task-id') is None:
      arg_7 = arg_5
      arg_8 = {'task-id': None}
      arg_9 = {}
    else:
      arg_7 = {}
      arg_8 = {'task-id': str(arg_1.get('task-id'))}
      arg_9 = arg_5

    arg_10 = Resources(logging_path=arg_1.get('logging'))

    arg_11 = [
        TaskDescriptor.get_complete_descriptor(arg_8, arg_9,
                                               arg_10)
    ]

    return JobDescriptor.get_complete_descriptor(
        arg_2, arg_7, arg_4, arg_11)

Populate a JobDescriptor from the local provider s original meta . yaml .


return {test.__name__: test(self) for test in this_tests}

def Func ( arg_0 , arg_1 , arg_2 = None ) : arg_2 = arg_2 or { } arg_2 = arg_2 . get ( 'striplog' , arg_2 . get ( 'Striplog' , [ ] ) ) arg_3 = arg_1 . get ( 'all' , [ ] ) + arg_1 . get ( 'All' , [ ] ) + arg_1 . get ( 'ALL' , [ ] ) + arg_1 . get ( 'striplog' , arg_1 . get ( 'Striplog' , [ ] ) ) + utils . flatten_list ( [ arg_1 . get ( a ) for a in arg_2 ] ) arg_3 = filter ( None , arg_3 ) if not arg_1 . get ( 'striplog' , arg_1 . get ( 'Striplog' , 1 ) ) : arg_3 = [ ] return { arg_4 . __name__ : arg_4 ( arg_0 ) for arg_4 in arg_3 }

def Func(arg_0, arg_1, arg_2=None):
        """
        Run a series of tests and return the corresponding results.

        Based on curve testing for ``welly``.

        Args:
            tests (list): a list of functions.

        Returns:
            list. The results. Stick to booleans (True = pass) or ints.
        """
        # This is hacky... striplog should probably merge with welly...

        # Ignore aliases
        arg_2 = arg_2 or {}
        arg_2 = arg_2.get('striplog', arg_2.get('Striplog', []))

        # Gather the tests.
        # First, anything called 'all', 'All', or 'ALL'.
        # Second, anything with the name of the curve we're in now.
        # Third, anything that the alias list has for this curve.
        # (This requires a reverse look-up so it's a bit messy.)
        arg_3 =\
            arg_1.get('all', [])+arg_1.get('All', [])+arg_1.get('ALL', [])\
            + arg_1.get('striplog', arg_1.get('Striplog', []))\
            + utils.flatten_list([arg_1.get(a) for a in arg_2])
        arg_3 = filter(None, arg_3)

        # If we explicitly set zero tests for a particular key, then this
        # overrides the 'all' tests.
        if not arg_1.get('striplog', arg_1.get('Striplog', 1)):
            arg_3 = []

        return {arg_4.__name__: arg_4(arg_0) for arg_4 in arg_3}

Run a series of tests and return the corresponding results .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . context . get ( 'enterprise_customer' ) try : arg_3 = ThirdPartyAuthApiClient ( ) arg_4 = arg_3 . get_username_from_remote_id ( arg_2 . identity_provider , arg_1 ) arg_5 = User . objects . get ( arg_4 = arg_4 ) return models . EnterpriseCustomerUser . objects . get ( user_id = arg_5 . id , arg_2 = arg_2 ) except ( models . EnterpriseCustomerUser . DoesNotExist , User . DoesNotExist ) : pass return None

def Func(arg_0, arg_1):
        """
        Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.

        It first uses the third party auth api to find the associated username to do the lookup.
        """
        arg_2 = arg_0.context.get('enterprise_customer')

        try:
            arg_3 = ThirdPartyAuthApiClient()
            arg_4 = arg_3.get_username_from_remote_id(
                arg_2.identity_provider, arg_1
            )
            arg_5 = User.objects.get(arg_4=arg_4)
            return models.EnterpriseCustomerUser.objects.get(
                user_id=arg_5.id,
                arg_2=arg_2
            )
        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):
            pass

        return None

Validates the tpa_user_id if is given to see if there is an existing EnterpriseCustomerUser for it .


def Func ( arg_0 ) : arg_1 = dict ( ) arg_2 = 0 for arg_3 in arg_0 : if arg_3 == SENTINEL_VALUE_FOR_MISSING_DATA : continue arg_2 += 1 if arg_3 in arg_1 : arg_1 [ arg_3 ] += 1 else : arg_1 [ arg_3 ] = 1 if arg_2 == 0 : return None arg_4 = arg_1 . items ( ) arg_4 . sort ( cmp = lambda x , y : x [ 1 ] - y [ 1 ] , reverse = True ) return arg_4 [ 0 ] [ 0 ]

def Func(arg_0):
  """ Returns most common value seen in the non-None elements of the list
  """

  arg_1 = dict()
  arg_2 = 0

  for arg_3 in arg_0:
    if arg_3 == SENTINEL_VALUE_FOR_MISSING_DATA:
      continue

    arg_2 += 1
    if arg_3 in arg_1:
      arg_1[arg_3] += 1
    else:
      arg_1[arg_3] = 1

  # Get the most common one
  if arg_2 == 0:
    return None

  # Sort by counts
  arg_4 = arg_1.items()
  arg_4.sort(cmp=lambda x,y: x[1] - y[1], reverse=True)
  return arg_4[0][0]

Returns most common value seen in the non - None elements of the list


def Func(arg_0, arg_1, arg_2):
    '''
    This will call `clean_attribute` on the attribute and also allows for the
    creation of boolean attributes.

    Ex. input(selected=True) is equivalent to input(selected="selected")
    '''
    arg_1 = arg_0.clean_attribute(arg_1)

    # Check for boolean attributes
    # (i.e. selected=True becomes selected="selected")
    if arg_2 is True:
      arg_2 = arg_1

    if arg_2 is False:
      arg_2 = "false"

    return (arg_1, arg_2)

This will call clean_attribute on the attribute and also allows for the creation of boolean attributes .


(returns, factor_returns=None, positions=None,
               transactions=None, turnover_denom='AGB')

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
,
arg_3
=
,
arg_4
=
'AGB'
)
:
arg_5
=
pd
.
Series
(
)
for
arg_6
in
SIMPLE_STAT_FUNCS
:
arg_5
[
arg_7
[
arg_6
.
__name__
]
]
=
arg_6
(
arg_0
)
if
arg_2
is
not
:
arg_5
[
'Gross leverage'
]
=
gross_lev
(
arg_2
)
.
mean
(
)
if
arg_3
is
not
:
arg_5
[
'Daily turnover'
]
=
get_turnover
(
arg_2
,
arg_3
,
arg_4
)
.
mean
(
)
if
arg_1
is
not
:
for
arg_6
in
FACTOR_STAT_FUNCS
:
arg_9
=
arg_6
(
arg_0
,
arg_1
)
arg_5
[
arg_7
[
arg_6
.
__name__
]
]
=
arg_9
return
arg_5

def Func(arg_0, arg_1=None, arg_2=None,
               arg_3=None, arg_4='AGB'):
    """
    Calculates various performance metrics of a strategy, for use in
    plotting.show_Func.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
         - If None, do not compute alpha, beta, and information ratio.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
        - See full explanation in tears.create_full_tear_sheet.
    turnover_denom : str
        Either AGB or portfolio_value, default AGB.
        - See full explanation in txn.get_turnover.

    Returns
    -------
    pd.Series
        Performance metrics.
    """

    arg_5 = pd.Series()
    for arg_6 in SIMPLE_STAT_FUNCS:
        arg_5[arg_7[arg_6.__name__]] = arg_6(arg_0)

    if arg_2 is not None:
        arg_5['Gross leverage'] = gross_lev(arg_2).mean()
        if arg_3 is not None:
            arg_5['Daily turnover'] = get_turnover(arg_2,
                                                   arg_3,
                                                   arg_4).mean()
    if arg_1 is not None:
        for arg_6 in FACTOR_STAT_FUNCS:
            arg_9 = arg_6(arg_0, arg_1)
            arg_5[arg_7[arg_6.__name__]] = arg_9

    return arg_5

Calculates various performance metrics of a strategy, for use in
    plotting.show_perf_stats.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
         - If None, do not compute alpha, beta, and information ratio.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
        - See full explanation in tears.create_full_tear_sheet.
    turnover_denom : str
        Either AGB or portfolio_value, default AGB.
        - See full explanation in txn.get_turnover.

    Returns
    -------
    pd.Series
        Performance metrics.

Calculates various performance metrics of a strategy for use in plotting . show_perf_stats .


'            start_time=UTC_TIMESTAMP(), '

'          WHERE (job_id=%%s AND status=%%s)'

def Func(arg_0, arg_1):
    """ Place the given job in STATUS_RUNNING mode; the job is expected to be
    STATUS_NOTSTARTED.

    NOTE: this function was factored out of jobStartNext because it's also
     needed for testing (e.g., test_client_jobs_dao.py)
    """
    with ConnectionFactory.get() as conn:
      arg_2 = 'UPDATE %s SET status=%%s, ' \
                '            _eng_cjm_conn_id=%%s, ' \
                '            start_time=UTC_TIMESTAMP(), ' \
                '            _eng_last_update_time=UTC_TIMESTAMP() ' \
                '          WHERE (job_id=%%s AND status=%%s)' \
                % (arg_0.jobsTableName,)
      arg_3 = [arg_0.STATUS_RUNNING, arg_0._connectionID,
                   arg_1, arg_0.STATUS_NOTSTARTED]
      arg_4 = conn.cursor.execute(arg_2, arg_3)
      if arg_4 != 1:
        arg_0._logger.warn('jobStartNext: numRowsUpdated=%r instead of 1; '
                          'likely side-effect of transient connection '
                          'failure', arg_4)
    return

Place the given job in STATUS_RUNNING mode ; the job is expected to be STATUS_NOTSTARTED .


(pfpickledir,
                      outdir,
                      lcbasedir,
                      pfpickleglob='periodfinding-*.pkl*',
                      lclistpkl=None,
                      cprenorm=False,
                      nbrradiusarcsec=60.0,
                      maxnumneighbors=5,
                      makeneighborlcs=True,
                      fast_mode=False,
                      gaia_max_timeout=60.0,
                      gaia_mirror=None,
                      xmatchinfo=None,
                      xmatchradiusarcsec=3.0,
                      minobservations=99,
                      sigclip=10.0,
                      lcformat='hat-sql',
                      lcformatdir=None,
                      timecols=None,
                      magcols=None,
                      errcols=None,
                      skipdone=False,
                      done_callback=None,
                      done_callback_args=None,
                      done_callback_kwargs=None,
                      maxobjects=None,
                      nworkers=32)

return parallel_cp(pfpicklelist,
                       outdir,
                       lcbasedir,
                       fast_mode=fast_mode,
                       lclistpkl=lclistpkl,
                       nbrradiusarcsec=nbrradiusarcsec,
                       gaia_max_timeout=gaia_max_timeout,
                       gaia_mirror=gaia_mirror,
                       maxnumneighbors=maxnumneighbors,
                       makeneighborlcs=makeneighborlcs,
                       xmatchinfo=xmatchinfo,
                       xmatchradiusarcsec=xmatchradiusarcsec,
                       sigclip=sigclip,
                       minobservations=minobservations,
                       cprenorm=cprenorm,
                       maxobjects=maxobjects,
                       lcformat=lcformat,
                       lcformatdir=lcformatdir,
                       timecols=timecols,
                       magcols=magcols,
                       errcols=errcols,
                       skipdone=skipdone,
                       nworkers=nworkers,
                       done_callback=done_callback,
                       done_callback_args=done_callback_args,
                       done_callback_kwargs=done_callback_kwargs)

def Func(arg_0,
                      arg_1,
                      arg_2,
                      arg_3='periodfinding-*.pkl*',
                      arg_4=None,
                      arg_5=False,
                      arg_6=60.0,
                      arg_7=5,
                      arg_8=True,
                      arg_9=False,
                      arg_10=60.0,
                      arg_11=None,
                      arg_12=None,
                      arg_13=3.0,
                      arg_14=99,
                      arg_15=10.0,
                      arg_16='hat-sql',
                      arg_17=None,
                      arg_18=None,
                      arg_19=None,
                      arg_20=None,
                      arg_21=False,
                      arg_22=None,
                      arg_23=None,
                      arg_24=None,
                      arg_25=None,
                      arg_26=32):

    '''This drives the parallel execution of `runcp` for a directory of
    periodfinding pickles.

    Parameters
    ----------

    pfpickledir : str
        This is the directory containing all of the period-finding pickles to
        process.

    outdir : str
        The directory the checkplot pickles will be written to.

    lcbasedir : str
        The base directory that this function will look in to find the light
        curves pointed to by the period-finding result files. If you're using
        `lcfnamelist` to provide a list of light curve filenames directly, this
        arg is ignored.

    pkpickleglob : str
        This is a UNIX file glob to select period-finding result pickles in the
        specified `pfpickledir`.

    lclistpkl : str or dict
        This is either the filename of a pickle or the actual dict produced by
        lcproc.make_lclist. This is used to gather neighbor information.

    cprenorm : bool
        Set this to True if the light curves should be renormalized by
        `checkplot.checkplot_pickle`. This is set to False by default because we
        do our own normalization in this function using the light curve's
        registered normalization function and pass the normalized times, mags,
        errs to the `checkplot.checkplot_pickle` function.

    nbrradiusarcsec : float
        The radius in arcseconds to use for a search conducted around the
        coordinates of this object to look for any potential confusion and
        blending of variability amplitude caused by their proximity.

    maxnumneighbors : int
        The maximum number of neighbors that will have their light curves and
        magnitudes noted in this checkplot as potential blends with the target
        object.

    makeneighborlcs : bool
        If True, will make light curve and phased light curve plots for all
        neighbors found in the object collection for each input object.

    fast_mode : bool or float
        This runs the external catalog operations in a "fast" mode, with short
        timeouts and not trying to hit external catalogs that take a long time
        to respond.

        If this is set to True, the default settings for the external requests
        will then become::

                skyview_lookup = False
                skyview_timeout = 10.0
                skyview_retry_failed = False
                dust_timeout = 10.0
                gaia_submit_timeout = 7.0
                gaia_max_timeout = 10.0
                gaia_submit_tries = 2
                complete_query_later = False
                search_simbad = False

        If this is a float, will run in "fast" mode with the provided timeout
        value in seconds and the following settings::

                skyview_lookup = True
                skyview_timeout = fast_mode
                skyview_retry_failed = False
                dust_timeout = fast_mode
                gaia_submit_timeout = 0.66*fast_mode
                gaia_max_timeout = fast_mode
                gaia_submit_tries = 2
                complete_query_later = False
                search_simbad = False

    gaia_max_timeout : float
        Sets the timeout in seconds to use when waiting for the GAIA service to
        respond to our request for the object's information. Note that if
        `fast_mode` is set, this is ignored.

    gaia_mirror : str or None
        This sets the GAIA mirror to use. This is a key in the
        `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each
        mirror.

    xmatchinfo : str or dict
        This is either the xmatch dict produced by the function
        `load_xmatch_external_catalogs` above, or the path to the xmatch info
        pickle file produced by that function.

    xmatchradiusarcsec : float
        This is the cross-matching radius to use in arcseconds.

    minobservations : int
        The minimum of observations the input object's mag/flux time-series must
        have for this function to plot its light curve and phased light
        curve. If the object has less than this number, no light curves will be
        plotted, but the checkplotdict will still contain all of the other
        information.

    sigclip : float or int or sequence of two floats/ints or None
        If a single float or int, a symmetric sigma-clip will be performed using
        the number provided as the sigma-multiplier to cut out from the input
        time-series.

        If a list of two ints/floats is provided, the function will perform an
        'asymmetric' sigma-clip. The first element in this list is the sigma
        value to use for fainter flux/mag values; the second element in this
        list is the sigma value to use for brighter flux/mag values. For
        example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
        dimmings and greater than 3-sigma brightenings. Here the meaning of
        "dimming" and "brightening" is set by *physics* (not the magnitude
        system), which is why the `magsarefluxes` kwarg must be correctly set.

        If `sigclip` is None, no sigma-clipping will be performed, and the
        time-series (with non-finite elems removed) will be passed through to
        the output.

    lcformat : str
        This is the `formatkey` associated with your light curve format, which
        you previously passed in to the `lcproc.register_lcformat`
        function. This will be used to look up how to find and read the light
        curves specified in `basedir` or `use_list_of_filenames`.

    lcformatdir : str or None
        If this is provided, gives the path to a directory when you've stored
        your lcformat description JSONs, other than the usual directories lcproc
        knows to search for them in. Use this along with `lcformat` to specify
        an LC format JSON file that's not currently registered with lcproc.

    timecols : list of str or None
        The timecol keys to use from the lcdict in generating this checkplot.

    magcols : list of str or None
        The magcol keys to use from the lcdict in generating this checkplot.

    errcols : list of str or None
        The errcol keys to use from the lcdict in generating this checkplot.

    skipdone : bool
        This indicates if this function will skip creating checkplots that
        already exist corresponding to the current `objectid` and `magcol`. If
        `skipdone` is set to True, this will be done.

    done_callback : Python function or None
        This is used to provide a function to execute after the checkplot
        pickles are generated. This is useful if you want to stream the results
        of checkplot making to some other process, e.g. directly running an
        ingestion into an LCC-Server collection. The function will always get
        the list of the generated checkplot pickles as its first arg, and all of
        the kwargs for runcp in the kwargs dict. Additional args and kwargs can
        be provided by giving a list in the `done_callbacks_args` kwarg and a
        dict in the `done_callbacks_kwargs` kwarg.

        NOTE: the function you pass in here should be pickleable by normal
        Python if you want to use it with the parallel_cp and parallel_cp_lcdir
        functions below.

    done_callback_args : tuple or None
        If not None, contains any args to pass into the `done_callback`
        function.

    done_callback_kwargs : dict or None
        If not None, contains any kwargs to pass into the `done_callback`
        function.

    maxobjects : int
        The maximum number of objects to process in this run.

    nworkers : int
        The number of parallel workers that will work on the checkplot
        generation process.

    Returns
    -------

    dict
        This returns a dict with keys = input period-finding pickles and vals =
        list of the corresponding checkplot pickles produced.

    '''

    arg_27 = sorted(glob.glob(os.path.join(arg_0, arg_3)))

    LOGINFO('found %s period-finding pickles, running cp...' %
            len(arg_27))

    return parallel_cp(arg_27,
                       arg_1,
                       arg_2,
                       arg_9=arg_9,
                       arg_4=arg_4,
                       arg_6=arg_6,
                       arg_10=arg_10,
                       arg_11=arg_11,
                       arg_7=arg_7,
                       arg_8=arg_8,
                       arg_12=arg_12,
                       arg_13=arg_13,
                       arg_15=arg_15,
                       arg_14=arg_14,
                       arg_5=arg_5,
                       arg_25=arg_25,
                       arg_16=arg_16,
                       arg_17=arg_17,
                       arg_18=arg_18,
                       arg_19=arg_19,
                       arg_20=arg_20,
                       arg_21=arg_21,
                       arg_26=arg_26,
                       arg_22=arg_22,
                       arg_23=arg_23,
                       arg_24=arg_24)

This drives the parallel execution of runcp for a directory of periodfinding pickles .


def Func ( arg_0 ) : if isinstance ( arg_0 , tf . DType ) : arg_0 = arg_0 . as_numpy_dtype ( ) return np . finfo ( arg_0 ) . eps

def Func(arg_0):
  """Returns the machine epsilon for the supplied dtype."""
  if isinstance(arg_0, tf.DType):
    arg_0 = arg_0.as_numpy_dtype()
  return np.finfo(arg_0).eps

Returns the machine epsilon for the supplied dtype .


(self, endpoint, request_pb, response_pb)

async def Func(arg_0, arg_1, arg_2, arg_3):
        """Send a Protocol Buffer formatted chat API request.

        Args:
            endpoint (str): The chat API endpoint to use.
            request_pb: The request body as a Protocol Buffer message.
            response_pb: The response body as a Protocol Buffer message.

        Raises:
            NetworkError: If the request fails.
        """
        logger.debug('Sending Protocol Buffer request %s:\n%s', arg_1,
                     arg_2)
        arg_4 = await arg_0._base_request(
            'https://clients6.google.com/chat/v1/{}'.format(arg_1),
            'application/x-protobuf',  # Request body is Protocol Buffer.
            'proto',  # Response body is Protocol Buffer.
            arg_2.SerializeToString()
        )
        try:
            arg_3.ParseFromString(base64.b64decode(arg_4.body))
        except binascii.Error as e:
            raise exceptions.NetworkError(
                'Failed to decode base64 response: {}'.format(e)
            )
        except google.protobuf.message.DecodeError as e:
            raise exceptions.NetworkError(
                'Failed to decode Protocol Buffer response: {}'.format(e)
            )
        logger.debug('Received Protocol Buffer response:\n%s', arg_3)
        arg_5 = arg_3.response_header.status
        if arg_5 != hangouts_pb2.RESPONSE_STATUS_OK:
            arg_6 = arg_3.response_header.error_description
            raise exceptions.NetworkError(
                'Request failed with status {}: \'{}\''
                .format(arg_5, arg_6)
            )

Send a Protocol Buffer formatted chat API request .


def
Func
(
arg_0
=
,
arg_1
=
'model.npz'
,
arg_2
=
)
:
if
arg_2
is
:
raise
ValueError
(
"session is None."
)
if
arg_0
is
:
arg_0
=
[
]
arg_3
=
[
tensor
.
name
for
tensor
in
arg_0
]
arg_4
=
arg_2
.
run
(
arg_0
)
arg_5
=
{
arg_3
[
idx
]
:
val
for
idx
,
val
in
enumerate
(
arg_4
)
}
np
.
savez
(
arg_1
,
**
arg_5
)
arg_4
=
arg_5
=
del
arg_4
del
arg_5
logging
.
info
(
"[*] Model saved in npz_dict %s"
%
arg_1
)

def Func(arg_0=None, arg_1='model.npz', arg_2=None):
    """Input parameters and the file name, save parameters as a dictionary into .npz file.

    Use ``tl.files.load_and_assign_npz_dict()`` to restore.

    Parameters
    ----------
    save_list : list of parameters
        A list of parameters (tensor) to be saved.
    name : str
        The name of the `.npz` file.
    sess : Session
        TensorFlow Session.

    """
    if arg_2 is None:
        raise ValueError("session is None.")
    if arg_0 is None:
        arg_0 = []

    arg_3 = [tensor.name for tensor in arg_0]
    arg_4 = arg_2.run(arg_0)
    arg_5 = {arg_3[idx]: val for idx, val in enumerate(arg_4)}
    np.savez(arg_1, **arg_5)
    arg_4 = None
    arg_5 = None
    del arg_4
    del arg_5
    logging.info("[*] Model saved in npz_dict %s" % arg_1)

Input parameters and the file name save parameters as a dictionary into . npz file .


(to, subject, html_content, files=None,
                    dryrun=False, cc=None, bcc=None,
                    mime_subtype='mixed', mime_charset='utf-8',
                    **kwargs)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
=
,
arg_4
=
False
,
arg_5
=
,
arg_6
=
,
arg_7
=
'mixed'
,
arg_8
=
'utf-8'
,
**
arg_9
)
:
arg_10
=
configuration
.
conf
.
get
(
'smtp'
,
'SMTP_MAIL_FROM'
)
arg_0
=
get_email_address_list
(
arg_0
)
arg_11
=
MIMEMultipart
(
arg_7
)
arg_11
[
'Subject'
]
=
arg_1
arg_11
[
'From'
]
=
arg_10
arg_11
[
'To'
]
=
", "
.
join
(
arg_0
)
arg_12
=
arg_0
if
arg_5
:
arg_5
=
get_email_address_list
(
arg_5
)
arg_11
[
'CC'
]
=
", "
.
join
(
arg_5
)
arg_12
=
arg_12
+
arg_5
if
arg_6
:
arg_6
=
get_email_address_list
(
arg_6
)
arg_12
=
arg_12
+
arg_6
arg_11
[
'Date'
]
=
formatdate
(
localtime
=
True
)
arg_13
=
MIMEText
(
arg_2
,
'html'
,
arg_8
)
arg_11
.
attach
(
arg_13
)
for
arg_14
in
arg_3
or
[
]
:
arg_15
=
os
.
path
.
basename
(
arg_14
)
with
open
(
arg_14
,
"rb"
)
as
f
:
arg_16
=
MIMEApplication
(
f
.
read
(
)
,
Name
=
arg_15
)
arg_16
[
'Content-Disposition'
]
=
'attachment; filename="%s"'
%
arg_15
arg_16
[
'Content-ID'
]
=
'<%s>'
%
arg_15
arg_11
.
attach
(
arg_16
)
send_MIME_email
(
arg_10
,
arg_12
,
arg_11
,
arg_4
)

def Func(arg_0, arg_1, arg_2, arg_3=None,
                    arg_4=False, arg_5=None, arg_6=None,
                    arg_7='mixed', arg_8='utf-8',
                    **arg_9):
    """
    Send an email with html content

    >>> send_email('test@example.com', 'foo', '<b>Foo</b> bar', ['/dev/null'], dryrun=True)
    """
    arg_10 = configuration.conf.get('smtp', 'SMTP_MAIL_FROM')

    arg_0 = get_email_address_list(arg_0)

    arg_11 = MIMEMultipart(arg_7)
    arg_11['Subject'] = arg_1
    arg_11['From'] = arg_10
    arg_11['To'] = ", ".join(arg_0)
    arg_12 = arg_0
    if arg_5:
        arg_5 = get_email_address_list(arg_5)
        arg_11['CC'] = ", ".join(arg_5)
        arg_12 = arg_12 + arg_5

    if arg_6:
        # don't add bcc in header
        arg_6 = get_email_address_list(arg_6)
        arg_12 = arg_12 + arg_6

    arg_11['Date'] = formatdate(localtime=True)
    arg_13 = MIMEText(arg_2, 'html', arg_8)
    arg_11.attach(arg_13)

    for arg_14 in arg_3 or []:
        arg_15 = os.path.basename(arg_14)
        with open(arg_14, "rb") as f:
            arg_16 = MIMEApplication(
                f.read(),
                Name=arg_15
            )
            arg_16['Content-Disposition'] = 'attachment; filename="%s"' % arg_15
            arg_16['Content-ID'] = '<%s>' % arg_15
            arg_11.attach(arg_16)

    send_MIME_email(arg_10, arg_12, arg_11, arg_4)


def
Func
(
)
:
if
LINUX
:
arg_0
=
os
.
environ
.
get
(
'XDG_CONFIG_HOME'
,
'~/.config'
)
elif
DARWIN
:
arg_0
=
'~/Library/Application Support'
elif
WIN32
:
arg_0
=
os
.
environ
.
get
(
'APPDATA'
,
'~/AppData/Roaming'
)
else
:
raise
NotImplementedError
(
'Unknown Platform  %r'
%
(
sys
.
platform
,
)
)
arg_1
=
normpath
(
expanduser
(
arg_0
)
)
return
arg_1

def Func():
    """
    Returns a directory which should be writable for any application
    This should be used for persistent configuration files.

    Returns:
        PathLike : path to the cahce dir used by the current operating system
    """
    if LINUX:  # nocover
        arg_0 = os.environ.get('XDG_CONFIG_HOME', '~/.config')
    elif DARWIN:  # nocover
        arg_0  = '~/Library/Application Support'
    elif WIN32:  # nocover
        arg_0 = os.environ.get('APPDATA', '~/AppData/Roaming')
    else:  # nocover
        raise NotImplementedError('Unknown Platform  %r' % (sys.platform,))
    arg_1 = normpath(expanduser(arg_0))
    return arg_1

Returns a directory which should be writable for any application This should be used for persistent configuration files .


return (t
            # Convert HTML special chars into HTML entities.
            .replace("&", "&").replace("<", "<").replace(">", ">")
            .replace("'", "'").replace('"', """)
            # Convert runs of spaces: "......" -> " . . ."
            .replace("  ", "  ")
            # To deal with odd-length runs, convert the final pair of spaces
            # so that "....." -> " .  ."
            .replace("  ", "  ")
        )

def Func(arg_0):
    """HTML-Func the text in `t`."""
    return (arg_0
            # Convert HTML special chars into HTML entities.
            .replace("&", "&").replace("<", "<").replace(">", ">")
            .replace("'", "'").replace('"', """)
            # Convert runs of spaces: "......" -> " . . ."
            .replace("  ", "  ")
            # To deal with odd-length runs, convert the final pair of spaces
            # so that "....." -> " .  ."
            .replace("  ", "  ")
        )


def Func ( arg_0 , arg_1 , arg_2 , arg_3 ) : if arg_1 . help : if arg_0 . classic : arg_0 . help_fn ( topic = 'help' ) else : arg_0 . help_fn ( arg_3 = arg_3 ) return True if "help" in arg_1 . actions : if arg_2 : for arg_4 in arg_2 : arg_3 = CMDS . get ( arg_4 ) if arg_3 : arg_0 . help_fn ( arg_3 = arg_3 ) else : arg_0 . help_fn ( topic = arg_4 ) else : arg_0 . help_fn ( topic = 'help' ) return True if arg_1 . version : arg_0 . help_fn ( topic = 'version' ) return True return False

def Func(arg_0, arg_1, arg_2, arg_3):
        """Deal with help requests.

        Return True if it handled the request, False if not.

        """
        # Handle help.
        if arg_1.help:
            if arg_0.classic:
                arg_0.help_fn(topic='help')
            else:
                arg_0.help_fn(arg_3=arg_3)
            return True

        if "help" in arg_1.actions:
            if arg_2:
                for arg_4 in arg_2:
                    arg_3 = CMDS.get(arg_4)
                    if arg_3:
                        arg_0.help_fn(arg_3=arg_3)
                    else:
                        arg_0.help_fn(topic=arg_4)
            else:
                arg_0.help_fn(topic='help')
            return True

        # Handle version.
        if arg_1.version:
            arg_0.help_fn(topic='version')
            return True

        return False


return {
            type_: [
                [s - ss, e - ss] for s, e in spans[bisect(spans, [ss]):]
                if e <= se
            ] for type_, spans in self._type_to_spans.items()}

def Func ( arg_0 ) -> Dict [ str , List [ List [ int ] ] ] : arg_1 , arg_2 = arg_0 . _span if arg_1 == 0 and arg_2 == len ( arg_0 . _lststr [ 0 ] ) : return deepcopy ( arg_0 . _type_to_spans ) return { arg_5 : [ [ arg_3 - arg_1 , arg_4 - arg_1 ] for arg_3 , arg_4 in arg_6 [ bisect ( arg_6 , [ arg_1 ] ) : ] if arg_4 <= arg_2 ] for arg_5 , arg_6 in arg_0 . _type_to_spans . items ( ) }

def Func(arg_0) -> Dict[str, List[List[int]]]:
        """Create the arguments for the parse function used in pformat method.

        Only return sub-spans and change the them to fit the new scope, i.e
        self.string.
        """
        arg_1, arg_2 = arg_0._span
        if arg_1 == 0 and arg_2 == len(arg_0._lststr[0]):
            return deepcopy(arg_0._type_to_spans)
        return {
            arg_5: [
                [arg_3 - arg_1, arg_4 - arg_1] for arg_3, arg_4 in arg_6[bisect(arg_6, [arg_1]):]
                if arg_4 <= arg_2
            ] for arg_5, arg_6 in arg_0._type_to_spans.items()}

Create the arguments for the parse function used in pformat method .


def Func(arg_0, arg_1, arg_2, arg_3):
        """Validates access token is available for client."""
        log.debug('Validate access token %r for %r',
                  arg_2, arg_1)
        arg_4 = arg_3.access_token or arg_0._tokengetter(
            arg_1=arg_1,
            arg_2=arg_2,
        )
        if arg_4:
            arg_3.access_token = arg_4
            return True
        return False

Validates access token is available for client .


(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False)

def Func ( arg_0 , arg_1 , arg_2 = False , arg_3 = 10 , arg_4 = False , arg_5 = False ) : arg_6 = [ AutoCompleter . SUGGET_COMMAND , arg_0 . key , arg_1 , 'MAX' , arg_3 ] if arg_2 : arg_6 . append ( AutoCompleter . FUZZY ) if arg_4 : arg_6 . append ( AutoCompleter . WITHSCORES ) if arg_5 : arg_6 . append ( AutoCompleter . WITHPAYLOADS ) arg_7 = arg_0 . redis . execute_command ( * arg_6 ) arg_8 = [ ] if not arg_7 : return arg_8 arg_9 = SuggestionParser ( arg_4 , arg_5 , arg_7 ) return [ arg_10 for arg_10 in arg_9 ]

def Func(arg_0, arg_1, arg_2 = False, arg_3 = 10, arg_4 = False, arg_5=False):
        """
        Get a list of suggestions from the AutoCompleter, for a given prefix

        ### Parameters:
        - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**
        - **fuzzy**: If set to true, the prefix search is done in fuzzy mode.
            **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.
        - **with_scores**: if set to true, we also return the (refactored) score of each suggestion.
          This is normally not needed, and is NOT the original score inserted into the index
        - **with_payloads**: Return suggestion payloads
        - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.

        Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.
        """

        arg_6 = [AutoCompleter.SUGGET_COMMAND, arg_0.key, arg_1, 'MAX', arg_3]
        if arg_2:
            arg_6.append(AutoCompleter.FUZZY)
        if arg_4:
            arg_6.append(AutoCompleter.WITHSCORES)
        if arg_5:
            arg_6.append(AutoCompleter.WITHPAYLOADS)

        arg_7 = arg_0.redis.execute_command(*arg_6)
        arg_8 = []
        if not arg_7:
            return arg_8

        arg_9 = SuggestionParser(arg_4, arg_5, arg_7)
        return [arg_10 for arg_10 in arg_9]

Get a list of suggestions from the AutoCompleter for a given prefix


(self, url, method='GET', headers={}, data=None, socket=None)

return self.request(url, method, headers, data, socket)

def
Func
(
arg_0
,
arg_1
,
arg_2
=
'GET'
,
arg_3
=
{
}
,
arg_4
=
,
arg_5
=
)
:
if
not
'User-Agent'
in
arg_3
:
arg_3
[
'User-Agent'
]
=
[
'Tensor HTTP checker'
]
return
arg_0
.
request
(
arg_1
,
arg_2
,
arg_3
,
arg_4
,
arg_5
)

def Func(arg_0, arg_1, arg_2='GET', arg_3={}, arg_4=None, arg_5=None):
        """Make an HTTP request and return the body
        """

        if not 'User-Agent' in arg_3:
            arg_3['User-Agent'] = ['Tensor HTTP checker']

        return arg_0.request(arg_1, arg_2, arg_3, arg_4, arg_5)


def Func(arg_0, arg_1, arg_2=True):
    """
    A utility method called from learnBacktrack. This will backtrack
    starting from the given startOffset in our prevLrnPatterns queue.

    It returns True if the backtrack was successful and we managed to get
    predictions all the way up to the current time step.

    If readOnly, then no segments are updated or modified, otherwise, all
    segment updates that belong to the given path are applied.

    This updates/modifies:

        - lrnActiveState['t']

    This trashes:

        - lrnPredictedState['t']
        - lrnPredictedState['t-1']
        - lrnActiveState['t-1']

    :param startOffset: Start offset within the prevLrnPatterns input history
    :param readOnly:
    :return: True if we managed to lock on to a sequence that started
                       earlier.
                       If False, we lost predictions somewhere along the way
                       leading up to the current time.
    """
    # How much input history have we accumulated?
    # The current input is always at the end of self._prevInfPatterns (at
    # index -1), but it is also evaluated as a potential starting point by
    # turning on it's start cells and seeing if it generates sufficient
    # predictions going forward.
    arg_3 = len(arg_0._prevLrnPatterns)

    # This is an easy to use label for the current time step
    arg_4 = arg_3 - 1

    # Clear out any old segment updates. learnPhase2() adds to the segment
    # updates if we're not readOnly
    if not arg_2:
      arg_0.segmentUpdates = {}

    # Status message
    if arg_0.verbosity >= 3:
      if arg_2:
        print (
            "Trying to lock-on using startCell state from %d steps ago:" % (
                arg_3 - 1 - arg_1),
            arg_0._prevLrnPatterns[arg_1])
      else:
        print (
            "Locking on using startCell state from %d steps ago:" % (
                arg_3 - 1 - arg_1),
            arg_0._prevLrnPatterns[arg_1])

    # Play through up to the current time step
    arg_6 = True
    for arg_7 in range(arg_1, arg_3):

      # Copy predicted and active states into t-1
      arg_0.lrnPredictedState['t-1'][:, :] = arg_0.lrnPredictedState['t'][:, :]
      arg_0.lrnActiveState['t-1'][:, :] = arg_0.lrnActiveState['t'][:, :]

      # Get the input pattern
      arg_10 = arg_0._prevLrnPatterns[arg_7]

      # Apply segment updates from the last set of predictions
      if not arg_2:
        arg_0._processSegmentUpdates(arg_10)

      # Phase 1:
      # Compute activeState[t] given bottom-up and predictedState[t-1]
      if arg_7 == arg_1:
        arg_0.lrnActiveState['t'].fill(0)
        for arg_11 in arg_10:
          arg_0.lrnActiveState['t'][arg_11, 0] = 1
        arg_6 = True
      else:
        # Uses lrnActiveState['t-1'] and lrnPredictedState['t-1']
        # computes lrnActiveState['t']
        arg_6 = arg_0._learnPhase1(arg_10, arg_2=arg_2)

      # Break out immediately if we fell out of sequence or reached the current
      # time step
      if not arg_6 or arg_7 == arg_4:
        break

      # Phase 2:
      # Computes predictedState['t'] given activeState['t'] and also queues
      # up active segments into self.segmentUpdates, unless this is readOnly
      if arg_0.verbosity >= 3:
        print "  backtrack: computing predictions from ", arg_10
      arg_0._learnPhase2(arg_2=arg_2)

    # Return whether or not this starting point was valid
    return arg_6

A utility method called from learnBacktrack . This will backtrack starting from the given startOffset in our prevLrnPatterns queue .


(
        ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs
)

def Func ( arg_0 , arg_1 = 'Geo' , arg_2 = 'Revenue' , arg_3 = None , arg_4 = None , ** arg_5 ) -> pd . DataFrame : arg_6 = 'G' if arg_1 [ 0 ] . upper ( ) == 'G' else 'P' arg_7 = dict ( raw = True , Product_Geo_Override = arg_6 ) arg_8 = bds ( tickers = arg_0 , flds = 'PG_Bulk_Header' , ** arg_7 , ** arg_5 ) if arg_3 : arg_5 [ 'Eqy_Fund_Crncy' ] = arg_3 if arg_4 : arg_5 [ 'PG_Hierarchy_Level' ] = arg_4 arg_9 = bds ( tickers = arg_0 , flds = f'PG_{typ}' , ** arg_7 , ** arg_5 ) return assist . format_Func ( arg_9 = arg_9 , arg_8 = arg_8 )

def Func(
        arg_0, arg_1='Geo', arg_2='Revenue', arg_3=None, arg_4=None, **arg_5
) -> pd.DataFrame:
    """
    Earning exposures by Geo or Products

    Args:
        ticker: ticker name
        by: [G(eo), P(roduct)]
        typ: type of Func, start with `PG_` in Bloomberg FLDS - default `Revenue`
        ccy: currency of Funcs
        level: hierarchy level of Funcs

    Returns:
        pd.DataFrame

    Examples:
        >>> data = Func('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1)
        >>> data.round(2)
                         level  fy2017  fy2017_pct
        Asia-Pacific       1.0  3540.0       66.43
           China           2.0  1747.0       49.35
           Japan           2.0  1242.0       35.08
           Singapore       2.0   551.0       15.56
        United States      1.0  1364.0       25.60
        Europe             1.0   263.0        4.94
        Other Countries    1.0   162.0        3.04
    """
    arg_6 = 'G' if arg_1[0].upper() == 'G' else 'P'
    arg_7 = dict(raw=True, Product_Geo_Override=arg_6)
    arg_8 = bds(tickers=arg_0, flds='PG_Bulk_Header', **arg_7, **arg_5)
    if arg_3: arg_5['Eqy_Fund_Crncy'] = arg_3
    if arg_4: arg_5['PG_Hierarchy_Level'] = arg_4
    arg_9 = bds(tickers=arg_0, flds=f'PG_{typ}', **arg_7, **arg_5)
    return assist.format_Func(arg_9=arg_9, arg_8=arg_8)

Earning exposures by Geo or Products

    Args:
        ticker: ticker name
        by: [G(eo), P(roduct)]
        typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue`
        ccy: currency of earnings
        level: hierarchy level of earnings

    Returns:
        pd.DataFrame

    Examples:
        >>> data = earning('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1)
        >>> data.round(2)
                         level  fy2017  fy2017_pct
        Asia-Pacific       1.0  3540.0       66.43
           China           2.0  1747.0       49.35
           Japan           2.0  1242.0       35.08
           Singapore       2.0   551.0       15.56
        United States      1.0  1364.0       25.60
        Europe             1.0   263.0        4.94
        Other Countries    1.0   162.0        3.04


def Func ( arg_0 ) : arg_0 = arg_0 [ : : - 1 ] . strip ( ) . replace ( "A" , "t" ) . replace ( "T" , "a" ) . replace ( "C" , "g" ) . replace ( "G" , "c" ) . upper ( ) return arg_0

def Func(arg_0):
    "returns reverse complement of a string"
    arg_0 = arg_0[::-1].strip()\
                             .replace("A", "t")\
                             .replace("T", "a")\
                             .replace("C", "g")\
                             .replace("G", "c").upper()
    return arg_0


def Func ( arg_0 , arg_1 ) : assert_is_type ( arg_1 , str , [ str ] ) arg_2 = H2OFrame . _expr ( expr = ExprNode ( "Func" , arg_0 , arg_1 ) ) arg_2 . _ex . _cache . nrows = arg_0 . nrow arg_2 . _ex . _cache . ncols = arg_0 . ncol return arg_2

def Func(arg_0, arg_1):
        """
        For each string in the frame, count the occurrences of the provided pattern.  If countmathces is applied to
        a frame, all columns of the frame must be type string, otherwise, the returned frame will contain errors.

        The pattern here is a plain string, not a regular expression. We will search for the occurrences of the
        pattern as a substring in element of the frame. This function is applicable to frames containing only
        string or categorical columns.

        :param str pattern: The pattern to count matches on in each string. This can also be a list of strings,
            in which case all of them will be searched for.
        :returns: numeric H2OFrame with the same shape as the original, containing counts of matches of the
            pattern for each cell in the original frame.
        """
        assert_is_type(arg_1, str, [str])
        arg_2 = H2OFrame._expr(expr=ExprNode("Func", arg_0, arg_1))
        arg_2._ex._cache.nrows = arg_0.nrow
        arg_2._ex._cache.ncols = arg_0.ncol
        return arg_2

For each string in the frame count the occurrences of the provided pattern . If countmathces is applied to a frame all columns of the frame must be type string otherwise the returned frame will contain errors .