def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Writes the contents of two registers to memory."""
        assert arg_1.type == 'register'
        assert arg_2.type == 'register'
        assert arg_3.type == 'memory'
        arg_5 = arg_1.read()
        arg_6 = arg_2.read()
        arg_7 = arg_0._compute_writeback(arg_3, arg_4)
        arg_0.write_int(arg_3.address(), arg_5, 32)
        arg_0.write_int(arg_3.address() + 4, arg_6, 32)
        arg_0._cs_hack_ldr_str_writeback(arg_3, arg_4, arg_7)

Writes the contents of two registers to memory .


def Func ( arg_0 , arg_1 ) : arg_0 . lock . acquire ( ) try : if arg_1 and arg_1 . type != "cancel" : arg_0 . registration_form = arg_1 arg_3 = Iq ( stanza_type = "set" ) arg_3 . set_content ( arg_0 . __register . submit_form ( arg_1 ) ) arg_0 . set_response_handlers ( arg_3 , arg_0 . registration_success , arg_0 . registration_error ) arg_0 . send ( arg_3 ) else : arg_0 . __register = None finally : arg_0 . lock . release ( )

def Func(arg_0, arg_1):
        """Submit a registration form.

        [client only]

        :Parameters:
            - `form`: the filled-in form. When form is `None` or its type is
              "cancel" the registration is to be canceled.

        :Types:
            - `form`: `pyxmpp.jabber.dataforms.Form`"""
        arg_0.lock.acquire()
        try:
            if arg_1 and arg_1.type!="cancel":
                arg_0.registration_form = arg_1
                arg_3 = Iq(stanza_type = "set")
                arg_3.set_content(arg_0.__register.submit_form(arg_1))
                arg_0.set_response_handlers(arg_3, arg_0.registration_success, arg_0.registration_error)
                arg_0.send(arg_3)
            else:
                arg_0.__register = None
        finally:
            arg_0.lock.release()


def Func ( arg_0 , arg_1 ) : try : arg_1 . message = arg_1 . getMessage ( ) except TypeError : if arg_1 . args : if isinstance ( arg_1 . args , collections . Mapping ) : arg_1 . message = arg_1 . msg . Func ( ** arg_1 . args ) else : arg_1 . message = arg_1 . msg . Func ( arg_1 . args ) arg_0 . _fmt = arg_0 . getfmt ( arg_1 . levelname ) if arg_0 . usesTime ( ) : arg_1 . asctime = arg_0 . FuncTime ( arg_1 , arg_0 . datefmt ) arg_5 = arg_0 . _fmt . Func ( ** arg_1 . __dict__ ) if arg_1 . exc_info : if not arg_1 . exc_text : arg_1 . exc_text = arg_0 . FuncException ( arg_1 . exc_info ) if arg_1 . exc_text : if arg_5 [ - 1 : ] != '\n' : arg_5 += '\n' try : arg_5 = arg_5 + arg_1 . exc_text except UnicodeError : arg_5 = arg_5 + arg_1 . exc_text . decode ( sys . getfilesystemencoding ( ) , 'replace' ) return arg_5

def Func(arg_0, arg_1):
        """tweaked from source of base"""
        try:
            arg_1.message = arg_1.getMessage()
        except TypeError:
            # if error during msg = msg % self.args
            if arg_1.args:
                if isinstance(arg_1.args, collections.Mapping):
                    arg_1.message = arg_1.msg.Func(**arg_1.args)
                else:
                    arg_1.message = arg_1.msg.Func(arg_1.args)
        arg_0._fmt = arg_0.getfmt(arg_1.levelname)
        if arg_0.usesTime():
            arg_1.asctime = arg_0.FuncTime(arg_1, arg_0.datefmt)

        arg_5 = arg_0._fmt.Func(**arg_1.__dict__)

        if arg_1.exc_info:
            # Cache the traceback text to avoid converting it multiple times
            # (it's constant anyway)
            if not arg_1.exc_text:
                arg_1.exc_text = arg_0.FuncException(arg_1.exc_info)
        if arg_1.exc_text:
            if arg_5[-1:] != '\n':
                arg_5 += '\n'
            try:
                arg_5 = arg_5 + arg_1.exc_text
            except UnicodeError:
                arg_5 = arg_5 + arg_1.exc_text.decode(sys.getfilesystemencoding(), 'replace')
        return arg_5


def Func ( arg_0 , arg_1 = 8.6 , arg_2 = 'numpy' ) : if arg_0 == 1 : return ones ( 1 ) if arg_2 == 'numpy' : from numpy import kaiser return kaiser ( arg_0 , arg_1 ) else : return _kaiser ( arg_0 , arg_1 )

def Func(arg_0, arg_1=8.6, arg_2='numpy'):
    r"""Kaiser window

    :param N: window length
    :param beta: kaiser parameter (default is 8.6)

    To obtain a Kaiser window that designs an FIR filter with
    sidelobe attenuation of :math:`\alpha` dB, use the following :math:`\beta` where
    :math:`\beta = \pi \alpha`.

    .. math::

        w_n = \frac{I_0\left(\pi\alpha\sqrt{1-\left(\frac{2n}{M}-1\right)^2}\right)} {I_0(\pi \alpha)}

    where

      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.
      * :math:`\alpha` is a real number that determines the shape of the
        window. It determines the trade-off between main-lobe width and side
        lobe level.
      * the length of the sequence is N=M+1.

    The Kaiser window can approximate many other windows by varying
    the :math:`\beta` parameter:

    ===== ========================
    beta  Window shape
    ===== ========================
    0     Rectangular
    5     Similar to a Hamming
    6     Similar to a Hanning
    8.6   Similar to a Blackman
    ===== ========================

    .. plot::
        :width: 80%
        :include-source:

        from pylab import plot, legend, xlim
        from spectrum import Func
        N = 64
        for beta in [1,2,4,8,16]:
            plot(Func(N, beta), label='beta='+str(beta))
        xlim(0,N)
        legend()

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'kaiser', beta=8.)

    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`
    """
    if arg_0 == 1:
        return ones(1)
    if arg_2 == 'numpy':
        from numpy import kaiser
        return kaiser(arg_0, arg_1)
    else:
        return _kaiser(arg_0, arg_1)

r"""Kaiser window

    :param N: window length
    :param beta: kaiser parameter (default is 8.6)

    To obtain a Kaiser window that designs an FIR filter with
    sidelobe attenuation of :math:`\alpha` dB, use the following :math:`\beta` where
    :math:`\beta = \pi \alpha`.

    .. math::

        w_n = \frac{I_0\left(\pi\alpha\sqrt{1-\left(\frac{2n}{M}-1\right)^2}\right)} {I_0(\pi \alpha)}

    where

      * :math:`I_0` is the zeroth order Modified Bessel function of the first kind.
      * :math:`\alpha` is a real number that determines the shape of the
        window. It determines the trade-off between main-lobe width and side
        lobe level.
      * the length of the sequence is N=M+1.

    The Kaiser window can approximate many other windows by varying
    the :math:`\beta` parameter:

    ===== ========================
    beta  Window shape
    ===== ========================
    0     Rectangular
    5     Similar to a Hamming
    6     Similar to a Hanning
    8.6   Similar to a Blackman
    ===== ========================

    .. plot::
        :width: 80%
        :include-source:

        from pylab import plot, legend, xlim
        from spectrum import window_kaiser
        N = 64
        for beta in [1,2,4,8,16]:
            plot(window_kaiser(N, beta), label='beta='+str(beta))
        xlim(0,N)
        legend()

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'kaiser', beta=8.)

    .. seealso:: numpy.kaiser, :func:`spectrum.window.create_window`


def Func ( arg_0 = 3 ) : for arg_1 , arg_2 in traverse_local_prefs ( arg_0 ) : if isinstance ( arg_2 [ arg_1 ] , PatchedLocal ) : arg_2 [ arg_1 ] = arg_2 [ arg_1 ] . val del get_frame_locals ( arg_0 ) [ __PATCHED_LOCALS_SENTINEL ]

def Func(arg_0=3):
    """Restores the original values of module variables
    considered preferences if they are still PatchedLocal
    and not PrefProxy.

    """
    for arg_1, arg_2 in traverse_local_prefs(arg_0):
        if isinstance(arg_2[arg_1], PatchedLocal):
            arg_2[arg_1] = arg_2[arg_1].val

    del get_frame_locals(arg_0)[__PATCHED_LOCALS_SENTINEL]

Restores the original values of module variables considered preferences if they are still PatchedLocal and not PrefProxy .


def
Func
(
arg_0
,
arg_1
)
:
if
len
(
arg_1
)
>
0
:
if
arg_1
.
strip
(
)
.
lower
(
)
==
"on"
:
log
.
write
(
"Table ON"
)
arg_0
.
table_output
=
True
return
elif
arg_1
.
strip
(
)
.
lower
(
)
==
"off"
:
log
.
write
(
"Table OFF"
)
arg_0
.
table_output
=
False
return
log
.
write
(
"Table output: {}"
.
format
(
"ON"
if
arg_0
.
table_output
else
"OFF"
)
)

def Func(arg_0, arg_1):
        """Display results in table format"""
        if len(arg_1) > 0:
            if arg_1.strip().lower() == "on":
                log.write("Table ON")
                arg_0.table_output = True
                return
            elif arg_1.strip().lower() == "off":
                log.write("Table OFF")
                arg_0.table_output = False
                return
        log.write("Table output: {}".format("ON" if arg_0.table_output else "OFF"))


return HTTPResponse(
            body=body,
            preload_content=False,
            **cached["response"]
        )

def Func ( arg_0 , arg_1 , arg_2 ) : if "*" in arg_2 . get ( "vary" , { } ) : return for arg_3 , arg_4 in arg_2 . get ( "vary" , { } ) . items ( ) : if arg_1 . headers . get ( arg_3 , None ) != arg_4 : return arg_5 = arg_2 [ "response" ] . pop ( "body" ) try : arg_6 = io . BytesIO ( arg_5 ) except TypeError : arg_6 = io . BytesIO ( arg_5 . encode ( 'utf8' ) ) return HTTPResponse ( arg_6 = arg_6 , preload_content = False , ** arg_2 [ "response" ] )

def Func(arg_0, arg_1, arg_2):
        """Verify our vary headers match and construct a real urllib3
        HTTPResponse object.
        """
        # Special case the '*' Vary value as it means we cannot actually
        # determine if the cached response is suitable for this request.
        if "*" in arg_2.get("vary", {}):
            return

        # Ensure that the Vary headers for the cached response match our
        # request
        for arg_3, arg_4 in arg_2.get("vary", {}).items():
            if arg_1.headers.get(arg_3, None) != arg_4:
                return

        arg_5 = arg_2["response"].pop("body")

        try:
            arg_6 = io.BytesIO(arg_5)
        except TypeError:
            # This can happen if cachecontrol serialized to v1 format (pickle)
            # using Python 2. A Python 2 str(byte string) will be unpickled as
            # a Python 3 str (unicode string), which will cause the above to
            # fail with:
            #
            #     TypeError: 'str' does not support the buffer interface
            arg_6 = io.BytesIO(arg_5.encode('utf8'))

        return HTTPResponse(
            arg_6=arg_6,
            preload_content=False,
            **arg_2["response"]
        )

Verify our vary headers match and construct a real urllib3 HTTPResponse object .


def Func ( arg_0 , arg_1 ) : arg_2 = [ ] arg_3 = { } if arg_0 . preserve_json_order : arg_3 [ "object_pairs_hook" ] = OrderedDict for arg_4 in arg_1 . entries : arg_2 . append ( json . loads ( arg_4 [ "content" ] [ 0 ] [ "value" ] , ** arg_3 ) ) arg_0 . url_params = None return arg_2

def Func(arg_0, arg_1):
        """ Return a list of dicts which are dumped CSL JSON
        """
        arg_2 = []
        arg_3 = {}
        if arg_0.preserve_json_order:
            arg_3["object_pairs_hook"] = OrderedDict
        for arg_4 in arg_1.entries:
            arg_2.append(json.loads(arg_4["content"][0]["value"], **arg_3))
        arg_0.url_params = None
        return arg_2


return galaxy.Galaxy(redshift=redshift, pixelization=pixelization, regularization=regularization,
                             hyper_galaxy=hyper_galaxy, **profiles)

def Func ( arg_0 , arg_1 ) : arg_2 = { ** { key : value . Func ( arg_1 ) for key , value in arg_0 . profile_prior_model_dict . items ( ) } , ** arg_0 . constant_profile_dict } try : arg_3 = arg_0 . redshift . Func ( arg_1 ) except AttributeError : arg_3 = arg_0 . redshift arg_4 = arg_0 . pixelization . Func ( arg_1 ) if isinstance ( arg_0 . pixelization , pm . PriorModel ) else arg_0 . pixelization arg_5 = arg_0 . regularization . Func ( arg_1 ) if isinstance ( arg_0 . regularization , pm . PriorModel ) else arg_0 . regularization arg_6 = arg_0 . hyper_galaxy . Func ( arg_1 ) if isinstance ( arg_0 . hyper_galaxy , pm . PriorModel ) else arg_0 . hyper_galaxy return galaxy . Galaxy ( arg_3 = arg_3 , arg_4 = arg_4 , arg_5 = arg_5 , arg_6 = arg_6 , ** arg_2 )

def Func(arg_0, arg_1):
        """
        Create an instance of the associated class for a set of arguments

        Parameters
        ----------
        arguments: {Prior: value}
            Dictionary mapping_matrix priors to attribute analysis_path and value pairs

        Returns
        -------
            An instance of the class
        """
        arg_2 = {**{key: value.Func(arg_1)
                       for key, value
                       in arg_0.profile_prior_model_dict.items()}, **arg_0.constant_profile_dict}

        try:
            arg_3 = arg_0.redshift.Func(arg_1)
        except AttributeError:
            arg_3 = arg_0.redshift
        arg_4 = arg_0.pixelization.Func(arg_1) \
            if isinstance(arg_0.pixelization, pm.PriorModel) \
            else arg_0.pixelization
        arg_5 = arg_0.regularization.Func(arg_1) \
            if isinstance(arg_0.regularization, pm.PriorModel) \
            else arg_0.regularization
        arg_6 = arg_0.hyper_galaxy.Func(arg_1) \
            if isinstance(arg_0.hyper_galaxy, pm.PriorModel) \
            else arg_0.hyper_galaxy

        return galaxy.Galaxy(arg_3=arg_3, arg_4=arg_4, arg_5=arg_5,
                             arg_6=arg_6, **arg_2)


return self._post(
            request=ApiActions.DELETE.value,
            uri=ApiUri.TAGS.value,
            params={'id': id}
        )

def Func ( arg_0 , arg_1 ) : return arg_0 . _post ( request = ApiActions . DELETE . value , uri = ApiUri . TAGS . value , params = { 'id' : arg_1 } )

def Func(arg_0, arg_1):
        """
        Delete the specified label

        :param id: the label's ID
        :type id: str

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        return arg_0._post(
            request=ApiActions.DELETE.value,
            uri=ApiUri.TAGS.value,
            params={'id': arg_1}
        )


(cls, url=None, token_file=None, token=None)

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
,
arg_3
=
)
:
if
arg_1
is
:
arg_1
=
'/'
if
arg_1
.
startswith
(
'http'
)
:
arg_4
=
get_root_url
(
arg_1
)
else
:
arg_1
=
URL_BASE
+
'/'
+
arg_1
.
lstrip
(
'/'
)
arg_4
=
URL_BASE
if
arg_3
is
:
arg_2
=
arg_2
or
get_token_filename
(
)
try
:
with
open
(
arg_2
)
as
tf
:
arg_5
=
json
.
load
(
tf
)
except
FileNotFoundError
:
raise
LuminosoAuthError
(
'No token file at %s'
%
arg_2
)
try
:
arg_3
=
arg_5
[
urlparse
(
arg_4
)
.
netloc
]
except
KeyError
:
raise
LuminosoAuthError
(
'No token stored for %s'
%
arg_4
)
arg_6
=
requests
.
session
(
)
arg_6
.
auth
=
_TokenAuth
(
arg_3
)
return
arg_0
(
arg_6
,
arg_1
)

def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """
        Returns an object that makes requests to the API, authenticated
        with a saved or specified long-lived token, at URLs beginning with
        `url`.

        If no URL is specified, or if the specified URL is a path such as
        '/projects' without a scheme and domain, the client will default to
        https://analytics.luminoso.com/api/v5/.

        If neither token nor token_file are specified, the client will look
        for a token in $HOME/.luminoso/tokens.json. The file should contain
        a single json dictionary of the format
        `{'root_url': 'token', 'root_url2': 'token2', ...}`.
        """
        if arg_1 is None:
            arg_1 = '/'

        if arg_1.startswith('http'):
            arg_4 = get_root_url(arg_1)
        else:
            arg_1 = URL_BASE + '/' + arg_1.lstrip('/')
            arg_4 = URL_BASE

        if arg_3 is None:
            arg_2 = arg_2 or get_token_filename()
            try:
                with open(arg_2) as tf:
                    arg_5 = json.load(tf)
            except FileNotFoundError:
                raise LuminosoAuthError('No token file at %s' % arg_2)
            try:
                arg_3 = arg_5[urlparse(arg_4).netloc]
            except KeyError:
                raise LuminosoAuthError('No token stored for %s' % arg_4)

        arg_6 = requests.session()
        arg_6.auth = _TokenAuth(arg_3)
        return arg_0(arg_6, arg_1)

Returns an object that makes requests to the API authenticated with a saved or specified long - lived token at URLs beginning with url .


def
Func
(
arg_0
)
->
:
if
abs
(
arg_0
.
_idx
1
)
>
arg_0
.
_Func_depth
:
raise
IndexError
(
"Exceeded Func depth"
)
arg_0
.
_idx
-=
1

def Func(arg_0) -> None:
        """Push one character back onto the stream, allowing it to be
        read again."""
        if abs(arg_0._idx - 1) > arg_0._Func_depth:
            raise IndexError("Exceeded Func depth")
        arg_0._idx -= 1

Push one character back onto the stream allowing it to be read again .


def
Func
(
arg_0
)
:
with
open
(
arg_0
)
as
f
:
arg_1
=
f
.
read
(
)
.
split
(
"\n"
)
arg_2
=
{
}
for
arg_3
in
arg_1
:
arg_4
=
arg_3
.
split
(
'"'
)
[
1
]
+
"\\"
arg_3
=
[
]
+
arg_3
.
split
(
'"'
)
[
2
]
.
split
(
", "
)
for
arg_5
in
arg_3
[
1
:
]
:
if
not
arg_5
in
arg_2
:
arg_2
[
arg_5
]
=
[
]
arg_2
[
arg_5
]
=
arg_2
[
arg_5
]
+
[
arg_4
]
arg_6
=
len
(
arg_2
)
arg_7
=
sorted
(
arg_2
.
keys
(
)
)
[
0
]
arg_8
=
sorted
(
arg_2
.
keys
(
)
)
[
1
]
arg_7
=
datetime
.
datetime
.
strptime
(
arg_7
,
"%Y-%m-%d"
)
arg_8
=
datetime
.
datetime
.
strptime
(
arg_8
,
"%Y-%m-%d"
)
arg_9
=
(
arg_8
arg_7
)
.
days
+
1
arg_10
=
0
for
arg_11
in
range
(
arg_9
)
:
arg_5
=
arg_7
+
datetime
.
timedelta
(
days
=
arg_11
)
arg_12
=
datetime
.
datetime
.
strftime
(
arg_5
,
"%Y-%m-%d"
)
if
not
arg_12
in
arg_2
:
arg_2
[
arg_12
]
=
[
]
arg_10
+=
1
arg_13
=
arg_6
/
arg_9
*
100
print
(
"%d of %d days were active (%.02f%%)"
%
(
arg_6
,
arg_9
,
arg_13
)
)
return
arg_2

def Func(arg_0):
    """returns a dict of active folders with days as keys."""
    with open(arg_0) as f:
        arg_1=f.read().split("\n")
    arg_2={}
    for arg_3 in arg_1:
        arg_4=arg_3.split('"')[1]+"\\"
        arg_3=[]+arg_3.split('"')[2].split(", ")
        for arg_5 in arg_3[1:]:
            if not arg_5 in arg_2:
                arg_2[arg_5]=[]
            arg_2[arg_5]=arg_2[arg_5]+[arg_4]
    arg_6=len(arg_2)
    arg_7=sorted(arg_2.keys())[0]
    arg_8=sorted(arg_2.keys())[-1]
    arg_7=datetime.datetime.strptime(arg_7, "%Y-%m-%d" )
    arg_8=datetime.datetime.strptime(arg_8, "%Y-%m-%d" )
    arg_9 = (arg_8 - arg_7).days + 1
    arg_10=0
    for arg_11 in range(arg_9):
        arg_5=arg_7+datetime.timedelta(days=arg_11)
        arg_12=datetime.datetime.strftime(arg_5, "%Y-%m-%d" )
        if not arg_12 in arg_2:
            arg_2[arg_12]=[]
            arg_10+=1
    arg_13=arg_6/arg_9*100
    print("%d of %d days were active (%.02f%%)"%(arg_6,arg_9,arg_13))
    return arg_2

returns a dict of active folders with days as keys .


(returns,
                         factor_returns=None,
                         live_start_date=None,
                         logy=False,
                         cone_std=None,
                         legend_loc='best',
                         volatility_match=False,
                         cone_function=timeseries.forecast_cone_bootstrap,
                         ax=None, **kwargs)

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
,
arg_3
=
False
,
arg_4
=
,
arg_5
=
'best'
,
arg_6
=
False
,
arg_7
=
arg_8
.
forecast_cone_bootstrap
,
arg_10
=
,
**
arg_11
)
:
if
arg_10
is
:
arg_10
=
plt
.
gca
(
)
arg_10
.
set_xlabel
(
''
)
arg_10
.
set_ylabel
(
'Cumulative returns'
)
arg_10
.
set_yscale
(
'log'
if
arg_3
else
'linear'
)
if
arg_6
and
arg_1
is
:
raise
ValueError
(
'volatility_match requires passing of '
'factor_returns.'
)
elif
arg_6
and
arg_1
is
not
:
arg_12
=
arg_1
.
loc
[
arg_0
.
index
]
.
std
(
)
arg_0
=
(
arg_0
/
arg_0
.
std
(
)
)
*
arg_12
arg_13
=
ep
.
cum_returns
(
arg_0
,
1.0
)
arg_14
=
FuncFormatter
(
utils
.
two_dec_places
)
arg_10
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
arg_14
)
)
if
arg_1
is
not
:
arg_15
=
ep
.
cum_returns
(
arg_1
[
arg_13
.
index
]
,
1.0
)
arg_15
.
plot
(
lw
=
2
,
color
=
'gray'
,
label
=
arg_1
.
name
,
alpha
=
0.60
,
arg_10
=
arg_10
,
**
arg_11
)
if
arg_2
is
not
:
arg_2
=
ep
.
utils
.
get_utc_timestamp
(
arg_2
)
arg_16
=
arg_13
.
loc
[
arg_13
.
index
<
arg_2
]
arg_17
=
arg_13
.
loc
[
arg_13
.
index
>=
arg_2
]
else
:
arg_16
=
arg_13
arg_17
=
pd
.
Series
(
[
]
)
arg_16
.
plot
(
lw
=
3
,
color
=
'forestgreen'
,
alpha
=
0.6
,
label
=
'Backtest'
,
arg_10
=
arg_10
,
**
arg_11
)
if
len
(
arg_17
)
>
0
:
arg_17
.
plot
(
lw
=
4
,
color
=
'red'
,
alpha
=
0.6
,
label
=
'Live'
,
arg_10
=
arg_10
,
**
arg_11
)
if
arg_4
is
not
:
if
isinstance
(
arg_4
,
(
float
,
int
)
)
:
arg_4
=
[
arg_4
]
arg_18
=
arg_0
.
loc
[
arg_0
.
index
<
arg_2
]
arg_19
=
arg_7
(
arg_18
,
len
(
arg_17
)
,
arg_4
=
arg_4
,
starting_value
=
arg_16
[
1
]
)
arg_19
=
arg_19
.
set_index
(
arg_17
.
index
)
for
arg_20
in
arg_4
:
arg_10
.
fill_between
(
arg_19
.
index
,
arg_19
[
float
(
arg_20
)
]
,
arg_19
[
float
(
arg_20
)
]
,
color
=
'steelblue'
,
alpha
=
0.5
)
if
arg_5
is
not
:
arg_10
.
legend
(
loc
=
arg_5
,
frameon
=
True
,
framealpha
=
0.5
)
arg_10
.
axhline
(
1.0
,
linestyle
=
'--'
,
color
=
'black'
,
lw
=
2
)
return
arg_10

def Func(arg_0,
                         arg_1=None,
                         arg_2=None,
                         arg_3=False,
                         arg_4=None,
                         arg_5='best',
                         arg_6=False,
                         arg_7=arg_8.forecast_cone_bootstrap,
                         arg_10=None, **arg_11):
    """
    Plots cumulative rolling returns versus some benchmarks'.

    Backtest returns are in green, and out-of-sample (live trading)
    returns are in red.

    Additionally, a non-parametric cone plot may be added to the
    out-of-sample returns region.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    live_start_date : datetime, optional
        The date when the strategy began live trading, after
        its backtest period. This date should be normalized.
    logy : bool, optional
        Whether to log-scale the y-axis.
    cone_std : float, or tuple, optional
        If float, The standard deviation to use for the cone plots.
        If tuple, Tuple of standard deviation values to use for the cone plots
         - See timeseries.forecast_cone_bounds for more details.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    volatility_match : bool, optional
        Whether to normalize the volatility of the returns to those of the
        benchmark returns. This helps compare strategies with different
        volatilities. Requires passing of benchmark_rets.
    cone_function : function, optional
        Function to use when generating forecast probability cone.
        The function signiture must follow the form:
        def cone(in_sample_returns (pd.Series),
                 days_to_project_forward (int),
                 cone_std= (float, or tuple),
                 starting_value= (int, or float))
        See timeseries.forecast_cone_bootstrap for an example.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_10 is None:
        arg_10 = plt.gca()

    arg_10.set_xlabel('')
    arg_10.set_ylabel('Cumulative returns')
    arg_10.set_yscale('log' if arg_3 else 'linear')

    if arg_6 and arg_1 is None:
        raise ValueError('volatility_match requires passing of '
                         'factor_returns.')
    elif arg_6 and arg_1 is not None:
        arg_12 = arg_1.loc[arg_0.index].std()
        arg_0 = (arg_0 / arg_0.std()) * arg_12

    arg_13 = ep.cum_returns(arg_0, 1.0)

    arg_14 = FuncFormatter(utils.two_dec_places)
    arg_10.yaxis.set_major_formatter(FuncFormatter(arg_14))

    if arg_1 is not None:
        arg_15 = ep.cum_returns(
            arg_1[arg_13.index], 1.0)
        arg_15.plot(lw=2, color='gray',
                                label=arg_1.name, alpha=0.60,
                                arg_10=arg_10, **arg_11)

    if arg_2 is not None:
        arg_2 = ep.utils.get_utc_timestamp(arg_2)
        arg_16 = arg_13.loc[arg_13.index < arg_2]
        arg_17 = arg_13.loc[arg_13.index >= arg_2]
    else:
        arg_16 = arg_13
        arg_17 = pd.Series([])

    arg_16.plot(lw=3, color='forestgreen', alpha=0.6,
                        label='Backtest', arg_10=arg_10, **arg_11)

    if len(arg_17) > 0:
        arg_17.plot(lw=4, color='red', alpha=0.6,
                             label='Live', arg_10=arg_10, **arg_11)

        if arg_4 is not None:
            if isinstance(arg_4, (float, int)):
                arg_4 = [arg_4]

            arg_18 = arg_0.loc[arg_0.index < arg_2]
            arg_19 = arg_7(
                arg_18,
                len(arg_17),
                arg_4=arg_4,
                starting_value=arg_16[-1])

            arg_19 = arg_19.set_index(arg_17.index)
            for arg_20 in arg_4:
                arg_10.fill_between(arg_19.index,
                                arg_19[float(arg_20)],
                                arg_19[float(-arg_20)],
                                color='steelblue', alpha=0.5)

    if arg_5 is not None:
        arg_10.legend(loc=arg_5, frameon=True, framealpha=0.5)
    arg_10.axhline(1.0, linestyle='--', color='black', lw=2)

    return arg_10

Plots cumulative rolling returns versus some benchmarks .


def Func ( arg_0 ) : arg_1 = arg_0 . matchdict [ 'id' ] arg_2 , arg_3 = check_publication_state ( arg_1 ) arg_4 = { 'publication' : arg_1 , 'state' : arg_2 , 'messages' : arg_3 , } return arg_4

def Func(arg_0):
    """Lookup publication state"""
    arg_1 = arg_0.matchdict['id']
    arg_2, arg_3 = check_publication_state(arg_1)
    arg_4 = {
        'publication': arg_1,
        'state': arg_2,
        'messages': arg_3,
    }
    return arg_4


def
Func
(
)
:
if
NO_SOX
:
return
[
]
arg_0
=
subprocess
.
check_output
(
[
'sox'
,
'-h'
]
)
if
type
(
arg_0
)
is
not
str
:
arg_0
=
str
(
arg_0
,
encoding
=
'UTF-8'
)
arg_0
=
arg_0
.
split
(
'\n'
)
arg_1
=
[
i
for
i
in
range
(
len
(
arg_0
)
)
if
'AUDIO FILE FORMATS:'
in
arg_0
[
i
]
]
[
0
]
arg_2
=
arg_0
[
arg_1
]
.
split
(
' '
)
[
3
:
]
return
arg_2

def Func():
    ''' Calls SoX help for a lists of audio formats available with the current
    install of SoX.

    Returns:
    --------
    formats : list
        List of audio file extensions that SoX can process.

    '''
    if NO_SOX:
        return []

    arg_0 = subprocess.check_output(['sox', '-h'])
    if type(arg_0) is not str:
        arg_0 = str(arg_0, encoding='UTF-8')
    arg_0 = arg_0.split('\n')
    arg_1 = [i for i in range(len(arg_0)) if 'AUDIO FILE FORMATS:' in arg_0[i]][0]
    arg_2 = arg_0[arg_1].split(' ')[3:]

    return arg_2

Calls SoX help for a lists of audio formats available with the current install of SoX .


(self, table, field, unique=False, ascending=True)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
=
False
,
arg_4
=
True
)
:
if
arg_3
:
arg_5
=
"unique "
else
:
arg_5
=
""
if
arg_4
:
arg_6
=
"asc"
else
:
arg_6
=
"desc"
arg_7
=
"create "
+
arg_5
+
"index index_"
+
arg_1
+
"_"
+
arg_2
+
" "
arg_7
+=
"on "
+
arg_1
+
"("
+
arg_2
+
" "
+
arg_6
+
")"
arg_0
.
_cur
.
execute
(
arg_7
)
arg_0
.
_con
.
commit
(
)

def Func(arg_0, arg_1, arg_2, arg_3=False, arg_4=True):

        """Creates a table index.

        Creates an index on the given table,
        on the given field with unique values enforced or not,
        in ascending or descending order.

        """

        if arg_3: arg_5 = "unique "
        else: arg_5 = ""
        if arg_4: arg_6 = "asc"
        else: arg_6 = "desc"
        arg_7  = "create "+arg_5+"index index_"+arg_1+"_"+arg_2+" "
        arg_7 += "on "+arg_1+"("+arg_2+" "+arg_6+")"
        arg_0._cur.execute(arg_7)
        arg_0._con.commit()

Creates a table index . Creates an index on the given table on the given field with unique values enforced or not in ascending or descending order .


def
Func
(
arg_0
)
:
assert_is_type
(
arg_0
,
str
)
arg_1
=
api
(
"GET /3/Models/%s"
%
arg_0
)
[
"models"
]
[
0
]
arg_2
=
arg_1
[
"algo"
]
if
arg_2
==
"svd"
:
arg_3
=
H2OSVD
(
)
elif
arg_2
==
"pca"
:
arg_3
=
H2OPrincipalComponentAnalysisEstimator
(
)
elif
arg_2
==
"drf"
:
arg_3
=
H2ORandomForestEstimator
(
)
elif
arg_2
==
"naivebayes"
:
arg_3
=
H2ONaiveBayesEstimator
(
)
elif
arg_2
==
"kmeans"
:
arg_3
=
H2OKMeansEstimator
(
)
elif
arg_2
==
"glrm"
:
arg_3
=
H2OGeneralizedLowRankEstimator
(
)
elif
arg_2
==
"glm"
:
arg_3
=
H2OGeneralizedLinearEstimator
(
)
elif
arg_2
==
"gbm"
:
arg_3
=
H2OGradientBoostingEstimator
(
)
elif
arg_2
==
"deepwater"
:
arg_3
=
H2ODeepWaterEstimator
(
)
elif
arg_2
==
"xgboost"
:
arg_3
=
H2OXGBoostEstimator
(
)
elif
arg_2
==
"word2vec"
:
arg_3
=
H2OWord2vecEstimator
(
)
elif
arg_2
==
"generic"
:
arg_3
=
H2OGenericEstimator
(
)
elif
arg_2
==
"deeplearning"
:
if
arg_1
[
"output"
]
[
"model_category"
]
==
"AutoEncoder"
:
arg_3
=
H2OAutoEncoderEstimator
(
)
else
:
arg_3
=
H2ODeepLearningEstimator
(
)
elif
arg_2
==
"stackedensemble"
:
arg_3
=
H2OStackedEnsembleEstimator
(
)
elif
arg_2
==
"isolationforest"
:
arg_3
=
H2OIsolationForestEstimator
(
)
else
:
raise
ValueError
(
"Unknown algo type: "
+
arg_2
)
arg_3
.
_resolve_model
(
arg_0
,
arg_1
)
return
arg_3

def Func(arg_0):
    """
    Load a model from the server.

    :param model_id: The model identification in H2O

    :returns: Model object, a subclass of H2OEstimator
    """
    assert_is_type(arg_0, str)
    arg_1 = api("GET /3/Models/%s" % arg_0)["models"][0]
    arg_2 = arg_1["algo"]
    if arg_2 == "svd":            arg_3 = H2OSVD()
    elif arg_2 == "pca":          arg_3 = H2OPrincipalComponentAnalysisEstimator()
    elif arg_2 == "drf":          arg_3 = H2ORandomForestEstimator()
    elif arg_2 == "naivebayes":   arg_3 = H2ONaiveBayesEstimator()
    elif arg_2 == "kmeans":       arg_3 = H2OKMeansEstimator()
    elif arg_2 == "glrm":         arg_3 = H2OGeneralizedLowRankEstimator()
    elif arg_2 == "glm":          arg_3 = H2OGeneralizedLinearEstimator()
    elif arg_2 == "gbm":          arg_3 = H2OGradientBoostingEstimator()
    elif arg_2 == "deepwater":    arg_3 = H2ODeepWaterEstimator()
    elif arg_2 == "xgboost":      arg_3 = H2OXGBoostEstimator()
    elif arg_2 == "word2vec":     arg_3 = H2OWord2vecEstimator()
    elif arg_2 == "generic": arg_3 = H2OGenericEstimator()
    elif arg_2 == "deeplearning":
        if arg_1["output"]["model_category"] == "AutoEncoder":
            arg_3 = H2OAutoEncoderEstimator()
        else:
            arg_3 = H2ODeepLearningEstimator()
    elif arg_2 == "stackedensemble": arg_3 = H2OStackedEnsembleEstimator()
    elif arg_2 == "isolationforest": arg_3 = H2OIsolationForestEstimator()
    else:
        raise ValueError("Unknown algo type: " + arg_2)
    arg_3._resolve_model(arg_0, arg_1)
    return arg_3


def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
if
arg_2
==
"xml"
and
arg_1
!=
XML_NS
:
raise
ValueError
,
"Cannot change 'xml' prefix meaning"
arg_0
.
_prefixes
[
arg_1
]
=
arg_2

def Func(arg_0, arg_1, arg_2):
        """Add a new namespace prefix.

        If the root element has not yet been emitted the prefix will
        be declared there, otherwise the prefix will be declared on the
        top-most element using this namespace in every stanza.

        :Parameters:
            - `namespace`: the namespace URI
            - `prefix`: the prefix string
        :Types:
            - `namespace`: `unicode`
            - `prefix`: `unicode`
        """
        if arg_2 == "xml" and arg_1 != XML_NS:
            raise ValueError, "Cannot change 'xml' prefix meaning"
        arg_0._prefixes[arg_1] = arg_2


def Func():
    """
    Per profile, adds each model to a dictionary mapping the morango model name to its model class.
    We sort by ForeignKey dependencies to safely sync data.
    """

    import django.apps
    from morango.models import SyncableModel
    from morango.manager import SyncableModelManager
    from morango.query import SyncableModelQuerySet

    arg_0 = []
    for arg_1 in django.apps.apps.get_models():
        # several validation checks to assert models will be syncing correctly
        if issubclass(arg_1, SyncableModel):
            arg_2 = arg_1.__name__
            if _multiple_self_ref_fk_check(arg_1):
                raise InvalidMorangoModelConfiguration("Syncing models with more than 1 self referential ForeignKey is not supported.")
            try:
                from mptt import models
                from morango.utils.morango_mptt import MorangoMPTTModel, MorangoMPTTTreeManager, MorangoTreeQuerySet
                # mptt syncable model checks
                if issubclass(arg_1, models.MPTTModel):
                    if not issubclass(arg_1, MorangoMPTTModel):
                        raise InvalidMorangoModelConfiguration("{} that inherits from MPTTModel, should instead inherit from MorangoMPTTModel.".format(arg_2))
                    if not isinstance(arg_1.objects, MorangoMPTTTreeManager):
                        raise InvalidMPTTManager("Manager for {} must inherit from MorangoMPTTTreeManager.".format(arg_2))
                    if not isinstance(arg_1.objects.none(), MorangoTreeQuerySet):
                        raise InvalidMPTTQuerySet("Queryset for {} model must inherit from MorangoTreeQuerySet.".format(arg_2))
            except ImportError:
                pass
            # syncable model checks
            if not isinstance(arg_1.objects, SyncableModelManager):
                raise InvalidSyncableManager("Manager for {} must inherit from SyncableModelManager.".format(arg_2))
            if not isinstance(arg_1.objects.none(), SyncableModelQuerySet):
                raise InvalidSyncableQueryset("Queryset for {} model must inherit from SyncableModelQuerySet.".format(arg_2))
            if arg_1._meta.many_to_many:
                raise UnsupportedFieldType("{} model with a ManyToManyField is not supported in morango.")
            if not hasattr(arg_1, 'morango_model_name'):
                raise InvalidMorangoModelConfiguration("{} model must define a morango_model_name attribute".format(arg_2))
            if not hasattr(arg_1, 'morango_profile'):
                raise InvalidMorangoModelConfiguration("{} model must define a morango_profile attribute".format(arg_2))

            # create empty list to hold model classes for profile if not yet created
            arg_3 = arg_1.morango_profile
            arg_4[arg_3] = arg_4.get(arg_3, [])

            # don't sync models where morango_model_name is None
            if arg_1.morango_model_name is not None:
                _insert_model_into_profile_dict(arg_1, arg_3)

    # for each profile, create a dict mapping from morango model names to model class
    for arg_3, arg_0 in iteritems(arg_4):
        arg_5 = OrderedDict()
        for arg_1 in arg_0:
            arg_5[arg_1.morango_model_name] = arg_1
        arg_4[arg_3] = arg_5

Per profile adds each model to a dictionary mapping the morango model name to its model class . We sort by ForeignKey dependencies to safely sync data .


def Func ( arg_0 , arg_1 , arg_2 = None ) : if arg_2 is None : arg_2 = LockManager . LOCK_TIME_OUT_DEFAULT return arg_0 . storage . Func ( arg_1 , arg_2 )

def Func(arg_0, arg_1, arg_2=None):
        """Set new timeout for lock, if existing and valid."""
        if arg_2 is None:
            arg_2 = LockManager.LOCK_TIME_OUT_DEFAULT
        return arg_0.storage.Func(arg_1, arg_2)

Set new timeout for lock if existing and valid .


def Func ( arg_0 ) : if arg_0 is None : return '' else : arg_1 = str ( arg_0 [ 0 ] ) arg_2 = str ( arg_0 [ 1 ] ) return ( '_image_psf_' + arg_1 + 'x' + arg_2 )

def Func(arg_0):
    """Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \
    is trimmed to for faster run times.

    This changes the phase name 'phase_name' as follows:

    image_psf_shape = 1 -> phase_name
    image_psf_shape = 2 -> phase_name_image_psf_shape_2
    image_psf_shape = 2 -> phase_name_image_psf_shape_2
    """
    if arg_0 is None:
        return ''
    else:
        arg_1 = str(arg_0[0])
        arg_2 = str(arg_0[1])
        return ('_image_psf_' + arg_1 + 'x' + arg_2)

Generate an image psf shape tag to customize phase names based on size of the image PSF that the original PSF \ is trimmed to for faster run times .


def Func(arg_0):
        """Initialize archive based on the parsed parameters"""

        if 'archive_path' not in arg_0.parsed_args:
            arg_1 = None
        elif arg_0.parsed_args.no_archive:
            arg_1 = None
        else:
            if not arg_0.parsed_args.archive_path:
                arg_2 = os.path.expanduser(ARCHIVES_DEFAULT_PATH)
            else:
                arg_2 = arg_0.parsed_args.archive_path

            arg_1 = ArchiveManager(arg_2)

        arg_0.archive_manager = arg_1


def Func ( arg_0 ) : arg_1 = set ( ) for arg_2 in arg_0 : if not os . path . isdir ( arg_2 ) : arg_1 . add ( arg_2 ) continue for arg_3 , arg_4 , arg_5 in os . walk ( arg_2 ) : for arg_6 in arg_5 : arg_7 = os . path . join ( arg_3 , arg_6 ) if arg_7 . startswith ( '.' + os . path . sep ) : arg_7 = arg_7 [ len ( '.' + os . path . sep ) : ] arg_1 . add ( arg_7 ) arg_8 = [ ] for arg_2 in arg_1 : if os . path . splitext ( arg_2 ) [ 1 ] [ 1 : ] in GetAllExtensions ( ) : arg_8 . append ( arg_2 ) return arg_8

def Func(arg_0):
  """Searches a list of filenames and replaces directories in the list with
  all files descending from those directories. Files with extensions not in
  the valid extensions list are excluded.

  Args:
    filenames: A list of files or directories

  Returns:
    A list of all files that are members of filenames or descended from a
    directory in filenames
  """
  arg_1 = set()
  for arg_2 in arg_0:
      if not os.path.isdir(arg_2):
        arg_1.add(arg_2)
        continue

      for arg_3, arg_4, arg_5 in os.walk(arg_2):
        for arg_6 in arg_5:
          arg_7 = os.path.join(arg_3, arg_6)
          if arg_7.startswith('.' + os.path.sep):
            arg_7 = arg_7[len('.' + os.path.sep):]
          arg_1.add(arg_7)

  arg_8 = []
  for arg_2 in arg_1:
      if os.path.splitext(arg_2)[1][1:] in GetAllExtensions():
          arg_8.append(arg_2)

  return arg_8

Searches a list of filenames and replaces directories in the list with all files descending from those directories . Files with extensions not in the valid extensions list are excluded .


def Func(arg_0):
        """Direct link to the overview group"""
        if arg_0.Func_ is None:
            arg_0.Func_ = arg_0._all_create_or_get_groups('overview')[0]
        return arg_0.Func_


(jobID, modelID, jobsDAO, experimentDir, logger,
                                e)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                                arg_5):
  """ Perform standard handling of an exception that occurs while running
  a model.

  Parameters:
  -------------------------------------------------------------------------
  jobID:                ID for this hypersearch job in the jobs table
  modelID:              model ID
  jobsDAO:              ClientJobsDAO instance
  experimentDir:        directory containing the experiment
  logger:               the logger to use
  e:                    the exception that occurred
  retval:               (completionReason, completionMsg)
  """

  arg_6 = StringIO.StringIO()
  print >>arg_6, "Exception occurred while running model %s: %r (%s)" % (
    arg_1, arg_5, type(arg_5))
  traceback.print_exc(None, arg_6)

  arg_7 = arg_2.CMPL_REASON_ERROR
  arg_8 = arg_6.getvalue()
  arg_4.error(arg_8)

  # Write results to the model database for the error case. Ignore
  # InvalidConnectionException, as this is usually caused by orphaned models
  #
  # TODO: do we really want to set numRecords to 0? Last updated value might
  #       be useful for debugging
  if type(arg_5) is not InvalidConnectionException:
    arg_2.modelUpdateResults(arg_1,  results=None, numRecords=0)

  # TODO: Make sure this wasn't the best model in job. If so, set the best
  # appropriately

  # If this was an exception that should mark the job as failed, do that
  # now.
  if type(arg_5) == JobFailException:
    arg_9 = arg_2.jobGetFields(arg_0,
        ['workerCompletionReason'])[0]
    if arg_9 == ClientJobsDAO.CMPL_REASON_SUCCESS:
      arg_2.jobSetFields(arg_0, fields=dict(
          cancel=True,
          workerCompletionReason = ClientJobsDAO.CMPL_REASON_ERROR,
          workerCompletionMsg = ": ".join(str(arg_10) for arg_10 in arg_5.args)),
          useConnectionID=False,
          ignoreUnchanged=True)

  return (arg_7, arg_8)

Perform standard handling of an exception that occurs while running a model .


(self, datacenter_id, server_id, depth=1)

def Func(arg_0, arg_1, arg_2, arg_3=1):
        """
        Retrieves a server by its ID.

        :param      datacenter_id: The unique ID of the data center.
        :type       datacenter_id: ``str``

        :param      server_id: The unique ID of the server.
        :type       server_id: ``str``

        :param      depth: The depth of the response data.
        :type       depth: ``int``

        """
        arg_4 = arg_0._perform_request(
            '/datacenters/%s/servers/%s?depth=%s' % (
                arg_1,
                arg_2,
                str(arg_3)))

        return arg_4


def Func ( ) : from keras . models import Sequential from keras . layers import Dense , Dropout , Activation , Flatten from keras . layers import Convolution2D , MaxPooling2D arg_0 = Sequential ( ) arg_0 . add ( Convolution2D ( 32 , 3 , 3 , border_mode = 'valid' , input_shape = input_shape ) ) arg_0 . add ( Activation ( 'relu' ) ) arg_0 . add ( Convolution2D ( 32 , 3 , 3 ) ) arg_0 . add ( Activation ( 'relu' ) ) arg_0 . add ( MaxPooling2D ( pool_size = ( 2 , 2 ) ) ) arg_0 . add ( Dropout ( 0.25 ) ) arg_0 . add ( Flatten ( ) ) arg_0 . add ( Dense ( 128 ) ) arg_0 . add ( Activation ( 'relu' ) ) arg_0 . add ( Dropout ( 0.5 ) ) arg_0 . add ( Dense ( 10 ) ) arg_0 . add ( Activation ( 'softmax' ) ) return arg_0

def Func():
    """
    Define a convnet model in Keras 1.2.2
    """
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Activation, Flatten
    from keras.layers import Convolution2D, MaxPooling2D

    arg_0 = Sequential()
    arg_0.add(Convolution2D(32, 3, 3, border_mode='valid',
                                  input_shape=input_shape))
    arg_0.add(Activation('relu'))
    arg_0.add(Convolution2D(32, 3, 3))
    arg_0.add(Activation('relu'))
    arg_0.add(MaxPooling2D(pool_size=(2, 2)))
    arg_0.add(Dropout(0.25))
    arg_0.add(Flatten())
    arg_0.add(Dense(128))
    arg_0.add(Activation('relu'))
    arg_0.add(Dropout(0.5))
    arg_0.add(Dense(10))
    arg_0.add(Activation('softmax'))
    return arg_0

Define a convnet model in Keras 1 . 2 . 2


def
Func
(
*
arg_0
)
:
arg_1
=
float
(
time
.
time
(
)
*
1000
)
arg_2
=
float
(
random
.
random
(
)
*
10000000000000
)
arg_3
=
random
.
random
(
)
*
10000000000000
arg_4
=
str
(
arg_1
)
+
' '
+
str
(
arg_2
)
+
' '
+
str
(
arg_3
)
+
' '
+
str
(
arg_0
)
arg_4
=
hashlib
.
md5
(
arg_4
.
encode
(
)
)
.
hexdigest
(
)
[
:
10
]
return
arg_4

def Func(*arg_0):
    """
    Generates a universally unique ID.
    Any arguments only create more randomness.
    """
    arg_1 = float(time.time() * 1000)
    arg_2 = float(random.random()*10000000000000)

    arg_3 = random.random() * 10000000000000
    arg_4 = str(arg_1) + ' ' + str(arg_2) + ' ' + str(arg_3) + ' ' + str(arg_0)
    arg_4 = hashlib.md5(arg_4.encode()).hexdigest()[:10]

    return arg_4

Generates a universally unique ID . Any arguments only create more randomness .


def Func ( arg_0 , arg_1 , arg_2 = '37' ) : arg_3 = { 'hgnc_symbol' : arg_1 , 'build' : arg_2 } arg_4 = { 'Func' : 1 , '_id' : 0 } arg_5 = arg_0 . hgnc_collection . find ( arg_3 , arg_4 ) if arg_5 . count ( ) > 0 : return arg_5 [ 0 ] [ 'Func' ] else : return None

def Func(arg_0, arg_1, arg_2='37'):
        """Query the genes with a hgnc symbol and return the hgnc id

        Args:
            hgnc_symbol(str)
            build(str)

        Returns:
            Func(int)
        """
        #LOG.debug("Fetching gene %s", hgnc_symbol)
        arg_3 = {'hgnc_symbol':arg_1, 'build':arg_2}
        arg_4 = {'Func':1, '_id':0}
        arg_5 = arg_0.hgnc_collection.find(arg_3, arg_4)

        if arg_5.count() > 0:
            return arg_5[0]['Func']
        else:
            return None

Query the genes with a hgnc symbol and return the hgnc id

        Args:
            hgnc_symbol(str)
            build(str)

        Returns:
            hgnc_id(int)


def Func ( arg_0 , arg_1 ) : if ( arg_1 . fail is None and isinstance ( arg_1 . test , astroid . Tuple ) and len ( arg_1 . test . elts ) == 2 ) : arg_0 . add_message ( "assert-on-tuple" , arg_1 = arg_1 )

def Func(arg_0, arg_1):
        """check the use of an assert statement on a tuple."""
        if (
            arg_1.fail is None
            and isinstance(arg_1.test, astroid.Tuple)
            and len(arg_1.test.elts) == 2
        ):
            arg_0.add_message("assert-on-tuple", arg_1=arg_1)

check the use of an assert statement on a tuple .


def Func ( arg_0 , arg_1 = '' , arg_2 = '' ) : if arg_1 : return FuncIEXCloud ( arg_0 , arg_1 , arg_2 ) return FuncOrig ( arg_0 )

def Func(arg_0, arg_1='', arg_2=''):
    '''for backwards compat, accepting token and version but ignoring'''
    if arg_1:
        return FuncIEXCloud(arg_0, arg_1, arg_2)
    return FuncOrig(arg_0)

for backwards compat accepting token and version but ignoring


(self, block_hash, verbose=True, **kwargs)

return self._call(
            JSONRPCMethods.GET_BLOCK.value, params=[block_hash, int(verbose), ], **kwargs)

def Func ( arg_0 , arg_1 , arg_2 = True , ** arg_3 ) : return arg_0 . _call ( JSONRPCMethods . GET_BLOCK . value , params = [ arg_1 , int ( arg_2 ) , ] , ** arg_3 )

def Func(arg_0, arg_1, arg_2=True, **arg_3):
        """ Returns the block information associated with a specific hash value or block index.

        :param block_hash: a block hash value or a block index (block height)
        :param verbose:
            a boolean indicating whether the detailed block information should be returned in JSON
            format (otherwise the block information is returned as an hexadecimal string by the
            JSON-RPC endpoint)
        :type block_hash: str or int
        :type verbose: bool
        :return:
            dictionary containing the block information (or an hexadecimal string if verbose is set
            to False)
        :rtype: dict or str

        """
        return arg_0._call(
            JSONRPCMethods.GET_BLOCK.value, params=[arg_1, int(arg_2), ], **arg_3)

Returns the block information associated with a specific hash value or block index .


def Func ( arg_0 , arg_1 = ( - 10.0 , 10.0 ) , arg_2 = ( - 10.0 , 10.0 ) , arg_3 = ( - 10.0 , 10.0 ) , arg_4 = None ) -> VAO : random . seed ( arg_4 ) def gen ( ) : for arg_5 in range ( arg_0 ) : yield random . uniform ( * arg_1 ) yield random . uniform ( * arg_2 ) yield random . uniform ( * arg_3 ) arg_6 = numpy . fromiter ( gen ( ) , arg_0 = arg_0 * 3 , dtype = numpy . float32 ) arg_7 = VAO ( "geometry:Func" , mode = moderngl . POINTS ) arg_7 . buffer ( arg_6 , '3f' , [ 'in_position' ] ) return arg_7

def Func(arg_0, arg_1=(-10.0, 10.0), arg_2=(-10.0, 10.0), arg_3=(-10.0, 10.0), arg_4=None) -> VAO:
    """
    Generates random positions inside a confied box.

    Args:
        count (int): Number of points to generate

    Keyword Args:
        range_x (tuple): min-max range for x axis: Example (-10.0. 10.0)
        range_y (tuple): min-max range for y axis: Example (-10.0. 10.0)
        range_z (tuple): min-max range for z axis: Example (-10.0. 10.0)
        seed (int): The random seed

    Returns:
        A :py:class:`demosys.opengl.vao.VAO` instance
    """
    random.seed(arg_4)

    def gen():
        for arg_5 in range(arg_0):
            yield random.uniform(*arg_1)
            yield random.uniform(*arg_2)
            yield random.uniform(*arg_3)

    arg_6 = numpy.fromiter(gen(), arg_0=arg_0 * 3, dtype=numpy.float32)

    arg_7 = VAO("geometry:Func", mode=moderngl.POINTS)
    arg_7.buffer(arg_6, '3f', ['in_position'])

    return arg_7

Generates random positions inside a confied box .


def Func ( arg_0 = None ) : def handler ( ) : if arg_0 : print ( arg_0 , file = sys . stderr ) sys . exit ( 1 ) signal . signal ( signal . SIGINT , handler )

def Func(arg_0=None):
    """add a handler for SIGINT that optionally prints a given message.
    For stopping scripts without having to see the stacktrace.
    """

    def handler():
        if arg_0:
            print(arg_0, file=sys.stderr)
        sys.exit(1)

    signal.signal(signal.SIGINT, handler)

add a handler for SIGINT that optionally prints a given message . For stopping scripts without having to see the stacktrace .


def Func(arg_0):
        """
        Deletes record, and removes it from database.
        """
        # workflow
        # --------
        # (methods belonging to create/update/Func framework:
        #     epm._dev_populate_from_json_data, table.batch_add, record.update, queryset.Func, record.Func)
        # 1. unregister: links, hooks and external files
        # 3. remove from table without unregistering

        # unregister links
        arg_0._unregister_links()

        # unregister hooks
        arg_0._unregister_hooks()

        # unregister external files
        arg_0._unregister_external_files()

        # tell table to remove without unregistering
        arg_0.get_table()._dev_remove_record_without_unregistering(arg_0)

        # make stale
        arg_0._table = None
        arg_0._data = None

Deletes record and removes it from database .


def Func ( arg_0 , arg_1 = 10 ) : arg_0 . file . seek ( 0 , SEEK_END ) for arg_2 in range ( arg_1 ) : if arg_0 . seek_previous_line ( ) == - 1 : break arg_3 = arg_0 . file . read ( ) for arg_4 in arg_0 . LINE_TERMINATORS : if arg_3 . endswith ( arg_4 ) : arg_3 = arg_3 [ : - len ( arg_4 ) ] break if arg_3 : return arg_0 . splitlines ( arg_3 ) else : return [ ]

def Func(arg_0, arg_1=10):
        """
        Return the last lines of the file.
        """
        arg_0.file.seek(0, SEEK_END)

        for arg_2 in range(arg_1):
            if arg_0.seek_previous_line() == -1:
                break

        arg_3 = arg_0.file.read()

        for arg_4 in arg_0.LINE_TERMINATORS:
            if arg_3.endswith(arg_4):
                # Only terminators _between_ lines should be preserved.
                # Otherwise terminator of the last line will be treated as separtaing line and empty line.
                arg_3 = arg_3[:-len(arg_4)]
                break

        if arg_3:
            return arg_0.splitlines(arg_3)
        else:
            return []


def Func ( arg_0 , arg_1 ) : arg_0 . model = arg_0 . func ( arg_1 , * arg_0 . func_args , ** arg_0 . func_kwargs ) arg_3 = arg_0 . calc_residuals ( ) return np . dot ( arg_3 . flat , arg_3 . flat )

def Func(arg_0, arg_1):
        """Takes an array param_vals, updates function, returns the new error"""
        arg_0.model = arg_0.func(arg_1, *arg_0.func_args, **arg_0.func_kwargs)
        arg_3 = arg_0.calc_residuals()
        return np.dot(arg_3.flat, arg_3.flat)

Takes an array param_vals updates function returns the new error


return self._perform_put(self._get_image_path(image_name),
            _XmlSerializer.update_os_image_to_xml(os_image), as_async=True
        )

def Func(arg_0, arg_1, arg_2):
        '''
        Updates metadata elements from a given OS image reference.

        image_name:
            The name of the image to update.
        os_image:
            An instance of OSImage class.
        os_image.label: Optional. Specifies an identifier for the image.
        os_image.description: Optional. Specifies the description of the image.
        os_image.language: Optional. Specifies the language of the image.
        os_image.image_family:
            Optional. Specifies a value that can be used to group VM Images.
        os_image.recommended_vm_size:
            Optional. Specifies the size to use for the Virtual Machine that
            is created from the VM Image.
        os_image.eula:
            Optional. Specifies the End User License Agreement that is
            associated with the image. The value for this element is a string,
            but it is recommended that the value be a URL that points to a EULA.
        os_image.icon_uri:
            Optional. Specifies the URI to the icon that is displayed for the
            image in the Management Portal.
        os_image.small_icon_uri:
            Optional. Specifies the URI to the small icon that is displayed for
            the image in the Management Portal.
        os_image.privacy_uri:
            Optional. Specifies the URI that points to a document that contains
            the privacy policy related to the image.
        os_image.published_date:
            Optional. Specifies the date when the image was added to the image
            repository.
        os.image.media_link:
            Required: Specifies the location of the blob in Windows Azure
            blob store where the media for the image is located. The blob
            location must belong to a storage account in the subscription
            specified by the <subscription-id> value in the operation call.
            Example:
            http://example.blob.core.windows.net/disks/mydisk.vhd
        os_image.name:
            Specifies a name for the OS image that Windows Azure uses to
            identify the image when creating one or more VM Roles.
        os_image.os:
            The operating system type of the OS image. Possible values are:
            Linux, Windows
        '''
        _validate_not_none('image_name', arg_1)
        _validate_not_none('os_image', arg_2)
        return arg_0._perform_put(arg_0._get_image_path(arg_1),
            _XmlSerializer.update_os_image_to_xml(arg_2), as_async=True
        )

Updates metadata elements from a given OS image reference .


def Func ( arg_0 ) : arg_1 = deepcopy ( arg_0 . metadata ) if 'links' not in arg_1 : arg_1 [ 'links' ] = [ ] arg_1 [ 'links' ] . append ( { 'rel' : 'property' , 'href' : arg_0 . href_prefix + arg_0 . href , } ) return arg_1

def Func(arg_0):
        """
        Get the property description.

        Returns a dictionary describing the property.
        """
        arg_1 = deepcopy(arg_0.metadata)

        if 'links' not in arg_1:
            arg_1['links'] = []

        arg_1['links'].append(
            {
                'rel': 'property',
                'href': arg_0.href_prefix + arg_0.href,
            }
        )
        return arg_1


def
Func
(
arg_0
,
arg_1
)
:
plt
.
figure
(
figsize
=
(
14
,
6
)
)
arg_2
=
plt
.
gca
(
)
arg_3
=
plt
.
gcf
(
)
plt
.
subplot
(
122
)
arg_4
=
np
.
zeros_like
(
arg_0
.
postcard
)
arg_0
.
roll_best
=
np
.
zeros
(
(
4
,
2
)
)
for
arg_6
in
range
(
4
)
:
arg_7
=
np
.
where
(
arg_0
.
qs
==
arg_6
)
[
0
]
arg_8
=
np
.
where
(
arg_0
.
times
[
arg_7
]
>
54947
)
arg_0
.
roll_best
[
arg_6
]
=
arg_0
.
do_rolltest
(
arg_7
,
arg_8
)
arg_0
.
do_photometry
(
)
for
arg_6
in
range
(
4
)
:
arg_7
=
np
.
where
(
arg_0
.
qs
==
arg_6
)
[
0
]
plt
.
errorbar
(
arg_0
.
times
[
arg_7
]
,
arg_0
.
obs_flux
[
arg_7
]
,
yerr
=
arg_0
.
flux_uncert
[
arg_6
]
,
fmt
=
fmt
[
arg_6
]
)
plt
.
xlabel
(
'Time'
,
fontsize
=
20
)
plt
.
ylabel
(
'Relative Flux'
,
fontsize
=
20
)
plt
.
subplot
(
121
)
arg_9
=
plt
.
imshow
(
arg_1
,
interpolation
=
'nearest'
,
cmap
=
'gray'
,
vmin
=
98000
*
52
,
vmax
=
104000
*
52
)
arg_10
=
arg_3
.
canvas
.
mpl_connect
(
'button_press_event'
,
arg_0
.
onclick
)
plt
.
show
(
block
=
True
)

def Func(arg_0, arg_1):
        """
        Creates the figure shown in ``adjust_aperture`` for visualization purposes. Called by other functions
        and generally not called by the user directly.

        Args:
            img: The data frame to be passed through to be plotted. A cutout of the ``integrated_postcard``

        """
        plt.figure(figsize=(14,6))
        arg_2 = plt.gca()
        arg_3 = plt.gcf()
        plt.subplot(122)

        arg_4 = np.zeros_like(arg_0.postcard)
        arg_0.roll_best = np.zeros((4,2))

        for arg_6 in range(4):
            arg_7 = np.where(arg_0.qs == arg_6)[0]
            arg_8 = np.where(arg_0.times[arg_7] > 54947)

            arg_0.roll_best[arg_6] = arg_0.do_rolltest(arg_7, arg_8)

        arg_0.do_photometry()
        for arg_6 in range(4):
            arg_7 = np.where(arg_0.qs == arg_6)[0]
            plt.errorbar(arg_0.times[arg_7], arg_0.obs_flux[arg_7], yerr=arg_0.flux_uncert[arg_6], fmt=fmt[arg_6])

        plt.xlabel('Time', fontsize=20)
        plt.ylabel('Relative Flux', fontsize=20)

        plt.subplot(121)
        arg_9 = plt.imshow(arg_1, interpolation='nearest', cmap='gray', vmin=98000*52, vmax=104000*52)
        arg_10 = arg_3.canvas.mpl_connect('button_press_event', arg_0.onclick)

        plt.show(block=True)

Creates the figure shown in adjust_aperture for visualization purposes . Called by other functions and generally not called by the user directly .


return linop.matmul(mean) + dist.mean()[..., tf.newaxis]

def Func ( arg_0 , arg_1 , arg_2 ) : return arg_1 . matmul ( arg_0 ) + arg_2 . mean ( ) [ ... , tf . newaxis ]

def Func(arg_0, arg_1, arg_2):
  """Propagate a mean through linear Gaussian transformation."""
  return arg_1.matmul(arg_0) + arg_2.mean()[..., tf.newaxis]

Propagate a mean through linear Gaussian transformation .


def Func ( arg_0 ) : try : arg_0 = str ( arg_0 ) if len ( arg_0 ) != 32 : return False arg_1 = int ( arg_0 , 2 ) except ( TypeError , ValueError ) : return False if arg_1 > 4294967295 or arg_1 < 0 : return False return True

def Func(arg_0):
    """Return true if the IP address is in binary notation."""
    try:
        arg_0 = str(arg_0)
        if len(arg_0) != 32:
            return False
        arg_1 = int(arg_0, 2)
    except (TypeError, ValueError):
        return False
    if arg_1 > 4294967295 or arg_1 < 0:
        return False
    return True

Return true if the IP address is in binary notation .


def Func ( arg_0 , arg_1 , arg_2 ) : try : arg_3 = arg_0 . objects ( ) . delete ( bucket = arg_1 , object = arg_2 ) . execute ( ) except HttpError as e : pass arg_3 = e return arg_3

def Func(arg_0, arg_1, arg_2):
    '''delete object will delete a file from a bucket

       Parameters
       ==========
       storage_service: the service obtained with get_storage_service
       bucket_name: the name of the bucket
       object_name: the "name" parameter of the object.

    '''
    try:
        arg_3 = arg_0.objects().delete(bucket=arg_1,
                                             object=arg_2).execute()
    except HttpError as e:
        pass
        arg_3 = e
    return arg_3


def Func ( arg_0 ) : arg_0 . parent . addLayout ( arg_0 . _logSelectLayout ) arg_0 . menuCount += 1 arg_0 . _connectSlots ( )

def Func(arg_0):
        '''Display menus and connect even signals.'''
        arg_0.parent.addLayout(arg_0._logSelectLayout)
        arg_0.menuCount += 1
        arg_0._connectSlots()

Display menus and connect even signals .


return [nt_connection(*conn) for conn in ret]

def Func(arg_0, arg_1='inet'):
        """Return etwork connections opened by a process as a list of
        namedtuples.
        """
        if arg_1 not in conn_tmap:
            raise ValueError("invalid %r kind argument; choose between %s"
                             % (arg_1, ', '.join([repr(arg_2) for arg_2 in conn_tmap])))
        arg_3, arg_4 = conn_tmap[arg_1]
        arg_5 = _psutil_osx.get_process_connections(arg_0.pid, arg_3, arg_4)
        return [nt_connection(*arg_6) for arg_6 in arg_5]

Return etwork connections opened by a process as a list of namedtuples .


def Func ( arg_0 ) : def _normalize ( arg_1 , arg_2 ) : arg_3 = [ arg_5 . get_values ( arg_2 ) for arg_5 in arg_1 ] arg_4 = any ( [ arg_3 [ i ] != arg_3 [ i + 1 ] for i in range ( len ( arg_3 ) - 1 ) ] ) if arg_4 : for arg_5 in arg_1 : arg_5 . set_values ( arg_2 , arg_3 [ 0 ] ) for arg_2 , arg_1 in iteritems ( arg_0 . lmap ) : if isinstance ( arg_1 , list ) and len ( arg_1 ) > 1 : _normalize ( arg_1 , arg_2 )

def Func(arg_0):
        """ Ensure that shared parameters are the same value everywhere """
        def _normalize(arg_1, arg_2):
            arg_3 = [arg_5.get_values(arg_2) for arg_5 in arg_1]
            arg_4 = any([arg_3[i] != arg_3[i+1] for i in range(len(arg_3)-1)])

            if arg_4:
                for arg_5 in arg_1:
                    arg_5.set_values(arg_2, arg_3[0])

        for arg_2, arg_1 in iteritems(arg_0.lmap):
            if isinstance(arg_1, list) and len(arg_1) > 1:
                _normalize(arg_1, arg_2)


def Func(arg_0, arg_1='en', arg_2=None):
    """Converts a Open511 JSON document to XML.

    lang: the appropriate language code

    Takes a dict deserialized from JSON, returns an lxml Element.

    Accepts only the full root-level JSON object from an Open511 response."""
    if 'meta' not in arg_0:
        raise Exception("This function requires a conforming Open511 JSON document with a 'meta' section.")
    arg_0 = dict(arg_0)
    arg_3 = arg_0.pop('meta')
    arg_4 = get_base_open511_element(arg_1=arg_1, version=arg_3.pop('version'))

    arg_5 = arg_0.pop('pagination', None)

    json_struct_to_xml(arg_0, arg_4, arg_2=arg_2)

    if arg_5:
        arg_4.append(json_struct_to_xml(arg_5, 'pagination', arg_2=arg_2))

    json_struct_to_xml(arg_3, arg_4)

    return arg_4

Converts a Open511 JSON document to XML .


def Func ( arg_0 ) : arg_1 = - derivative ( phase ( arg_0 , unwrap = True ) / ( 2 * math . pi ) ) arg_1 . dep_name = "Func({0})" . format ( arg_0 . dep_name ) arg_1 . dep_units = "sec" return arg_1

def Func(arg_0):
    r"""
    Return the group delay of a waveform.

    :param wave: Waveform
    :type  wave: :py:class:`peng.eng.Waveform`

    :rtype: :py:class:`peng.eng.Waveform`

    .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
    .. Auto-generated exceptions documentation for
    .. peng.wave_functions.Func

    :raises: RuntimeError (Argument \`wave\` is not valid)

    .. [[[end]]]
    """
    arg_1 = -derivative(phase(arg_0, unwrap=True) / (2 * math.pi))
    arg_1.dep_name = "Func({0})".format(arg_0.dep_name)
    arg_1.dep_units = "sec"
    return arg_1

r"""
    Return the group delay of a waveform.

    :param wave: Waveform
    :type  wave: :py:class:`peng.eng.Waveform`

    :rtype: :py:class:`peng.eng.Waveform`

    .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
    .. Auto-generated exceptions documentation for
    .. peng.wave_functions.group_delay

    :raises: RuntimeError (Argument \`wave\` is not valid)

    .. [[[end]]]

r Return the group delay of a waveform .


def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
get_line_count
(
arg_0
)
arg_3
=
open
(
arg_0
,
'r+'
)
arg_4
=
open
(
arg_1
,
'w'
)
for
arg_5
in
range
(
arg_2
)
:
arg_6
=
arg_3
.
readline
(
)
.
strip
(
)
arg_6
=
re
.
sub
(
'\{'
,
'{\n'
,
arg_6
)
arg_6
=
re
.
sub
(
'; '
,
';'
,
arg_6
)
arg_6
=
re
.
sub
(
';'
,
';\n'
,
arg_6
)
arg_6
=
re
.
sub
(
'} /*'
,
'}/*'
,
arg_6
)
arg_6
=
re
.
sub
(
'\}'
,
'}\n'
,
arg_6
)
arg_6
=
re
.
sub
(
'\*/'
,
'*/\n'
,
arg_6
)
arg_4
.
write
(
arg_6
)
arg_4
.
close
(
)
arg_3
.
close
(
)
indent_css
(
arg_1
,
arg_1
)
add_whitespace_before
(
"{"
,
arg_1
,
arg_1
)

def Func(arg_0, arg_1):
    """Reformats poorly written css. This function does not validate or fix errors in the code.
    It only gives code the proper indentation.

    Args:
        input_file: string, path to the input file.

        output_file: string, path to where the reformatted css should be saved. If the target file
        doesn't exist, a new file is created.

    Returns:
        None.
    """
    # Number of lines in the file.
    arg_2 = get_line_count(arg_0)

    # Open source and target files.
    arg_3 = open(arg_0, 'r+')
    arg_4 = open(arg_1, 'w')

    # Loop over every line in the file.
    for arg_5 in range(arg_2):
        # Eliminate whitespace at the beginning and end of lines.
        arg_6 = arg_3.readline().strip()
        # New lines after {
        arg_6 = re.sub('\{', '{\n', arg_6)
        # New lines after ;
        arg_6 = re.sub('; ', ';', arg_6)
        arg_6 = re.sub(';', ';\n', arg_6)
        # Eliminate whitespace before comments
        arg_6 = re.sub('} /*', '}/*', arg_6)
        # New lines after }
        arg_6 = re.sub('\}', '}\n', arg_6)
        # New lines at the end of comments
        arg_6 = re.sub('\*/', '*/\n', arg_6)
        # Write to the output file.
        arg_4.write(arg_6)

    # Close the files.
    arg_4.close()
    arg_3.close()

    # Indent the css.
    indent_css(arg_1, arg_1)

    # Make sure there's a space before every {
    add_whitespace_before("{", arg_1, arg_1)

Reformats poorly written css . This function does not validate or fix errors in the code . It only gives code the proper indentation .


return BoltArraySpark(newrdd, shape=newshape, ordered=False).__finalize__(self._barray)

def Func ( arg_0 , * arg_1 ) : arg_2 = argpack ( arg_1 ) arg_3 = range ( arg_0 . ndim ) isFuncable ( arg_2 , arg_3 ) if arg_2 == arg_3 : return arg_0 . _barray def f ( arg_4 ) : return tuple ( arg_4 [ arg_5 ] for arg_5 in arg_2 ) arg_6 = arg_0 . _barray . _rdd . map ( lambda kv : ( f ( kv [ 0 ] ) , kv [ 1 ] ) ) arg_7 = tuple ( arg_0 . shape [ arg_5 ] for arg_5 in arg_2 ) + arg_0 . _barray . values . shape return BoltArraySpark ( arg_6 , shape = arg_7 , ordered = False ) . __finalize__ ( arg_0 . _barray )

def Func(arg_0, *arg_1):
        """
        Transpose just the keys of a BoltArraySpark, returning a
        new BoltArraySpark.

        Parameters
        ----------
        axes : tuple
             New proposed axes.
        """
        arg_2 = argpack(arg_1)
        arg_3 = range(arg_0.ndim)
        isFuncable(arg_2, arg_3)

        if arg_2 == arg_3:
            return arg_0._barray

        def f(arg_4):
            return tuple(arg_4[arg_5] for arg_5 in arg_2)

        arg_6 = arg_0._barray._rdd.map(lambda kv: (f(kv[0]), kv[1]))
        arg_7 = tuple(arg_0.shape[arg_5] for arg_5 in arg_2) + arg_0._barray.values.shape

        return BoltArraySpark(arg_6, shape=arg_7, ordered=False).__finalize__(arg_0._barray)

Transpose just the keys of a BoltArraySpark returning a new BoltArraySpark .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . rpc . get_account ( arg_1 ) for arg_3 in arg_2 [ "active" ] [ "key_auths" ] : try : return arg_0 . getPrivateKeyForPublicKey ( arg_3 [ 0 ] ) except Exception : pass return False

def Func(arg_0, arg_1):
        """ Obtain owner Active Key for an account from the wallet database
        """
        arg_2 = arg_0.rpc.get_account(arg_1)
        for arg_3 in arg_2["active"]["key_auths"]:
            try:
                return arg_0.getPrivateKeyForPublicKey(arg_3[0])
            except Exception:
                pass
        return False


def Func ( arg_0 , arg_1 ) : arg_2 = ProcessStats ( arg_1 ) arg_3 = [ ] for arg_4 in arg_2 . get_cpu_memory_stat ( ) : try : arg_3 . append ( round ( arg_4 . get_memory_percent ( ) , 2 ) ) except psutil . AccessDenied : pass return arg_3

def Func(arg_0, arg_1):
        """
        get memory stat

        @param process_name: Process name, ex: firefox-bin.
        @type process_name: string

        @return: memory stat list on success, else empty list
                If same process name, running multiple instance,
                get the stat of all the process memory usage
        @rtype: list
        """
        # Create an instance of process stat
        arg_2 = ProcessStats(arg_1)
        arg_3 = []
        for arg_4 in arg_2.get_cpu_memory_stat():
            # Memory percent returned with 17 decimal values
            # ex: 0.16908645629882812, round it to 2 decimal values
            # as 0.03
            try:
                arg_3.append(round(arg_4.get_memory_percent(), 2))
            except psutil.AccessDenied:
                pass
        return arg_3


def Func ( arg_0 , arg_1 = None , ** arg_2 ) : arg_0 . attrs = arg_0 . widget . Func ( arg_1 = None , ** arg_2 ) return arg_0 . attrs

def Func(arg_0, arg_1=None, **arg_2):
        "Helper function for building an attribute dictionary."
        arg_0.attrs = arg_0.widget.Func(arg_1=None, **arg_2)
        return arg_0.attrs

Helper function for building an attribute dictionary .


(self,
                    args: List[str],
                    max_num_processes: int=None,
                    max_stack_size: int=None,
                    max_virtual_memory: int=None,
                    as_root: bool=False,
                    stdin: FileIO=None,
                    timeout: int=None,
                    check: bool=False,
                    truncate_stdout: int=None,
                    truncate_stderr: int=None)

def
Func
(
arg_0
,
arg_1
:
arg_2
[
arg_3
]
,
arg_4
:
arg_5
=
,
arg_6
:
arg_5
=
,
arg_7
:
arg_5
=
,
arg_8
:
arg_9
=
False
,
arg_10
:
arg_11
=
,
arg_12
:
arg_5
=
,
arg_13
:
arg_9
=
False
,
arg_14
:
arg_5
=
,
arg_15
:
arg_5
=
)
->
'CompletedCommand'
:
arg_16
=
[
'docker'
,
'exec'
,
'-i'
,
arg_0
.
name
,
'cmd_runner.py'
]
if
arg_10
is
:
arg_16
.
append
(
'--stdin_devnull'
)
if
arg_4
is
not
:
arg_16
+=
[
'--max_num_processes'
,
arg_3
(
arg_4
)
]
if
arg_6
is
not
:
arg_16
+=
[
'--max_stack_size'
,
arg_3
(
arg_6
)
]
if
arg_7
is
not
:
arg_16
+=
[
'--max_virtual_memory'
,
arg_3
(
arg_7
)
]
if
arg_12
is
not
:
arg_16
+=
[
'--timeout'
,
arg_3
(
arg_12
)
]
if
arg_14
is
not
:
arg_16
+=
[
'--truncate_stdout'
,
arg_3
(
arg_14
)
]
if
arg_15
is
not
:
arg_16
+=
[
'--truncate_stderr'
,
arg_3
(
arg_15
)
]
if
not
arg_8
:
arg_16
+=
[
'--linux_user_id'
,
arg_3
(
arg_0
.
_linux_uid
)
]
arg_16
+=
arg_1
if
arg_0
.
debug
:
print
(
'running: {}'
.
format
(
arg_16
)
,
flush
=
True
)
with
tempfile
.
TemporaryFile
(
)
as
f
:
try
:
subprocess
.
run
(
arg_16
,
arg_10
=
arg_10
,
arg_20
=
f
,
arg_22
=
subprocess
.
PIPE
,
arg_13
=
True
)
f
.
seek
(
0
)
arg_17
=
arg_5
(
f
.
readline
(
)
.
decode
(
)
.
rstrip
(
)
)
arg_18
=
json
.
loads
(
f
.
read
(
arg_17
)
.
decode
(
)
)
arg_19
=
arg_5
(
f
.
readline
(
)
.
decode
(
)
.
rstrip
(
)
)
arg_20
=
tempfile
.
NamedTemporaryFile
(
)
arg_20
.
write
(
f
.
read
(
arg_19
)
)
arg_20
.
seek
(
0
)
arg_21
=
arg_5
(
f
.
readline
(
)
.
decode
(
)
.
rstrip
(
)
)
arg_22
=
tempfile
.
NamedTemporaryFile
(
)
arg_22
.
write
(
f
.
read
(
arg_21
)
)
arg_22
.
seek
(
0
)
arg_23
=
CompletedCommand
(
return_code
=
arg_18
[
'return_code'
]
,
timed_out
=
arg_18
[
'timed_out'
]
,
arg_20
=
arg_20
,
arg_22
=
arg_22
,
stdout_truncated
=
arg_18
[
'stdout_truncated'
]
,
stderr_truncated
=
arg_18
[
'stderr_truncated'
]
)
if
(
arg_23
.
return_code
!=
0
or
arg_18
[
'timed_out'
]
)
and
arg_13
:
raise
subprocess
.
CalledProcessError
(
arg_23
.
return_code
,
arg_16
,
output
=
arg_23
.
stdout
,
arg_22
=
arg_23
.
stderr
)
return
arg_23
except
subprocess
.
CalledProcessError
as
e
:
f
.
seek
(
0
)
print
(
f
.
read
(
)
)
print
(
e
.
stderr
)
raise

def Func(arg_0,
                    arg_1: arg_2[arg_3],
                    arg_4: arg_5=None,
                    arg_6: arg_5=None,
                    arg_7: arg_5=None,
                    arg_8: arg_9=False,
                    arg_10: arg_11=None,
                    arg_12: arg_5=None,
                    arg_13: arg_9=False,
                    arg_14: arg_5=None,
                    arg_15: arg_5=None) -> 'CompletedCommand':
        """
        Runs a command inside the sandbox and returns the results.

        :param args: A list of strings that specify which command should
            be run inside the sandbox.

        :param max_num_processes: The maximum number of processes the
            command is allowed to spawn.

        :param max_stack_size: The maximum stack size, in bytes, allowed
            for the command.

        :param max_virtual_memory: The maximum amount of memory, in
            bytes, allowed for the command.

        :param as_root: Whether to run the command as a root user.

        :param stdin: A file object to be redirected as input to the
            command's stdin. If this is None, /dev/null is sent to the
            command's stdin.

        :param timeout: The time limit for the command.

        :param check: Causes CalledProcessError to be raised if the
            command exits nonzero or times out.

        :param truncate_stdout: When not None, stdout from the command
            will be truncated after this many bytes.

        :param truncate_stderr: When not None, stderr from the command
            will be truncated after this many bytes.
        """
        arg_16 = ['docker', 'exec', '-i', arg_0.name, 'cmd_runner.py']

        if arg_10 is None:
            arg_16.append('--stdin_devnull')

        if arg_4 is not None:
            arg_16 += ['--max_num_processes', arg_3(arg_4)]

        if arg_6 is not None:
            arg_16 += ['--max_stack_size', arg_3(arg_6)]

        if arg_7 is not None:
            arg_16 += ['--max_virtual_memory', arg_3(arg_7)]

        if arg_12 is not None:
            arg_16 += ['--timeout', arg_3(arg_12)]

        if arg_14 is not None:
            arg_16 += ['--truncate_stdout', arg_3(arg_14)]

        if arg_15 is not None:
            arg_16 += ['--truncate_stderr', arg_3(arg_15)]

        if not arg_8:
            arg_16 += ['--linux_user_id', arg_3(arg_0._linux_uid)]

        arg_16 += arg_1

        if arg_0.debug:
            print('running: {}'.format(arg_16), flush=True)

        with tempfile.TemporaryFile() as f:
            try:
                subprocess.run(arg_16, arg_10=arg_10, arg_20=f, arg_22=subprocess.PIPE, arg_13=True)
                f.seek(0)
                arg_17 = arg_5(f.readline().decode().rstrip())
                arg_18 = json.loads(f.read(arg_17).decode())

                arg_19 = arg_5(f.readline().decode().rstrip())
                arg_20 = tempfile.NamedTemporaryFile()
                arg_20.write(f.read(arg_19))
                arg_20.seek(0)

                arg_21 = arg_5(f.readline().decode().rstrip())
                arg_22 = tempfile.NamedTemporaryFile()
                arg_22.write(f.read(arg_21))
                arg_22.seek(0)

                arg_23 = CompletedCommand(return_code=arg_18['return_code'],
                                          timed_out=arg_18['timed_out'],
                                          arg_20=arg_20,
                                          arg_22=arg_22,
                                          stdout_truncated=arg_18['stdout_truncated'],
                                          stderr_truncated=arg_18['stderr_truncated'])

                if (arg_23.return_code != 0 or arg_18['timed_out']) and arg_13:
                    raise subprocess.CalledProcessError(
                        arg_23.return_code, arg_16,
                        output=arg_23.stdout, arg_22=arg_23.stderr)

                return arg_23
            except subprocess.CalledProcessError as e:
                f.seek(0)
                print(f.read())
                print(e.stderr)
                raise

Runs a command inside the sandbox and returns the results .


(cls, shape, pixel_scale, sub_grid_size=2)

return GridStack(regular_grid, sub_grid, blurring_grid)

def Func(arg_0, arg_1, arg_2, arg_3=2):
        """Setup a grid-stack of grid_stack from a 2D array shape, a pixel scale and a sub-grid size.

        This grid corresponds to a fully unmasked 2D array.

        Parameters
        -----------
        shape : (int, int)
            The 2D shape of the array, where all pixels are used to generate the grid-stack's grid_stack.
        pixel_scale : float
            The size of each pixel in arc seconds.
        sub_grid_size : int
            The size of a sub-pixel's sub-grid (sub_grid_size x sub_grid_size).
        """
        arg_4 = RegularGrid.from_shape_and_pixel_scale(arg_1=arg_1, arg_2=arg_2)
        arg_5 = SubGrid.Func(arg_1=arg_1, arg_2=arg_2,
                                                                    arg_3=arg_3)
        arg_6 = np.array([[0.0, 0.0]])
        return GridStack(arg_4, arg_5, arg_6)

Setup a grid - stack of grid_stack from a 2D array shape a pixel scale and a sub - grid size . This grid corresponds to a fully unmasked 2D array .


def Func(arg_0, arg_1, arg_2=True):
        """Inject a group of variables into the IPython user namespace.

        Parameters
        ----------
        variables : dict, str or list/tuple of str
            The variables to inject into the user's namespace.  If a dict, a
            simple update is done.  If a str, the string is assumed to have
            variable names separated by spaces.  A list/tuple of str can also
            be used to give the variable names.  If just the variable names are
            give (list/tuple/str) then the variable values looked up in the
            callers frame.
        interactive : bool
            If True (default), the variables will be listed with the ``who``
            magic.
        """
        arg_3 = None

        # We need a dict of name/value pairs to do namespace updates.
        if isinstance(arg_1, dict):
            arg_3 = arg_1
        elif isinstance(arg_1, (basestring, list, tuple)):
            if isinstance(arg_1, basestring):
                arg_4 = arg_1.split()
            else:
                arg_4 = arg_1
            arg_3 = {}
            arg_5 = sys._getframe(1)
            for arg_6 in arg_4:
                try:
                    arg_3[arg_6] = eval(arg_6, arg_5.f_globals, arg_5.f_locals)
                except:
                    print ('Could not get variable %s from %s' %
                           (arg_6,arg_5.f_code.co_name))
        else:
            raise ValueError('variables must be a dict/str/list/tuple')

        # Propagate variables to user namespace
        arg_0.user_ns.update(arg_3)

        # And configure interactive visibility
        arg_7 = arg_0.user_ns_hidden
        if arg_2:
            arg_7.difference_update(arg_3)
        else:
            arg_7.update(arg_3)

Inject a group of variables into the IPython user namespace .


def Func(arg_0):
        '''The user is required to have an application secrets file in his
           or her environment. The information isn't saved to the secrets
           file, but the client exists with error if the variable isn't found.
        '''
        arg_1 = 'GOOGLE_APPLICATION_CREDENTIALS'
        arg_0._secrets = arg_0._get_and_update_setting(arg_1)
        if arg_0._secrets is None:
            bot.error('You must export %s to use Google Storage client' %arg_1)
            sys.exit(1)

The user is required to have an application secrets file in his or her environment . The information isn t saved to the secrets file but the client exists with error if the variable isn t found .


def Func(arg_0, arg_1):
        """Format a string for latex inclusion."""

        # Characters that need to be escaped for latex:
        arg_2 = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
        # Magic command names as headers:
        arg_3 = re.compile(r'^(%s.*?):' % ESC_MAGIC,
                                 re.MULTILINE)
        # Magic commands
        arg_4 = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
                            re.MULTILINE)
        # Paragraph continue
        arg_5 = re.compile(r'\\$',re.MULTILINE)

        # The "\n" symbol
        arg_6 = re.compile(r'\\n')

        # Now build the string for output:
        #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
        arg_1 = arg_3.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
                                arg_1)
        arg_1 = arg_4.sub(r'\\texttt{\g<cmd>}',arg_1)
        arg_1 = arg_5.sub(r'\\\\',arg_1)
        arg_1 = arg_2.sub(r'\\\1',arg_1)
        arg_1 = arg_6.sub(r'\\textbackslash{}n',arg_1)
        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
  """Used as optparse callback for reaping a variable number of option args.
  The option may be specified multiple times, and all the args associated with
  that option name will be accumulated in the order that they are encountered
  """
  arg_4 = []

  # Reap the args, taking care to stop before the next option or '.'
  arg_5 = False
  for arg_6 in arg_3.rargs:
    # Stop on --longname options
    if arg_6.startswith("--") and len(arg_6) > 2:
      break

    # Stop on -b options
    if arg_6.startswith("-") and len(arg_6) > 1:
      break

    if arg_6 == ".":
      arg_5 = True
      break

    arg_4.append(arg_6)

  if not arg_4:
    raise optparse.OptionValueError(
      ("Empty arg list for option %r expecting one or more args "
       "(remaining tokens: %r)") % (arg_1, arg_3.rargs))

  del arg_3.rargs[:len(arg_4) + int(arg_5)]

  # Retrieve the existing arg accumulator, if any
  arg_2 = getattr(arg_3.values, arg_0.dest, [])
  #print "Previous value: %r" % value
  if arg_2 is None:
    arg_2 = []

  # Append the new args to the existing ones and save to the parser
  arg_2.extend(arg_4)
  setattr(arg_3.values, arg_0.dest, arg_2)

Used as optparse callback for reaping a variable number of option args . The option may be specified multiple times and all the args associated with that option name will be accumulated in the order that they are encountered


def Func(arg_0):
        """Extract standard gromacs doc

        Extract by running the program and chopping the header to keep from
        'DESCRIPTION' onwards.
        """
        if arg_0._doc_cache is not None:
            return arg_0._doc_cache

        try:
            logging.disable(logging.CRITICAL)
            arg_1, arg_2, arg_3 = arg_0.run('h', stdout=PIPE, stderr=PIPE, use_input=False)
        except:
            logging.critical("Invoking command {0} failed when determining its doc string. Proceed with caution".format(arg_0.command_name))
            arg_0._doc_cache = "(No Gromacs documentation available)"
            return arg_0._doc_cache
        finally:
            # ALWAYS restore logging...
            logging.disable(logging.NOTSET)

        # The header is on STDOUT and is ignored. The docs are read from STDERR in GMX 4.
        arg_5 = re.match(arg_0.doc_pattern, arg_3, re.DOTALL)

        if arg_5 is None:
            # In GMX 5, the opposite is true (Grrr)
            arg_5 = re.match(arg_0.doc_pattern, arg_2, re.DOTALL)
            if arg_5 is None:
                arg_0._doc_cache = "(No Gromacs documentation available)"
                return arg_0._doc_cache

        arg_0._doc_cache = arg_5.group('DOCS')
        return arg_0._doc_cache


(
    num_results=int(3e3),
    num_burnin_steps=int(3e3),
    num_leapfrog_steps=3)

return dict(
      iters=(num_results + num_burnin_steps) * num_leapfrog_steps,
      extras={'acceptance_rate': acceptance_rate},
      wall_time=wall_time)

def Func ( arg_0 = arg_1 ( 3e3 ) , arg_2 = arg_1 ( 3e3 ) , arg_3 = 3 ) : if not tf . executing_eagerly ( ) : tf . compat . v1 . reset_default_graph ( ) arg_4 = tf . cast ( tf . concat ( [ tfd . Poisson ( rate = 15. ) . sample ( 43 ) , tfd . Poisson ( rate = 25. ) . sample ( 31 ) ] , axis = 0 ) , dtype = tf . float32 ) if tf . executing_eagerly ( ) : arg_4 = arg_4 . numpy ( ) else : with tf . compat . v1 . Session ( ) : arg_4 = arg_4 . eval ( ) def unnormalized_log_posterior ( arg_5 , arg_6 , arg_7 ) : return text_messages_joint_log_prob ( arg_4 , arg_5 , arg_6 , arg_7 ) if tf . executing_eagerly ( ) : arg_8 = tf . function ( tfp . mcmc . sample_chain ) else : arg_8 = tfp . mcmc . sample_chain arg_9 = tf . compat . v2 . Variable ( name = 'step_size' , initial_value = tf . constant ( 0.05 , dtype = tf . float32 ) , trainable = False ) def computation ( ) : arg_10 = [ tf . constant ( arg_4 . mean ( ) , name = 'init_lambda1' ) , tf . constant ( arg_4 . mean ( ) , name = 'init_lambda2' ) , tf . constant ( 0.5 , name = 'init_tau' ) , ] arg_11 = [ tfp . bijectors . Exp ( ) , tfp . bijectors . Exp ( ) , tfp . bijectors . Sigmoid ( ) , ] arg_12 , arg_13 = arg_8 ( arg_0 = arg_0 , arg_2 = arg_2 , current_state = arg_10 , kernel = tfp . mcmc . TransformedTransitionKernel ( inner_kernel = tfp . mcmc . HamiltonianMonteCarlo ( target_log_prob_fn = unnormalized_log_posterior , arg_3 = arg_3 , arg_9 = arg_9 , step_size_update_fn = tfp . mcmc . make_simple_step_size_update_policy ( arg_2 ) , state_gradients_are_stopped = True ) , bijector = arg_11 ) ) return arg_13 . inner_results . is_accepted arg_14 = computation ( ) if not tf . executing_eagerly ( ) : arg_15 = tf . compat . v1 . Session ( ) arg_15 . run ( tf . compat . v1 . global_variables_initializer ( ) ) arg_15 . run ( arg_14 ) arg_16 = time . time ( ) if tf . executing_eagerly ( ) : arg_17 = computation ( ) else : arg_17 = arg_15 . run ( arg_14 ) arg_18 = time . time ( ) - arg_16 arg_19 = np . sum ( arg_17 ) arg_20 = np . float32 ( arg_19 ) / np . float32 ( arg_0 ) return dict ( iters = ( arg_0 + arg_2 ) * arg_3 , extras = { 'acceptance_rate' : arg_20 } , arg_18 = arg_18 )

def Func(
    arg_0=arg_1(3e3),
    arg_2=arg_1(3e3),
    arg_3=3):
  """Runs HMC on the text-messages unnormalized posterior."""

  if not tf.executing_eagerly():
    tf.compat.v1.reset_default_graph()

  # Build a static, pretend dataset.
  arg_4 = tf.cast(
      tf.concat(
          [tfd.Poisson(rate=15.).sample(43),
           tfd.Poisson(rate=25.).sample(31)],
          axis=0),
      dtype=tf.float32)
  if tf.executing_eagerly():
    arg_4 = arg_4.numpy()
  else:
    with tf.compat.v1.Session():
      arg_4 = arg_4.eval()

  # Define a closure over our joint_log_prob.
  def unnormalized_log_posterior(arg_5, arg_6, arg_7):
    return text_messages_joint_log_prob(arg_4, arg_5, arg_6, arg_7)

  if tf.executing_eagerly():
    arg_8 = tf.function(tfp.mcmc.sample_chain)
  else:
    arg_8 = tfp.mcmc.sample_chain

  # Initialize the step_size. (It will be automatically adapted.)
  arg_9 = tf.compat.v2.Variable(
      name='step_size',
      initial_value=tf.constant(0.05, dtype=tf.float32),
      trainable=False)

  def computation():
    """The benchmark computation."""

    arg_10 = [
        tf.constant(arg_4.mean(), name='init_lambda1'),
        tf.constant(arg_4.mean(), name='init_lambda2'),
        tf.constant(0.5, name='init_tau'),
    ]

    arg_11 = [
        tfp.bijectors.Exp(),       # Maps a positive real to R.
        tfp.bijectors.Exp(),       # Maps a positive real to R.
        tfp.bijectors.Sigmoid(),   # Maps [0,1] to R.
    ]

    arg_12, arg_13 = arg_8(
        arg_0=arg_0,
        arg_2=arg_2,
        current_state=arg_10,
        kernel=tfp.mcmc.TransformedTransitionKernel(
            inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(
                target_log_prob_fn=unnormalized_log_posterior,
                arg_3=arg_3,
                arg_9=arg_9,
                step_size_update_fn=
                tfp.mcmc.make_simple_step_size_update_policy(arg_2),
                state_gradients_are_stopped=True),
            bijector=arg_11))

    return arg_13.inner_results.is_accepted

  # Let's force evaluation of graph to ensure build time is not part of our time
  # trial.
  arg_14 = computation()
  if not tf.executing_eagerly():
    arg_15 = tf.compat.v1.Session()
    arg_15.run(tf.compat.v1.global_variables_initializer())
    arg_15.run(arg_14)

  arg_16 = time.time()
  if tf.executing_eagerly():
    arg_17 = computation()
  else:
    arg_17 = arg_15.run(arg_14)
  arg_18 = time.time() - arg_16

  arg_19 = np.sum(arg_17)
  arg_20 = np.float32(arg_19) / np.float32(arg_0)

  return dict(
      iters=(arg_0 + arg_2) * arg_3,
      extras={'acceptance_rate': arg_20},
      arg_18=arg_18)

Runs HMC on the text - messages unnormalized posterior .


def
Func
(
arg_0
,
arg_1
=
)
:
arg_2
=
arg_0
.
split
(
'.'
)
[
1
]
if
arg_1
:
arg_2
=
arg_1
arg_2
=
arg_2
.
lower
(
)
if
arg_2
in
[
'png'
,
'jpg'
,
'tiff'
,
'tif'
,
'jpeg'
]
:
return
Image
.
Func
(
arg_0
)
else
:
raise
NotImplementedError
(
"Cannot Func file of type {fmt}"
.
format
(
arg_2
)
)

def Func(arg_0, arg_1=None):
    """
    Reads in a file from disk.

    Arguments:
        in_file: The name of the file to read in
        in_fmt: The format of in_file, if you want to be explicit

    Returns:
        numpy.ndarray
    """
    arg_2 = arg_0.split('.')[-1]
    if arg_1:
        arg_2 = arg_1
    arg_2 = arg_2.lower()

    if arg_2 in ['png', 'jpg', 'tiff', 'tif', 'jpeg']:
        return Image.Func(arg_0)
    else:
        raise NotImplementedError("Cannot Func file of type {fmt}".format(arg_2))


def Func ( ) : arg_0 = os . path . join ( os . path . dirname ( __file__ ) , "txspinneret" , "_version.py" ) with open ( arg_0 ) as version_module : exec ( version_module . read ( ) ) return locals ( ) [ "__version__" ]

def Func():
    """
    Get the version from version module without importing more than
    necessary.
    """
    arg_0 = os.path.join(
        os.path.dirname(__file__), "txspinneret", "_version.py")
    # The version module contains a variable called __version__
    with open(arg_0) as version_module:
        exec(version_module.read())
    return locals()["__version__"]

Get the version from version module without importing more than necessary .


def Func(arg_0):
    """Assess the optimal trim range for a given FastQC data file.

    This function will parse a single FastQC data file, namely the
    *'Per base sequence content'* category. It will retrieve the A/T and G/C
    content for each nucleotide position in the reads, and check whether the
    G/C and A/T proportions are between 80% and 120%. If they are, that
    nucleotide position is marked as biased for future removal.

    Parameters
    ----------
    data_file: str
        Path to FastQC data file.

    Returns
    -------
    trim_nt: list
        List containing the range with the best trimming positions for the
        corresponding FastQ file. The first element is the 5' end trim index
        and the second element is the 3' end trim index.
    """

    logger.debug("Starting trim range assessment")

    # Target string for nucleotide bias assessment
    arg_1 = ">>Per base sequence content"
    logger.debug("Target string to start nucleotide bias assessment set to "
                 "{}".format(arg_1))
    # This flag will become True when gathering base proportion data
    # from file.
    arg_2 = False

    # This variable will store a boolean array on the biased/unbiased
    # positions. Biased position will be True, while unbiased positions
    # will be False
    arg_3 = []

    with open(arg_0) as fh:

        for arg_4 in fh:
            # Start assessment of nucleotide bias
            if arg_4.startswith(arg_1):
                # Skip comment line
                logger.debug("Found target string at line: {}".format(arg_4))
                next(fh)
                arg_2 = True
            # Stop assessment when reaching end of target module
            elif arg_4.startswith(">>END_MODULE") and arg_2:
                logger.debug("Stopping parsing at line: {}".format(arg_4))
                break
            elif arg_2:
                # Get proportions of each nucleotide
                arg_5, arg_6, arg_7, arg_8 = [float(x) for x in arg_4.strip().split()[1:]]
                # Get 'GC' and 'AT content
                arg_9 = (arg_5 + 0.1) / (arg_8 + 0.1)
                arg_10 = (arg_6 + 0.1) / (arg_7 + 0.1)
                # Assess bias
                if 0.8 <= arg_9 <= 1.2 and 0.8 <= arg_10 <= 1.2:
                    arg_3.append(False)
                else:
                    arg_3.append(True)

    logger.debug("Finished bias assessment with result: {}".format(arg_3))

    # Split biased list in half to get the 5' and 3' ends
    arg_11, arg_12 = arg_3[:int(len(arg_3)/2)],\
        arg_3[int(len(arg_3)/2):][::-1]

    logger.debug("Getting optimal trim range from biased list")
    arg_13 = [0, 0]
    # Assess number of nucleotides to clip at 5' end
    arg_13[0] = get_trim_index(arg_11)
    logger.debug("Optimal trim range at 5' end set to: {}".format(arg_13[0]))
    # Assess number of nucleotides to clip at 3' end
    arg_13[1] = len(arg_3) - get_trim_index(arg_12)
    logger.debug("Optimal trim range at 3' end set to: {}".format(arg_13[1]))

    return arg_13

Assess the optimal trim range for a given FastQC data file .


return [image_to_colorlist(i, container) for i in it]

def Func ( arg_0 , arg_1 = arg_2 ) : deprecated . deprecated ( 'util.gif.Func' ) from PIL import ImageSequence arg_3 = ImageSequence . Iterator ( arg_0 ) return [ image_to_colorlist ( arg_4 , arg_1 ) for arg_4 in arg_3 ]

def Func(arg_0, arg_1=arg_2):
    """
    Given an animated GIF, return a list with a colorlist for each frame.
    """
    deprecated.deprecated('util.gif.Func')

    from PIL import ImageSequence

    arg_3 = ImageSequence.Iterator(arg_0)
    return [image_to_colorlist(arg_4, arg_1) for arg_4 in arg_3]

Given an animated GIF return a list with a colorlist for each frame .