def
Func
(
arg_0
=
2
,
arg_1
=
False
)
:
arg_2
=
[
sntc
.
strip
(
)
for
sntc
in
random
.
sample
(
get_dictionary
(
'lorem_ipsum'
)
,
arg_0
)
]
if
arg_1
:
return
arg_2
else
:
return
' '
.
join
(
arg_2
)

def Func(arg_0=2, arg_1=False):
    """Return random Func."""
    arg_2 = [sntc.strip() for sntc in
              random.sample(get_dictionary('lorem_ipsum'), arg_0)]

    if arg_1:
        return arg_2
    else:
        return ' '.join(arg_2)


def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
arg_3
(
'inf'
)
)
:
logger
.
info
(
"Loading local playlists..."
)
arg_4
=
[
]
arg_5
=
[
]
arg_6
=
get_supported_filepaths
(
arg_0
,
SUPPORTED_PLAYLIST_FORMATS
,
arg_2
=
arg_2
)
arg_4
,
arg_5
=
exclude_filepaths
(
arg_6
,
arg_1
=
arg_1
)
logger
.
info
(
"Excluded {0} local playlists"
.
format
(
len
(
arg_5
)
)
)
logger
.
info
(
"Loaded {0} local playlists"
.
format
(
len
(
arg_4
)
)
)
return
arg_4
,
arg_5

def Func(arg_0, arg_1=None, arg_2=arg_3('inf')):
		"""Load playlists from local filepaths.

		Parameters:
			filepaths (list or str): Filepath(s) to search for music files.

			exclude_patterns (list or str): Pattern(s) to exclude.
				Patterns are Python regex patterns.
				Filepaths are excluded if they match any of the exclude patterns.

			max_depth (int): The depth in the directory tree to walk.
				A depth of '0' limits the walk to the top directory.
				Default: No limit.

		Returns:
			A list of local playlist filepaths matching criteria
			and a list of local playlist filepaths excluded using exclusion criteria.
		"""

		logger.info("Loading local playlists...")

		arg_4 = []
		arg_5 = []

		arg_6 = get_supported_filepaths(arg_0, SUPPORTED_PLAYLIST_FORMATS, arg_2=arg_2)

		arg_4, arg_5 = exclude_filepaths(arg_6, arg_1=arg_1)

		logger.info("Excluded {0} local playlists".format(len(arg_5)))
		logger.info("Loaded {0} local playlists".format(len(arg_4)))

		return arg_4, arg_5


def Func(arg_0, arg_1):
    """
    Get google API credentials for user.
    """

    try:
        if arg_0.Func:
            arg_2 = flow_from_clientsecrets(arg_1["secrets"], scope=SCOPE, redirect_uri="oob")
            sys.stdout.write("Follow this URL: {url} and grant access to calendar.\n".format(url=arg_2.step1_get_authorize_url()))
            arg_3 = raw_input("Enter token:")
            arg_4 = arg_2.step2_exchange(arg_3)
            arg_5 = Storage(os.path.join(arg_1["credentials"], "{username}.json".format(username=arg_0.username)))
            arg_5.put(arg_4)
            arg_4.set_store(arg_5)
        else:
            arg_5 = Storage(os.path.join(arg_1["credentials"], "{username}.json".format(username=arg_0.username)))
            arg_4 = arg_5.get()
    except Exception, err:
        if not arg_0.quiet:
            sys.stderr.write("ERROR: Getting google API credentials error. {err}\n".format(err=err))
        sys.exit(-1)

    return arg_4


def Func ( arg_0 ) : if not hasattr ( arg_0 , '_paths' ) : Func = [ ] for arg_2 in arg_0 . finders : if hasattr ( arg_2 , 'paths' ) : Func . extend ( arg_2 . paths ) arg_0 . _paths = Func return arg_0 . _paths

def Func(arg_0):
        """The list of search paths. It is built from registered finders, which
        has ``paths`` property. Can be useful for compilers to resolve internal
        dependencies.
        """
        if not hasattr(arg_0, '_paths'):
            Func = []
            for arg_2 in arg_0.finders:
                if hasattr(arg_2, 'paths'):
                    Func.extend(arg_2.paths)
            arg_0._paths = Func
        return arg_0._paths

The list of search paths . It is built from registered finders which has paths property . Can be useful for compilers to resolve internal dependencies .


def Func(arg_0, arg_1, arg_2):
        """ Looks up the precomputed adversarial image for a given image.

        """
        arg_3 = np.square(arg_0._input_images - arg_2)
        arg_4 = np.mean(arg_3, axis=tuple(range(1, arg_3.ndim)))
        arg_5 = np.argmin(arg_4)

        # if we run into numerical problems with this approach, we might
        # need to add a very tiny threshold here
        if arg_4[arg_5] > 0:
            raise ValueError('No precomputed output image for this image')
        return arg_0._output_images[arg_5]

Looks up the precomputed adversarial image for a given image .


return (n_v_column.dot(n_v_column.T) - np.eye(len(value_domain)) * n_v_column) / (n - 1)

def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = arg_2 . reshape ( - 1 , 1 ) return ( arg_3 . dot ( arg_3 . T ) - np . eye ( len ( arg_0 ) ) * arg_3 ) / ( arg_1 - 1 )

def Func(arg_0, arg_1, arg_2):
    """Random coincidence matrix.

    Parameters
    ----------
    value_domain : array_like, with shape (V,)
        Possible values V the units can take.
        If the level of measurement is not nominal, it must be ordered.

    n : scalar
        Number of pairable values.

    n_v : ndarray, with shape (V,)
        Number of pairable elements for each value.

    Returns
    -------
    e : ndarray, with shape (V, V)
        Random coincidence matrix.
    """
    arg_3 = arg_2.reshape(-1, 1)
    return (arg_3.dot(arg_3.T) - np.eye(len(arg_0)) * arg_3) / (arg_1 - 1)


(self, name, values, ttl=60, weight=None, region=None,
                        set_identifier=None)

def Func ( arg_0 , arg_1 , arg_2 , arg_3 = 60 , arg_4 = None , arg_5 = None , arg_6 = None ) : arg_0 . _halt_if_already_deleted ( ) arg_2 = locals ( ) del arg_2 [ 'self' ] return arg_0 . _add_record ( AAAAResourceRecordSet , ** arg_2 )

def Func(arg_0, arg_1, arg_2, arg_3=60, arg_4=None, arg_5=None,
                        arg_6=None):
        """
        Creates an AAAA record attached to this hosted zone.

        :param str name: The fully qualified name of the record to add.
        :param list values: A list of value strings for the record.
        :keyword int ttl: The time-to-live of the record (in seconds).
        :keyword int weight: *For weighted record sets only*. Among resource record
            sets that have the same combination of DNS name and type, a value
            that determines what portion of traffic for the current resource
            record set is routed to the associated location. Ranges from 0-255.
        :keyword str region: *For latency-based record sets*. The Amazon EC2 region
            where the resource that is specified in this resource record set
            resides.
        :keyword str set_identifier: *For weighted and latency resource record
            sets only*. An identifier that differentiates among multiple
            resource record sets that have the same combination of DNS name
            and type. 1-128 chars.
        :rtype: tuple
        :returns: A tuple in the form of ``(rrset, change_info)``, where
            ``rrset`` is the newly created AAAAResourceRecordSet instance.
        """

        arg_0._halt_if_already_deleted()

        # Grab the params/kwargs here for brevity's sake.
        arg_2 = locals()
        del arg_2['self']

        return arg_0._add_record(AAAAResourceRecordSet, **arg_2)

Creates an AAAA record attached to this hosted zone .


def Func ( arg_0 , arg_1 ) : if arg_0 . has_feature ( arg_1 ) : return arg_2 = arg_0 . xmlnode . newChild ( None , "feature" , None ) arg_2 . setProp ( "var" , to_utf8 ( arg_1 ) )

def Func(arg_0,arg_1):
        """Add a feature to `self`.

        :Parameters:
            - `var`: the feature name.
        :Types:
            - `var`: `unicode`"""
        if arg_0.has_feature(arg_1):
            return
        arg_2=arg_0.xmlnode.newChild(None, "feature", None)
        arg_2.setProp("var", to_utf8(arg_1))


def Func(arg_0):
        """
        Run complete analysis and return results.
        """
        try:
            arg_1, arg_2 =  arg_0.kernel.iaca_analysis(
                micro_architecture=arg_0.machine['micro-architecture'],
                arg_2=arg_0.asm_block,
                pointer_increment=arg_0.pointer_increment,
                verbose=arg_0.verbose > 2)
        except RuntimeError as e:
            print("IACA analysis failed: " + str(e))
            sys.exit(1)

        arg_3 = arg_1['throughput']
        arg_4 = arg_1['port cycles']
        arg_5 = arg_1['uops']

        # Normalize to cycles per cacheline
        arg_6 = abs(arg_2['pointer_increment']
                                 // arg_0.kernel.datatypes_size[arg_0.kernel.datatype])
        arg_7 = arg_6*arg_0.kernel.datatypes_size[arg_0.kernel.datatype]
        try:
            arg_8 = float(arg_0.machine['cacheline size'])/arg_7
        except ZeroDivisionError as e:
            print("Too small block_size / pointer_increment:", e, file=sys.stderr)
            sys.exit(1)

        arg_4 = dict([(i[0], i[1]*arg_8) for i in list(arg_4.items())])
        arg_5 = arg_5*arg_8
        arg_9 = arg_3*arg_8

        # Compile most relevant information
        arg_10 = max([v for k, v in list(arg_4.items())
                    if k in arg_0.machine['overlapping model']['ports']])
        arg_11 = max([v for k, v in list(arg_4.items())
                     if k in arg_0.machine['non-overlapping model']['ports']])

        # Use IACA throughput prediction if it is slower then T_nOL
        if arg_11 < arg_9:
            arg_10 = arg_9

        # Create result dictionary
        arg_0.results = {
            'port cycles': arg_4,
            'cl throughput': arg_0.conv_cy(arg_9),
            'uops': arg_5,
            'T_nOL': arg_11,
            'T_OL': arg_10,
            'IACA output': arg_1['output'],
            'elements_per_block': arg_6,
            'pointer_increment': arg_2['pointer_increment'],
            'flops per iteration': sum(arg_0.kernel._flops.values())}
        return arg_0.results

Run complete analysis and return results .


def Func(arg_0, arg_1, arg_2=False):
        '''Add a torque to this body.

        Parameters
        ----------
        force : 3-tuple of float
            A vector giving the torque along each world or body coordinate axis.
        relative : bool, optional
            If False, the torque values are assumed to be given in the world
            coordinate frame. If True, they are assumed to be given in the
            body-relative coordinate frame. Defaults to False.
        '''
        arg_3 = arg_0.ode_body.addRelTorque if arg_2 else arg_0.ode_body.addTorque
        arg_3(arg_1)


def
Func
(
arg_0
,
arg_1
)
:
if
arg_0
.
blacklist_jobs
and
arg_1
in
arg_0
.
blacklist_jobs
:
logger
.
warning
(
"Not getting blacklisted job: %s"
,
arg_1
)
return
arg_2
=
{
'depth'
:
arg_0
.
detail_depth
}
arg_3
=
urijoin
(
arg_0
.
base_url
,
"job"
,
arg_1
,
"api"
,
"json"
)
arg_4
=
arg_0
.
fetch
(
arg_3
,
arg_2
=
arg_2
)
return
arg_4
.
text

def Func(arg_0, arg_1):
        """ Retrieve all builds from a job"""

        if arg_0.blacklist_jobs and arg_1 in arg_0.blacklist_jobs:
            logger.warning("Not getting blacklisted job: %s", arg_1)
            return

        arg_2 = {'depth': arg_0.detail_depth}
        arg_3 = urijoin(arg_0.base_url, "job", arg_1, "api", "json")

        arg_4 = arg_0.fetch(arg_3, arg_2=arg_2)
        return arg_4.text


def Func ( arg_0 : arg_1 ) -> arg_1 : arg_2 = lambda x , y : x if y in x else x + ( y , ) return reduce ( arg_2 , arg_0 , arg_1 ( ) )

def Func(arg_0: arg_1) -> arg_1:
    '''Remove duplicates from the stack in first-seen order.'''
    # Initializes with an accumulator and then reduces the stack with first match
    # Funclication.
    arg_2 = lambda x, y: x if y in x else x + (y,)
    return reduce(arg_2, arg_0, arg_1())

Remove duplicates from the stack in first - seen order .


(cls, user, due_delta, description_price_pairs)

return cls._generate(user, None, min_due_time, line_items)

def Func ( arg_0 , arg_1 , arg_2 , arg_3 ) : arg_4 = [ ] for arg_5 , arg_6 in arg_3 : arg_7 = commerce . LineItem ( arg_5 = arg_5 , quantity = 1 , arg_6 = Decimal ( arg_6 ) , product = None , ) arg_4 . append ( arg_7 ) arg_8 = timezone . now ( ) + arg_2 return arg_0 . _generate ( arg_1 , None , arg_8 , arg_4 )

def Func(arg_0, arg_1, arg_2, arg_3):
        ''' Generates an invoice for arbitrary items, not held in a user's
        cart.

        Arguments:
            user (User): The user the invoice is being generated for.
            due_delta (datetime.timedelta): The length until the invoice is
                due.
            description_price_pairs ([(str, long or Decimal), ...]): A list of
                pairs. Each pair consists of the description for each line item
                and the price for that line item. The price will be cast to
                Decimal.

        Returns:
            an Invoice.
        '''

        arg_4 = []
        for arg_5, arg_6 in arg_3:
            arg_7 = commerce.LineItem(
                arg_5=arg_5,
                quantity=1,
                arg_6=Decimal(arg_6),
                product=None,
            )
            arg_4.append(arg_7)

        arg_8 = timezone.now() + arg_2
        return arg_0._generate(arg_1, None, arg_8, arg_4)

Generates an invoice for arbitrary items not held in a user s cart .


return open(apply(os.path.join, [dir] + components), mode)

def Func ( arg_0 , arg_1 = 'r' ) : import utils arg_2 = os . path . dirname ( utils . __file__ ) return open ( apply ( os . path . join , [ arg_2 ] + arg_0 ) , arg_1 )

def Func(arg_0, arg_1='r'):
    "Open a file based at the AIMA root directory."
    import utils
    arg_2 = os.path.dirname(utils.__file__)
    return open(apply(os.path.join, [arg_2] + arg_0), arg_1)

Open a file based at the AIMA root directory .


def Func(*, arg_0=0, arg_1=None):
    """ Function to create a new empty las data object

    .. note::

        If you provide both point_format and file_version
        an exception will be raised if they are not compatible

    >>> las = Func(point_format_id=6,file_version="1.2")
    Traceback (most recent call last):
     ...
    pylas.errors.PylasError: Point format 6 is not compatible with file version 1.2

    If you provide only the point_format the file_version will automatically
    selected for you.

    >>> las = Func(point_format_id=0)
    >>> las.header.version == '1.2'
    True

    >>> las = Func(point_format_id=6)
    >>> las.header.version == '1.4'
    True

    Parameters
    ----------
    point_format_id: int
        The point format you want the created file to have

    file_version: str, optional, default=None
        The las version you want the created las to have

    Returns
    -------
    pylas.lasdatas.base.LasBase
       A new las data object

    """
    if arg_1 is not None:
        dims.raise_if_version_not_compatible_with_fmt(arg_0, arg_1)
    else:
        arg_1 = dims.min_file_version_for_point_format(arg_0)

    arg_2 = headers.HeaderFactory.new(arg_1)
    arg_2.point_format_id = arg_0

    if arg_1 >= "1.4":
        return las14.LasData(arg_2=arg_2)
    return las12.LasData(arg_2=arg_2)

Function to create a new empty las data object

    .. note::

        If you provide both point_format and file_version
        an exception will be raised if they are not compatible

    >>> las = create_las(point_format_id=6,file_version="1.2")
    Traceback (most recent call last):
     ...
    pylas.errors.PylasError: Point format 6 is not compatible with file version 1.2

    If you provide only the point_format the file_version will automatically
    selected for you.

    >>> las = create_las(point_format_id=0)
    >>> las.header.version == '1.2'
    True

    >>> las = create_las(point_format_id=6)
    >>> las.header.version == '1.4'
    True

    Parameters
    ----------
    point_format_id: int
        The point format you want the created file to have

    file_version: str, optional, default=None
        The las version you want the created las to have

    Returns
    -------
    pylas.lasdatas.base.LasBase
       A new las data object


def
Func
(
arg_0
)
:
for
arg_1
in
arg_0
:
cli_args
.
add_verbose
(
arg_1
)
cli_args
.
add_config
(
arg_1
)
arg_1
.
add_argument
(
'--heron-dir'
,
default
=
config
.
get_heron_dir
(
)
,
help
=
'Path to Heron home directory'
)

def Func(arg_0):
  '''
  add additional parameters to parser
  '''
  for arg_1 in arg_0:
    cli_args.add_verbose(arg_1)
    cli_args.add_config(arg_1)
    arg_1.add_argument(
        '--heron-dir',
        default=config.get_heron_dir(),
        help='Path to Heron home directory')


return not_after < datetime.datetime.utcnow()

def Func ( arg_0 ) : arg_1 = _native ( arg_0 . get_notAfter ( ) ) arg_2 = datetime . datetime . strptime ( arg_1 , "%Y%m%d%H%M%SZ" ) return arg_2 < datetime . datetime . utcnow ( )

def Func(arg_0):
        """
        Check whether the certificate has expired.

        :return: ``True`` if the certificate has expired, ``False`` otherwise.
        :rtype: bool
        """
        arg_1 = _native(arg_0.get_notAfter())
        arg_2 = datetime.datetime.strptime(arg_1, "%Y%m%d%H%M%SZ")

        return arg_2 < datetime.datetime.utcnow()

Check whether the certificate has expired .


return subprocess.call('echo "{0}"'.format(message or ''), **kwargs)

def
Func
(
arg_0
=
)
:
arg_1
=
{
'stdout'
:
sys
.
stdout
,
'stderr'
:
sys
.
stderr
,
'shell'
:
True
}
return
subprocess
.
call
(
'echo "{0}"'
.
format
(
arg_0
or
''
)
,
**
arg_1
)

def Func(arg_0=None):
    """Print message via ``subprocess.call`` function.

    This helps to ensure consistent output and avoid situations where print
    messages actually shown after messages from all inner threads.

    :param message: Text message to print.
    """
    arg_1 = {'stdout': sys.stdout,
              'stderr': sys.stderr,
              'shell': True}
    return subprocess.call('echo "{0}"'.format(arg_0 or ''), **arg_1)

Print message via subprocess . call function .


def Func ( arg_0 , arg_1 = 10 ) : if "user" in arg_0 : arg_2 = arg_0 [ "user" ] if arg_2 . is_authenticated ( ) : arg_3 = MessageArchive . objects . select_related ( "message" ) . filter ( arg_2 = arg_2 ) return { "messages" : arg_3 [ : arg_1 ] , "count" : arg_3 . count ( ) , }

def Func(arg_0, arg_1=10):
    """
    Renders a list of archived messages for the current user
    """
    if "user" in arg_0:
        arg_2 = arg_0["user"]
        if arg_2.is_authenticated():
            arg_3 = MessageArchive.objects.select_related("message").filter(arg_2=arg_2)
            return {
                "messages": arg_3[:arg_1],
                "count": arg_3.count(),
            }


def
Func
(
arg_0
,
arg_1
)
:
with
cd
(
"/tmp"
)
:
download
(
EZ_SETUP_URL
)
arg_2
=
'%(python_cmd)s ez_setup.py'
%
locals
(
)
if
arg_1
:
run_as_root
(
arg_2
)
else
:
run
(
arg_2
)
run
(
'rm -f ez_setup.py'
)

def Func(arg_0, arg_1):
    """
    Install setuptools from scratch using installer
    """

    with cd("/tmp"):
        download(EZ_SETUP_URL)

        arg_2 = '%(python_cmd)s ez_setup.py' % locals()
        if arg_1:
            run_as_root(arg_2)
        else:
            run(arg_2)

        run('rm -f ez_setup.py')


def Func ( arg_0 , arg_1 = arg_2 ) : arg_3 = c_int ( ) lib . lsl_Func ( arg_0 . obj , c_double ( arg_1 ) , byref ( arg_3 ) ) handle_error ( arg_3 )

def Func(arg_0, arg_1=arg_2):
        """Subscribe to the data stream.

        All samples pushed in at the other end from this moment onwards will be
        queued and eventually be delivered in response to pull_sample() or
        pull_chunk() calls. Pulling a sample without some preceding Func
        is permitted (the stream will then be opened implicitly).

        Keyword arguments:
        timeout -- Optional timeout of the operation (default FOREVER).

        Throws a TimeoutError (if the timeout expires), or LostError (if the
        stream source has been lost).

        """
        arg_3 = c_int()
        lib.lsl_Func(arg_0.obj, c_double(arg_1), byref(arg_3))
        handle_error(arg_3)

Subscribe to the data stream.

        All samples pushed in at the other end from this moment onwards will be
        queued and eventually be delivered in response to pull_sample() or
        pull_chunk() calls. Pulling a sample without some preceding open_stream
        is permitted (the stream will then be opened implicitly).

        Keyword arguments:
        timeout -- Optional timeout of the operation (default FOREVER).

        Throws a TimeoutError (if the timeout expires), or LostError (if the
        stream source has been lost).


def Func(arg_0, arg_1, arg_2):
    """
    Unencrypt data for all users.

    Parameters
    ----------
    engine : SQLAlchemy.engine
        Engine encapsulating database connections.
    old_crypto_factory : function[str -> Any]
        A function from user_id to an object providing the interface required
        by PostgresContentsManager.crypto.  Results of this will be used for
        decryption of existing database content.
    logger : logging.Logger, optional
        A logger to user during re-encryption.
    """
    arg_2.info("Beginning re-encryption for all users.")
    for arg_3 in all_user_ids(arg_0):
        unencrypt_single_user(
            arg_0=arg_0,
            arg_3=arg_3,
            old_crypto=arg_1(arg_3),
            arg_2=arg_2,
        )
    arg_2.info("Finished re-encryption for all users.")


(self, instruction, qargs=None, cargs=None)

def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Append an instruction to the end of the circuit, modifying
        the circuit in place.

        Args:
            instruction (Instruction or Operator): Instruction instance to Func
            qargs (list(tuple)): qubits to attach instruction to
            cargs (list(tuple)): clbits to attach instruction to

        Returns:
            Instruction: a handle to the instruction that was just added

        Raises:
            QiskitError: if the gate is of a different shape than the wires
                it is being attached to.
        """
        arg_2 = arg_2 or []
        arg_3 = arg_3 or []

        # Convert input to instruction
        if not isinstance(arg_1, Instruction) and hasattr(arg_1, 'to_instruction'):
            arg_1 = arg_1.to_instruction()
        if not isinstance(arg_1, Instruction):
            raise QiskitError('object is not an Instruction.')

        # do some compatibility checks
        arg_0._check_dups(arg_2)
        arg_0._check_qargs(arg_2)
        arg_0._check_cargs(arg_3)
        if arg_1.num_qubits != len(arg_2) or \
                arg_1.num_clbits != len(arg_3):
            raise QiskitError("instruction %s with %d qubits and %d clbits "
                              "cannot be Funced onto %d qubits and %d clbits." %
                              (arg_1.name,
                               arg_1.num_qubits, arg_1.num_clbits,
                               len(arg_2), len(arg_3)))

        # add the instruction onto the given wires
        arg_4 = arg_1, arg_2, arg_3
        arg_0.data.Func(arg_4)

        # track variable parameters in instruction
        for arg_5, arg_6 in enumerate(arg_1.params):
            if isinstance(arg_6, Parameter):
                arg_7 = arg_0.parameters

                if arg_6 in arg_7:
                    arg_0._parameter_table[arg_6].Func((arg_1, arg_5))
                else:
                    arg_0._parameter_table[arg_6] = [(arg_1, arg_5)]

        return arg_1

Append an instruction to the end of the circuit, modifying
        the circuit in place.

        Args:
            instruction (Instruction or Operator): Instruction instance to append
            qargs (list(tuple)): qubits to attach instruction to
            cargs (list(tuple)): clbits to attach instruction to

        Returns:
            Instruction: a handle to the instruction that was just added

        Raises:
            QiskitError: if the gate is of a different shape than the wires
                it is being attached to.

Append an instruction to the end of the circuit modifying the circuit in place .


def Func ( arg_0 ) : arg_1 = arg_0 . orig_settings arg_2 . setrecursionlimit ( arg_1 [ "sys.recursionlimit" ] ) if "sys.tracebacklimit" in arg_1 : arg_2 . tracebacklimit = arg_1 [ "sys.tracebacklimit" ] else : if hasattr ( arg_2 , "tracebacklimit" ) : del arg_2 . tracebacklimit if "showwarning" in arg_1 : arg_4 . showwarning = arg_1 [ "showwarning" ] arg_1 . clear ( ) threading . stack_size ( )

def Func(arg_0):
        """Restore Python settings to the original states"""
        arg_1 = arg_0.orig_settings
        arg_2.setrecursionlimit(arg_1["sys.recursionlimit"])

        if "sys.tracebacklimit" in arg_1:
            arg_2.tracebacklimit = arg_1["sys.tracebacklimit"]
        else:
            if hasattr(arg_2, "tracebacklimit"):
                del arg_2.tracebacklimit

        if "showwarning" in arg_1:
            arg_4.showwarning = arg_1["showwarning"]

        arg_1.clear()
        threading.stack_size()


(S, n_components=None, transformer=None, sort=False, fit=True, **kwargs)

def Func(arg_0, arg_1=None, arg_2=None, arg_3=False, arg_4=True, **arg_5):
    """Decompose a feature matrix.

    Given a spectrogram `S`, produce a decomposition into `components`
    and `activations` such that `S ~= components.dot(activations)`.

    By default, this is done with with non-negative matrix factorization (NMF),
    but any `sklearn.decomposition`-type object will work.

    Parameters
    ----------
    S : np.ndarray [shape=(n_features, n_samples), dtype=float]
        The input feature matrix (e.g., magnitude spectrogram)

    n_components : int > 0 [scalar] or None
        number of desired components

        if None, then `n_features` components are used

    transformer : None or object
        If None, use `sklearn.decomposition.NMF`

        Otherwise, any object with a similar interface to NMF should work.
        `transformer` must follow the scikit-learn convention, where
        input data is `(n_samples, n_features)`.

        `transformer.fit_transform()` will be run on `S.T` (not `S`),
        the return value of which is stored (transposed) as `activations`

        The components will be retrieved as `transformer.components_.T`

        `S ~= np.dot(activations, transformer.components_).T`

        or equivalently:
        `S ~= np.dot(transformer.components_.T, activations.T)`

    sort : bool
        If `True`, components are sorted by ascending peak frequency.

        .. note:: If used with `transformer`, sorting is applied to copies
            of the decomposition parameters, and not to `transformer`'s
            internal parameters.

    fit : bool
        If `True`, components are estimated from the input ``S``.

        If `False`, components are assumed to be pre-computed and stored
        in ``transformer``, and are not changed.

    kwargs : Additional keyword arguments to the default transformer
        `sklearn.decomposition.NMF`

    Returns
    -------
    components: np.ndarray [shape=(n_features, n_components)]
        matrix of components (basis elements).

    activations: np.ndarray [shape=(n_components, n_samples)]
        transformed matrix/activation matrix

    Raises
    ------
    ParameterError
        if `fit` is False and no `transformer` object is provided.

    See Also
    --------
    sklearn.decomposition : SciKit-Learn matrix decomposition modules

    Examples
    --------
    Decompose a magnitude spectrogram into 32 components with NMF

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> comps, acts = librosa.Func.Func(S, n_components=8)
    >>> comps
    array([[  1.876e-01,   5.559e-02, ...,   1.687e-01,   4.907e-02],
           [  3.148e-01,   1.719e-01, ...,   2.314e-01,   9.493e-02],
           ...,
           [  1.561e-07,   8.564e-08, ...,   7.167e-08,   4.997e-08],
           [  1.531e-07,   7.880e-08, ...,   5.632e-08,   4.028e-08]])
    >>> acts
    array([[  4.197e-05,   8.512e-03, ...,   3.056e-05,   9.159e-06],
           [  9.568e-06,   1.718e-02, ...,   3.322e-05,   7.869e-06],
           ...,
           [  5.982e-05,   1.311e-02, ...,  -0.000e+00,   6.323e-06],
           [  3.782e-05,   7.056e-03, ...,   3.290e-05,  -0.000e+00]])

    Sort components by ascending peak frequency

    >>> comps, acts = librosa.Func.Func(S, n_components=16,
    ...                                           sort=True)

    Or with sparse dictionary learning

    >>> import sklearn.decomposition
    >>> T = sklearn.decomposition.MiniBatchDictionaryLearning(n_components=16)
    >>> scomps, sacts = librosa.Func.Func(S, transformer=T, sort=True)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10,8))
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S,
    ...                                                  ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('Input spectrogram')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.subplot(3, 2, 3)
    >>> librosa.display.specshow(librosa.amplitude_to_db(comps,
    ...                                                  ref=np.max),
    ...                          y_axis='log')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Components')
    >>> plt.subplot(3, 2, 4)
    >>> librosa.display.specshow(acts, x_axis='time')
    >>> plt.ylabel('Components')
    >>> plt.title('Activations')
    >>> plt.colorbar()
    >>> plt.subplot(3, 1, 3)
    >>> S_approx = comps.dot(acts)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S_approx,
    ...                                                  ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Reconstructed spectrogram')
    >>> plt.tight_layout()
    """

    if arg_2 is None:
        if arg_4 is False:
            raise ParameterError('fit must be True if transformer is None')

        arg_2 = sklearn.decomposition.NMF(arg_1=arg_1,
                                                **arg_5)

    if arg_1 is None:
        arg_1 = arg_0.shape[0]

    if arg_4:
        arg_6 = arg_2.fit_transform(arg_0.T).T
    else:
        arg_6 = arg_2.transform(arg_0.T).T

    arg_7 = arg_2.components_.T

    if arg_3:
        arg_7, arg_8 = util.axis_sort(arg_7, index=True)
        arg_6 = arg_6[arg_8]

    return arg_7, arg_6

Decompose a feature matrix.

    Given a spectrogram `S`, produce a decomposition into `components`
    and `activations` such that `S ~= components.dot(activations)`.

    By default, this is done with with non-negative matrix factorization (NMF),
    but any `sklearn.decomposition`-type object will work.

    Parameters
    ----------
    S : np.ndarray [shape=(n_features, n_samples), dtype=float]
        The input feature matrix (e.g., magnitude spectrogram)

    n_components : int > 0 [scalar] or None
        number of desired components

        if None, then `n_features` components are used

    transformer : None or object
        If None, use `sklearn.decomposition.NMF`

        Otherwise, any object with a similar interface to NMF should work.
        `transformer` must follow the scikit-learn convention, where
        input data is `(n_samples, n_features)`.

        `transformer.fit_transform()` will be run on `S.T` (not `S`),
        the return value of which is stored (transposed) as `activations`

        The components will be retrieved as `transformer.components_.T`

        `S ~= np.dot(activations, transformer.components_).T`

        or equivalently:
        `S ~= np.dot(transformer.components_.T, activations.T)`

    sort : bool
        If `True`, components are sorted by ascending peak frequency.

        .. note:: If used with `transformer`, sorting is applied to copies
            of the decomposition parameters, and not to `transformer`'s
            internal parameters.

    fit : bool
        If `True`, components are estimated from the input ``S``.

        If `False`, components are assumed to be pre-computed and stored
        in ``transformer``, and are not changed.

    kwargs : Additional keyword arguments to the default transformer
        `sklearn.decomposition.NMF`

    Returns
    -------
    components: np.ndarray [shape=(n_features, n_components)]
        matrix of components (basis elements).

    activations: np.ndarray [shape=(n_components, n_samples)]
        transformed matrix/activation matrix

    Raises
    ------
    ParameterError
        if `fit` is False and no `transformer` object is provided.

    See Also
    --------
    sklearn.decomposition : SciKit-Learn matrix decomposition modules

    Examples
    --------
    Decompose a magnitude spectrogram into 32 components with NMF

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> comps, acts = librosa.decompose.decompose(S, n_components=8)
    >>> comps
    array([[  1.876e-01,   5.559e-02, ...,   1.687e-01,   4.907e-02],
           [  3.148e-01,   1.719e-01, ...,   2.314e-01,   9.493e-02],
           ...,
           [  1.561e-07,   8.564e-08, ...,   7.167e-08,   4.997e-08],
           [  1.531e-07,   7.880e-08, ...,   5.632e-08,   4.028e-08]])
    >>> acts
    array([[  4.197e-05,   8.512e-03, ...,   3.056e-05,   9.159e-06],
           [  9.568e-06,   1.718e-02, ...,   3.322e-05,   7.869e-06],
           ...,
           [  5.982e-05,   1.311e-02, ...,  -0.000e+00,   6.323e-06],
           [  3.782e-05,   7.056e-03, ...,   3.290e-05,  -0.000e+00]])

    Sort components by ascending peak frequency

    >>> comps, acts = librosa.decompose.decompose(S, n_components=16,
    ...                                           sort=True)

    Or with sparse dictionary learning

    >>> import sklearn.decomposition
    >>> T = sklearn.decomposition.MiniBatchDictionaryLearning(n_components=16)
    >>> scomps, sacts = librosa.decompose.decompose(S, transformer=T, sort=True)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10,8))
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S,
    ...                                                  ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('Input spectrogram')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.subplot(3, 2, 3)
    >>> librosa.display.specshow(librosa.amplitude_to_db(comps,
    ...                                                  ref=np.max),
    ...                          y_axis='log')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Components')
    >>> plt.subplot(3, 2, 4)
    >>> librosa.display.specshow(acts, x_axis='time')
    >>> plt.ylabel('Components')
    >>> plt.title('Activations')
    >>> plt.colorbar()
    >>> plt.subplot(3, 1, 3)
    >>> S_approx = comps.dot(acts)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S_approx,
    ...                                                  ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Reconstructed spectrogram')
    >>> plt.tight_layout()


def
Func
(
arg_0
,
arg_1
)
:
if
arg_0
is
or
arg_0
.
get
(
'SecondaryStatusTransitions'
)
is
or
len
(
arg_0
.
get
(
'SecondaryStatusTransitions'
)
)
==
0
:
return
''
arg_2
=
arg_1
.
get
(
'SecondaryStatusTransitions'
)
if
arg_1
is
not
else
arg_3
=
len
(
arg_1
[
'SecondaryStatusTransitions'
]
)
if
arg_2
is
not
else
0
arg_4
=
arg_0
[
'SecondaryStatusTransitions'
]
arg_5
=
arg_4
[
1
:
]
if
len
(
arg_4
)
==
arg_3
else
arg_4
[
arg_3
len
(
arg_4
)
:
]
arg_6
=
[
]
for
arg_7
in
arg_5
:
arg_8
=
arg_7
[
'StatusMessage'
]
arg_9
=
timezone
.
convert_to_utc
(
arg_0
[
'LastModifiedTime'
]
)
.
strftime
(
'%Y-%m-%d %H:%M:%S'
)
arg_6
.
append
(
'{} {} - {}'
.
format
(
arg_9
,
arg_7
[
'Status'
]
,
arg_8
)
)
return
'\n'
.
join
(
arg_6
)

def Func(arg_0, arg_1):
    """
    Returns a string contains start time and the secondary training job status message.

    :param job_description: Returned response from DescribeTrainingJob call
    :type job_description: dict
    :param prev_description: Previous job description from DescribeTrainingJob call
    :type prev_description: dict

    :return: Job status string to be printed.
    """

    if arg_0 is None or arg_0.get('SecondaryStatusTransitions') is None\
            or len(arg_0.get('SecondaryStatusTransitions')) == 0:
        return ''

    arg_2 = arg_1.get('SecondaryStatusTransitions')\
        if arg_1 is not None else None
    arg_3 = len(arg_1['SecondaryStatusTransitions'])\
        if arg_2 is not None else 0
    arg_4 = arg_0['SecondaryStatusTransitions']

    arg_5 = arg_4[-1:] if len(arg_4) == arg_3 else \
        arg_4[arg_3 - len(arg_4):]

    arg_6 = []
    for arg_7 in arg_5:
        arg_8 = arg_7['StatusMessage']
        arg_9 = timezone.convert_to_utc(arg_0['LastModifiedTime']).strftime('%Y-%m-%d %H:%M:%S')
        arg_6.append('{} {} - {}'.format(arg_9, arg_7['Status'], arg_8))

    return '\n'.join(arg_6)

Returns a string contains start time and the secondary training job status message .


def Func ( arg_0 ) : for arg_1 in arg_0 . __activities : if not arg_1 . iteratorHolder [ 0 ] : continue try : next ( arg_1 . iteratorHolder [ 0 ] ) except StopIteration : arg_1 . cb ( ) if arg_1 . repeating : arg_1 . iteratorHolder [ 0 ] = iter ( xrange ( arg_1 . period ) ) else : arg_1 . iteratorHolder [ 0 ] = None return True

def Func(arg_0):
    """ Activity Func handler; services all activities

    Returns:      True if controlling iterator says it's okay to keep going;
                  False to stop
    """

    # Run activities whose time has come
    for arg_1 in arg_0.__activities:
      if not arg_1.iteratorHolder[0]:
        continue

      try:
        next(arg_1.iteratorHolder[0])
      except StopIteration:
        arg_1.cb()
        if arg_1.repeating:
          arg_1.iteratorHolder[0] = iter(xrange(arg_1.period))
        else:
          arg_1.iteratorHolder[0] = None

    return True

Activity tick handler; services all activities

    Returns:      True if controlling iterator says it's okay to keep going;
                  False to stop

Activity tick handler ; services all activities


(self, x, timestamp=0.0, pushthrough=True)

def Func(arg_0, arg_1, arg_2=0.0, arg_3=True):
        """Push a list of samples into the outlet.

        samples -- A list of samples, either as a list of lists or a list of
                   multiplexed values.
        timestamp -- Optionally the capture time of the most recent sample, in
                     agreement with local_clock(); if omitted, the current
                     time is used. The time stamps of other samples are
                     automatically derived according to the sampling rate of
                     the stream. (default 0.0)
        pushthrough Whether to push the chunk through to the receivers instead
                    of buffering it with subsequent samples. Note that the
                    chunk_size, if specified at outlet construction, takes
                    precedence over the pushthrough flag. (default True)

        """
        try:
            arg_4 = arg_0.channel_count * len(arg_1)
            arg_5 = (arg_0.value_type * arg_4).from_buffer(arg_1)
            handle_error(arg_0.do_Func(arg_0.obj, arg_5,
                                            c_long(arg_4),
                                            c_double(arg_2),
                                            c_int(arg_3)))
        except TypeError:
            if len(arg_1):
                if type(arg_1[0]) is list:
                    arg_1 = [v for sample in arg_1 for v in sample]
                if arg_0.channel_format == cf_string:
                    arg_1 = [v.encode('utf-8') for v in arg_1]
                if len(arg_1) % arg_0.channel_count == 0:
                    arg_6 = arg_0.value_type*len(arg_1)
                    # noinspection PyCallingNonCallable
                    handle_error(arg_0.do_Func(arg_0.obj, arg_6(*arg_1),
                                                    c_long(len(arg_1)),
                                                    c_double(arg_2),
                                                    c_int(arg_3)))
                else:
                    raise ValueError("each sample must have the same number of "
                                     "channels.")

Push a list of samples into the outlet .


def Func ( arg_0 ) : with open ( arg_0 , 'rb' ) as opened : arg_1 = opened . read ( 2 ** 20 ) arg_2 , arg_3 = ftfy . guess_bytes ( arg_1 ) return arg_3

def Func(arg_0):
    """
    Use ftfy to detect the encoding of a file, based on a sample of its
    first megabyte.

    ftfy's encoding detector is limited. The only encodings it can detect are
    UTF-8, CESU-8, UTF-16, Windows-1252, and occasionally MacRoman. But it
    does much better than chardet.
    """
    with open(arg_0, 'rb') as opened:
        arg_1 = opened.read(2 ** 20)
        arg_2, arg_3 = ftfy.guess_bytes(arg_1)
        return arg_3

Use ftfy to detect the encoding of a file based on a sample of its first megabyte .


(lspinfo,
                             times,
                             mags,
                             errs,
                             nbootstrap=250,
                             magsarefluxes=False,
                             sigclip=10.0,
                             npeaks=None)

def Func(arg_0,
                             arg_1,
                             arg_2,
                             arg_3,
                             arg_4=250,
                             arg_5=False,
                             arg_6=10.0,
                             arg_7=None):
    '''Calculates the false alarm probabilities of periodogram peaks using
    bootstrap resampling of the magnitude time series.

    The false alarm probability here is defined as::

        (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)

    for each best periodogram peak j. The index i is for each bootstrap
    trial. This effectively gives us a significance for the peak. Smaller FAP
    means a better chance that the peak is real.

    The basic idea is to get the number of trial best peaks that are larger than
    the current best peak and divide this by the total number of trials. The
    distribution of these trial best peaks is obtained after scrambling the mag
    values and rerunning the specified periodogram method for a bunch of trials.

    `lspinfo` is the output dict from a periodbase periodogram function and MUST
    contain a 'method' key that corresponds to one of the keys in the LSPMETHODS
    dict above. This will let this function know which periodogram function to
    run to generate the bootstrap samples. The lspinfo SHOULD also have a
    'kwargs' key that corresponds to the input keyword arguments for the
    periodogram function as it was run originally, to keep everything the same
    during the bootstrap runs. If this is missing, default values will be used.

    FIXME: this may not be strictly correct; must look more into bootstrap
    significance testing. Also look into if we're doing resampling correctly for
    time series because the samples are not iid. Look into moving block
    bootstrap.

    Parameters
    ----------

    lspinfo : dict
        A dict of period-finder results from one of the period-finders in
        periodbase, or your own functions, provided it's of the form and
        contains at least the keys listed below::

            {'periods': np.array of all periods searched by the period-finder,
             'lspvals': np.array of periodogram power value for each period,
             'bestperiod': a float value that is the period with the highest
                           peak in the periodogram, i.e. the most-likely actual
                           period,
             'method': a three-letter code naming the period-finder used; must
                       be one of the keys in the
                       `astrobase.periodbase.METHODLABELS` dict,
             'nbestperiods': a list of the periods corresponding to periodogram
                             peaks (`nbestlspvals` below) to annotate on the
                             periodogram plot so they can be called out
                             visually,
             'nbestlspvals': a list of the power values associated with
                             periodogram peaks to annotate on the periodogram
                             plot so they can be called out visually; should be
                             the same length as `nbestperiods` above,
             'kwargs': dict of kwargs passed to your own period-finder function}

        If you provide your own function's period-finder results, you should add
        a corresponding key for it to the LSPMETHODS dict above so the bootstrap
        function can use it correctly. Your period-finder function should take
        `times`, `mags`, errs and any extra parameters as kwargs and return a
        dict of the form described above. A small worked example::

            from your_module import your_periodfinder_func
            from astrobase import periodbase

            periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func

            # run a period-finder session
            your_pfresults = your_periodfinder_func(times, mags, errs,
                                                    **extra_kwargs)

            # run bootstrap to find FAP
            falsealarm_info = periodbase.Func(
                your_pfresults,
                times, mags, errs,
                nbootstrap=250,
                magsarefluxes=False,
            )

    times,mags,errs : np.arrays
        The magnitude/flux time-series to process along with their associated
        measurement errors.

    nbootstrap : int
        The total number of bootstrap trials to run. This is set to 250 by
        default, but should probably be around 1000 for realistic results.

    magsarefluxes : bool
        If True, indicates the input time-series is fluxes and not mags.

    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.

    npeaks : int or None
        The number of peaks from the list of 'nbestlspvals' in the period-finder
        result dict to run the bootstrap for. If None, all of the peaks in this
        list will have their FAP calculated.

    Returns
    -------

    dict
        Returns a dict of the form::

            {'peaks':allpeaks,
             'periods':allperiods,
             'probabilities':allfaps,
             'alltrialbestpeaks':alltrialbestpeaks}

    '''

    # figure out how many periods to work on
    if (arg_7 and (0 < arg_7 < len(arg_0['nbestperiods']))):
        arg_8 = arg_7
    else:
        LOGWARNING('npeaks not specified or invalid, '
                   'getting FAP for all %s periodogram peaks' %
                   len(arg_0['nbestperiods']))
        arg_8 = len(arg_0['nbestperiods'])

    arg_9 = arg_0['nbestperiods'][:arg_8]
    arg_10 = arg_0['nbestlspvals'][:arg_8]

    # get rid of nans first and sigclip
    arg_11, arg_12, arg_13 = sigclip_magseries(arg_1,
                                             arg_2,
                                             arg_3,
                                             arg_5=arg_5,
                                             arg_6=arg_6)

    arg_14 = []
    arg_15 = []
    arg_16 = []
    arg_17 = []

    # make sure there are enough points to calculate a spectrum
    if len(arg_11) > 9 and len(arg_12) > 9 and len(arg_13) > 9:

        for arg_18, arg_19, arg_20 in zip(range(len(arg_9)),
                                     arg_9,
                                     arg_10):

            LOGINFO('peak %s: running %s trials...' % (arg_18+1, arg_4))

            arg_21 = []

            for arg_22 in range(arg_4):

                # get a scrambled index
                arg_23 = np.random.randint(0,
                                           high=arg_2.size,
                                           size=arg_2.size)

                # get the kwargs dict out of the lspinfo
                if 'kwargs' in arg_0:

                    arg_24 = arg_0['kwargs']

                    # update the kwargs with some local stuff
                    arg_24.update({'magsarefluxes':arg_5,
                                   'sigclip':arg_6,
                                   'verbose':False})
                else:
                    arg_24 = {'magsarefluxes':arg_5,
                              'sigclip':arg_6,
                              'verbose':False}

                # run the periodogram with scrambled mags and errs
                # and the appropriate keyword arguments
                arg_25 = LSPMETHODS[arg_0['method']](
                    arg_1, arg_2[arg_23], arg_3[arg_23],
                    **arg_24
                )
                arg_21.append(arg_25['bestlspval'])

            arg_21 = np.array(arg_21)
            arg_17.append(arg_21)

            # calculate the FAP for a trial peak j = FAP[j] =
            # (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)
            if arg_0['method'] != 'pdm':
                arg_26 = (
                    (1.0 + arg_21[arg_21 > arg_20].size) /
                    (arg_21.size + 1.0)
                )
            # for PDM, we're looking for a peak smaller than the best peak
            # because values closer to 0.0 are more significant
            else:
                arg_26 = (
                    (1.0 + arg_21[arg_21 < arg_20].size) /
                    (arg_21.size + 1.0)
                )

            LOGINFO('FAP for peak %s, period: %.6f = %.3g' % (arg_18+1,
                                                              arg_19,
                                                              arg_26))

            arg_14.append(arg_20)
            arg_15.append(arg_19)
            arg_16.append(arg_26)

        return {'peaks':arg_14,
                'periods':arg_15,
                'probabilities':arg_16,
                'alltrialbestpeaks':arg_17}

    else:
        LOGERROR('not enough mag series points to calculate periodogram')
        return None

Calculates the false alarm probabilities of periodogram peaks using
    bootstrap resampling of the magnitude time series.

    The false alarm probability here is defined as::

        (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)

    for each best periodogram peak j. The index i is for each bootstrap
    trial. This effectively gives us a significance for the peak. Smaller FAP
    means a better chance that the peak is real.

    The basic idea is to get the number of trial best peaks that are larger than
    the current best peak and divide this by the total number of trials. The
    distribution of these trial best peaks is obtained after scrambling the mag
    values and rerunning the specified periodogram method for a bunch of trials.

    `lspinfo` is the output dict from a periodbase periodogram function and MUST
    contain a 'method' key that corresponds to one of the keys in the LSPMETHODS
    dict above. This will let this function know which periodogram function to
    run to generate the bootstrap samples. The lspinfo SHOULD also have a
    'kwargs' key that corresponds to the input keyword arguments for the
    periodogram function as it was run originally, to keep everything the same
    during the bootstrap runs. If this is missing, default values will be used.

    FIXME: this may not be strictly correct; must look more into bootstrap
    significance testing. Also look into if we're doing resampling correctly for
    time series because the samples are not iid. Look into moving block
    bootstrap.

    Parameters
    ----------

    lspinfo : dict
        A dict of period-finder results from one of the period-finders in
        periodbase, or your own functions, provided it's of the form and
        contains at least the keys listed below::

            {'periods': np.array of all periods searched by the period-finder,
             'lspvals': np.array of periodogram power value for each period,
             'bestperiod': a float value that is the period with the highest
                           peak in the periodogram, i.e. the most-likely actual
                           period,
             'method': a three-letter code naming the period-finder used; must
                       be one of the keys in the
                       `astrobase.periodbase.METHODLABELS` dict,
             'nbestperiods': a list of the periods corresponding to periodogram
                             peaks (`nbestlspvals` below) to annotate on the
                             periodogram plot so they can be called out
                             visually,
             'nbestlspvals': a list of the power values associated with
                             periodogram peaks to annotate on the periodogram
                             plot so they can be called out visually; should be
                             the same length as `nbestperiods` above,
             'kwargs': dict of kwargs passed to your own period-finder function}

        If you provide your own function's period-finder results, you should add
        a corresponding key for it to the LSPMETHODS dict above so the bootstrap
        function can use it correctly. Your period-finder function should take
        `times`, `mags`, errs and any extra parameters as kwargs and return a
        dict of the form described above. A small worked example::

            from your_module import your_periodfinder_func
            from astrobase import periodbase

            periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func

            # run a period-finder session
            your_pfresults = your_periodfinder_func(times, mags, errs,
                                                    **extra_kwargs)

            # run bootstrap to find FAP
            falsealarm_info = periodbase.bootstrap_falsealarmprob(
                your_pfresults,
                times, mags, errs,
                nbootstrap=250,
                magsarefluxes=False,
            )

    times,mags,errs : np.arrays
        The magnitude/flux time-series to process along with their associated
        measurement errors.

    nbootstrap : int
        The total number of bootstrap trials to run. This is set to 250 by
        default, but should probably be around 1000 for realistic results.

    magsarefluxes : bool
        If True, indicates the input time-series is fluxes and not mags.

    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.

    npeaks : int or None
        The number of peaks from the list of 'nbestlspvals' in the period-finder
        result dict to run the bootstrap for. If None, all of the peaks in this
        list will have their FAP calculated.

    Returns
    -------

    dict
        Returns a dict of the form::

            {'peaks':allpeaks,
             'periods':allperiods,
             'probabilities':allfaps,
             'alltrialbestpeaks':alltrialbestpeaks}

Calculates the false alarm probabilities of periodogram peaks using bootstrap resampling of the magnitude time series .


(data_url: str,
                    data_path: str,
                    *,
                    preparsed_path: Optional[str] = None,
                    )

def Func ( arg_0 : arg_1 , arg_2 : arg_1 , * , arg_3 : arg_4 [ arg_1 ] = None , ) -> Callable [ [ arg_4 [ arg_1 ] , arg_8 , arg_8 ] , MultiDiGraph ] : arg_5 = make_downloader ( arg_0 , arg_2 ) def get_obo ( arg_6 : arg_4 [ arg_1 ] = None , arg_7 : arg_8 = True , arg_9 : arg_8 = False ) -> MultiDiGraph : if arg_3 is not None and os . path . exists ( arg_3 ) : return read_gpickle ( arg_3 ) if arg_6 is None and arg_7 : arg_6 = arg_5 ( arg_9 = arg_9 ) arg_10 = obonet . read_obo ( arg_6 ) if arg_3 is not None : write_gpickle ( arg_10 , arg_3 ) return arg_10 return get_obo

def Func(arg_0: arg_1,
                    arg_2: arg_1,
                    *,
                    arg_3: arg_4[arg_1] = None,
                    ) -> Callable[[arg_4[arg_1], arg_8, arg_8], MultiDiGraph]:
    """Build a function that handles downloading OBO data and parsing it into a NetworkX object.

    :param data_url: The URL of the data
    :param data_path: The path where the data should get stored
    :param preparsed_path: The optional path to cache a pre-parsed json version
    """
    arg_5 = make_downloader(arg_0, arg_2)

    def get_obo(arg_6: arg_4[arg_1] = None, arg_7: arg_8 = True, arg_9: arg_8 = False) -> MultiDiGraph:
        """Download and parse a GO obo file with :mod:`obonet` into a MultiDiGraph.

        :param url: The URL (or file path) to download.
        :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet
        :param force_download: If true, overwrites a previously cached file
        """
        if arg_3 is not None and os.path.exists(arg_3):
            return read_gpickle(arg_3)

        if arg_6 is None and arg_7:
            arg_6 = arg_5(arg_9=arg_9)

        arg_10 = obonet.read_obo(arg_6)

        if arg_3 is not None:
            write_gpickle(arg_10, arg_3)

        return arg_10

    return get_obo

Build a function that handles downloading OBO data and parsing it into a NetworkX object .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 [ 'event_type' ] arg_3 = keystone_customer_process . get ( arg_2 ) if arg_3 is not None : arg_3 ( arg_0 , arg_1 ) else : arg_4 = False arg_5 = None for arg_6 in keystone_customer_process_wildcard . keys ( ) : if arg_6 . match ( arg_2 ) : arg_5 = keystone_customer_process_wildcard . get ( arg_6 ) arg_4 = True break if arg_4 : arg_5 ( arg_0 , arg_1 ) else : default_process ( arg_0 , arg_1 ) arg_1 . ack ( )

def Func(arg_0, arg_1):
    """
    This function deal with the keystone notification.

    First, find process from customer_process that not include wildcard.
    if not find from customer_process, then find process from customer_process_wildcard.
    if not find from customer_process_wildcard, then use ternya default process.
    :param body: dict of openstack notification.
    :param message: kombu Message class
    :return:
    """
    arg_2 = arg_0['event_type']
    arg_3 = keystone_customer_process.get(arg_2)
    if arg_3 is not None:
        arg_3(arg_0, arg_1)
    else:
        arg_4 = False
        arg_5 = None
        for arg_6 in keystone_customer_process_wildcard.keys():
            if arg_6.match(arg_2):
                arg_5 = keystone_customer_process_wildcard.get(arg_6)
                arg_4 = True
                break
        if arg_4:
            arg_5(arg_0, arg_1)
        else:
            default_process(arg_0, arg_1)
    arg_1.ack()

This function deal with the keystone notification .


def Func ( arg_0 ) : arg_1 = SchemaGeneratorState ( ) arg_2 = get_schema_dict ( arg_0 , arg_1 ) del arg_1 . record_schemas [ arg_0 . _schema_name ] if arg_1 . record_schemas : arg_2 [ 'definitions' ] = dict ( ) for arg_3 , arg_4 in arg_1 . record_schemas . iteritems ( ) : arg_2 [ 'definitions' ] [ arg_3 ] = arg_4 return arg_2

def Func(arg_0):
    """Return a root jsonschema for a given record

    A root schema includes the $schema attribute and all sub-record
    schemas and definitions.
    """
    arg_1 = SchemaGeneratorState()
    arg_2 = get_schema_dict(arg_0, arg_1)
    del arg_1.record_schemas[arg_0._schema_name]
    if arg_1.record_schemas:
        arg_2['definitions'] = dict()
        for arg_3, arg_4 in arg_1.record_schemas.iteritems():
            arg_2['definitions'][arg_3] = arg_4
    return arg_2


def
Func
(
arg_0
,
arg_1
)
:
if
arg_1
.
name
in
arg_0
.
current_symtab
:
arg_2
=
arg_0
.
current_symtab
[
arg_1
.
name
]
raise
QasmError
(
"Duplicate declaration for"
,
arg_1
.
type
+
" '"
+
arg_1
.
name
+
"' at line"
,
str
(
arg_1
.
line
)
+
', file'
,
arg_1
.
file
+
'.\nPrevious occurrence at line'
,
str
(
arg_2
.
line
)
+
', file'
,
arg_2
.
file
)
arg_0
.
current_symtab
[
arg_1
.
name
]
=
arg_1

def Func(arg_0, arg_1):
        """Update a node in the symbol table.

        Everything in the symtab must be a node with these attributes:
        name - the string name of the object
        type - the string type of the object
        line - the source line where the type was first found
        file - the source file where the type was first found
        """
        if arg_1.name in arg_0.current_symtab:
            arg_2 = arg_0.current_symtab[arg_1.name]
            raise QasmError("Duplicate declaration for", arg_1.type + " '"
                            + arg_1.name + "' at line", str(arg_1.line)
                            + ', file', arg_1.file
                            + '.\nPrevious occurrence at line',
                            str(arg_2.line) + ', file', arg_2.file)
        arg_0.current_symtab[arg_1.name] = arg_1


def
Func
(
arg_0
,
arg_1
,
arg_2
=
arg_3
.
ImpossibleDependency
)
:
if
arg_1
not
in
arg_0
.
depending
:
arg_0
.
log
.
error
(
"msg %r already failed!"
,
arg_1
)
return
arg_5
=
arg_0
.
depending
.
pop
(
arg_1
)
for
arg_6
in
arg_5
.
dependents
:
if
arg_6
in
arg_0
.
graph
:
arg_0
.
graph
[
arg_6
]
.
remove
(
arg_1
)
try
:
raise
arg_2
(
)
except
:
arg_7
=
arg_3
.
wrap_exception
(
)
arg_0
.
all_done
.
add
(
arg_1
)
arg_0
.
all_failed
.
add
(
arg_1
)
arg_8
=
arg_0
.
session
.
send
(
arg_0
.
client_stream
,
'apply_reply'
,
arg_7
,
parent
=
arg_5
.
header
,
ident
=
arg_5
.
idents
)
arg_0
.
session
.
send
(
arg_0
.
mon_stream
,
arg_8
,
ident
=
[
b'outtask'
]
+
arg_5
.
idents
)
arg_0
.
update_graph
(
arg_1
,
success
=
False
)

def Func(arg_0, arg_1, arg_2=arg_3.ImpossibleDependency):
        """a task has become unreachable, send a reply with an ImpossibleDependency
        error."""
        if arg_1 not in arg_0.depending:
            arg_0.log.error("msg %r already failed!", arg_1)
            return
        arg_5 = arg_0.depending.pop(arg_1)
        for arg_6 in arg_5.dependents:
            if arg_6 in arg_0.graph:
                arg_0.graph[arg_6].remove(arg_1)

        try:
            raise arg_2()
        except:
            arg_7 = arg_3.wrap_exception()

        arg_0.all_done.add(arg_1)
        arg_0.all_failed.add(arg_1)

        arg_8 = arg_0.session.send(arg_0.client_stream, 'apply_reply', arg_7,
                                                parent=arg_5.header, ident=arg_5.idents)
        arg_0.session.send(arg_0.mon_stream, arg_8, ident=[b'outtask']+arg_5.idents)

        arg_0.update_graph(arg_1, success=False)

a task has become unreachable send a reply with an ImpossibleDependency error .


def Func ( arg_0 ) : if sum ( ~ np . isnan ( arg_0 ) ) > 2 : arg_1 = arg_0 [ ~ np . isnan ( arg_0 ) ] arg_2 = np . median ( arg_1 ) arg_3 = np . diff ( np . percentile ( arg_1 , [ 25 , 75 ] ) ) return ( arg_0 - arg_2 ) / arg_3 else : return np . full ( arg_0 . shape , np . nan )

def Func(arg_0):
    """
    Remove median, divide by IQR.
    """
    if sum(~np.isnan(arg_0)) > 2:
        arg_1 = arg_0[~np.isnan(arg_0)]
        arg_2 = np.median(arg_1)
        arg_3 = np.diff(np.percentile(arg_1, [25, 75]))
        return (arg_0 - arg_2) / arg_3
    else:
        return np.full(arg_0.shape, np.nan)


(infile,
                                            lctype,
                                            cadence_min=2)

def Func(arg_0,
                                            arg_1,
                                            arg_2=2):
    '''Reads TESS Ames-format FITS light curve files.

    MIT TOI alerts include Ames lightcurve files. This function gets the finite,
    nonzero times, fluxes, and errors with QUALITY == 0.

    NOTE: the PDCSAP lightcurve typically still need "pre-whitening" after this
    step.

    .. deprecated:: 0.3.20
        This function will be removed in astrobase v0.4.2. Use the
        `read_tess_fitslc` and `consolidate_tess_fitslc` functions instead.

    Parameters
    ----------

    infile : str
        The path to `*.fits.gz` TOI alert file, from Ames pipeline.

    lctype : {'PDCSAP','SAP'}
        The type of light curve to extract from the FITS LC file.

    cadence_min : int
        The expected frame cadence in units of minutes. Raises ValueError if you
        use the wrong cadence.

    Returns
    -------

    tuple
        The tuple returned is of the form:

        (times, normalized (to median) fluxes, flux errors)

    '''

    warnings.warn(
        "Use the astrotess.read_tess_fitslc and "
        "astrotess.consolidate_tess_fitslc functions instead of this function. "
        "This function will be removed in astrobase v0.4.2.",
        FutureWarning
    )

    if arg_1 not in ('PDCSAP','SAP'):
        raise ValueError('unknown light curve type requested: %s' % arg_1)

    arg_3 = pyfits.open(arg_0)

    arg_4 = arg_3[0].header
    arg_5 = arg_3[1].header
    arg_6 = arg_3[1].data

    if (('Ames' not in arg_4['ORIGIN']) or
        ('LIGHTCURVE' not in arg_5['EXTNAME'])):
        raise ValueError(
            'could not understand input LC format. '
            'Is it a TESS TOI LC file?'
        )

    arg_7 = arg_6['TIME']
    arg_8 = arg_6['{:s}_FLUX'.format(arg_1)]
    arg_9 = arg_6['{:s}_FLUX_ERR'.format(arg_1)]

    # REMOVE POINTS FLAGGED WITH:
    # attitude tweaks, safe mode, coarse/earth pointing, argabrithening events,
    # reaction wheel desaturation events, cosmic rays in optimal aperture
    # pixels, manual excludes, discontinuities, stray light from Earth or Moon
    # in camera FoV.
    # (Note: it's not clear to me what a lot of these mean. Also most of these
    # columns are probably not correctly propagated right now.)
    arg_10 = (arg_6['QUALITY'] == 0)
    arg_10 &= np.isfinite(arg_7)
    arg_10 &= np.isfinite(arg_8)
    arg_10 &= np.isfinite(arg_9)
    arg_10 &= ~np.isnan(arg_7)
    arg_10 &= ~np.isnan(arg_8)
    arg_10 &= ~np.isnan(arg_9)
    arg_10 &= (arg_7 != 0)
    arg_10 &= (arg_8 != 0)
    arg_10 &= (arg_9 != 0)

    arg_7 = arg_7[arg_10]
    arg_8 = arg_8[arg_10]
    arg_9 = arg_9[arg_10]

    # ensure desired cadence
    arg_11 = np.abs(np.nanmedian(np.diff(arg_7))*24*60 - arg_2)

    if arg_11 > 1.0e-2:
        raise ValueError(
            'the light curve is not at the required cadence specified: %.2f' %
            arg_2
        )

    arg_12 = np.nanmedian(arg_8)
    arg_8 /= arg_12
    arg_9 /= arg_12

    return arg_7, arg_8, arg_9

Reads TESS Ames - format FITS light curve files .


def
Func
(
arg_0
,
arg_1
=
'37'
)
:
LOG
.
info
(
"Exporting all genes to .bed format"
)
for
arg_2
in
arg_0
.
all_genes
(
arg_1
=
arg_1
)
:
yield
arg_2

def Func(arg_0, arg_1='37'):
    """Export all genes from the database"""
    LOG.info("Exporting all genes to .bed format")

    for arg_2 in arg_0.all_genes(arg_1=arg_1):
        yield arg_2


(self, title, description=None, expires_at=None)

def Func ( arg_0 , arg_1 , arg_2 = None , arg_3 = None ) : arg_0 . link = SecretLink . create ( arg_1 , arg_0 . receiver , extra_data = dict ( recid = arg_0 . recid ) , arg_2 = arg_2 , arg_3 = arg_3 , ) return arg_0 . link

def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Create a secret link from request."""
        arg_0.link = SecretLink.create(
            arg_1,
            arg_0.receiver,
            extra_data=dict(recid=arg_0.recid),
            arg_2=arg_2,
            arg_3=arg_3,
        )
        return arg_0.link


def Func ( arg_0 , arg_1 , arg_2 = 'J2000' ) : arg_3 = SkyCoord ( arg_0 = arg_0 * u . degree , dec = arg_1 * u . degree , arg_2 = arg_2 ) arg_4 = arg_3 . galactic . l . degree arg_5 = arg_3 . galactic . b . degree return arg_4 , arg_5

def Func(arg_0, arg_1, arg_2='J2000'):
    '''This converts from equatorial coords to galactic coords.

    Parameters
    ----------

    ra : float or array-like
        Right ascension values(s) in decimal degrees.

    decl : float or array-like
        Declination value(s) in decimal degrees.

    equinox : str
        The equinox that the coordinates are measured at. This must be
        recognizable by Astropy's `SkyCoord` class.

    Returns
    -------

    tuple of (float, float) or tuple of (np.array, np.array)
        The galactic coordinates (l, b) for each element of the input
        (`ra`, `decl`).

    '''

    # convert the ra/decl to gl, gb
    arg_3 = SkyCoord(arg_0=arg_0*u.degree, dec=arg_1*u.degree, arg_2=arg_2)

    arg_4 = arg_3.galactic.l.degree
    arg_5 = arg_3.galactic.b.degree

    return arg_4, arg_5

This converts from equatorial coords to galactic coords .


def Func ( arg_0 , arg_1 ) : if arg_1 [ - 1 ] is not None : return [ ] else : arg_2 = arg_1 . index ( None ) return [ arg_3 for arg_3 in range ( arg_0 . N ) if not arg_0 . conflicted ( arg_1 , arg_3 , arg_2 ) ]

def Func(arg_0, arg_1):
        "In the leftmost empty column, try all non-conflicting rows."
        if arg_1[-1] is not None:
            return []  # All columns filled; no successors
        else:
            arg_2 = arg_1.index(None)
            return [arg_3 for arg_3 in range(arg_0.N)
                    if not arg_0.conflicted(arg_1, arg_3, arg_2)]

In the leftmost empty column try all non - conflicting rows .


def Func ( arg_0 , arg_1 , arg_2 = False ) : if arg_1 is None : arg_0 . wx_obj . SetSelection ( - 1 ) if hasattr ( arg_0 . wx_obj , "SetValue" ) : arg_0 . wx_obj . SetValue ( "" ) else : arg_0 . wx_obj . SetSelection ( arg_1 ) arg_3 = ItemContainerControlSelectEvent ( arg_0 . _commandtype , arg_1 , arg_0 . wx_obj ) if hasattr ( arg_0 , "onchange" ) and arg_0 . onchange : arg_4 = FormEvent ( name = "change" , arg_3 = arg_3 ) arg_0 . onchange ( arg_4 )

def Func(arg_0, arg_1, arg_2=False):
        "Sets the item at index 'n' to be the selected item."
        # only change selection if index is None and not dummy:
        if arg_1 is None:
            arg_0.wx_obj.SetSelection(-1)
            # clean up text if control supports it:
            if hasattr(arg_0.wx_obj, "SetValue"):
                arg_0.wx_obj.SetValue("")
        else:
            arg_0.wx_obj.SetSelection(arg_1)
        # send a programmatically event (not issued by wx)
        arg_3 = ItemContainerControlSelectEvent(arg_0._commandtype,
                                                   arg_1, arg_0.wx_obj)
        if hasattr(arg_0, "onchange") and arg_0.onchange:
            # TODO: fix (should work but it doesn't):
            ## wx.PostEvent(self.wx_obj, wx_evt)
            # WORKAROUND:
            arg_4 = FormEvent(name="change", arg_3=arg_3)
            arg_0.onchange(arg_4)

Sets the item at index n to be the selected item .


def Func(arg_0, arg_1):
        """
        Convert a given month into our unified format.

        :param data: The month to convert or shorten.
        :type data: str

        :return: The unified month name.
        :rtype: str
        """

        # We map the different month and their possible representation.
        arg_2 = {
            "jan": [str(1), "01", "Jan", "January"],
            "feb": [str(2), "02", "Feb", "February"],
            "mar": [str(3), "03", "Mar", "March"],
            "apr": [str(4), "04", "Apr", "April"],
            "may": [str(5), "05", "May"],
            "jun": [str(6), "06", "Jun", "June"],
            "jul": [str(7), "07", "Jul", "July"],
            "aug": [str(8), "08", "Aug", "August"],
            "sep": [str(9), "09", "Sep", "September"],
            "oct": [str(10), "Oct", "October"],
            "nov": [str(11), "Nov", "November"],
            "dec": [str(12), "Dec", "December"],
        }

        for arg_3 in arg_2:
            # We loop through our map.

            if arg_1 in arg_2[arg_3]:
                # If the parsed data (or month if you prefer) is into our map.

                # We return the element (or key if you prefer) assigned to
                # the month.
                return arg_3

        # The element is not into our map.

        # We return the parsed element (or month if you prefer).
        return arg_1

Convert a given month into our unified format .


def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
0
)
:
from
burlap
import
notifier
arg_3
=
arg_0
.
get_satchel
(
'service'
)
arg_0
.
lock
(
)
try
:
arg_2
=
int
(
arg_2
)
if
not
arg_2
:
if
arg_0
.
genv
.
host_string
==
arg_0
.
genv
.
hosts
[
0
]
:
execute
(
partial
(
arg_0
.
preview
,
arg_1
=
arg_1
,
ask
=
1
)
)
notifier
.
notify_pre_deployment
(
)
arg_4
,
arg_5
=
arg_0
.
get_component_funcs
(
arg_1
=
arg_1
)
arg_3
.
pre_deploy
(
)
for
arg_6
,
arg_7
in
arg_5
:
print
(
'Executing %s...'
%
arg_6
)
arg_7
(
)
arg_0
.
fake
(
arg_1
=
arg_1
)
arg_3
.
post_deploy
(
)
notifier
.
notify_post_deployment
(
)
finally
:
arg_0
.
unlock
(
)

def Func(arg_0, arg_1=None, arg_2=0):
        """
        Executes all satchel configurators to apply pending changes to the server.
        """
        from burlap import notifier
        arg_3 = arg_0.get_satchel('service')
        arg_0.lock()
        try:

            arg_2 = int(arg_2)
            if not arg_2:
                # If we want to confirm the deployment with the user, and we're at the first server,
                # then run the preview.
                if arg_0.genv.host_string == arg_0.genv.hosts[0]:
                    execute(partial(arg_0.preview, arg_1=arg_1, ask=1))

            notifier.notify_pre_deployment()
            arg_4, arg_5 = arg_0.get_component_funcs(arg_1=arg_1)

            arg_3.pre_deploy()
            for arg_6, arg_7 in arg_5:
                print('Executing %s...' % arg_6)
                arg_7()
            arg_0.fake(arg_1=arg_1)

            arg_3.post_deploy()
            notifier.notify_post_deployment()

        finally:
            arg_0.unlock()

Executes all satchel configurators to apply pending changes to the server .


(self, analytes=None, win=15, samples=None, ranges=False,
                       focus=None, outdir=None,
                       figsize=[10, 4], subset='All_Analyses')

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
15
,
arg_3
=
,
arg_4
=
False
,
arg_5
=
,
arg_6
=
,
arg_7
=
[
10
,
4
]
,
arg_8
=
'All_Analyses'
)
:
if
arg_5
is
:
arg_5
=
arg_0
.
focus_stage
if
arg_6
is
:
arg_6
=
arg_0
.
report_dir
+
'/'
+
arg_5
+
'_gradient'
if
not
os
.
path
.
isdir
(
arg_6
)
:
os
.
mkdir
(
arg_6
)
if
arg_8
is
not
:
arg_3
=
arg_0
.
_get_samples
(
arg_8
)
elif
arg_3
is
:
arg_3
=
arg_0
.
subsets
[
'All_Analyses'
]
elif
isinstance
(
arg_3
,
str
)
:
arg_3
=
[
arg_3
]
with
arg_0
.
pbar
.
set
(
total
=
len
(
arg_3
)
,
desc
=
'Drawing Plots'
)
as
prog
:
for
arg_9
in
arg_3
:
arg_10
,
arg_11
=
arg_0
.
data
[
arg_9
]
.
gplot
(
arg_1
=
arg_1
,
arg_2
=
arg_2
,
arg_7
=
arg_7
,
arg_4
=
arg_4
,
focus_stage
=
arg_5
)
arg_10
.
savefig
(
arg_6
+
'/'
+
arg_9
+
'_gradients.pdf'
)
plt
.
close
(
arg_10
)
prog
.
update
(
)
return

def Func(arg_0, arg_1=None, arg_2=15, arg_3=None, arg_4=False,
                       arg_5=None, arg_6=None,
                       arg_7=[10, 4], arg_8='All_Analyses'):
        """
        Plot analyte gradients as a function of time.

        Parameters
        ----------
        analytes : optional, array_like or str
            The analyte(s) to plot. Defaults to all analytes.
        samples: optional, array_like or str
            The sample(s) to plot. Defaults to all samples.
        ranges : bool
            Whether or not to show the signal/backgroudn regions
            identified by 'autorange'.
        focus : str
            The focus 'stage' of the analysis to plot. Can be
            'rawdata', 'despiked':, 'signal', 'background',
            'bkgsub', 'ratios' or 'calibrated'.
        outdir : str
            Path to a directory where you'd like the plots to be
            saved. Defaults to 'reports/[focus]' in your data directory.
        filt : str, dict or bool
            Either logical filter expression contained in a str,
            a dict of expressions specifying the filter string to
            use for each analyte or a boolean. Passed to `grab_filt`.
        scale : str
            If 'log', plots the data on a log scale.
        figsize : array_like
            Array of length 2 specifying figure [width, height] in
            inches.
        stats : bool
            Whether or not to overlay the mean and standard deviations
            for each trace.
        stat, err: str
            The names of the statistic and error components to plot.
            Deafaults to 'nanmean' and 'nanstd'.

        Returns
        -------
        None
        """
        if arg_5 is None:
            arg_5 = arg_0.focus_stage
        if arg_6 is None:
            arg_6 = arg_0.report_dir + '/' + arg_5 + '_gradient'
        if not os.path.isdir(arg_6):
            os.mkdir(arg_6)

        # if samples is not None:
        #     subset = self.make_subset(samples)

        if arg_8 is not None:
            arg_3 = arg_0._get_samples(arg_8)
        elif arg_3 is None:
            arg_3 = arg_0.subsets['All_Analyses']
        elif isinstance(arg_3, str):
            arg_3 = [arg_3]

        with arg_0.pbar.set(total=len(arg_3), desc='Drawing Plots') as prog:
            for arg_9 in arg_3:
                arg_10, arg_11 = arg_0.data[arg_9].gplot(arg_1=arg_1, arg_2=arg_2, arg_7=arg_7,
                                        arg_4=arg_4, focus_stage=arg_5)
                # ax = fig.axes[0]
                # for l, u in s.sigrng:
                #     ax.axvspan(l, u, color='r', alpha=0.1)
                # for l, u in s.bkgrng:
                #     ax.axvspan(l, u, color='k', alpha=0.1)
                arg_10.savefig(arg_6 + '/' + arg_9 + '_gradients.pdf')
                # TODO: on older(?) computers raises
                # 'OSError: [Errno 24] Too many open files'
                plt.close(arg_10)
                prog.update()
        return

Plot analyte gradients as a function of time .


def Func ( arg_0 ) : arg_1 = ForceNumeric . is_convertible ( arg_0 ) if not arg_1 or isinstance ( arg_0 , bool ) : raise ValueError if isinstance ( str ( arg_0 ) , str ) : return ForceNumeric . str_to_num ( arg_0 ) return float ( arg_0 )

def Func(arg_0):
        """Convert value to a numeric value or raise a ValueError
        if that isn't possible.

        """
        arg_1 = ForceNumeric.is_convertible(arg_0)
        if not arg_1 or isinstance(arg_0, bool):
            raise ValueError
        if isinstance(str(arg_0), str):
            return ForceNumeric.str_to_num(arg_0)
        return float(arg_0)

Convert value to a numeric value or raise a ValueError if that isn t possible .


def Func(arg_0, arg_1):
        """
        Calculate the modelled progress state for the given time moment.

        :returns: tuple (x, v) of the progress level and progress speed.
        """
        arg_2, arg_3, arg_4, arg_5 = arg_0._t0, arg_0._x0, arg_0._v0, arg_0._ve
        arg_6 = (arg_4 - arg_5) * math.exp(-arg_0.BETA * (arg_1 - arg_2))
        arg_7 = arg_5 + arg_6
        arg_8 = clamp(arg_3 + arg_5 * (arg_1 - arg_2) + (arg_4 - arg_5 - arg_6) / arg_0.BETA, 0, 1)
        return arg_8, arg_7

Calculate the modelled progress state for the given time moment .


def Func(arg_0, arg_1):
        """Return the instance of RarInfo given 'name'."""
        arg_2 = arg_0.NameToInfo.get(arg_1)
        if arg_2 is None:
            raise KeyError('There is no item named %r in the archive' % arg_1)
        return arg_2

Return the instance of RarInfo given name .


def Func ( arg_0 , arg_1 = None , arg_2 = None ) : with db . session . begin_nested ( ) : if arg_0 . status != RequestStatus . PENDING : raise InvalidRequestStateError ( RequestStatus . PENDING ) arg_0 . status = RequestStatus . ACCEPTED request_Funced . send ( arg_0 , arg_1 = arg_1 , arg_2 = arg_2 )

def Func(arg_0, arg_1=None, arg_2=None):
        """Accept request."""
        with db.session.begin_nested():
            if arg_0.status != RequestStatus.PENDING:
                raise InvalidRequestStateError(RequestStatus.PENDING)
            arg_0.status = RequestStatus.ACCEPTED
        request_Funced.send(arg_0, arg_1=arg_1, arg_2=arg_2)


def
Func
(
arg_0
)
:
global
arg_1
try
:
arg_1
=
arg_0
.
open
(
)
except
StreamError
as
err
:
raise
StreamError
(
"Could not open stream: {0}"
.
format
(
err
)
)
try
:
log
.
debug
(
"Pre-buffering 8192 bytes"
)
arg_2
=
arg_1
.
read
(
8192
)
except
IOError
as
err
:
arg_1
.
close
(
)
raise
StreamError
(
"Failed to read data from stream: {0}"
.
format
(
err
)
)
if
not
arg_2
:
arg_1
.
close
(
)
raise
StreamError
(
"No data returned from stream"
)
return
arg_1
,
arg_2

def Func(arg_0):
    """Opens a stream and reads 8192 bytes from it.

    This is useful to check if a stream actually has data
    before opening the output.

    """
    global arg_1

    # Attempts to open the stream
    try:
        arg_1 = arg_0.open()
    except StreamError as err:
        raise StreamError("Could not open stream: {0}".format(err))

    # Read 8192 bytes before proceeding to check for errors.
    # This is to avoid opening the output unnecessarily.
    try:
        log.debug("Pre-buffering 8192 bytes")
        arg_2 = arg_1.read(8192)
    except IOError as err:
        arg_1.close()
        raise StreamError("Failed to read data from stream: {0}".format(err))

    if not arg_2:
        arg_1.close()
        raise StreamError("No data returned from stream")

    return arg_1, arg_2

Opens a stream and reads 8192 bytes from it .


def Func ( arg_0 ) : arg_1 = os . path . join ( arg_0 . temp_path , LOCAL_ODS ) try : po_to_ods ( arg_0 . languages , arg_0 . locale_root , arg_0 . po_files_path , arg_1 ) except ( IOError , OSError ) as e : raise PODocsError ( e ) arg_0 . _Func_file_to_gdoc ( arg_1 ) arg_0 . _clear_temp ( )

def Func(arg_0):
        """
        Upload all po files to GDocs ignoring conflicts.
        This method looks for all msgids in po_files and sends them
        as ods to GDocs Spreadsheet.
        """
        arg_1 = os.path.join(arg_0.temp_path, LOCAL_ODS)
        try:
            po_to_ods(arg_0.languages, arg_0.locale_root,
                      arg_0.po_files_path, arg_1)
        except (IOError, OSError) as e:
            raise PODocsError(e)

        arg_0._Func_file_to_gdoc(arg_1)

        arg_0._clear_temp()

Upload all po files to GDocs ignoring conflicts . This method looks for all msgids in po_files and sends them as ods to GDocs Spreadsheet .


def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
arg_3
=
[
]
for
arg_4
in
arg_2
.
childNodes
:
if
arg_4
.
nodeType
!=
minidom
.
Node
.
ELEMENT_NODE
:
continue
if
arg_4
.
nodeName
.
lower
(
)
==
'assign'
:
arg_3
.
append
(
arg_0
.
deserialize_assign
(
arg_1
,
arg_4
)
)
else
:
_exc
(
'Unknown node: %s'
%
arg_4
.
nodeName
)
return
arg_3

def Func(arg_0, arg_1, arg_2):
        """
        Reads a list of assignments from the given node.

        workflow -- the workflow
        start_node -- the xml structure (xml.dom.minidom.Node)
        """
        # Collect all information.
        arg_3 = []
        for arg_4 in arg_2.childNodes:
            if arg_4.nodeType != minidom.Node.ELEMENT_NODE:
                continue
            if arg_4.nodeName.lower() == 'assign':
                arg_3.append(arg_0.deserialize_assign(arg_1, arg_4))
            else:
                _exc('Unknown node: %s' % arg_4.nodeName)
        return arg_3

Reads a list of assignments from the given node .


def Func ( arg_0 , arg_1 , arg_2 = None ) : if not arg_2 : ( arg_2 , arg_1 ) = arg_0 . parse_s3_url ( arg_1 ) try : arg_0 . get_conn ( ) . head_object ( Bucket = arg_2 , Key = arg_1 ) return True except ClientError as e : arg_0 . log . info ( e . response [ "Error" ] [ "Message" ] ) return False

def Func(arg_0, arg_1, arg_2=None):
        """
        Checks if a key exists in a bucket

        :param key: S3 key that will point to the file
        :type key: str
        :param bucket_name: Name of the bucket in which the file is stored
        :type bucket_name: str
        """
        if not arg_2:
            (arg_2, arg_1) = arg_0.parse_s3_url(arg_1)

        try:
            arg_0.get_conn().head_object(Bucket=arg_2, Key=arg_1)
            return True
        except ClientError as e:
            arg_0.log.info(e.response["Error"]["Message"])
            return False


def Func ( ) : if sys . platform == 'win32' : import locale , codecs arg_0 = locale . getdefaultlocale ( ) [ 1 ] if arg_0 . startswith ( 'cp' ) : try : codecs . lookup ( arg_0 ) except LookupError : import arg_1 arg_1 . _cache [ arg_0 ] = arg_1 . _unknown arg_1 . aliases . aliases [ arg_0 ] = 'mbcs'

def Func():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        arg_0 = locale.getdefaultlocale()[1]
        if arg_0.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(arg_0)
            except LookupError:
                import arg_1
                arg_1._cache[arg_0] = arg_1._unknown
                arg_1.aliases.aliases[arg_0] = 'mbcs'

On Windows some default encodings are not provided by Python while they are always available as mbcs in each locale . Make them usable by aliasing to mbcs in such a case .


def
Func
(
arg_0
,
*
arg_1
,
**
arg_2
)
:
try
:
arg_0
.
acquire_lock
(
)
return
arg_0
.
_storage_service
.
Func
(
*
arg_1
,
**
arg_2
)
finally
:
if
arg_0
.
lock
is
not
:
try
:
arg_0
.
release_lock
(
)
except
RuntimeError
:
arg_0
.
_logger
.
error
(
'Could not release lock `%s`!'
%
str
(
arg_0
.
lock
)
)

def Func(arg_0, *arg_1, **arg_2):
        """Acquires a lock before storage and releases it afterwards."""
        try:
            arg_0.acquire_lock()
            return arg_0._storage_service.Func(*arg_1, **arg_2)
        finally:
            if arg_0.lock is not None:
                try:
                    arg_0.release_lock()
                except RuntimeError:
                    arg_0._logger.error('Could not release lock `%s`!' % str(arg_0.lock))

Acquires a lock before storage and releases it afterwards .


return L @ random.randn(L.shape[0]) + mean

def Func ( arg_0 , arg_1 , arg_2 ) : from numpy . linalg import cholesky arg_3 = cholesky ( arg_2 ) return arg_3 @ arg_0 . randn ( arg_3 . shape [ 0 ] ) + arg_1

def Func(arg_0, arg_1, arg_2):
    """
    Draw random samples from a multivariate normal distribution.

    Parameters
    ----------
    random : np.random.RandomState instance
        Random state.
    mean : array_like
        Mean of the n-dimensional distribution.
    cov : array_like
        Covariance matrix of the distribution. It must be symmetric and
        positive-definite for proper sampling.

    Returns
    -------
    out : ndarray
        The drawn sample.
    """
    from numpy.linalg import cholesky

    arg_3 = cholesky(arg_2)
    return arg_3 @ arg_0.randn(arg_3.shape[0]) + arg_1

Draw random samples from a multivariate normal distribution .


def
Func
(
arg_0
,
arg_1
)
:
if
arg_1
==
""
:
raise
ValueError
(
"Archive manager path cannot be empty"
)
if
arg_1
:
arg_0
.
archive_manager
=
perceval
.
archive
.
ArchiveManager
(
arg_1
)

def Func(arg_0, arg_1):
        """Initialize the archive manager.

        :param archive_path: path where the archive manager is located
        """
        if arg_1 == "":
            raise ValueError("Archive manager path cannot be empty")

        if arg_1:
            arg_0.archive_manager = perceval.archive.ArchiveManager(arg_1)


return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF]
                             for j in self.joints)

def Func ( arg_0 ) : return as_flat_array ( getattr ( arg_1 , 'amotor' , arg_1 ) . feedback [ - 1 ] [ : arg_1 . ADOF ] for arg_1 in arg_0 . joints )

def Func(arg_0):
        '''Get a list of all current joint torques in the skeleton.'''
        return as_flat_array(getattr(arg_1, 'amotor', arg_1).feedback[-1][:arg_1.ADOF]
                             for arg_1 in arg_0.joints)

Get a list of all current joint torques in the skeleton .


def Func ( arg_0 , arg_1 = False ) : if arg_1 : with zipfile . ZipFile ( arg_0 , "r" , arg_1 = zipfile . ZIP_DEFLATED ) as myzip : with myzip . open ( "data" ) as f : return pickle . load ( f ) else : with open ( arg_0 , "rb" ) as f : return pickle . load ( f )

def Func(arg_0, arg_1=False):
    """Unpickle a possible compressed pickle.

    Parameters
    ----------
    path: str
        path to the output file
    compression: bool
        if true assumes that pickle was compressed when created and attempts decompression.

    Returns
    -------
    obj: object
        the unpickled object
    """

    if arg_1:
        with zipfile.ZipFile(arg_0, "r", arg_1=zipfile.ZIP_DEFLATED) as myzip:
            with myzip.open("data") as f:
                return pickle.load(f)
    else:
        with open(arg_0, "rb") as f:
            return pickle.load(f)


def Func(arg_0):
    """
    Names of all state locations must be unique.
    """
    arg_1 = map(lambda loc: loc["name"], arg_0.locations)
    assert len(arg_1) == len(set(arg_1)), "Names of state locations must be unique"

Names of all state locations must be unique .


def Func ( arg_0 , arg_1 ) : if isinstance ( arg_1 , Metabolite ) : return arg_0 . _metabolites [ arg_1 ] arg_2 = { m . id : m for m in arg_0 . _metabolites } return arg_0 . _metabolites [ arg_2 [ arg_1 ] ]

def Func(arg_0, arg_1):
        """
        Return the stoichiometric coefficient of a metabolite.

        Parameters
        ----------
        metabolite_id : str or cobra.Metabolite

        """
        if isinstance(arg_1, Metabolite):
            return arg_0._metabolites[arg_1]

        arg_2 = {m.id: m for m in arg_0._metabolites}
        return arg_0._metabolites[arg_2[arg_1]]

Return the stoichiometric coefficient of a metabolite .


def
Func
(
arg_0
)
:
try
:
arg_1
=
open
(
arg_0
,
"rb"
)
except
IOError
:
raise
NoCode
(
"No file to run: %r"
%
arg_0
)
try
:
arg_2
=
arg_1
.
read
(
4
)
if
arg_2
!=
imp
.
get_magic
(
)
:
raise
NoCode
(
"Bad magic number in .pyc file"
)
arg_1
.
read
(
4
)
if
sys
.
version_info
>=
(
3
,
3
)
:
arg_1
.
read
(
4
)
arg_3
=
marshal
.
load
(
arg_1
)
finally
:
arg_1
.
close
(
)
return
arg_3

def Func(arg_0):
    """Get a code object from a .pyc file."""
    try:
        arg_1 = open(arg_0, "rb")
    except IOError:
        raise NoCode("No file to run: %r" % arg_0)

    try:
        # First four bytes are a version-specific magic number.  It has to
        # match or we won't run the file.
        arg_2 = arg_1.read(4)
        if arg_2 != imp.get_magic():
            raise NoCode("Bad magic number in .pyc file")

        # Skip the junk in the header that we don't need.
        arg_1.read(4)            # Skip the moddate.
        if sys.version_info >= (3, 3):
            # 3.3 added another long to the header (size), skip it.
            arg_1.read(4)

        # The rest of the file is the code object we want.
        arg_3 = marshal.load(arg_1)
    finally:
        arg_1.close()

    return arg_3


def Func ( arg_0 , arg_1 ) : arg_2 = { 'jobs[]' : arg_1 } arg_3 = make_put_request ( arg_0 , 'self/jobs' , arg_4 = arg_2 ) arg_4 = arg_3 . json ( ) if arg_3 . status_code == 200 : return arg_4 [ 'status' ] else : raise UserJobsNotSetException ( message = arg_4 [ 'message' ] , error_code = arg_4 [ 'error_code' ] , request_id = arg_4 [ 'request_id' ] )

def Func(arg_0, arg_1):
    """
    Replace the currently authenticated user's list of jobs with a new list of
    jobs
    """
    arg_2 = {
        'jobs[]': arg_1
    }
    arg_3 = make_put_request(arg_0, 'self/jobs', arg_4=arg_2)
    arg_4 = arg_3.json()
    if arg_3.status_code == 200:
        return arg_4['status']
    else:
        raise UserJobsNotSetException(
            message=arg_4['message'],
            error_code=arg_4['error_code'],
            request_id=arg_4['request_id'])

Replace the currently authenticated user s list of jobs with a new list of jobs


def Func(arg_0=None, **arg_1):
	"""Check that the Paypal API keys are configured correctly"""
	arg_2 = []

	arg_3 = getattr(djpaypal_settings, "PAYPAL_MODE", None)
	if arg_3 not in VALID_MODES:
		arg_4 = "Invalid PAYPAL_MODE specified: {}.".format(repr(arg_3))
		arg_5 = "PAYPAL_MODE must be one of {}".format(", ".join(repr(k) for k in VALID_MODES))
		arg_2.append(checks.Critical(arg_4, arg_5=arg_5, id="djpaypal.C001"))

	for arg_6 in "PAYPAL_CLIENT_ID", "PAYPAL_CLIENT_SECRET":
		if not getattr(djpaypal_settings, arg_6, None):
			arg_4 = "Invalid value specified for {}".format(arg_6)
			arg_5 = "Add PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET to your settings."
			arg_2.append(checks.Critical(arg_4, arg_5=arg_5, id="djpaypal.C002"))

	return arg_2


(self, query, count, offset=None, sort=None)

def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """
        Apply pagination to query

        :attr query: Instance of `peewee.Query`
        :attr count: Max rows to return
        :attr offset: Pagination offset, str/int
        :attr sort: List of tuples, e.g. [('id', 'asc')]

        :returns: Instance of `peewee.Query`
        """
        assert isinstance(arg_1, peewee.Query)
        assert isinstance(arg_2, int)
        assert isinstance(arg_3, (str, int, type(None)))
        assert isinstance(arg_4, (list, set, tuple, type(None)))

         # ensure our model has a primary key
        arg_5 = arg_1.model._meta.get_primary_keys()
        if len(arg_5) == 0:
            raise peewee.ProgrammingError(
                'Cannot apply pagination on model without primary key')

        # ensure our model doesn't use a compound primary key
        if len(arg_5) > 1:
            raise peewee.ProgrammingError(
                'Cannot apply pagination on model with compound primary key')

        # apply offset
        if arg_3 is not None:
            arg_1 = arg_1.where(arg_5[0] >= arg_3)

        # do we need to apply sorting?
        arg_6 = []
        if arg_4:
            for arg_7, arg_8 in arg_4:
                # does this field have a valid sort direction?
                if not isinstance(arg_8, str):
                    raise ValueError("Invalid sort direction on field '{}'".format(arg_7))

                arg_8 = arg_8.lower().strip()
                if arg_8 not in ['asc', 'desc']:
                    raise ValueError("Invalid sort direction on field '{}'".format(arg_7))

                # apply sorting
                arg_9 = peewee.SQL(arg_7)
                arg_9 = getattr(arg_9, arg_8)()
                arg_6 += [arg_9]

        # add primary key ordering after user sorting
        arg_6 += [arg_5[0].asc()]

        # apply ordering and limits
        arg_1 = arg_1.order_by(*arg_6)
        arg_1 = arg_1.limit(arg_2)
        return arg_1


def
Func
(
arg_0
)
:
arg_1
=
set
(
[
token
.
INDENT
,
token
.
DEDENT
,
token
.
NEWLINE
,
tokenize
.
NL
]
)
arg_2
=
[
]
arg_3
=
0
arg_0
=
arg_0
.
expandtabs
(
8
)
.
replace
(
'\r\n'
,
'\n'
)
arg_4
=
generate_tokens
(
arg_0
)
for
arg_5
,
arg_6
,
(
arg_7
,
arg_8
)
,
(
arg_7
,
arg_9
)
,
arg_7
in
phys_tokens
(
arg_4
)
:
arg_10
=
True
for
arg_11
in
re
.
split
(
'(\n)'
,
arg_6
)
:
if
arg_11
==
'\n'
:
yield
arg_2
arg_2
=
[
]
arg_3
=
0
arg_12
=
False
elif
arg_11
==
''
:
arg_12
=
False
elif
arg_5
in
arg_1
:
arg_12
=
False
else
:
if
arg_10
and
arg_8
>
arg_3
:
arg_2
.
append
(
(
"ws"
,
" "
*
(
arg_8
arg_3
)
)
)
arg_10
=
False
arg_13
=
tokenize
.
tok_name
.
get
(
arg_5
,
'xx'
)
.
lower
(
)
[
:
3
]
if
arg_5
==
token
.
NAME
and
keyword
.
iskeyword
(
arg_6
)
:
arg_13
=
"key"
arg_2
.
append
(
(
arg_13
,
arg_11
)
)
arg_12
=
True
arg_8
=
0
if
arg_12
:
arg_3
=
arg_9
if
arg_2
:
yield
arg_2

def Func(arg_0):
    """Generate a series of lines, one for each line in `source`.

    Each line is a list of pairs, each pair is a token::

        [('key', 'def'), ('ws', ' '), ('nam', 'hello'), ('op', '('), ... ]

    Each pair has a token class, and the token text.

    If you concatenate all the token texts, and then join them with newlines,
    you should have your original `source` back, with two differences:
    trailing whitespace is not preserved, and a final line with no newline
    is indistinguishable from a final line with a newline.

    """
    arg_1 = set([token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL])
    arg_2 = []
    arg_3 = 0
    arg_0 = arg_0.expandtabs(8).replace('\r\n', '\n')
    arg_4 = generate_tokens(arg_0)
    for arg_5, arg_6, (arg_7, arg_8), (arg_7, arg_9), arg_7 in phys_tokens(arg_4):
        arg_10 = True
        for arg_11 in re.split('(\n)', arg_6):
            if arg_11 == '\n':
                yield arg_2
                arg_2 = []
                arg_3 = 0
                arg_12 = False
            elif arg_11 == '':
                arg_12 = False
            elif arg_5 in arg_1:
                arg_12 = False
            else:
                if arg_10 and arg_8 > arg_3:
                    arg_2.append(("ws", " " * (arg_8 - arg_3)))
                    arg_10 = False
                arg_13 = tokenize.tok_name.get(arg_5, 'xx').lower()[:3]
                if arg_5 == token.NAME and keyword.iskeyword(arg_6):
                    arg_13 = "key"
                arg_2.append((arg_13, arg_11))
                arg_12 = True
            arg_8 = 0
        if arg_12:
            arg_3 = arg_9

    if arg_2:
        yield arg_2

Generate a series of lines one for each line in source .