def Func(arg_0):
    """
    Propagate "clk" clock signal to all subcomponents
    """
    arg_1 = arg_0.clk
    for arg_2 in arg_0._units:
        _tryConnect(arg_1, arg_2, 'clk')

Propagate clk clock signal to all subcomponents


def Func ( arg_0 , arg_1 , arg_2 = 'fresh' ) : arg_0 . _lock . acquire ( ) try : arg_3 = arg_0 . _items . get ( arg_1 ) if not arg_3 : return None arg_0 . update_item ( arg_3 ) if _state_values [ arg_2 ] >= arg_3 . state_value : return arg_3 return None finally : arg_0 . _lock . release ( )

def Func(arg_0, arg_1, arg_2 = 'fresh'):
        """Get an item from the cache.

        :Parameters:
            - `address`: its address.
            - `state`: the worst state that is acceptable.
        :Types:
            - `address`: any hashable
            - `state`: `str`

        :return: the item or `None` if it was not found.
        :returntype: `CacheItem`"""
        arg_0._lock.acquire()
        try:
            arg_3 = arg_0._items.get(arg_1)
            if not arg_3:
                return None
            arg_0.update_item(arg_3)
            if _state_values[arg_2] >= arg_3.state_value:
                return arg_3
            return None
        finally:
            arg_0._lock.release()


def
Func
(
arg_0
,
arg_1
)
:
assert
isinstance
(
arg_1
,
str
)
and
len
(
arg_1
)
<=
3
and
arg_1
.
strip
(
)
in
[
''
,
'r'
,
'w'
,
'x'
,
'rw'
,
'r x'
,
'rx'
,
'rwx'
,
'wx'
,
]
arg_0
.
_perms
=
arg_1

def Func(arg_0, arg_1):
        """
        Sets the access permissions of the map.

        :param perms: the new permissions.
        """
        assert isinstance(arg_1, str) and len(arg_1) <= 3 and arg_1.strip() in ['', 'r', 'w', 'x', 'rw', 'r x', 'rx', 'rwx', 'wx', ]
        arg_0._perms = arg_1

Sets the access permissions of the map .


def
Func
(
arg_0
,
arg_1
)
:
for
arg_2
in
arg_1
:
print
(
"== Launching  %s =="
%
arg_2
.
batch_name
)
arg_2
(
)
return
True

def Func(arg_0, arg_1):
        """
        Launches all available launchers.
        """
        for arg_2 in arg_1:
            print("== Launching  %s ==" % arg_2.batch_name)
            arg_2()
        return True


return itertools.chain.from_iterable(six.moves.map(
		every_other, six.moves.map(
			operator.itemgetter(1),
			itertools.groupby(iterable, key)
		)))

def Func ( arg_0 , arg_1 = None ) : return itertools . chain . from_iterable ( six . moves . map ( every_other , six . moves . map ( operator . itemgetter ( 1 ) , itertools . groupby ( arg_0 , arg_1 ) ) ) )

def Func(arg_0, arg_1=None):
	"""
	Given an iterable with items that may come in as sequential duplicates,
	remove those duplicates.

	Unlike unique_justseen, this function does not remove triplicates.

	>>> ' '.join(Func('abcaabbccaaabbbcccbcbc'))
	'a b c a b c a a b b c c b c b c'
	>>> ' '.join(Func('aaaabbbbb'))
	'a a b b b'
	"""
	return itertools.chain.from_iterable(six.moves.map(
		every_other, six.moves.map(
			operator.itemgetter(1),
			itertools.groupby(arg_0, arg_1)
		)))

Given an iterable with items that may come in as sequential duplicates,
	remove those duplicates.

	Unlike unique_justseen, this function does not remove triplicates.

	>>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc'))
	'a b c a b c a a b b c c b c b c'
	>>> ' '.join(remove_duplicates('aaaabbbbb'))
	'a a b b b'

Given an iterable with items that may come in as sequential duplicates remove those duplicates .


def Func ( arg_0 , arg_1 , ** arg_2 ) : arg_3 = { 'progressive' : VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG , 'quality' : QUAL } if arg_1 . mode != 'RGB' : arg_1 = arg_1 . convert ( 'RGB' ) return ( arg_1 , arg_3 )

def Func(arg_0, arg_1, **arg_2):
        """
        Receive a PIL Image instance of a JPEG and returns 2-tuple.

        Args:
            * [0]: Image instance, converted to RGB
            * [1]: Dict with a quality key (mapped to the value of `QUAL` as
                   defined by the `VERSATILEIMAGEFIELD_JPEG_RESIZE_QUALITY`
                   setting)
        """
        arg_3 = {
            'progressive': VERSATILEIMAGEFIELD_PROGRESSIVE_JPEG,
            'quality': QUAL
        }
        if arg_1.mode != 'RGB':
            arg_1 = arg_1.convert('RGB')
        return (arg_1, arg_3)

Receive a PIL Image instance of a JPEG and returns 2 - tuple .


async def Func ( arg_0 , * , arg_1 : arg_2 = None ) -> int : arg_3 = await arg_0 . __client . http . artist_albums ( arg_0 . id , limit = 1 , offset = 0 , arg_1 = arg_1 ) return arg_3 [ 'total' ]

async def Func(arg_0, *, arg_1: arg_2 = None) -> int:
        """get the total amout of tracks in the album.

        Parameters
        ----------
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.

        Returns
        -------
        total : int
            The total amount of albums.
        """
        arg_3 = await arg_0.__client.http.artist_albums(arg_0.id, limit=1, offset=0, arg_1=arg_1)
        return arg_3['total']

get the total amout of tracks in the album .


def
Func
(
arg_0
,
arg_1
=
)
:
arg_0
.
offset
=
len
(
arg_0
.
buffer
)
if
arg_1
is
:
arg_3
=
len
(
arg_0
.
objects
)
arg_4
=
_PDFObject
(
arg_3
,
arg_0
.
offset
)
arg_0
.
objects
.
append
(
arg_4
)
else
:
arg_3
=
arg_1
arg_4
=
_PDFObject
(
arg_3
,
arg_0
.
offset
)
arg_0
.
objects
[
arg_1
]
=
arg_4
arg_0
.
_out
(
str
(
arg_3
)
+
' 0 obj'
)
return
arg_4

def Func(arg_0, arg_1=None):
        """ The flag is a simple integer to force the placement
            of the object into position in the object array.
            Used for overwriting the placeholder objects.

        """
        arg_0.offset = len(arg_0.buffer)
        if arg_1 is None:
            arg_3 = len(arg_0.objects)
            arg_4 = _PDFObject(arg_3, arg_0.offset)
            arg_0.objects.append(arg_4)
        else:
            arg_3 = arg_1
            arg_4 = _PDFObject(arg_3, arg_0.offset)
            arg_0.objects[arg_1] = arg_4
        arg_0._out(str(arg_3) + ' 0 obj')
        return arg_4

The flag is a simple integer to force the placement of the object into position in the object array . Used for overwriting the placeholder objects .


def Func(arg_0, arg_1, arg_2):
        """
        Use with caution!

        Directly set the pixel buffers.

        :param colors: A list of color tuples
        :param int pos: Position in color list to begin set operation.
        """
        arg_0._colors = arg_1
        arg_0._pos = arg_2

        arg_5 = arg_0._pos + arg_0.numLEDs
        if arg_5 > len(arg_0._colors):
            raise ValueError('Needed %d colors but found %d' % (
                arg_5, len(arg_0._colors)))


(
        collected_features,
        test_fraction=0.25,
        n_crossval_iterations=20,
        n_kfolds=5,
        crossval_scoring_metric='f1',
        classifier_to_pickle=None,
        nworkers=-1,
)

def Func(
        arg_0,
        arg_1=0.25,
        arg_2=20,
        arg_3=5,
        arg_4='f1',
        arg_5=None,
        arg_6=-1,
):

    '''This gets the best RF classifier after running cross-validation.

    - splits the training set into test/train samples
    - does `KFold` stratified cross-validation using `RandomizedSearchCV`
    - gets the `RandomForestClassifier` with the best performance after CV
    - gets the confusion matrix for the test set

    Runs on the output dict from functions that produce dicts similar to that
    produced by `collect_nonperiodic_features` above.

    Parameters
    ----------

    collected_features : dict or str
        This is either the dict produced by a `collect_*_features` function or
        the pickle produced by the same.

    test_fraction : float
        This sets the fraction of the input set that will be used as the
        test set after training.

    n_crossval_iterations : int
        This sets the number of iterations to use when running the
        cross-validation.

    n_kfolds : int
        This sets the number of K-folds to use on the data when doing a
        test-train split.

    crossval_scoring_metric : str
        This is a string that describes how the cross-validation score is
        calculated for each iteration. See the URL below for how to specify this
        parameter:

        http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter
        By default, this is tuned for binary classification and uses the F1
        scoring metric. Change the `crossval_scoring_metric` to another metric
        (probably 'accuracy') for multi-class classification, e.g. for periodic
        variable classification.

    classifier_to_pickle : str
        If this is a string indicating the name of a pickle file to write, will
        write the trained classifier to the pickle that can be later loaded and
        used to classify data.

    nworkers : int
        This is the number of parallel workers to use in the
        RandomForestClassifier. Set to -1 to use all CPUs on your machine.

    Returns
    -------

    dict
        A dict containing the trained classifier, cross-validation results, the
        input data set, and all input kwargs used is returned, along with
        cross-validation score metrics.

    '''

    if (isinstance(arg_0,str) and
        os.path.exists(arg_0)):
        with open(arg_0,'rb') as infd:
            arg_7 = pickle.load(infd)
    elif isinstance(arg_0, dict):
        arg_7 = arg_0
    else:
        LOGERROR("can't figure out the input collected_features arg")
        return None

    arg_8 = arg_7['features_array']
    arg_9 = arg_7['labels_array']
    arg_10 = arg_7['availablefeatures']
    arg_11 = arg_7['magcol']
    arg_12 = arg_7['objectids']

    # split the training set into training/test samples using stratification
    # to keep the same fraction of variable/nonvariables in each
    arg_13, arg_14, arg_15, arg_16 = (
        train_test_split(
            arg_8,
            arg_9,
            test_size=arg_1,
            random_state=RANDSEED,
            stratify=arg_9
        )
    )

    # get a random forest classifier
    arg_17 = RandomForestClassifier(n_jobs=arg_6,
                                 random_state=RANDSEED)

    # this is the grid def for hyperparam optimization
    arg_18 = {
        "max_depth": [3,4,5,None],
        "n_estimators":sp_randint(100,2000),
        "max_features": sp_randint(1, 5),
        "min_samples_split": sp_randint(2, 11),
        "min_samples_leaf": sp_randint(2, 11),
    }

    # run the stratified kfold cross-validation on training features using our
    # random forest classifier object
    arg_19 = RandomizedSearchCV(
        arg_17,
        param_distributions=arg_18,
        n_iter=arg_2,
        scoring=arg_4,
        cv=StratifiedKFold(n_splits=arg_3,
                           shuffle=True,
                           random_state=RANDSEED),
        random_state=RANDSEED
    )

    LOGINFO('running grid-search CV to optimize RF hyperparameters...')
    arg_20 = arg_19.fit(arg_13,
                                        arg_15)

    # report on the classifiers' performance
    _gridsearch_report(arg_20.cv_results_)

    # get the best classifier after CV is done
    arg_21 = arg_20.best_estimator_
    arg_22 = arg_20.best_score_
    arg_23 = arg_20.best_params_

    # test this classifier on the testing set
    arg_24 = arg_21.predict(arg_14)

    arg_25 = recall_score(arg_16, arg_24)
    arg_26 = precision_score(arg_16,arg_24)
    arg_27 = f1_score(arg_16, arg_24)
    arg_28 = confusion_matrix(arg_16, arg_24)

    # write the classifier, its training/testing set, and its stats to the
    # pickle if requested
    arg_29 = {'features':arg_8,
               'labels':arg_9,
               'feature_names':arg_10,
               'magcol':arg_11,
               'objectids':arg_12,
               'kwargs':{'test_fraction':arg_1,
                         'n_crossval_iterations':arg_2,
                         'n_kfolds':arg_3,
                         'crossval_scoring_metric':arg_4,
                         'nworkers':arg_6},
               'collect_kwargs':arg_7['kwargs'],
               'testing_features':arg_14,
               'testing_labels':arg_16,
               'training_features':arg_13,
               'training_labels':arg_15,
               'best_classifier':arg_21,
               'best_score':arg_22,
               'best_hyperparams':arg_23,
               'best_recall':arg_25,
               'best_precision':arg_26,
               'best_f1':arg_27,
               'best_confmatrix':arg_28}

    if arg_5:

        with open(arg_5,'wb') as outfd:
            pickle.dump(arg_29, outfd, pickle.HIGHEST_PROTOCOL)

    # return this classifier and accompanying info
    return arg_29

This gets the best RF classifier after running cross - validation .


(
        path_name, keyword='', ext='', full_path=True,
        has_date=False, date_fmt=DATE_FMT
)

return files if full_path else [f.split('/')[-1] for f in files]

def Func ( arg_0 , arg_1 = '' , arg_2 = '' , arg_3 = True , arg_4 = False , arg_5 = arg_6 ) -> list : if not os . path . exists ( path = arg_0 ) : return [ ] arg_0 = arg_0 . replace ( '\\' , '/' ) if arg_1 or arg_2 : arg_1 = f'*{keyword}*' if arg_1 else '*' if not arg_2 : arg_2 = '*' arg_7 = sort_by_modified ( [ arg_8 . replace ( '\\' , '/' ) for arg_8 in glob . iglob ( f'{path_name}/{keyword}.{ext}' ) if os . path . isfile ( arg_8 ) and ( arg_8 . replace ( '\\' , '/' ) . split ( '/' ) [ - 1 ] [ 0 ] != '~' ) ] ) else : arg_7 = sort_by_modified ( [ f'{path_name}/{f}' for arg_8 in os . listdir ( path = arg_0 ) if os . path . isfile ( f'{path_name}/{f}' ) and ( arg_8 [ 0 ] != '~' ) ] ) if arg_4 : arg_7 = filter_by_dates ( arg_7 , arg_5 = arg_5 ) return arg_7 if arg_3 else [ arg_8 . split ( '/' ) [ - 1 ] for arg_8 in arg_7 ]

def Func(
        arg_0, arg_1='', arg_2='', arg_3=True,
        arg_4=False, arg_5=arg_6
) -> list:
    """
    Search all files with criteria
    Returned list will be sorted by last modified

    Args:
        path_name: full path name
        keyword: keyword to search
        ext: file extensions, split by ','
        full_path: whether return full path (default True)
        has_date: whether has date in file name (default False)
        date_fmt: date format to check for has_date parameter

    Returns:
        list: all file names with criteria fulfilled
    """
    if not os.path.exists(path=arg_0): return []
    arg_0 = arg_0.replace('\\', '/')

    if arg_1 or arg_2:
        arg_1 = f'*{keyword}*' if arg_1 else '*'
        if not arg_2: arg_2 = '*'
        arg_7 = sort_by_modified([
            arg_8.replace('\\', '/') for arg_8 in glob.iglob(f'{path_name}/{keyword}.{ext}')
            if os.path.isfile(arg_8) and (arg_8.replace('\\', '/').split('/')[-1][0] != '~')
        ])

    else:
        arg_7 = sort_by_modified([
            f'{path_name}/{f}' for arg_8 in os.listdir(path=arg_0)
            if os.path.isfile(f'{path_name}/{f}') and (arg_8[0] != '~')
        ])

    if arg_4:
        arg_7 = filter_by_dates(arg_7, arg_5=arg_5)

    return arg_7 if arg_3 else [arg_8.split('/')[-1] for arg_8 in arg_7]


adapt source to a packarray according to the layout of template

return cls(source, template.start, template.end)

def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
if
not
isinstance
(
arg_2
,
packarray
)
:
raise
TypeError
(
'template must be a packarray'
)
return
arg_0
(
arg_1
,
arg_2
.
start
,
arg_2
.
end
)

def Func(arg_0, arg_1, arg_2):
    """ Func source to a packarray according to the layout of template """
    if not isinstance(arg_2, packarray):
      raise TypeError('template must be a packarray')
    return arg_0(arg_1, arg_2.start, arg_2.end)


def Func ( arg_0 , arg_1 , arg_2 , arg_3 ) : arg_4 = normal . Normal ( loc = dtype_util . as_numpy_dtype ( arg_2 ) ( 0 ) , scale = dtype_util . as_numpy_dtype ( arg_2 ) ( 1 ) ) . sample ( tf . concat ( [ arg_1 , [ arg_0 ] ] , axis = 0 ) , arg_3 = arg_3 ( ) ) arg_5 = arg_4 / tf . norm ( tensor = arg_4 , ord = 2 , axis = - 1 ) [ ... , tf . newaxis ] return arg_5

def Func(arg_0, arg_1, arg_2, arg_3):
  """Returns a batch of points chosen uniformly from the unit hypersphere."""
  # This works because the Gaussian distribution is spherically symmetric.
  # raw shape: shape + [dimension]
  arg_4 = normal.Normal(
      loc=dtype_util.as_numpy_dtype(arg_2)(0),
      scale=dtype_util.as_numpy_dtype(arg_2)(1)).sample(
          tf.concat([arg_1, [arg_0]], axis=0), arg_3=arg_3())
  arg_5 = arg_4 / tf.norm(tensor=arg_4, ord=2, axis=-1)[..., tf.newaxis]
  return arg_5

Returns a batch of points chosen uniformly from the unit hypersphere .


def Func ( arg_0 ) : arg_1 = yield from arg_0 . handle_int ( arg_0 . API . get ( 'status' ) ) return arg_0 . PLAY_STATES . get ( arg_1 )

def Func(arg_0):
        """Get the play status of the device."""
        arg_1 = yield from arg_0.handle_int(arg_0.API.get('status'))
        return arg_0.PLAY_STATES.get(arg_1)


def Func(arg_0, arg_1):
        """Ensure statement only contains allowed nodes."""
        if not isinstance(arg_1, arg_0.ALLOWED):
            raise SyntaxError('Not allowed in environment markers.\n%s\n%s' %
                               (arg_0.statement,
                               (' ' * arg_1.col_offset) + '^'))
        return ast.NodeTransformer.Func(arg_0, arg_1)

Ensure statement only contains allowed nodes .


def Func ( ) -> ast . ImportFrom : return ast . ImportFrom ( module = "basilisp.lang.runtime" , names = [ ast . alias ( name = "Var" , asname = _VAR_ALIAS ) ] , level = 0 , )

def Func() -> ast.ImportFrom:
    """Generate the Python From ... Import AST node for importing
    language support modules."""
    return ast.ImportFrom(
        module="basilisp.lang.runtime",
        names=[ast.alias(name="Var", asname=_VAR_ALIAS)],
        level=0,
    )

Generate the Python From ... Import AST node for importing language support modules .


def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
arg_3
=
{
"selection"
:
{
"selectionType"
:
"thermostats"
,
"selectionMatch"
:
arg_0
.
thermostats
[
arg_1
]
[
'identifier'
]
}
,
"thermostat"
:
{
"settings"
:
{
"fanMinOnTime"
:
arg_2
}
}
}
arg_4
=
"set fan minimum on time."
return
arg_0
.
make_request
(
arg_3
,
arg_4
)

def Func(arg_0, arg_1, arg_2):
        ''' The minimum time, in minutes, to run the fan each hour. Value from 1 to 60 '''
        arg_3 = {"selection": {"selectionType": "thermostats",
                        "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                        "thermostat": {
                            "settings": {
                                "fanMinOnTime": arg_2
                            }
                        }}
        arg_4 = "set fan minimum on time."
        return arg_0.make_request(arg_3, arg_4)

The minimum time in minutes to run the fan each hour . Value from 1 to 60


def Func(arg_0, arg_1, arg_2):
        """Keep a reference of the callback on this socket."""
        if arg_1 in arg_0.ack_callbacks:
            return False
        arg_0.ack_callbacks[arg_1] = arg_2

Keep a reference of the callback on this socket .


def
Func
(
arg_0
)
:
if
not
arg_0
.
user
:
return
arg_1
=
convert_path
(
os
.
path
.
expanduser
(
"~"
)
)
for
arg_2
,
arg_3
in
arg_0
.
config_vars
.
iteritems
(
)
:
if
arg_3
.
startswith
(
arg_1
)
and
not
os
.
path
.
isdir
(
arg_3
)
:
arg_0
.
debug_print
(
"os.makedirs('%s', 0700)"
%
arg_3
)
os
.
makedirs
(
arg_3
,
0700
)

def Func(arg_0):
        """Create directories under ~."""
        if not arg_0.user:
            return
        arg_1 = convert_path(os.path.expanduser("~"))
        for arg_2, arg_3 in arg_0.config_vars.iteritems():
            if arg_3.startswith(arg_1) and not os.path.isdir(arg_3):
                arg_0.debug_print("os.makedirs('%s', 0700)" % arg_3)
                os.makedirs(arg_3, 0700)


(self, drop_nan=True, drop_masked=True, column_names=None, mode="replace", name="default")

def Func ( arg_0 , arg_1 = True , arg_2 = True , arg_3 = None , arg_4 = "replace" , arg_5 = "default" ) : arg_3 = arg_3 or arg_0 . get_column_names ( virtual = False ) def create ( arg_6 ) : return selections . SelectionDropNa ( arg_1 , arg_2 , arg_3 , arg_6 , arg_4 ) arg_0 . _selection ( create , arg_5 )

def Func(arg_0, arg_1=True, arg_2=True, arg_3=None, arg_4="replace", arg_5="default"):
        """Create a selection that selects rows having non missing values for all columns in column_names.

        The name reflect Panda's, no rows are really dropped, but a mask is kept to keep track of the selection

        :param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
        :param drop_masked: drop rows when there is a masked value in any of the columns
        :param column_names: The columns to consider, default: all (real, non-virtual) columns
        :param str mode: Possible boolean operator: replace/and/or/xor/subtract
        :param str name: history tree or selection 'slot' to use
        :return:
        """
        arg_3 = arg_3 or arg_0.get_column_names(virtual=False)

        def create(arg_6):
            return selections.SelectionDropNa(arg_1, arg_2, arg_3, arg_6, arg_4)
        arg_0._selection(create, arg_5)

Create a selection that selects rows having non missing values for all columns in column_names .


Customize check_type for handling containers.

def Func ( arg_0 , arg_1 , arg_2 , arg_3 ) : arg_4 = super ( InstructionParameter , arg_0 ) . Func ( arg_1 , arg_2 , arg_3 ) if is_collection ( arg_1 ) : arg_5 = [ super ( InstructionParameter , arg_0 ) . Func ( item , arg_2 , arg_3 ) for item in arg_1 ] return arg_4

def Func(arg_0, arg_1, arg_2, arg_3):
        """Customize Func for handling containers."""
        # Check the type in the standard way first, in order to fail quickly
        # in case of invalid values.
        arg_4 = super(InstructionParameter, arg_0).Func(
            arg_1, arg_2, arg_3)

        if is_collection(arg_1):
            arg_5 = [super(InstructionParameter, arg_0).Func(item, arg_2, arg_3)
                 for item in arg_1]

        return arg_4

Customize check_type for handling containers .


def Func ( arg_0 ) : super ( IPythonWidget , arg_0 ) . Func ( ) arg_0 . _load_guiref_magic ( ) arg_0 . kernel_manager . shell_channel . history ( hist_access_type = 'tail' , n = 1000 )

def Func(arg_0):
        """Reimplemented to make a history request and load %guiref."""
        super(IPythonWidget, arg_0).Func()
        arg_0._load_guiref_magic()
        arg_0.kernel_manager.shell_channel.history(hist_access_type='tail',
                                                  n=1000)

Reimplemented to make a history request and load %guiref .


def Func(arg_0):
    """Get priority value.

    Args:
        priority (int or str or :obj:`Priority`): Priority.

    Returns:
        int: The priority value.
    """
    if isinstance(arg_0, int):
        if arg_0 < 0 or arg_0 > 100:
            raise ValueError('priority must be between 0 and 100')
        return arg_0
    elif isinstance(arg_0, Priority):
        return arg_0.value
    elif isinstance(arg_0, str):
        return Priority[arg_0.upper()].value
    else:
        raise TypeError('priority must be an integer or Priority enum value')


(self, nActive=1, queues=None, edges=None, edge_type=None)

def Func(arg_0, arg_1=1, arg_2=None, arg_3=None, arg_4=None):
        """Prepares the ``QueueNetwork`` for simulation.

        Each :class:`.QueueServer` in the network starts inactive,
        which means they do not accept arrivals from outside the
        network, and they have no agents in their system. This method
        sets queues to active, which then allows agents to arrive from
        outside the network.

        Parameters
        ----------
        nActive : int (optional, default: ``1``)
            The number of queues to set as active. The queues are
            selected randomly.
        queues : int *array_like* (optional)
            The edge index (or an iterable of edge indices) identifying
            the :class:`QueueServer(s)<.QueueServer>` to make active by.
        edges : 2-tuple of int or *array_like* (optional)
            Explicitly specify which queues to make active. Must be
            either:

            * A 2-tuple of the edge's source and target vertex
              indices, or
            * An iterable of 2-tuples of the edge's source and
              target vertex indices.

        edge_type : int or an iterable of int (optional)
            A integer, or a collection of integers identifying which
            edge types will be set active.

        Raises
        ------
        ValueError
            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``
            and ``nActive`` is an integer less than 1
            :exc:`~ValueError` is raised.
        TypeError
            If ``queues``, ``egdes``, and ``edge_type`` are all ``None``
            and ``nActive`` is not an integer then a :exc:`~TypeError`
            is raised.
        QueueingToolError
            Raised if all the queues specified are
            :class:`NullQueues<.NullQueue>`.

        Notes
        -----
        :class:`NullQueues<.NullQueue>` cannot be activated, and are
        sifted out if they are specified. More specifically, every edge
        with edge type 0 is sifted out.
        """
        if arg_2 is None and arg_3 is None and arg_4 is None:
            if arg_1 >= 1 and isinstance(arg_1, numbers.Integral):
                arg_5 = [q.edge[2] for q in arg_0.edge2queue if q.edge[3] != 0]
                arg_6 = min(arg_1, len(arg_5))
                arg_2 = np.random.choice(arg_5, size=arg_6, replace=False)
            elif not isinstance(arg_1, numbers.Integral):
                arg_7 = "If queues is None, then nActive must be an integer."
                raise TypeError(arg_7)
            else:
                arg_7 = ("If queues is None, then nActive must be a "
                       "positive int.")
                raise ValueError(arg_7)
        else:
            arg_2 = _get_queues(arg_0.g, arg_2, arg_3, arg_4)

        arg_2 = [e for e in arg_2 if arg_0.edge2queue[e].edge[3] != 0]

        if len(arg_2) == 0:
            raise QueueingToolError("There were no queues to Func.")

        if len(arg_2) > arg_0.max_agents:
            arg_2 = arg_2[:arg_0.max_agents]

        for arg_8 in arg_2:
            arg_0.edge2queue[arg_8].set_active()
            arg_0.num_agents[arg_8] = arg_0.edge2queue[arg_8]._num_total

        arg_10 = [q._key() for q in arg_0.edge2queue if q._time < np.infty]
        arg_0._fancy_heap = PriorityQueue(arg_10, arg_0.nE)
        arg_0._Funcd = True

Prepares the QueueNetwork for simulation .


def Func ( arg_0 ) : assert arg_0 . endswith ( g_defaultCheckpointExtension ) arg_1 = os . path . split ( arg_0 ) [ 1 ] arg_2 = arg_1 [ 0 : - len ( g_defaultCheckpointExtension ) ] return arg_2

def Func(arg_0):
  """Returns a checkpoint label string for the given model checkpoint directory

  checkpointDir: relative or absolute model checkpoint directory path
  """
  assert arg_0.endswith(g_defaultCheckpointExtension)

  arg_1 = os.path.split(arg_0)[1]

  arg_2 = arg_1[0:-len(g_defaultCheckpointExtension)]

  return arg_2


(model,
                                    observed_time_series,
                                    init_batch_shape=(),
                                    seed=None,
                                    name=None)

def Func ( arg_0 , arg_1 , arg_2 = ( ) , arg_3 = None , arg_4 = None ) : with tf . compat . v1 . name_scope ( arg_4 , 'Func' , values = [ arg_1 ] ) as arg_4 : arg_3 = tfd . SeedStream ( arg_3 , salt = 'StructuralTimeSeries_Func' ) arg_5 = collections . OrderedDict ( ) arg_6 = [ ] for arg_7 in arg_0 . parameters : def initial_loc_fn ( arg_7 ) : return sample_uniform_initial_state ( arg_7 , return_constrained = True , init_sample_shape = arg_2 , arg_3 = arg_3 ( ) ) arg_8 = _build_trainable_posterior ( arg_7 , initial_loc_fn = initial_loc_fn ) arg_5 [ arg_7 . name ] = arg_8 arg_6 . append ( arg_8 . sample ( arg_3 = arg_3 ( ) ) ) arg_1 = sts_util . pad_batch_dimension_for_multiple_chains ( arg_1 , arg_0 , chain_batch_shape = arg_2 ) arg_9 = arg_0 . joint_log_prob ( arg_1 ) arg_10 = arg_9 ( * arg_6 ) arg_11 = tf . reduce_sum ( input_tensor = [ - arg_8 . log_prob ( sample ) for ( arg_8 , sample ) in zip ( arg_5 . values ( ) , arg_6 ) ] , axis = 0 ) arg_12 = - ( arg_10 + arg_11 ) return arg_12 , arg_5

def Func(arg_0,
                                    arg_1,
                                    arg_2=(),
                                    arg_3=None,
                                    arg_4=None):
  """Build a loss function for variational inference in STS models.

  Variational inference searches for the distribution within some family of
  approximate posteriors that minimizes a divergence between the approximate
  posterior `q(z)` and true posterior `p(z|observed_time_series)`. By converting
  inference to optimization, it's generally much faster than sampling-based
  inference algorithms such as HMC. The tradeoff is that the approximating
  family rarely contains the true posterior, so it may miss important aspects of
  posterior structure (in particular, dependence between variables) and should
  not be blindly trusted. Results may vary; it's generally wise to compare to
  HMC to evaluate whether inference quality is sufficient for your task at hand.

  This method constructs a loss function for variational inference using the
  Kullback-Liebler divergence `KL[q(z) || p(z|observed_time_series)]`, with an
  approximating family given by independent Normal distributions transformed to
  the appropriate parameter space for each parameter. Minimizing this loss (the
  negative ELBO) maximizes a lower bound on the log model evidence `-log
  p(observed_time_series)`. This is equivalent to the 'mean-field' method
  implemented in [1]. and is a standard approach. The resulting posterior
  approximations are unimodal; they will tend to underestimate posterior
  uncertainty when the true posterior contains multiple modes (the `KL[q||p]`
  divergence encourages choosing a single mode) or dependence between variables.

  Args:
    model: An instance of `StructuralTimeSeries` representing a
      time-series model. This represents a joint distribution over
      time-series and their parameters with batch shape `[b1, ..., bN]`.
    observed_time_series: `float` `Tensor` of shape
      `concat([sample_shape, model.batch_shape, [num_timesteps, 1]]) where
      `sample_shape` corresponds to i.i.d. observations, and the trailing `[1]`
      dimension may (optionally) be omitted if `num_timesteps > 1`. May
      optionally be an instance of `tfp.sts.MaskedTimeSeries`, which includes
      a mask `Tensor` to specify timesteps with missing observations.
    init_batch_shape: Batch shape (Python `tuple`, `list`, or `int`) of initial
      states to optimize in parallel.
      Default value: `()`. (i.e., just run a single optimization).
    seed: Python integer to seed the random number generator.
    name: Python `str` name prefixed to ops created by this function.
      Default value: `None` (i.e., 'Func').

  Returns:
    variational_loss: `float` `Tensor` of shape
      `concat([init_batch_shape, model.batch_shape])`, encoding a stochastic
      estimate of an upper bound on the negative model evidence `-log p(y)`.
      Minimizing this loss performs variational inference; the gap between the
      variational bound and the true (generally unknown) model evidence
      corresponds to the divergence `KL[q||p]` between the approximate and true
      posterior.
    variational_distributions: `collections.OrderedDict` giving
      the approximate posterior for each model parameter. The keys are
      Python `str` parameter names in order, corresponding to
      `[param.name for param in model.parameters]`. The values are
      `tfd.Distribution` instances with batch shape
      `concat([init_batch_shape, model.batch_shape])`; these will typically be
      of the form `tfd.TransformedDistribution(tfd.Normal(...),
      bijector=param.bijector)`.

  #### Examples

  Assume we've built a structural time-series model:

  ```python
    day_of_week = tfp.sts.Seasonal(
        num_seasons=7,
        observed_time_series=observed_time_series,
        name='day_of_week')
    local_linear_trend = tfp.sts.LocalLinearTrend(
        observed_time_series=observed_time_series,
        name='local_linear_trend')
    model = tfp.sts.Sum(components=[day_of_week, local_linear_trend],
                        observed_time_series=observed_time_series)
  ```

  To run variational inference, we simply construct the loss and optimize
  it:

  ```python
    (variational_loss,
     variational_distributions) = tfp.sts.Func(
       model=model, observed_time_series=observed_time_series)

    train_op = tf.train.AdamOptimizer(0.1).minimize(variational_loss)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())

      for step in range(200):
        _, loss_ = sess.run((train_op, variational_loss))

        if step % 20 == 0:
          print("step {} loss {}".format(step, loss_))

      posterior_samples_ = sess.run({
        param_name: q.sample(50)
        for param_name, q in variational_distributions.items()})
  ```

  As a more complex example, we might try to avoid local optima by optimizing
  from multiple initializations in parallel, and selecting the result with the
  lowest loss:

  ```python
    (variational_loss,
     variational_distributions) = tfp.sts.Func(
       model=model, observed_time_series=observed_time_series,
       init_batch_shape=[10])

    train_op = tf.train.AdamOptimizer(0.1).minimize(variational_loss)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())

      for step in range(200):
        _, loss_ = sess.run((train_op, variational_loss))

        if step % 20 == 0:
          print("step {} losses {}".format(step, loss_))

      # Draw multiple samples to reduce Monte Carlo error in the optimized
      # variational bounds.
      avg_loss = np.mean(
        [sess.run(variational_loss) for _ in range(25)], axis=0)
      best_posterior_idx = np.argmin(avg_loss, axis=0).astype(np.int32)
  ```

  #### References

  [1]: Alp Kucukelbir, Dustin Tran, Rajesh Ranganath, Andrew Gelman, and
       David M. Blei. Automatic Differentiation Variational Inference. In
       _Journal of Machine Learning Research_, 2017.
       https://arxiv.org/abs/1603.00788

  """

  with tf.compat.v1.name_scope(
      arg_4, 'Func',
      values=[arg_1]) as arg_4:
    arg_3 = tfd.SeedStream(
        arg_3, salt='StructuralTimeSeries_Func')

    arg_5 = collections.OrderedDict()
    arg_6 = []
    for arg_7 in arg_0.parameters:
      def initial_loc_fn(arg_7):
        return sample_uniform_initial_state(
            arg_7, return_constrained=True,
            init_sample_shape=arg_2,
            arg_3=arg_3())
      arg_8 = _build_trainable_posterior(arg_7, initial_loc_fn=initial_loc_fn)
      arg_5[arg_7.name] = arg_8
      arg_6.append(arg_8.sample(arg_3=arg_3()))

    # Multiple initializations (similar to HMC chains) manifest as an extra
    # param batch dimension, so we need to add corresponding batch dimension(s)
    # to `observed_time_series`.
    arg_1 = sts_util.pad_batch_dimension_for_multiple_chains(
        arg_1, arg_0, chain_batch_shape=arg_2)

    # Construct the variational bound.
    arg_9 = arg_0.joint_log_prob(arg_1)
    arg_10 = arg_9(*arg_6)
    arg_11 = tf.reduce_sum(
        input_tensor=[
            -arg_8.log_prob(sample) for (arg_8, sample) in zip(
                arg_5.values(), arg_6)
        ],
        axis=0)
    arg_12 = -(arg_10 + arg_11)  # -ELBO

  return arg_12, arg_5

Build a loss function for variational inference in STS models.

  Variational inference searches for the distribution within some family of
  approximate posteriors that minimizes a divergence between the approximate
  posterior `q(z)` and true posterior `p(z|observed_time_series)`. By converting
  inference to optimization, it's generally much faster than sampling-based
  inference algorithms such as HMC. The tradeoff is that the approximating
  family rarely contains the true posterior, so it may miss important aspects of
  posterior structure (in particular, dependence between variables) and should
  not be blindly trusted. Results may vary; it's generally wise to compare to
  HMC to evaluate whether inference quality is sufficient for your task at hand.

  This method constructs a loss function for variational inference using the
  Kullback-Liebler divergence `KL[q(z) || p(z|observed_time_series)]`, with an
  approximating family given by independent Normal distributions transformed to
  the appropriate parameter space for each parameter. Minimizing this loss (the
  negative ELBO) maximizes a lower bound on the log model evidence `-log
  p(observed_time_series)`. This is equivalent to the 'mean-field' method
  implemented in [1]. and is a standard approach. The resulting posterior
  approximations are unimodal; they will tend to underestimate posterior
  uncertainty when the true posterior contains multiple modes (the `KL[q||p]`
  divergence encourages choosing a single mode) or dependence between variables.

  Args:
    model: An instance of `StructuralTimeSeries` representing a
      time-series model. This represents a joint distribution over
      time-series and their parameters with batch shape `[b1, ..., bN]`.
    observed_time_series: `float` `Tensor` of shape
      `concat([sample_shape, model.batch_shape, [num_timesteps, 1]]) where
      `sample_shape` corresponds to i.i.d. observations, and the trailing `[1]`
      dimension may (optionally) be omitted if `num_timesteps > 1`. May
      optionally be an instance of `tfp.sts.MaskedTimeSeries`, which includes
      a mask `Tensor` to specify timesteps with missing observations.
    init_batch_shape: Batch shape (Python `tuple`, `list`, or `int`) of initial
      states to optimize in parallel.
      Default value: `()`. (i.e., just run a single optimization).
    seed: Python integer to seed the random number generator.
    name: Python `str` name prefixed to ops created by this function.
      Default value: `None` (i.e., 'build_factored_variational_loss').

  Returns:
    variational_loss: `float` `Tensor` of shape
      `concat([init_batch_shape, model.batch_shape])`, encoding a stochastic
      estimate of an upper bound on the negative model evidence `-log p(y)`.
      Minimizing this loss performs variational inference; the gap between the
      variational bound and the true (generally unknown) model evidence
      corresponds to the divergence `KL[q||p]` between the approximate and true
      posterior.
    variational_distributions: `collections.OrderedDict` giving
      the approximate posterior for each model parameter. The keys are
      Python `str` parameter names in order, corresponding to
      `[param.name for param in model.parameters]`. The values are
      `tfd.Distribution` instances with batch shape
      `concat([init_batch_shape, model.batch_shape])`; these will typically be
      of the form `tfd.TransformedDistribution(tfd.Normal(...),
      bijector=param.bijector)`.

  #### Examples

  Assume we've built a structural time-series model:

  ```python
    day_of_week = tfp.sts.Seasonal(
        num_seasons=7,
        observed_time_series=observed_time_series,
        name='day_of_week')
    local_linear_trend = tfp.sts.LocalLinearTrend(
        observed_time_series=observed_time_series,
        name='local_linear_trend')
    model = tfp.sts.Sum(components=[day_of_week, local_linear_trend],
                        observed_time_series=observed_time_series)
  ```

  To run variational inference, we simply construct the loss and optimize
  it:

  ```python
    (variational_loss,
     variational_distributions) = tfp.sts.build_factored_variational_loss(
       model=model, observed_time_series=observed_time_series)

    train_op = tf.train.AdamOptimizer(0.1).minimize(variational_loss)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())

      for step in range(200):
        _, loss_ = sess.run((train_op, variational_loss))

        if step % 20 == 0:
          print("step {} loss {}".format(step, loss_))

      posterior_samples_ = sess.run({
        param_name: q.sample(50)
        for param_name, q in variational_distributions.items()})
  ```

  As a more complex example, we might try to avoid local optima by optimizing
  from multiple initializations in parallel, and selecting the result with the
  lowest loss:

  ```python
    (variational_loss,
     variational_distributions) = tfp.sts.build_factored_variational_loss(
       model=model, observed_time_series=observed_time_series,
       init_batch_shape=[10])

    train_op = tf.train.AdamOptimizer(0.1).minimize(variational_loss)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())

      for step in range(200):
        _, loss_ = sess.run((train_op, variational_loss))

        if step % 20 == 0:
          print("step {} losses {}".format(step, loss_))

      # Draw multiple samples to reduce Monte Carlo error in the optimized
      # variational bounds.
      avg_loss = np.mean(
        [sess.run(variational_loss) for _ in range(25)], axis=0)
      best_posterior_idx = np.argmin(avg_loss, axis=0).astype(np.int32)
  ```

  #### References

  [1]: Alp Kucukelbir, Dustin Tran, Rajesh Ranganath, Andrew Gelman, and
       David M. Blei. Automatic Differentiation Variational Inference. In
       _Journal of Machine Learning Research_, 2017.
       https://arxiv.org/abs/1603.00788

Build a loss function for variational inference in STS models .


def
Func
(
arg_0
,
arg_1
)
:
if
type
(
arg_1
)
is
MaterialPackage
:
if
arg_0
.
material
==
arg_1
.
material
:
arg_0
.
size_class_masses
=
arg_0
.
size_class_masses
+
arg_1
.
size_class_masses
else
:
for
arg_3
in
arg_1
.
material
.
size_classes
:
if
arg_3
not
in
arg_0
.
material
.
size_classes
:
raise
Exception
(
"Packages of '"
+
arg_1
.
material
.
name
+
"' cannot be added to packages of '"
+
arg_0
.
material
.
name
+
"'. The size class '"
+
arg_3
+
"' was not found in '"
+
arg_0
.
material
.
name
+
"'."
)
arg_0
.
Func
(
(
arg_3
,
arg_1
.
get_size_class_mass
(
arg_3
)
)
)
elif
arg_0
.
_is_size_class_mass_tuple
(
arg_1
)
:
arg_3
=
arg_1
[
0
]
arg_4
=
arg_0
.
material
.
get_size_class_index
(
arg_3
)
arg_5
=
arg_1
[
1
]
arg_0
.
size_class_masses
[
arg_4
]
=
arg_0
.
size_class_masses
[
arg_4
]
+
arg_5
else
:
raise
TypeError
(
"Invalid addition argument."
)

def Func(arg_0, arg_1):
        """
        Add another psd material package to this material package.

        :param other: The other material package.
        """

        # Add another package.
        if type(arg_1) is MaterialPackage:
            # Packages of the same material.
            if arg_0.material == arg_1.material:
                arg_0.size_class_masses = \
                        arg_0.size_class_masses + arg_1.size_class_masses
            else:  # Packages of different materials.
                for arg_3 in arg_1.material.size_classes:
                    if arg_3 not in arg_0.material.size_classes:
                        raise Exception(
                            "Packages of '" + arg_1.material.name +
                            "' cannot be added to packages of '" +
                            arg_0.material.name +
                            "'. The size class '" + arg_3 +
                            "' was not found in '" + arg_0.material.name + "'.")
                    arg_0.Func(
                        (arg_3, arg_1.get_size_class_mass(arg_3)))

        # Add the specified mass of the specified size class.
        elif arg_0._is_size_class_mass_tuple(arg_1):
            # Added material variables.
            arg_3 = arg_1[0]
            arg_4 = arg_0.material.get_size_class_index(arg_3)
            arg_5 = arg_1[1]

            # Create the result package.
            arg_0.size_class_masses[arg_4] = \
                arg_0.size_class_masses[arg_4] + arg_5

        # If not one of the above, it must be an invalid argument.
        else:
            raise TypeError("Invalid addition argument.")

Add another psd material package to this material package .


return dict(
            [
                [k, v]
                for k, v in list(to_clean.items())
                if (k in allow or k not in self.temp_keys)
            ]
        )

def Func ( arg_0 , arg_1 , arg_2 = ( ) ) : if arg_1 . keys ( ) == [ "links" , "library" , "version" , "meta" , "key" , "data" ] : arg_1 = arg_1 [ "data" ] return dict ( [ [ arg_3 , arg_4 ] for arg_3 , arg_4 in list ( arg_1 . items ( ) ) if ( arg_3 in arg_2 or arg_3 not in arg_0 . temp_keys ) ] )

def Func(arg_0, arg_1, arg_2=()):
        """ Remove keys we added for internal use
        """
        # this item's been retrieved from the API, we only need the 'data'
        # entry
        if arg_1.keys() == ["links", "library", "version", "meta", "key", "data"]:
            arg_1 = arg_1["data"]
        return dict(
            [
                [arg_3, arg_4]
                for arg_3, arg_4 in list(arg_1.items())
                if (arg_3 in arg_2 or arg_3 not in arg_0.temp_keys)
            ]
        )


def Func(arg_0, arg_1, arg_2):
    """ Takes your standard rgb color
        and converts it to a proper hue value """

    arg_3 = min(arg_0, 255)
    arg_4 = min(arg_1, 255)
    arg_5 = min(arg_2, 255)
    if arg_3 > 1 or arg_4 > 1 or arg_5 > 1:
        arg_3 = arg_3 / 255.0
        arg_4 = arg_4 / 255.0
        arg_5 = arg_5 / 255.0

    return color_from_hls(*rgb_to_hls(arg_3,arg_4,arg_5))


def Func(arg_0, arg_1):
        "Add an observation o to the distribution."
        arg_0.smooth_for(arg_1)
        arg_0.dictionary[arg_1] += 1
        arg_0.n_obs += 1
        arg_0.sampler = None

Add an observation o to the distribution .


return {instance: fsic2.get(instance, 0) for instance, counter in six.iteritems(fsic1) if fsic2.get(instance, 0) < counter}

def Func ( arg_0 , arg_1 ) : return { arg_2 : arg_1 . get ( arg_2 , 0 ) for arg_2 , arg_3 in six . iteritems ( arg_0 ) if arg_1 . get ( arg_2 , 0 ) < arg_3 }

def Func(arg_0, arg_1):
    """
    We set the lower counter between two same instance ids.
    If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.

    :param fsic1: dictionary containing (instance_id, counter) pairs
    :param fsic2: dictionary containing (instance_id, counter) pairs
    :return ``dict`` of fsics to be used in queueing the correct records to the buffer
    """
    return {arg_2: arg_1.get(arg_2, 0) for arg_2, arg_3 in six.iteritems(arg_0) if arg_1.get(arg_2, 0) < arg_3}

We set the lower counter between two same instance ids . If an instance_id exists in one fsic but not the other we want to give that counter a value of 0 .


def Func(arg_0, arg_1: arg_2):
        """Create of get a base space for a tuple of bases"""

        try:
            return arg_0._dynamic_bases_inverse[arg_1]
        except KeyError:
            arg_3 = arg_0._dynamic_base_namer.get_next(arg_0._dynamic_bases)
            arg_4 = arg_0._new_space(arg_3=arg_3)
            arg_0.spacegraph.add_space(arg_4)
            arg_0._dynamic_bases[arg_3] = arg_4
            arg_0._dynamic_bases_inverse[arg_1] = arg_4
            arg_4.add_bases(arg_1)
            return arg_4


def Func ( arg_0 ) : Func = set ( ) for arg_2 in arg_0 . _items : Func |= arg_2 . groups return Func

def Func(arg_0):
        """Set of groups defined in the roster.

        :Return: the groups
        :ReturnType: `set` of `unicode`
        """
        Func = set()
        for arg_2 in arg_0._items:
            Func |= arg_2.groups
        return Func


def
Func
(
arg_0
,
arg_1
)
:
try
:
arg_2
,
arg_3
=
map
(
float
,
arg_1
.
split
(
)
)
except
ValueError
:
print
(
red
(
'Invalid lat and lon {}'
.
format
(
arg_1
)
)
)
else
:
print
(
white
(
geohash
.
encode
(
arg_2
,
arg_3
,
config
.
GEOHASH_PRECISION
)
)
)

def Func(arg_0, arg_1):
        """Compute a geohash from latitude and longitude.
        GEOHASH 48.1234 2.9876"""
        try:
            arg_2, arg_3 = map(float, arg_1.split())
        except ValueError:
            print(red('Invalid lat and lon {}'.format(arg_1)))
        else:
            print(white(geohash.encode(arg_2, arg_3, config.GEOHASH_PRECISION)))

Compute a geohash from latitude and longitude . GEOHASH 48 . 1234 2 . 9876


Called for every timer tick. Calls self.get which can be a deferred
        and passes that result back to the queueBack method

        Returns a deferred

def
Func
(
arg_0
)
:
if
arg_0
.
sync
:
if
arg_0
.
running
:
defer
.
returnValue
(
)
arg_0
.
running
=
True
try
:
arg_2
=
yield
arg_0
.
_get
(
)
if
arg_2
:
arg_0
.
queueBack
(
arg_2
)
except
Exception
as
e
:
log
.
msg
(
"[%s] Unhandled error: %s"
%
(
arg_0
.
service
,
e
)
)
arg_0
.
running
=
False

def Func(arg_0):
        """Called for every timer Func. Calls self.get which can be a deferred
        and passes that result back to the queueBack method

        Returns a deferred"""

        if arg_0.sync:
            if arg_0.running:
                defer.returnValue(None)

        arg_0.running = True

        try:
            arg_2 = yield arg_0._get()
            if arg_2:
                arg_0.queueBack(arg_2)

        except Exception as e:
            log.msg("[%s] Unhandled error: %s" % (arg_0.service, e))

        arg_0.running = False

Called for every timer tick . Calls self . get which can be a deferred and passes that result back to the queueBack method Returns a deferred


Return nodes in the path between 'a' and 'b' going from
        parent to child NOT including 'a'

def Func ( arg_0 , arg_1 , arg_2 ) : def _Func ( arg_3 , arg_4 ) : if arg_3 is arg_4 : return [ arg_3 ] else : assert len ( arg_3 . children ) == 1 return [ arg_3 ] + _Func ( arg_3 . children [ 0 ] , arg_4 ) arg_3 = arg_0 . nodes [ arg_1 ] arg_4 = arg_0 . nodes [ arg_2 ] return _Func ( arg_3 , arg_4 ) [ 1 : ]

def Func(arg_0, arg_1, arg_2):
        """Return nodes in the Func between 'a' and 'b' going from
        parent to child NOT including 'a' """

        def _Func(arg_3, arg_4):
            if arg_3 is arg_4:
                return [arg_3]
            else:
                assert len(arg_3.children) == 1
                return [arg_3] + _Func(arg_3.children[0], arg_4)

        arg_3 = arg_0.nodes[arg_1]
        arg_4 = arg_0.nodes[arg_2]
        return _Func(arg_3, arg_4)[1:]

Return nodes in the path between a and b going from parent to child NOT including a


(desc, pre='pre_recursion', post=None, python_path=None)

def Func ( arg_0 , arg_1 = 'pre_recursion' , arg_2 = None , arg_3 = None ) : def call ( arg_4 , arg_0 ) : if isinstance ( arg_4 , str ) : arg_4 = getattr ( arg_5 , arg_4 , None ) return arg_4 and arg_4 ( arg_0 ) arg_0 = load . load_if_filename ( arg_0 ) or arg_0 arg_0 = construct . to_type_constructor ( arg_0 , arg_3 ) arg_5 = arg_0 . get ( 'datatype' ) arg_0 = call ( arg_1 , arg_0 ) or arg_0 for arg_6 in getattr ( arg_5 , 'CHILDREN' , [ ] ) : arg_7 = arg_0 . get ( arg_6 ) if arg_7 : arg_8 = arg_6 . endswith ( 's' ) arg_9 = arg_8 and arg_6 != 'drivers' arg_10 = arg_6 [ : - 1 ] if arg_9 else arg_6 arg_11 = arg_3 or ( 'bibliopixel.' + arg_10 ) if arg_8 : if isinstance ( arg_7 , ( dict , str ) ) : arg_7 = [ arg_7 ] for arg_12 , arg_13 in enumerate ( arg_7 ) : arg_7 [ arg_12 ] = Func ( arg_13 , arg_1 , arg_2 , arg_11 ) arg_0 [ arg_6 ] = arg_7 else : arg_0 [ arg_6 ] = Func ( arg_7 , arg_1 , arg_2 , arg_11 ) arg_14 = call ( arg_2 , arg_0 ) return arg_0 if arg_14 is None else arg_14

def Func(arg_0, arg_1='pre_recursion', arg_2=None, arg_3=None):
    """
    Depth first recursion through a dictionary containing type constructors

    The arguments pre, post and children are independently either:

    * None, which means to do nothing
    * a string, which means to use the static class method of that name on the
      class being constructed, or
    * a callable, to be called at each recursion

    Arguments:

    dictionary -- a project dictionary or one of its subdictionaries
    pre -- called before children are visited node in the recursion
    post -- called after children are visited in the recursion
    python_path -- relative path to start resolving typenames

    """
    def call(arg_4, arg_0):
        if isinstance(arg_4, str):
            # f is the name of a static class method on the datatype.
            arg_4 = getattr(arg_5, arg_4, None)
        return arg_4 and arg_4(arg_0)

    # Automatically load strings that look like JSON or Yaml filenames.
    arg_0 = load.load_if_filename(arg_0) or arg_0

    arg_0 = construct.to_type_constructor(arg_0, arg_3)
    arg_5 = arg_0.get('datatype')

    arg_0 = call(arg_1, arg_0) or arg_0

    for arg_6 in getattr(arg_5, 'CHILDREN', []):
        arg_7 = arg_0.get(arg_6)
        if arg_7:
            arg_8 = arg_6.endswith('s')
            arg_9 = arg_8 and arg_6 != 'drivers'
            # This is because it's the "drivers" directory, whereas
            # the others are animation, control, layout, project
            # without the s. TODO: rename drivers/ to driver/ in v4

            arg_10 = arg_6[:-1] if arg_9 else arg_6
            arg_11 = arg_3 or ('bibliopixel.' + arg_10)
            if arg_8:
                if isinstance(arg_7, (dict, str)):
                    arg_7 = [arg_7]
                for arg_12, arg_13 in enumerate(arg_7):
                    arg_7[arg_12] = Func(arg_13, arg_1, arg_2, arg_11)
                arg_0[arg_6] = arg_7
            else:
                arg_0[arg_6] = Func(arg_7, arg_1, arg_2, arg_11)

    arg_14 = call(arg_2, arg_0)
    return arg_0 if arg_14 is None else arg_14


def Func ( arg_0 , arg_1 , arg_2 ) : for arg_3 in arg_2 : if arg_3 . match ( arg_1 ) : yield arg_3

def Func(arg_0, arg_1, arg_2):
        """Yield all matching patterns for path."""
        for arg_3 in arg_2:
            if arg_3.match(arg_1):
                yield arg_3


def Func ( arg_0 , arg_1 ) : if arg_0 . is_initialized and arg_1 [ 'type' ] == 'update' : arg_2 = arg_1 [ 'oldvalue' ] for arg_3 in arg_0 . children : arg_2 . children . remove ( arg_3 ) arg_3 . set_parent ( None ) arg_0 . refresh_items ( )

def Func(arg_0, arg_1):
        """ A change handler for the 'objects' list of the Include.

        If the object is initialized objects which are removed will be
        unparented and objects which are added will be reparented. Old
        objects will be destroyed if the 'destroy_old' flag is True.

        """
        if arg_0.is_initialized and arg_1['type'] == 'update':
            arg_2 = arg_1['oldvalue']
            for arg_3 in arg_0.children:
                arg_2.children.remove(arg_3)
                arg_3.set_parent(None)
            arg_0.refresh_items()

A change handler for the objects list of the Include .


def Func(arg_0, arg_1, arg_2, arg_3):
        """Return the appropriate integer value. If a non-integer is
        provided, attempt a name-based lookup and return the primary key.
        """
        arg_4 = tower_cli.get_resource(arg_0.resource_name)

        # Ensure that None is passed through without trying to
        # do anything.
        if arg_1 is None:
            return None

        # If we were already given an integer, do nothing.
        # This ensures that the Func method is idempotent.
        if isinstance(arg_1, int):
            return arg_1

        # Do we have a string that contains only digits?
        # If so, then Func it to an integer and return it.
        if re.match(r'^[\d]+$', arg_1):
            return int(arg_1)

        # Special case to allow disassociations
        if arg_1 == 'null':
            return arg_1

        # Okay, we have a string. Try to do a name-based lookup on the
        # resource, and return back the ID that we get from that.
        #
        # This has the chance of erroring out, which is fine.
        try:
            debug.log('The %s field is given as a name; '
                      'looking it up.' % arg_2.name, header='details')
            arg_5 = {arg_4.identity[-1]: arg_1}
            arg_6 = arg_4.get(**arg_5)
        except exc.MultipleResults:
            raise exc.MultipleRelatedError(
                'Cannot look up {0} exclusively by name, because multiple {0} '
                'objects exist with that name.\n'
                'Please send an ID. You can get the ID for the {0} you want '
                'with:\n'
                '  tower-cli {0} list --name "{1}"'.format(arg_0.resource_name,
                                                           arg_1),
            )
        except exc.TowerCLIError as ex:
            raise exc.RelatedError('Could not get %s. %s' %
                                   (arg_0.resource_name, str(ex)))

        # Done! Return the ID.
        return arg_6['id']

Return the appropriate integer value . If a non - integer is provided attempt a name - based lookup and return the primary key .


def
Func
(
arg_0
,
arg_1
=
)
:
LOG
.
info
(
"Func for tenant %s with filters %s"
%
(
arg_0
.
tenant_id
,
arg_1
)
)
return
db_api
.
subnet_count_all
(
arg_0
,
**
arg_1
)

def Func(arg_0, arg_1=None):
    """Return the number of subnets.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.
    """
    LOG.info("Func for tenant %s with filters %s" %
             (arg_0.tenant_id, arg_1))
    return db_api.subnet_count_all(arg_0, **arg_1)


def Func ( arg_0 ) : try : arg_1 = arg_0 . id arg_0 = _forbidden_attributes ( arg_0 ) arg_2 = _pybossa_req ( 'put' , 'task' , arg_1 , payload = arg_0 . data ) if arg_2 . get ( 'id' ) : return Task ( arg_2 ) else : return arg_2 except : raise

def Func(arg_0):
    """Update a task for a given task ID.

    :param task: PYBOSSA task

    """
    try:
        arg_1 = arg_0.id
        arg_0 = _forbidden_attributes(arg_0)
        arg_2 = _pybossa_req('put', 'task', arg_1, payload=arg_0.data)
        if arg_2.get('id'):
            return Task(arg_2)
        else:
            return arg_2
    except:  # pragma: no cover
        raise


(stream, output, prebuffer, chunk_size=8192)

def Func(arg_0, arg_1, arg_2, arg_3=8192):
    """Reads data from stream and then writes it to the output."""
    arg_4 = isinstance(arg_1, PlayerOutput)
    arg_5 = isinstance(arg_1, HTTPServer)
    arg_6 = arg_4 and arg_1.namedpipe
    arg_7 = isinstance(arg_1, FileOutput) and arg_1.fd is not stdout and sys.stdout.isatty()
    arg_8 = hasattr(arg_1, "record") and isinstance(arg_1.record, FileOutput) and arg_1.record.fd is not stdout and sys.stdout.isatty()

    arg_9 = chain(
        [arg_2],
        iter(partial(arg_0.read, arg_3), b"")
    )
    if arg_7:
        arg_9 = progress(arg_9,
                                   prefix=os.path.basename(args.output))
    elif arg_8:
        arg_9 = progress(arg_9,
                                   prefix=os.path.basename(args.record))

    try:
        for arg_10 in arg_9:
            # We need to check if the player process still exists when
            # using named pipes on Windows since the named pipe is not
            # automatically closed by the player.
            if is_win32 and arg_6:
                arg_1.player.poll()

                if arg_1.player.returncode is not None:
                    log.info("Player closed")
                    break

            try:
                arg_1.write(arg_10)
            except IOError as err:
                if arg_4 and err.errno in ACCEPTABLE_ERRNO:
                    log.info("Player closed")
                elif arg_5 and err.errno in ACCEPTABLE_ERRNO:
                    log.info("HTTP connection closed")
                else:
                    console.exit("Error when writing to output: {0}, exiting", err)

                break
    except IOError as err:
        console.exit("Error when reading from stream: {0}, exiting", err)
    finally:
        arg_0.close()
        log.info("Stream ended")

Reads data from stream and then writes it to the output .


(templates, prefix=None, deffnm='md', jobname='MD', budget=None,
                            mdrun_opts=None, walltime=1.0, jobarray_string=None, startdir=None,
                            npme=None, **kwargs)

return [write_script(template) for template in config.get_templates(templates)]

def Func(arg_0, arg_1=None, arg_2='md', arg_3='MD', arg_4=None,
                            arg_5=None, arg_6=1.0, arg_7=None, arg_8=None,
                            arg_9=None, **arg_10):
    """Write scripts for queuing systems.

    This sets up queuing system run scripts with a simple search and replace in
    templates. See :func:`gromacs.cbook.edit_txt` for details. Shell scripts
    are made executable.

    :Arguments:
      *templates*
          Template file or list of template files. The "files" can also be names
          or symbolic names for templates in the templates directory. See
          :mod:`gromacs.config` for details and rules for writing templates.
      *prefix*
          Prefix for the final run script filename; by default the filename will be
          the same as the template. [None]
      *dirname*
          Directory in which to place the submit scripts. [.]
      *deffnm*
          Default filename prefix for :program:`mdrun` ``-deffnm`` [md]
      *jobname*
          Name of the job in the queuing system. [MD]
      *budget*
          Which budget to book the runtime on [None]
      *startdir*
          Explicit path on the remote system (for run scripts that need to `cd`
          into this directory at the beginning of execution) [None]
      *mdrun_opts*
          String of additional options for :program:`mdrun`.
      *walltime*
          Maximum runtime of the job in hours. [1]
      *npme*
          number of PME nodes
      *jobarray_string*
          Multi-line string that is spliced in for job array functionality
          (see :func:`gromacs.qsub.generate_submit_array`; do not use manually)
      *kwargs*
          all other kwargs are ignored

    :Returns: list of generated run scripts
    """
    if not arg_3[0].isalpha():
        arg_3 = 'MD_'+arg_3
        arg_11 = "To make the jobname legal it must start with a letter: changed to {0!r}".format(arg_3)
        logger.warn(arg_11)
        warnings.warn(arg_11, category=AutoCorrectionWarning)
    if arg_1 is None:
        arg_1 = ""
    if arg_5 is not None:
        arg_5 = '"'+str(arg_5)+'"'  # TODO: could test if quotes already present

    arg_12 = arg_10.pop('dirname', os.path.curdir)

    arg_13 = Timedelta(hours=arg_6)
    arg_6 = arg_13.strftime("%h:%M:%S")
    arg_14 = arg_13.ashours

    def write_script(arg_15):
        arg_16 = os.path.join(arg_12, arg_1 + os.path.basename(arg_15))
        logger.info("Setting up queuing system script {submitscript!r}...".format(**vars()))
        # These substitution rules are documented for the user in the module doc string
        arg_17 = detect_queuing_system(arg_15)
        if arg_17 is not None and (arg_17.name == 'Slurm'):
            cbook.edit_txt(arg_15,
                           [('^ *DEFFNM=','(?<==)(.*)', arg_2),
                            ('^#.*(-J)', '((?<=-J\s))\s*\w+', arg_3),
                            ('^#.*(-A|account_no)', '((?<=-A\s)|(?<=account_no\s))\s*\w+', arg_4),
                            ('^#.*(-t)', '(?<=-t\s)(\d+:\d+:\d+)', arg_6),
                            ('^ *WALL_HOURS=', '(?<==)(.*)', arg_14),
                            ('^ *STARTDIR=', '(?<==)(.*)', arg_8),
                            ('^ *NPME=', '(?<==)(.*)', arg_9),
                            ('^ *MDRUN_OPTS=', '(?<==)("")', arg_5),  # only replace literal ""
                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', arg_7),
                            ],
                           newname=arg_16)
            arg_18 = os.path.splitext(arg_16)[1]
        else:
            cbook.edit_txt(arg_15,
                           [('^ *DEFFNM=','(?<==)(.*)', arg_2),
                            ('^#.*(-N|job_name)', '((?<=-N\s)|(?<=job_name\s))\s*\w+', arg_3),
                            ('^#.*(-A|account_no)', '((?<=-A\s)|(?<=account_no\s))\s*\w+', arg_4),
                            ('^#.*(-l walltime|wall_clock_limit)', '(?<==)(\d+:\d+:\d+)', arg_6),
                            ('^ *WALL_HOURS=', '(?<==)(.*)', arg_14),
                            ('^ *STARTDIR=', '(?<==)(.*)', arg_8),
                            ('^ *NPME=', '(?<==)(.*)', arg_9),
                            ('^ *MDRUN_OPTS=', '(?<==)("")', arg_5),  # only replace literal ""
                            ('^# JOB_ARRAY_PLACEHOLDER', '^.*$', arg_7),
                           ],
                           newname=arg_16)
            arg_18 = os.path.splitext(arg_16)[1]
        if arg_18 in ('.sh', '.csh', '.bash'):
            os.chmod(arg_16, 0o755)
        return arg_16

    return [write_script(arg_15) for arg_15 in config.get_templates(arg_0)]


def Func ( arg_0 , arg_1 , arg_2 ) : arg_0 . ctx . front_face = 'cw' arg_0 . ctx . blend_func = moderngl . ONE , moderngl . ONE helper . _depth_sampler . use ( location = 1 ) with arg_0 . lightbuffer_scope : for arg_6 in arg_0 . point_lights : arg_7 = arg_6 . radius arg_8 = matrix44 . multiply ( arg_6 . matrix , arg_1 ) arg_0 . point_light_shader [ "m_proj" ] . write ( arg_2 . tobytes ( ) ) arg_0 . point_light_shader [ "m_light" ] . write ( arg_8 . astype ( 'f4' ) . tobytes ( ) ) arg_0 . gbuffer . color_attachments [ 1 ] . use ( location = 0 ) arg_0 . point_light_shader [ "g_normal" ] . value = 0 arg_0 . gbuffer . depth_attachment . use ( location = 1 ) arg_0 . point_light_shader [ "g_depth" ] . value = 1 arg_0 . point_light_shader [ "screensize" ] . value = ( arg_0 . width , arg_0 . height ) arg_0 . point_light_shader [ "proj_const" ] . value = arg_2 . projection_constants arg_0 . point_light_shader [ "radius" ] . value = arg_7 arg_0 . unit_cube . render ( arg_0 . point_light_shader ) helper . _depth_sampler . clear ( location = 1 )

def Func(arg_0, arg_1, arg_2):
        """Render light volumes"""
        # Draw light volumes from the inside
        arg_0.ctx.front_face = 'cw'
        arg_0.ctx.blend_func = moderngl.ONE, moderngl.ONE

        helper._depth_sampler.use(location=1)
        with arg_0.lightbuffer_scope:
            for arg_6 in arg_0.point_lights:
                # Calc light properties
                arg_7 = arg_6.radius
                arg_8 = matrix44.multiply(arg_6.matrix, arg_1)
                # Draw the light volume
                arg_0.point_light_shader["m_proj"].write(arg_2.tobytes())
                arg_0.point_light_shader["m_light"].write(arg_8.astype('f4').tobytes())
                arg_0.gbuffer.color_attachments[1].use(location=0)
                arg_0.point_light_shader["g_normal"].value = 0
                arg_0.gbuffer.depth_attachment.use(location=1)
                arg_0.point_light_shader["g_depth"].value = 1
                arg_0.point_light_shader["screensize"].value = (arg_0.width, arg_0.height)
                arg_0.point_light_shader["proj_const"].value = arg_2.projection_constants
                arg_0.point_light_shader["radius"].value = arg_7
                arg_0.unit_cube.render(arg_0.point_light_shader)

        helper._depth_sampler.clear(location=1)


def Func ( ) : arg_0 = distrib_family ( ) if arg_0 == 'debian' : return _parse_locales ( '/usr/share/i18n/SUPPORTED' ) elif arg_0 == 'arch' : return _parse_locales ( '/etc/locale.gen' ) elif arg_0 == 'redhat' : return _Func_redhat ( ) else : raise UnsupportedFamily ( supported = [ 'debian' , 'arch' , 'redhat' ] )

def Func():
    """
    Gets the list of supported locales.

    Each locale is returned as a ``(locale, charset)`` tuple.
    """
    arg_0 = distrib_family()
    if arg_0 == 'debian':
        return _parse_locales('/usr/share/i18n/SUPPORTED')
    elif arg_0 == 'arch':
        return _parse_locales('/etc/locale.gen')
    elif arg_0 == 'redhat':
        return _Func_redhat()
    else:
        raise UnsupportedFamily(supported=['debian', 'arch', 'redhat'])


def Func(arg_0):  # pragma: no cover
    """Prepare transcriptiondata from the transcription sources."""
    from lingpy.sequence.sound_classes import token2class
    from lingpy.data import Model

    arg_1 = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE']
    arg_2 = TranscriptionSystem('bipa')
    for arg_3, arg_4 in arg_0.repos.iter_sources(type='td'):
        arg_0.log.info('TranscriptionData {0} ...'.format(arg_3['NAME']))
        arg_5 = URITemplate(arg_3['URITEMPLATE']) if arg_3['URITEMPLATE'] else None
        arg_6 = [['BIPA_GRAPHEME', 'CLTS_NAME', 'GENERATED', 'EXPLICIT',
                'GRAPHEME', 'URL'] + arg_1]
        arg_7 = set()
        for arg_8 in arg_4:
            if arg_8['GRAPHEME'] in arg_7:
                arg_0.log.warn('skipping duplicate grapheme: {0}'.format(arg_8['GRAPHEME']))
                continue
            arg_7.add(arg_8['GRAPHEME'])
            if not arg_8['BIPA']:
                arg_9 = arg_2[arg_8['GRAPHEME']]
                arg_10 = ''
            else:
                arg_9 = arg_2[arg_8['BIPA']]
                arg_10 = '+'
            arg_11 = '+' if arg_9.generated else ''
            if is_valid_sound(arg_9, arg_2):
                arg_12 = arg_9.s
                arg_13 = arg_9.name
            else:
                arg_12, arg_13 = '<NA>', '<NA>'
            arg_14 = arg_5.expand(**arg_8) if arg_5 else arg_8.get('URL', '')
            arg_6.append(
                [arg_12, arg_13, arg_11, arg_10, arg_8['GRAPHEME'],
                 arg_14] + [
                    arg_8.get(arg_15, '') for arg_15 in arg_1])
        arg_16 = len([o for o in arg_6 if o[0] != '<NA>'])
        arg_0.log.info('... {0} of {1} graphemes found ({2:.0f}%)'.format(
            arg_16, len(arg_6), arg_16 / len(arg_6) * 100))
        with UnicodeWriter(
            pkg_path('transcriptiondata', '{0}.tsv'.format(arg_3['NAME'])), delimiter='\t'
        ) as writer:
            writer.writerows(arg_6)

    arg_17 = 0
    with UnicodeWriter(pkg_path('soundclasses', 'lingpy.tsv'), delimiter='\t') as writer:
        writer.writerow(['CLTS_NAME', 'BIPA_GRAPHEME'] + SOUNDCLASS_SYSTEMS)
        for arg_18, arg_19 in sorted(arg_2.sounds.items()):
            if not arg_19.alias:
                writer.writerow(
                    [arg_19.name, arg_18] + [token2class(
                        arg_18, Model(arg_20)) for arg_20 in SOUNDCLASS_SYSTEMS])
                arg_17 += 1
    arg_0.log.info('SoundClasses: {0} written to file.'.format(arg_17))

Prepare transcriptiondata from the transcription sources .


(self, url='',headers={}, date=str(datetime.date.today()),
        dict_to_store={}, type='', repo_name='')

def Func ( arg_0 , arg_1 = '' , arg_2 = { } , arg_3 = arg_4 ( arg_5 . date . today ( ) ) , arg_7 = { } , arg_8 = '' , arg_9 = '' ) : arg_1 = ( arg_1 + '/traffic/' + arg_8 ) arg_10 = requests . get ( arg_1 , arg_2 = arg_2 ) arg_11 = arg_10 . json ( ) if arg_8 == 'views' : arg_0 . views_json [ arg_9 ] = arg_11 elif arg_8 == 'clones' : arg_0 . clones_json [ arg_9 ] = arg_11 for arg_14 in arg_11 [ arg_8 ] : arg_15 = arg_14 [ 'timestamp' ] / 1000 try : arg_16 = arg_5 . datetime . utcfromtimestamp ( arg_15 ) . strftime ( '%Y-%m-%d' ) if arg_16 != arg_3 : arg_17 = ( arg_14 [ 'count' ] , arg_14 [ 'uniques' ] ) arg_18 = ( arg_7 [ arg_15 ] [ 0 ] + arg_17 [ 0 ] , arg_7 [ arg_15 ] [ 1 ] + arg_17 [ 1 ] ) arg_7 [ arg_15 ] = arg_18 except KeyError : arg_18 = arg_7 [ arg_15 ] = ( arg_14 [ 'count' ] , arg_14 [ 'uniques' ] )

def Func(arg_0, arg_1='',arg_2={}, arg_3=arg_4(arg_5.date.today()),
        arg_7={}, arg_8='', arg_9=''):
        """
        Retrieves data from json and stores it in the supplied dict. Accepts
        'clones' or 'views' as type.
        """
        #JSON
        arg_1 = (arg_1 + '/traffic/' + arg_8)
        arg_10 = requests.get(arg_1, arg_2=arg_2)
        arg_11 = arg_10.json()
        if arg_8 == 'views':
            arg_0.views_json[arg_9] = arg_11
        elif arg_8 == 'clones':
            arg_0.clones_json[arg_9] = arg_11
        #CSV
        for arg_14 in arg_11[arg_8]:
            arg_15 = arg_14['timestamp']/1000
            try:
                arg_16 = arg_5.datetime.utcfromtimestamp(
                    arg_15).strftime('%Y-%m-%d')
                #do not add todays date, some views might not be recorded yet
                if arg_16 != arg_3:
                    arg_17 = (arg_14['count'], arg_14['uniques'])
                    arg_18 = (arg_7[arg_15][0] + arg_17[0],
                        arg_7[arg_15][1] + arg_17[1])
                    arg_7[arg_15] = arg_18
            except KeyError:
                arg_18 = arg_7[arg_15] = (arg_14['count'],
                    arg_14['uniques'])

Retrieves data from json and stores it in the supplied dict . Accepts clones or views as type .


def Func():
  """A function that should be called after parsing all Gin config files.

  Calling this function allows registered "Func hooks" to inspect (and
  potentially modify) the Gin config, to provide additional functionality. Hooks
  should not modify the configuration object they receive directly; instead,
  they should return a dictionary mapping Gin binding keys to (new or updated)
  values. This way, all hooks see the config as originally parsed.

  Raises:
    RuntimeError: If the config is already locked.
    ValueError: If two or more hooks attempt to modify or introduce bindings for
      the same key. Since it is difficult to control the order in which hooks
      are registered, allowing this could yield unpredictable behavior.
  """
  if config_is_locked():
    raise RuntimeError('Finalize called twice (config already locked).')

  arg_0 = {}
  for arg_1 in _FINALIZE_HOOKS:
    arg_2 = arg_1(_CONFIG)
    if arg_2 is not None:
      for arg_3, arg_4 in six.iteritems(arg_2):
        arg_5 = ParsedBindingKey(arg_3)
        if arg_5 in arg_0:
          arg_6 = 'Received conflicting updates when running {}.'
          raise ValueError(arg_6.format(arg_1))
        arg_0[arg_5] = arg_4

  for arg_5, arg_4 in six.iteritems(arg_0):
    bind_parameter(arg_5, arg_4)

  _set_config_is_locked(True)

A function that should be called after parsing all Gin config files.

  Calling this function allows registered "finalize hooks" to inspect (and
  potentially modify) the Gin config, to provide additional functionality. Hooks
  should not modify the configuration object they receive directly; instead,
  they should return a dictionary mapping Gin binding keys to (new or updated)
  values. This way, all hooks see the config as originally parsed.

  Raises:
    RuntimeError: If the config is already locked.
    ValueError: If two or more hooks attempt to modify or introduce bindings for
      the same key. Since it is difficult to control the order in which hooks
      are registered, allowing this could yield unpredictable behavior.

A function that should be called after parsing all Gin config files .


def Func ( arg_0 , arg_1 , arg_2 , * arg_3 ) : arg_4 = iph_id_re . search ( arg_2 [ arg_1 . slug ] ) if arg_4 : arg_2 [ 'iph_id' ] = arg_4 . groupdict ( ) [ 'iph_id' ] return arg_2

def Func(arg_0, arg_1, arg_2, *arg_3):
    """
    mBank Collect uses ID IPH to distinguish between virtual accounts,
    adding iph_id may be helpful in further processing
    """
    arg_4 = iph_id_re.search(arg_2[arg_1.slug])

    if arg_4:  # pragma no branch
        arg_2['iph_id'] = arg_4.groupdict()['iph_id']

    return arg_2

mBank Collect uses ID IPH to distinguish between virtual accounts adding iph_id may be helpful in further processing


def
Func
(
arg_0
,
arg_1
)
:
Func
=
if
arg_1
in
arg_0
.
_users
:
return
arg_0
.
_users
[
arg_1
]
arg_3
=
urijoin
(
arg_0
.
base_url
,
'users'
,
arg_1
)
logging
.
info
(
"Getting info for %s"
%
(
arg_3
)
)
arg_4
=
arg_0
.
fetch
(
arg_3
)
Func
=
arg_4
.
text
arg_0
.
_users
[
arg_1
]
=
Func
return
Func

def Func(arg_0, arg_1):
        """Get the user information and update the user cache"""
        Func = None

        if arg_1 in arg_0._users:
            return arg_0._users[arg_1]

        arg_3 = urijoin(arg_0.base_url, 'users', arg_1)

        logging.info("Getting info for %s" % (arg_3))

        arg_4 = arg_0.fetch(arg_3)
        Func = arg_4.text
        arg_0._users[arg_1] = Func

        return Func


def Func ( arg_0 , arg_1 ) : arg_2 = { } arg_3 = 'cache-control' if 'Cache-Control' in arg_1 : arg_3 = 'Cache-Control' if arg_3 in arg_1 : arg_4 = arg_1 [ arg_3 ] . split ( ',' ) arg_5 = [ tuple ( [ x . strip ( ) . lower ( ) for x in part . split ( "=" , 1 ) ] ) for part in arg_4 if - 1 != part . find ( "=" ) ] arg_6 = [ ( name . strip ( ) . lower ( ) , 1 ) for name in arg_4 if - 1 == name . find ( "=" ) ] arg_2 = dict ( arg_5 + arg_6 ) return arg_2

def Func(arg_0, arg_1):
        """
        Parse the cache control headers returning a dictionary with values
        for the different directives.
        """
        arg_2 = {}

        arg_3 = 'cache-control'
        if 'Cache-Control' in arg_1:
            arg_3 = 'Cache-Control'

        if arg_3 in arg_1:
            arg_4 = arg_1[arg_3].split(',')
            arg_5 = [
                tuple([x.strip().lower() for x in part.split("=", 1)])
                for part in arg_4 if -1 != part.find("=")
            ]
            arg_6 = [
                (name.strip().lower(), 1)
                for name in arg_4 if -1 == name.find("=")
            ]
            arg_2 = dict(arg_5 + arg_6)
        return arg_2

Parse the cache control headers returning a dictionary with values for the different directives .


def Func(arg_0, arg_1, arg_2=25):
    """
    Reynold number utility function that return Reynold number for vehicle at specific length and speed.
    Optionally, it can also take account of temperature effect of sea water.

        Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf

    :param length: metres length of the vehicle
    :param speed: m/s speed of the vehicle
    :param temperature: degree C
    :return: Reynolds number of the vehicle (dimensionless)
    """
    arg_3 = interpolate.interp1d([0, 10, 20, 25, 30, 40],
                                               np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7)
    # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf
    arg_4 = arg_0 * arg_1 / arg_3(arg_2)
    return arg_4

Reynold number utility function that return Reynold number for vehicle at specific length and speed . Optionally it can also take account of temperature effect of sea water .


def Func(arg_0, arg_1, arg_2):
        """
            Exploits a single ip, exploit is based on the given operating system.
        """
        arg_3 = None
        if "Windows Server 2008" in arg_2 or "Windows 7" in arg_2:
            arg_3 = subprocess.run(['python2', os.path.join(arg_0.datadir, 'MS17-010', 'eternalblue_exploit7.py'), str(arg_1), os.path.join(arg_0.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        elif "Windows Server 2012" in arg_2 or "Windows 10" in arg_2 or "Windows 8.1" in arg_2:
            arg_3 = subprocess.run(['python2', os.path.join(arg_0.datadir, 'MS17-010', 'eternalblue_exploit8.py'), str(arg_1), os.path.join(arg_0.datadir, 'final_combined.bin'), "12"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            return ["System target could not be automatically identified"]
        return arg_3.stdout.decode('utf-8').split('\n')

Exploits a single ip exploit is based on the given operating system .


def
Func
(
arg_0
,
arg_1
=
True
)
:
try
:
arg_2
=
check_img
(
arg_0
)
if
arg_1
:
return
get_data
(
arg_2
)
else
:
return
arg_2
.
get_data
(
)
except
Exception
as
exc
:
raise
Exception
(
'Error when reading file {0}.'
.
format
(
repr_imgs
(
arg_0
)
)
)
from
exc

def Func(arg_0, arg_1=True):
    """Return the voxel matrix of the Nifti file.
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    copy: bool
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Returns
    -------
    array_like
    """
    try:
        arg_2 = check_img(arg_0)
        if arg_1:
            return get_data(arg_2)
        else:
            return arg_2.get_data()
    except Exception as exc:
        raise Exception('Error when reading file {0}.'.format(repr_imgs(arg_0))) from exc

Return the voxel matrix of the Nifti file . If safe_mode will make a copy of the img before returning the data so the input image is not modified .


def Func ( arg_0 , arg_1 , arg_2 ) : arg_0 . _valid_group_id ( arg_1 ) arg_2 = re . sub ( '@washington.edu' , '' , arg_2 ) arg_3 = "{}/group/{}/effective_member/{}" . format ( arg_0 . API , arg_1 , arg_2 ) try : arg_4 = arg_0 . _get_resource ( arg_3 ) return True except DataFailureException as ex : if ex . status == 404 : return False else : raise

def Func(arg_0, arg_1, arg_2):
        """
        Returns True if the netid is in the group, False otherwise.
        """
        arg_0._valid_group_id(arg_1)

        # GWS doesn't accept EPPNs on effective member checks, for UW users
        arg_2 = re.sub('@washington.edu', '', arg_2)

        arg_3 = "{}/group/{}/effective_member/{}".format(arg_0.API,
                                                       arg_1,
                                                       arg_2)

        try:
            arg_4 = arg_0._get_resource(arg_3)
            return True  # 200
        except DataFailureException as ex:
            if ex.status == 404:
                return False
            else:
                raise

Returns True if the netid is in the group False otherwise .


def Func ( arg_0 , arg_1 , arg_2 = None ) : arg_0 . grammar = arg_0 . _load ( arg_1 , arg_2 = arg_2 ) arg_0 . refs = { } for arg_4 in arg_0 . grammar . getElementsByTagName ( "ref" ) : arg_0 . refs [ arg_4 . attributes [ "id" ] . value ] = arg_4

def Func(arg_0, arg_1, arg_2=None):
        """load context-free grammar"""
        arg_0.grammar = arg_0._load(arg_1, arg_2=arg_2)
        arg_0.refs = {}
        for arg_4 in arg_0.grammar.getElementsByTagName("ref"):
            arg_0.refs[arg_4.attributes["id"].value] = arg_4


Same as `_close` but expects `lock` acquired.

def Func ( arg_0 ) : if arg_0 . _state != "closed" : arg_0 . event ( DisconnectedEvent ( arg_0 . _dst_addr ) ) arg_0 . _set_state ( "closed" ) if arg_0 . _socket is None : return try : arg_0 . _socket . shutdown ( socket . SHUT_RDWR ) except socket . error : pass arg_0 . _socket . close ( ) arg_0 . _socket = None arg_0 . _write_queue . clear ( ) arg_0 . _write_queue_cond . notify ( )

def Func(arg_0):
        """Same as `Func` but expects `lock` acquired.
        """
        if arg_0._state != "closed":
            arg_0.event(DisconnectedEvent(arg_0._dst_addr))
            arg_0._set_state("closed")
        if arg_0._socket is None:
            return
        try:
            arg_0._socket.shutdown(socket.SHUT_RDWR)
        except socket.error:
            pass
        arg_0._socket.close()
        arg_0._socket = None
        arg_0._write_queue.clear()
        arg_0._write_queue_cond.notify()

Same as _close but expects lock acquired .


def Func ( arg_0 ) : for arg_1 , arg_2 in arg_0 . layers : arg_1 . Func ( ) arg_0 . layers = [ ] arg_0 . _layers = { } super ( LayeredWidget , arg_0 ) . Func ( )

def Func(arg_0):
        """
        Deletes all layers within this LayeredWidget before deleting itself.

        Recommended to call if you are removing the widget, but not yet exiting the interpreter.
        """
        for arg_1,arg_2 in arg_0.layers:
            arg_1.Func()
        arg_0.layers = []
        arg_0._layers = {}
        super(LayeredWidget,arg_0).Func()

Deletes all layers within this LayeredWidget before deleting itself . Recommended to call if you are removing the widget but not yet exiting the interpreter .


def Func(arg_0, arg_1):
    """
    Return a basis state ndarray.

    Args:
        str_state (string): a string representing the state.
        num (int): the number of qubits
    Returns:
        ndarray:  state(2**num) a quantum state with basis basis state.
     Raises:
        QiskitError: if the dimensions is wrong
    """
    arg_2 = int(arg_0, 2)
    if arg_1 >= len(arg_0):
        arg_3 = np.zeros(1 << arg_1, dtype=complex)
        arg_3[arg_2] = 1
        return arg_3
    else:
        raise QiskitError('size of bitstring is greater than num.')


return c == ESCAPE or not (' ' <= c <= '~')

def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
if
arg_0
in
' \t'
:
return
arg_1
if
arg_0
==
'_'
:
return
arg_2
return
arg_0
==
ESCAPE
or
not
(
' '
<=
arg_0
<=
'~'
)

def Func(arg_0, arg_1, arg_2):
    """Decide whether a particular character needs to be quoted.

    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always encoded, as per
    RFC 1521.
    """
    if arg_0 in ' \t':
        return arg_1
    # if header, we have to escape _ because _ is used to escape space
    if arg_0 == '_':
        return arg_2
    return arg_0 == ESCAPE or not (' ' <= arg_0 <= '~')

Decide whether a particular character needs to be quoted .


def Func ( arg_0 , arg_1 , arg_2 ) : with open ( temple . constants . TEMPLE_CONFIG_FILE , 'w' ) as temple_config_file : arg_3 = { ** arg_0 , ** { '_version' : arg_2 , '_template' : arg_1 } , } yaml . dump ( arg_3 , temple_config_file , Dumper = yaml . SafeDumper )

def Func(arg_0, arg_1, arg_2):
    """Writes the temple YAML configuration"""
    with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file:
        arg_3 = {
            **arg_0,
            **{'_version': arg_2, '_template': arg_1},
        }
        yaml.dump(arg_3, temple_config_file, Dumper=yaml.SafeDumper)


def Func ( arg_0 , arg_1 , arg_2 = { } ) : arg_3 = arg_2 . get ( "include" , [ ] ) if "term" not in arg_3 : arg_3 . append ( "term" ) arg_2 [ "include" ] = arg_3 arg_4 = COURSES_API . format ( arg_1 ) return CanvasCourse ( data = arg_0 . _get_resource ( arg_4 , arg_2 = arg_2 ) )

def Func(arg_0, arg_1, arg_2={}):
        """
        Return course resource for given canvas course id.

        https://canvas.instructure.com/doc/api/courses.html#method.courses.show
        """
        arg_3 = arg_2.get("include", [])
        if "term" not in arg_3:
            arg_3.append("term")
        arg_2["include"] = arg_3

        arg_4 = COURSES_API.format(arg_1)
        return CanvasCourse(data=arg_0._get_resource(arg_4, arg_2=arg_2))

Return course resource for given canvas course id .


def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
,
arg_4
,
arg_5
)
:
if
arg_5
==
SIMPLE
:
arg_6
=
[
i
(
arg_1
)
for
i
in
arg_0
.
HeatCapacityLiquids
]
return
mixing_simple
(
arg_3
,
arg_6
)
elif
arg_5
==
LALIBERTE
:
arg_4
=
list
(
arg_4
)
arg_4
.
pop
(
arg_0
.
index_w
)
arg_7
=
Laliberte_heat_capacity
(
arg_1
,
arg_4
,
arg_0
.
wCASs
)
arg_8
=
mixing_simple
(
arg_3
,
arg_0
.
MWs
)
return
property_mass_to_molar
(
arg_7
,
arg_8
)
else
:
raise
Exception
(
'Method not valid'
)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        r'''Method to Func heat capacity of a liquid mixture at
        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
        `ws` with a given method.

        This method has no exception handling; see `mixture_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at which to Func the property, [K]
        P : float
            Pressure at which to Func the property, [Pa]
        zs : list[float]
            Mole fractions of all species in the mixture, [-]
        ws : list[float]
            Weight fractions of all species in the mixture, [-]
        method : str
            Name of the method to use

        Returns
        -------
        Cplm : float
            Molar heat capacity of the liquid mixture at the given conditions,
            [J/mol]
        '''
        if arg_5 == SIMPLE:
            arg_6 = [i(arg_1) for i in arg_0.HeatCapacityLiquids]
            return mixing_simple(arg_3, arg_6)
        elif arg_5 == LALIBERTE:
            arg_4 = list(arg_4) ; arg_4.pop(arg_0.index_w)
            arg_7 = Laliberte_heat_capacity(arg_1, arg_4, arg_0.wCASs)
            arg_8 = mixing_simple(arg_3, arg_0.MWs)
            return property_mass_to_molar(arg_7, arg_8)
        else:
            raise Exception('Method not valid')

r'''Method to calculate heat capacity of a liquid mixture at
        temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
        `ws` with a given method.

        This method has no exception handling; see `mixture_property`
        for that.

        Parameters
        ----------
        T : float
            Temperature at which to calculate the property, [K]
        P : float
            Pressure at which to calculate the property, [Pa]
        zs : list[float]
            Mole fractions of all species in the mixture, [-]
        ws : list[float]
            Weight fractions of all species in the mixture, [-]
        method : str
            Name of the method to use

        Returns
        -------
        Cplm : float
            Molar heat capacity of the liquid mixture at the given conditions,
            [J/mol]

r Method to calculate heat capacity of a liquid mixture at temperature T pressure P mole fractions zs and weight fractions ws with a given method .


(self, workflow_spec, read_only=False, **kwargs)

return BpmnWorkflow(workflow_spec, read_only=read_only, **kwargs)

def Func ( arg_0 , arg_1 , arg_2 = False , ** arg_3 ) : return BpmnWorkflow ( arg_1 , arg_2 = arg_2 , ** arg_3 )

def Func(arg_0, arg_1, arg_2=False, **arg_3):
        """
        Create a new workflow instance from the given spec and arguments.

        :param workflow_spec: the workflow spec to use

        :param read_only: this should be in read only mode

        :param kwargs: Any extra kwargs passed to the deserialize_workflow
        method will be passed through here
        """
        return BpmnWorkflow(arg_1, arg_2=arg_2, **arg_3)

Create a new workflow instance from the given spec and arguments .


def
Func
(
arg_0
,
arg_1
,
arg_2
=
False
)
:
arg_3
=
arg_2
and
_sudo
or
_run
with
arg_0
.
settings
(
hide
(
'running'
,
'warnings'
)
,
warn_only
=
True
)
:
return
arg_3
(
'[ -L "%(path)s" ]'
%
locals
(
)
)
.
succeeded

def Func(arg_0, arg_1, arg_2=False):
        """
        Check if a path exists, and is a symbolic link.
        """
        arg_3 = arg_2 and _sudo or _run
        with arg_0.settings(hide('running', 'warnings'), warn_only=True):
            return arg_3('[ -L "%(path)s" ]' % locals()).succeeded

Check if a path exists and is a symbolic link .


def Func(arg_0, arg_1=1):
        """Acquire a semaphore, decrementing the internal counter by one.

        When invoked without arguments: if the internal counter is larger than
        zero on entry, decrement it by one and return immediately. If it is zero
        on entry, block, waiting until some other thread has called release() to
        make it larger than zero. This is done with proper interlocking so that
        if multiple Func() calls are blocked, release() will wake exactly one
        of them up. The implementation may pick one at random, so the order in
        which blocked threads are awakened should not be relied on. There is no
        return value in this case.

        When invoked with blocking set to true, do the same thing as when called
        without arguments, and return true.

        When invoked with blocking set to false, do not block. If a call without
        an argument would block, return false immediately; otherwise, do the
        same thing as when called without arguments, and return true.

        """
        arg_2 = False
        with arg_0.__cond:
            while arg_0.__value == 0:
                if not arg_1:
                    break
                if __debug__:
                    arg_0._note("%s.Func(%s): blocked waiting, value=%s",
                            arg_0, arg_1, arg_0.__value)
                arg_0.__cond.wait()
            else:
                arg_0.__value = arg_0.__value - 1
                if __debug__:
                    arg_0._note("%s.Func: success, value=%s",
                            arg_0, arg_0.__value)
                arg_2 = True
        return arg_2

Acquire a semaphore, decrementing the internal counter by one.

        When invoked without arguments: if the internal counter is larger than
        zero on entry, decrement it by one and return immediately. If it is zero
        on entry, block, waiting until some other thread has called release() to
        make it larger than zero. This is done with proper interlocking so that
        if multiple acquire() calls are blocked, release() will wake exactly one
        of them up. The implementation may pick one at random, so the order in
        which blocked threads are awakened should not be relied on. There is no
        return value in this case.

        When invoked with blocking set to true, do the same thing as when called
        without arguments, and return true.

        When invoked with blocking set to false, do not block. If a call without
        an argument would block, return false immediately; otherwise, do the
        same thing as when called without arguments, and return true.

Acquire a semaphore decrementing the internal counter by one .


def Func ( arg_0 , arg_1 = 0 , arg_2 = 1 ) : arg_3 = ( KeyGenerator ( arg_0 . seed ) . Func ( arg_1 , arg_2 , arg_0 . security_level , ) ) while True : yield arg_0 . _generate_address ( arg_3 )

def Func(arg_0, arg_1=0, arg_2=1):
        # type: (int, int) -> Generator[Address, None, None]
        """
        Creates an iterator that can be used to progressively generate new
        addresses.

        :param start:
            Starting index.

            Warning: This method may take awhile to reset if ``start``
            is a large number!

        :param step:
            Number of indexes to advance after each address.

            Warning: The generator may take awhile to advance between
            iterations if ``step`` is a large number!
        """
        arg_3 = (
            KeyGenerator(arg_0.seed).Func(
                arg_1,
                arg_2,
                arg_0.security_level,
            )
        )

        while True:
            yield arg_0._generate_address(arg_3)

Creates an iterator that can be used to progressively generate new addresses .


def Func ( arg_0 , arg_1 , arg_2 = None ) : if arg_0 . current_app_is_admin ( ) : return arg_1 arg_3 = [ ] arg_4 = arg_0 . current_page_context arg_5 = arg_0 . check_access for arg_6 in arg_1 : if arg_6 . hidden : continue if not arg_5 ( arg_6 , arg_4 ) : continue if not getattr ( arg_6 , 'in%s' % arg_2 , True ) : continue arg_3 . append ( arg_6 ) return arg_3

def Func(arg_0, arg_1, arg_2=None):
        """Filters sitetree item's children if hidden and by navigation type.

        NB: We do not apply any filters to sitetree in admin app.

        :param list items:
        :param str|unicode navigation_type: sitetree, breadcrumbs, menu
        :rtype: list
        """
        if arg_0.current_app_is_admin():
            return arg_1

        arg_3 = []

        arg_4 = arg_0.current_page_context
        arg_5 = arg_0.check_access

        for arg_6 in arg_1:
            if arg_6.hidden:
                continue

            if not arg_5(arg_6, arg_4):
                continue

            if not getattr(arg_6, 'in%s' % arg_2, True):  # Hidden for current nav type
                continue

            arg_3.append(arg_6)

        return arg_3

Filters sitetree item s children if hidden and by navigation type .


def Func ( ) : request_created . connect ( send_email_validation ) request_confirmed . connect ( send_confirmed_notifications ) request_rejected . connect ( send_reject_notification ) request_accepted . connect ( create_secret_link ) request_accepted . connect ( send_accept_notification )

def Func():
    """Connect receivers to signals."""
    request_created.connect(send_email_validation)
    request_confirmed.connect(send_confirmed_notifications)
    request_rejected.connect(send_reject_notification)
    # Order is important:
    request_accepted.connect(create_secret_link)
    request_accepted.connect(send_accept_notification)


def Func ( arg_0 ) : arg_1 = arg_0 . _control . textCursor ( ) arg_1 . movePosition ( QtGui . QTextCursor . End ) return arg_1

def Func(arg_0):
        """ Convenience method that returns a cursor for the last character.
        """
        arg_1 = arg_0._control.textCursor()
        arg_1.movePosition(QtGui.QTextCursor.End)
        return arg_1

Convenience method that returns a cursor for the last character .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . size / arg_1 arg_3 = np . array ( np . reshape ( arg_0 , ( arg_2 , arg_1 ) ) ) return np . mean ( arg_3 [ : , 2 : - 1 ] , axis = 1 )

def Func(arg_0,arg_1):
    '''
    Converts a data array with length n_chans to an array of length n_coarse_chans
    by averaging over the coarse channels
    '''
    #find number of coarse channels and reshape array
    arg_2 = arg_0.size/arg_1
    arg_3 = np.array(np.reshape(arg_0,(arg_2,arg_1)))

    #Return the average over each coarse channel
    return np.mean(arg_3[:,2:-1],axis=1)


def Func ( arg_0 , arg_1 ) : if arg_0 . finished is not None : raise AlreadyFinished ( ) arg_2 = arg_0 . _get_step ( arg_1 ) if arg_2 is not None : if 'stop' in arg_2 : raise StepAlreadyFinished ( ) else : raise StepAlreadyStarted ( ) arg_3 = copy . deepcopy ( arg_0 . steps ) arg_3 . append ( { "start" : datetime . utcnow ( ) , "name" : arg_1 } ) arg_0 . _save ( arg_3 = arg_3 )

def Func(arg_0, arg_1):
        """ Start a step. """
        if arg_0.finished is not None:
            raise AlreadyFinished()

        arg_2 = arg_0._get_step(arg_1)
        if arg_2 is not None:
            if 'stop' in arg_2:
                raise StepAlreadyFinished()
            else:
                raise StepAlreadyStarted()

        arg_3 = copy.deepcopy(arg_0.steps)
        arg_3.append({
            "start": datetime.utcnow(),
            "name": arg_1
        })
        arg_0._save(arg_3=arg_3)