code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def reset(self):
""" Mark all dead proxies as unchecked """
for proxy in list(self.dead):
self.dead.remove(proxy)
self.unchecked.add(proxy) | def function[reset, parameter[self]]:
constant[ Mark all dead proxies as unchecked ]
for taget[name[proxy]] in starred[call[name[list], parameter[name[self].dead]]] begin[:]
call[name[self].dead.remove, parameter[name[proxy]]]
call[name[self].unchecked.add, parameter[name... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
keyword[for] identifier[proxy] keyword[in] identifier[list] ( identifier[self] . identifier[dead] ):
identifier[self] . identifier[dead] . identifier[remove] ( identifier[proxy] )
identifier[self] . id... | def reset(self):
""" Mark all dead proxies as unchecked """
for proxy in list(self.dead):
self.dead.remove(proxy)
self.unchecked.add(proxy) # depends on [control=['for'], data=['proxy']] |
def _decode_next_layer(self, dict_, proto=None, length=None, *, version=4, ipv6_exthdr=None):
"""Decode next layer extractor.
Positional arguments:
* dict_ -- dict, info buffer
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
... | def function[_decode_next_layer, parameter[self, dict_, proto, length]]:
constant[Decode next layer extractor.
Positional arguments:
* dict_ -- dict, info buffer
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword Arg... | keyword[def] identifier[_decode_next_layer] ( identifier[self] , identifier[dict_] , identifier[proto] = keyword[None] , identifier[length] = keyword[None] ,*, identifier[version] = literal[int] , identifier[ipv6_exthdr] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[... | def _decode_next_layer(self, dict_, proto=None, length=None, *, version=4, ipv6_exthdr=None):
"""Decode next layer extractor.
Positional arguments:
* dict_ -- dict, info buffer
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
... |
def assets(self):
"""
Access the assets
:returns: twilio.rest.serverless.v1.service.asset.AssetList
:rtype: twilio.rest.serverless.v1.service.asset.AssetList
"""
if self._assets is None:
self._assets = AssetList(self._version, service_sid=self._solution['sid'... | def function[assets, parameter[self]]:
constant[
Access the assets
:returns: twilio.rest.serverless.v1.service.asset.AssetList
:rtype: twilio.rest.serverless.v1.service.asset.AssetList
]
if compare[name[self]._assets is constant[None]] begin[:]
name[self]... | keyword[def] identifier[assets] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_assets] keyword[is] keyword[None] :
identifier[self] . identifier[_assets] = identifier[AssetList] ( identifier[self] . identifier[_version] , identifier[service_sid] = i... | def assets(self):
"""
Access the assets
:returns: twilio.rest.serverless.v1.service.asset.AssetList
:rtype: twilio.rest.serverless.v1.service.asset.AssetList
"""
if self._assets is None:
self._assets = AssetList(self._version, service_sid=self._solution['sid']) # depend... |
def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile,
thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC):
"""
Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
... | def function[__RetrieveContent, parameter[host, port, adapter, version, path, keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout]]:
constant[
Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
@type port: int
@p... | keyword[def] identifier[__RetrieveContent] ( identifier[host] , identifier[port] , identifier[adapter] , identifier[version] , identifier[path] , identifier[keyFile] , identifier[certFile] ,
identifier[thumbprint] , identifier[sslContext] , identifier[connectionPoolTimeout] = identifier[CONNECTION_POOL_IDLE_TIMEOUT_... | def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC):
"""
Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
@type port: int
... |
def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | def function[locked, parameter[self, lock]]:
constant[Locks or unlocks the thermostat.]
call[name[_LOGGER].debug, parameter[constant[Setting the lock: %s], name[lock]]]
variable[value] assign[=] call[name[struct].pack, parameter[constant[BB], name[PROP_LOCK], call[name[bool], parameter[name[lock... | keyword[def] identifier[locked] ( identifier[self] , identifier[lock] ):
literal[string]
identifier[_LOGGER] . identifier[debug] ( literal[string] , identifier[lock] )
identifier[value] = identifier[struct] . identifier[pack] ( literal[string] , identifier[PROP_LOCK] , identifier[bool] ( i... | def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug('Setting the lock: %s', lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) |
def entrance_distance(Di, t=None, l=None, method='Rennels'):
r'''Returns the loss coefficient for a sharp entrance to a pipe at a distance
from the wall of a reservoir. This calculation has five methods available;
all but 'Idelchik' require the pipe to be at least `Di/2` into the
reservoir.
The mos... | def function[entrance_distance, parameter[Di, t, l, method]]:
constant[Returns the loss coefficient for a sharp entrance to a pipe at a distance
from the wall of a reservoir. This calculation has five methods available;
all but 'Idelchik' require the pipe to be at least `Di/2` into the
reservoir.
... | keyword[def] identifier[entrance_distance] ( identifier[Di] , identifier[t] = keyword[None] , identifier[l] = keyword[None] , identifier[method] = literal[string] ):
literal[string]
keyword[if] identifier[method] keyword[is] keyword[None] :
identifier[method] = literal[string]
keyword[if]... | def entrance_distance(Di, t=None, l=None, method='Rennels'):
"""Returns the loss coefficient for a sharp entrance to a pipe at a distance
from the wall of a reservoir. This calculation has five methods available;
all but 'Idelchik' require the pipe to be at least `Di/2` into the
reservoir.
The most... |
def _create_hunt(self, name, args):
"""Create specified hunt.
Args:
name: string containing hunt name.
args: proto (*FlowArgs) for type of hunt, as defined in GRR flow proto.
Returns:
The newly created GRR hunt object.
Raises:
ValueError: if approval is needed and approvers we... | def function[_create_hunt, parameter[self, name, args]]:
constant[Create specified hunt.
Args:
name: string containing hunt name.
args: proto (*FlowArgs) for type of hunt, as defined in GRR flow proto.
Returns:
The newly created GRR hunt object.
Raises:
ValueError: if appr... | keyword[def] identifier[_create_hunt] ( identifier[self] , identifier[name] , identifier[args] ):
literal[string]
identifier[runner_args] = identifier[self] . identifier[grr_api] . identifier[types] . identifier[CreateHuntRunnerArgs] ()
identifier[runner_args] . identifier[description] = identifier[se... | def _create_hunt(self, name, args):
"""Create specified hunt.
Args:
name: string containing hunt name.
args: proto (*FlowArgs) for type of hunt, as defined in GRR flow proto.
Returns:
The newly created GRR hunt object.
Raises:
ValueError: if approval is needed and approvers we... |
def ping(self, targets=list(), filename=str(), status=str()):
"""
Attempt to ping a list of hosts or networks (can be a single host)
:param targets: List - Name(s) or IP(s) of the host(s).
:param filename: String - name of the file containing hosts to ping
:param status: String -... | def function[ping, parameter[self, targets, filename, status]]:
constant[
Attempt to ping a list of hosts or networks (can be a single host)
:param targets: List - Name(s) or IP(s) of the host(s).
:param filename: String - name of the file containing hosts to ping
:param status: ... | keyword[def] identifier[ping] ( identifier[self] , identifier[targets] = identifier[list] (), identifier[filename] = identifier[str] (), identifier[status] = identifier[str] ()):
literal[string]
keyword[if] identifier[targets] keyword[and] identifier[filename] :
keyword[raise] ide... | def ping(self, targets=list(), filename=str(), status=str()):
"""
Attempt to ping a list of hosts or networks (can be a single host)
:param targets: List - Name(s) or IP(s) of the host(s).
:param filename: String - name of the file containing hosts to ping
:param status: String - if ... |
def _load_base_class_fields(new_class, bases, attrs):
"""If this class is subclassing another Entity, add that Entity's
fields. Note that we loop over the bases in *reverse*.
This is necessary in order to maintain the correct order of fields.
"""
for base in reversed(bases):
... | def function[_load_base_class_fields, parameter[new_class, bases, attrs]]:
constant[If this class is subclassing another Entity, add that Entity's
fields. Note that we loop over the bases in *reverse*.
This is necessary in order to maintain the correct order of fields.
]
for tag... | keyword[def] identifier[_load_base_class_fields] ( identifier[new_class] , identifier[bases] , identifier[attrs] ):
literal[string]
keyword[for] identifier[base] keyword[in] identifier[reversed] ( identifier[bases] ):
keyword[if] identifier[hasattr] ( identifier[base] , literal[str... | def _load_base_class_fields(new_class, bases, attrs):
"""If this class is subclassing another Entity, add that Entity's
fields. Note that we loop over the bases in *reverse*.
This is necessary in order to maintain the correct order of fields.
"""
for base in reversed(bases):
if ... |
def name(self):
"""
The name of the functional. If the functional is not found in the aliases,
the string has the form X_NAME+C_NAME
"""
if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].name
xc = (self.x, self.c)
if xc in self.defined_alias... | def function[name, parameter[self]]:
constant[
The name of the functional. If the functional is not found in the aliases,
the string has the form X_NAME+C_NAME
]
if compare[name[self].xc in name[self].defined_aliases] begin[:]
return[call[name[self].defined_aliases][name[... | keyword[def] identifier[name] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[xc] keyword[in] identifier[self] . identifier[defined_aliases] : keyword[return] identifier[self] . identifier[defined_aliases] [ identifier[self] . identifier[xc] ]. identifier[name]
... | def name(self):
"""
The name of the functional. If the functional is not found in the aliases,
the string has the form X_NAME+C_NAME
"""
if self.xc in self.defined_aliases:
return self.defined_aliases[self.xc].name # depends on [control=['if'], data=[]]
xc = (self.x, self.c)... |
def func_args(func):
'''Basic function which returns a tuple of arguments of a function or
method.
'''
try:
return tuple(inspect.signature(func).parameters)
except:
return tuple(inspect.getargspec(func).args) | def function[func_args, parameter[func]]:
constant[Basic function which returns a tuple of arguments of a function or
method.
]
<ast.Try object at 0x7da1b11c4eb0> | keyword[def] identifier[func_args] ( identifier[func] ):
literal[string]
keyword[try] :
keyword[return] identifier[tuple] ( identifier[inspect] . identifier[signature] ( identifier[func] ). identifier[parameters] )
keyword[except] :
keyword[return] identifier[tuple] ( identifier[in... | def func_args(func):
"""Basic function which returns a tuple of arguments of a function or
method.
"""
try:
return tuple(inspect.signature(func).parameters) # depends on [control=['try'], data=[]]
except:
return tuple(inspect.getargspec(func).args) # depends on [control=['except'],... |
def getResultsInterpretationByDepartment(self, department=None):
"""Returns the results interpretation for this Analysis Request
and department. If department not set, returns the results
interpretation tagged as 'General'.
:returns: a dict with the following keys:
{'u... | def function[getResultsInterpretationByDepartment, parameter[self, department]]:
constant[Returns the results interpretation for this Analysis Request
and department. If department not set, returns the results
interpretation tagged as 'General'.
:returns: a dict with the following... | keyword[def] identifier[getResultsInterpretationByDepartment] ( identifier[self] , identifier[department] = keyword[None] ):
literal[string]
identifier[uid] = identifier[department] . identifier[UID] () keyword[if] identifier[department] keyword[else] literal[string]
identifier[rows] =... | def getResultsInterpretationByDepartment(self, department=None):
"""Returns the results interpretation for this Analysis Request
and department. If department not set, returns the results
interpretation tagged as 'General'.
:returns: a dict with the following keys:
{'uid':... |
def compute_K_analytical(self, spacing):
"""Compute geometrical factors over the homogeneous half-space with a
constant electrode spacing
"""
K = redaK.compute_K_analytical(self.data, spacing=spacing)
self.data = redaK.apply_K(self.data, K)
redafixK.fix_sign_with_K(self.d... | def function[compute_K_analytical, parameter[self, spacing]]:
constant[Compute geometrical factors over the homogeneous half-space with a
constant electrode spacing
]
variable[K] assign[=] call[name[redaK].compute_K_analytical, parameter[name[self].data]]
name[self].data assign[=... | keyword[def] identifier[compute_K_analytical] ( identifier[self] , identifier[spacing] ):
literal[string]
identifier[K] = identifier[redaK] . identifier[compute_K_analytical] ( identifier[self] . identifier[data] , identifier[spacing] = identifier[spacing] )
identifier[self] . identifier[d... | def compute_K_analytical(self, spacing):
"""Compute geometrical factors over the homogeneous half-space with a
constant electrode spacing
"""
K = redaK.compute_K_analytical(self.data, spacing=spacing)
self.data = redaK.apply_K(self.data, K)
redafixK.fix_sign_with_K(self.data) |
def calculate_diagram_ranges(data):
"""
Given a numpy array calculate what the ranges of the H-R
diagram should be.
"""
data = round_arr_teff_luminosity(data)
temps = data['temp']
x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)]
lums = data['lum']
y_range = [.50 * np.amin(lums... | def function[calculate_diagram_ranges, parameter[data]]:
constant[
Given a numpy array calculate what the ranges of the H-R
diagram should be.
]
variable[data] assign[=] call[name[round_arr_teff_luminosity], parameter[name[data]]]
variable[temps] assign[=] call[name[data]][constant[t... | keyword[def] identifier[calculate_diagram_ranges] ( identifier[data] ):
literal[string]
identifier[data] = identifier[round_arr_teff_luminosity] ( identifier[data] )
identifier[temps] = identifier[data] [ literal[string] ]
identifier[x_range] =[ literal[int] * identifier[np] . identifier[amax] ( ... | def calculate_diagram_ranges(data):
"""
Given a numpy array calculate what the ranges of the H-R
diagram should be.
"""
data = round_arr_teff_luminosity(data)
temps = data['temp']
x_range = [1.05 * np.amax(temps), 0.95 * np.amin(temps)]
lums = data['lum']
y_range = [0.5 * np.amin(lum... |
def get_pub_date(self, undefined=""):
"""
Args:
undefined (optional): Argument, which will be returned if the
`pub_date` record is not found.
Returns:
str: Date of publication (month and year usually) or `undefined` \
if `pub_date` ... | def function[get_pub_date, parameter[self, undefined]]:
constant[
Args:
undefined (optional): Argument, which will be returned if the
`pub_date` record is not found.
Returns:
str: Date of publication (month and year usually) or `undefined` ... | keyword[def] identifier[get_pub_date] ( identifier[self] , identifier[undefined] = literal[string] ):
literal[string]
identifier[dates] = identifier[self] [ literal[string] ]+ identifier[self] [ literal[string] ]
keyword[def] identifier[clean_date] ( identifier[date] ):
lite... | def get_pub_date(self, undefined=''):
"""
Args:
undefined (optional): Argument, which will be returned if the
`pub_date` record is not found.
Returns:
str: Date of publication (month and year usually) or `undefined` if `pub_date` is not... |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Write the AttributeReference structure encoding to the data stream.
Args:
output_buffer (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
... | def function[write, parameter[self, output_buffer, kmip_version]]:
constant[
Write the AttributeReference structure encoding to the data stream.
Args:
output_buffer (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
... | keyword[def] identifier[write] ( identifier[self] , identifier[output_buffer] , identifier[kmip_version] = identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_2_0] ):
literal[string]
keyword[if] identifier[kmip_version] < identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_2_0]... | def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Write the AttributeReference structure encoding to the data stream.
Args:
output_buffer (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
... |
def rlmb_base_stochastic():
"""Base setting with a stochastic next-frame model."""
hparams = rlmb_base()
hparams.initial_epoch_train_steps_multiplier = 5
hparams.generative_model = "next_frame_basic_stochastic"
hparams.generative_model_params = "next_frame_basic_stochastic"
return hparams | def function[rlmb_base_stochastic, parameter[]]:
constant[Base setting with a stochastic next-frame model.]
variable[hparams] assign[=] call[name[rlmb_base], parameter[]]
name[hparams].initial_epoch_train_steps_multiplier assign[=] constant[5]
name[hparams].generative_model assign[=] con... | keyword[def] identifier[rlmb_base_stochastic] ():
literal[string]
identifier[hparams] = identifier[rlmb_base] ()
identifier[hparams] . identifier[initial_epoch_train_steps_multiplier] = literal[int]
identifier[hparams] . identifier[generative_model] = literal[string]
identifier[hparams] . identifier... | def rlmb_base_stochastic():
"""Base setting with a stochastic next-frame model."""
hparams = rlmb_base()
hparams.initial_epoch_train_steps_multiplier = 5
hparams.generative_model = 'next_frame_basic_stochastic'
hparams.generative_model_params = 'next_frame_basic_stochastic'
return hparams |
def create_admin(ctx):
"""Creates a new local user and assigns admin role"""
try:
admin = _create_user(ctx)
admin.roles.append('admin')
admin.save()
log("Done")
except KeyError:
log('User already exists', lvl=warn) | def function[create_admin, parameter[ctx]]:
constant[Creates a new local user and assigns admin role]
<ast.Try object at 0x7da1b0fe9e70> | keyword[def] identifier[create_admin] ( identifier[ctx] ):
literal[string]
keyword[try] :
identifier[admin] = identifier[_create_user] ( identifier[ctx] )
identifier[admin] . identifier[roles] . identifier[append] ( literal[string] )
identifier[admin] . identifier[save] ()
... | def create_admin(ctx):
"""Creates a new local user and assigns admin role"""
try:
admin = _create_user(ctx)
admin.roles.append('admin')
admin.save()
log('Done') # depends on [control=['try'], data=[]]
except KeyError:
log('User already exists', lvl=warn) # depends o... |
def score_zernike(zf, radii, labels, indexes=None):
"""Score the output of construct_zernike_polynomials
zf - the output of construct_zernike_polynomials which is I x J x K
where K is the number of zernike polynomials computed
radii - a vector of the radius of each of N labeled objects
lab... | def function[score_zernike, parameter[zf, radii, labels, indexes]]:
constant[Score the output of construct_zernike_polynomials
zf - the output of construct_zernike_polynomials which is I x J x K
where K is the number of zernike polynomials computed
radii - a vector of the radius of each of... | keyword[def] identifier[score_zernike] ( identifier[zf] , identifier[radii] , identifier[labels] , identifier[indexes] = keyword[None] ):
literal[string]
keyword[if] identifier[indexes] keyword[is] keyword[None] :
identifier[indexes] = identifier[np] . identifier[arange] ( literal[int] , identi... | def score_zernike(zf, radii, labels, indexes=None):
"""Score the output of construct_zernike_polynomials
zf - the output of construct_zernike_polynomials which is I x J x K
where K is the number of zernike polynomials computed
radii - a vector of the radius of each of N labeled objects
lab... |
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
''' use bet to strip skull from given anatomy '''
# should add options to use betsurf and T1/T2 in the future
# Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :)
if ... | def function[skull_strip, parameter[dset, suffix, prefix, unifize]]:
constant[ use bet to strip skull from given anatomy ]
if compare[name[prefix] equal[==] constant[None]] begin[:]
variable[prefix] assign[=] call[name[nl].suffix, parameter[name[dset], name[suffix]]]
variable[uni... | keyword[def] identifier[skull_strip] ( identifier[dset] , identifier[suffix] = literal[string] , identifier[prefix] = keyword[None] , identifier[unifize] = keyword[True] ):
literal[string]
keyword[if] identifier[prefix] == keyword[None] :
identifier[prefix] = identifier[nl] . identifier... | def skull_strip(dset, suffix='_ns', prefix=None, unifize=True):
""" use bet to strip skull from given anatomy """
# should add options to use betsurf and T1/T2 in the future
# Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :)
... |
def poll(self):
""" Poll the job status.
Returns the changes in this iteration."""
self.runner.module_name = 'async_status'
self.runner.module_args = "jid=%s" % self.jid
self.runner.pattern = "*"
self.runner.background = 0
self.runner.inventory.restrict_to(s... | def function[poll, parameter[self]]:
constant[ Poll the job status.
Returns the changes in this iteration.]
name[self].runner.module_name assign[=] constant[async_status]
name[self].runner.module_args assign[=] binary_operation[constant[jid=%s] <ast.Mod object at 0x7da2590d6920> nam... | keyword[def] identifier[poll] ( identifier[self] ):
literal[string]
identifier[self] . identifier[runner] . identifier[module_name] = literal[string]
identifier[self] . identifier[runner] . identifier[module_args] = literal[string] % identifier[self] . identifier[jid]
identifier... | def poll(self):
""" Poll the job status.
Returns the changes in this iteration."""
self.runner.module_name = 'async_status'
self.runner.module_args = 'jid=%s' % self.jid
self.runner.pattern = '*'
self.runner.background = 0
self.runner.inventory.restrict_to(self.hosts_to_poll)
re... |
def add_fingerprint_to_nglview(self, view, fingerprint,
seqprop=None, structprop=None, chain_id=None, use_representatives=False,
color='red', opacity_range=(0.8, 1), scale_range=(1, 5)):
"""Add representations to an NGLWidget view object for ... | def function[add_fingerprint_to_nglview, parameter[self, view, fingerprint, seqprop, structprop, chain_id, use_representatives, color, opacity_range, scale_range]]:
constant[Add representations to an NGLWidget view object for residues that are mutated in the
``sequence_alignments`` attribute.
A... | keyword[def] identifier[add_fingerprint_to_nglview] ( identifier[self] , identifier[view] , identifier[fingerprint] ,
identifier[seqprop] = keyword[None] , identifier[structprop] = keyword[None] , identifier[chain_id] = keyword[None] , identifier[use_representatives] = keyword[False] ,
identifier[color] = literal[s... | def add_fingerprint_to_nglview(self, view, fingerprint, seqprop=None, structprop=None, chain_id=None, use_representatives=False, color='red', opacity_range=(0.8, 1), scale_range=(1, 5)):
"""Add representations to an NGLWidget view object for residues that are mutated in the
``sequence_alignments`` attribute... |
def _put_resource(self, resource_id, body):
"""
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
# resource_id could be a path such as '/asset... | def function[_put_resource, parameter[self, resource_id, body]]:
constant[
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
]
assert[call[name[isinstance], parameter[name[body], name[dict]]]]
variable[uri] assign[=] c... | keyword[def] identifier[_put_resource] ( identifier[self] , identifier[resource_id] , identifier[body] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[body] ,( identifier[dict] )), literal[string]
identifier[uri] = identifier[self] . identifier[_get_resour... | def _put_resource(self, resource_id, body):
"""
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, dict), 'PUT requires body to be a dict.'
# resource_id could be a path such as '/asset/123' so quote... |
def show_max(df):
"""Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s)
et la (les) date(s) du (des) max.
Paramètres:
df: DataFrame de valeurs à calculer
Retourne:
Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux dates
d'apparition.
"""
... | def function[show_max, parameter[df]]:
constant[Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s)
et la (les) date(s) du (des) max.
Paramètres:
df: DataFrame de valeurs à calculer
Retourne:
Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux d... | keyword[def] identifier[show_max] ( identifier[df] ):
literal[string]
identifier[df] = identifier[df] . identifier[astype] ( identifier[pd] . identifier[np] . identifier[float] )
identifier[res] = identifier[list] ()
keyword[for] identifier[c] keyword[in] identifier[df] . identifier[columns] :... | def show_max(df):
"""Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s)
et la (les) date(s) du (des) max.
Paramètres:
df: DataFrame de valeurs à calculer
Retourne:
Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux dates
d'apparition.
"""
... |
def log(self, message, severity=INFO, tag=u""):
"""
Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param string tag: the tag... | def function[log, parameter[self, message, severity, tag]]:
constant[
Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param s... | keyword[def] identifier[log] ( identifier[self] , identifier[message] , identifier[severity] = identifier[INFO] , identifier[tag] = literal[string] ):
literal[string]
identifier[entry] = identifier[_LogEntry] (
identifier[severity] = identifier[severity] ,
identifier[time] = ident... | def log(self, message, severity=INFO, tag=u''):
"""
Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param string tag: the tag ass... |
def _url_params(size:str='>400*300', format:str='jpg') -> str:
"Build Google Images Search Url params and return them as a string."
_fmts = {'jpg':'ift:jpg','gif':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'}
if size not in _img_sizes:
raise RuntimeError(... | def function[_url_params, parameter[size, format]]:
constant[Build Google Images Search Url params and return them as a string.]
variable[_fmts] assign[=] dictionary[[<ast.Constant object at 0x7da1b1e98a90>, <ast.Constant object at 0x7da1b1e99b70>, <ast.Constant object at 0x7da1b1e9bf70>, <ast.Constant ... | keyword[def] identifier[_url_params] ( identifier[size] : identifier[str] = literal[string] , identifier[format] : identifier[str] = literal[string] )-> identifier[str] :
literal[string]
identifier[_fmts] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[s... | def _url_params(size: str='>400*300', format: str='jpg') -> str:
"""Build Google Images Search Url params and return them as a string."""
_fmts = {'jpg': 'ift:jpg', 'gif': 'ift:gif', 'png': 'ift:png', 'bmp': 'ift:bmp', 'svg': 'ift:svg', 'webp': 'webp', 'ico': 'ift:ico'}
if size not in _img_sizes:
ra... |
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use. Don't fail if users username is provided.
"""
user = None
try:
user = User.objects.get(username__iexact=self.\
cleaned_data['username'])
... | def function[clean_username, parameter[self]]:
constant[
Validate that the username is alphanumeric and is not already
in use. Don't fail if users username is provided.
]
variable[user] assign[=] constant[None]
<ast.Try object at 0x7da207f03520>
if name[user] begin[:]... | keyword[def] identifier[clean_username] ( identifier[self] ):
literal[string]
identifier[user] = keyword[None]
keyword[try] :
identifier[user] = identifier[User] . identifier[objects] . identifier[get] ( identifier[username__iexact] = identifier[self] . identifier[cleaned_dat... | def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use. Don't fail if users username is provided.
"""
user = None
try:
user = User.objects.get(username__iexact=self.cleaned_data['username']) # depends on [control=['try'], data=[]]
... |
def getComponentMetrics(self,
tmaster,
componentName,
metricNames,
instances,
interval,
callback=None):
"""
Get the specified metrics for the given componen... | def function[getComponentMetrics, parameter[self, tmaster, componentName, metricNames, instances, interval, callback]]:
constant[
Get the specified metrics for the given component name of this topology.
Returns the following dict on success:
{
"metrics": {
<metricname>: {
<in... | keyword[def] identifier[getComponentMetrics] ( identifier[self] ,
identifier[tmaster] ,
identifier[componentName] ,
identifier[metricNames] ,
identifier[instances] ,
identifier[interval] ,
identifier[callback] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[tmaster] keyword[... | def getComponentMetrics(self, tmaster, componentName, metricNames, instances, interval, callback=None):
"""
Get the specified metrics for the given component name of this topology.
Returns the following dict on success:
{
"metrics": {
<metricname>: {
<instance>: <numeric value>,
... |
def _parse_options(opts, delim):
"""Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion."""
options = {}
for opt in opts.split(delim):
key, val = opt.split("=")
if key.lower() == 'readpre... | def function[_parse_options, parameter[opts, delim]]:
constant[Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion.]
variable[options] assign[=] dictionary[[], []]
for taget[name[opt]] in sta... | keyword[def] identifier[_parse_options] ( identifier[opts] , identifier[delim] ):
literal[string]
identifier[options] ={}
keyword[for] identifier[opt] keyword[in] identifier[opts] . identifier[split] ( identifier[delim] ):
identifier[key] , identifier[val] = identifier[opt] . identifier[sp... | def _parse_options(opts, delim):
"""Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion."""
options = {}
for opt in opts.split(delim):
(key, val) = opt.split('=')
if key.lower() == 'readp... |
def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if not hasattr(self, "levels_of_description"):
self.levels_of_description = [
item["name"]
for item in self._get(urljoin(s... | def function[get_levels_of_description, parameter[self]]:
constant[
Returns an array of all levels of description defined in this AtoM instance.
]
if <ast.UnaryOp object at 0x7da1b26aec20> begin[:]
name[self].levels_of_description assign[=] <ast.ListComp object at 0x7da1b... | keyword[def] identifier[get_levels_of_description] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[levels_of_description] =[
identifier[item] [ literal[string] ]
... | def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if not hasattr(self, 'levels_of_description'):
self.levels_of_description = [item['name'] for item in self._get(urljoin(self.base_url, 'taxonomies/34')).json()] # de... |
def set_placeholder(self, key, value):
"""Placeholders are custom magic variables defined during configuration
time.
.. note:: These are accessible, like any uWSGI option, in your application code via
``.runtime.environ.uwsgi_env.config``.
:param str|unicode key:
:... | def function[set_placeholder, parameter[self, key, value]]:
constant[Placeholders are custom magic variables defined during configuration
time.
.. note:: These are accessible, like any uWSGI option, in your application code via
``.runtime.environ.uwsgi_env.config``.
:param ... | keyword[def] identifier[set_placeholder] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[self] . identifier[_set] ( literal[string] , literal[string] %( identifier[key] , identifier[value] ), identifier[multi] = keyword[True] )
keyword[return] ident... | def set_placeholder(self, key, value):
"""Placeholders are custom magic variables defined during configuration
time.
.. note:: These are accessible, like any uWSGI option, in your application code via
``.runtime.environ.uwsgi_env.config``.
:param str|unicode key:
:para... |
def _workaround_no_vector_images(project):
"""Replace vector images with fake ones."""
RED = (255, 0, 0)
PLACEHOLDER = kurt.Image.new((32, 32), RED)
for scriptable in [project.stage] + project.sprites:
for costume in scriptable.costumes:
if costume.image.format == "SVG":
... | def function[_workaround_no_vector_images, parameter[project]]:
constant[Replace vector images with fake ones.]
variable[RED] assign[=] tuple[[<ast.Constant object at 0x7da18dc06d40>, <ast.Constant object at 0x7da18dc06ec0>, <ast.Constant object at 0x7da18dc05240>]]
variable[PLACEHOLDER] assign[... | keyword[def] identifier[_workaround_no_vector_images] ( identifier[project] ):
literal[string]
identifier[RED] =( literal[int] , literal[int] , literal[int] )
identifier[PLACEHOLDER] = identifier[kurt] . identifier[Image] . identifier[new] (( literal[int] , literal[int] ), identifier[RED] )
keywo... | def _workaround_no_vector_images(project):
"""Replace vector images with fake ones."""
RED = (255, 0, 0)
PLACEHOLDER = kurt.Image.new((32, 32), RED)
for scriptable in [project.stage] + project.sprites:
for costume in scriptable.costumes:
if costume.image.format == 'SVG':
... |
def _get_applicable_options(self, options: Dict[str, Dict[str, Any]]):
"""
Returns the options that are applicable to this particular parser, from the full map of options.
It first uses 'get_id_for_options()' to know the id of this parser, and then simply extracts the contents of
the opt... | def function[_get_applicable_options, parameter[self, options]]:
constant[
Returns the options that are applicable to this particular parser, from the full map of options.
It first uses 'get_id_for_options()' to know the id of this parser, and then simply extracts the contents of
the opt... | keyword[def] identifier[_get_applicable_options] ( identifier[self] , identifier[options] : identifier[Dict] [ identifier[str] , identifier[Dict] [ identifier[str] , identifier[Any] ]]):
literal[string]
keyword[return] identifier[get_options_for_id] ( identifier[options] , identifier[self] . ident... | def _get_applicable_options(self, options: Dict[str, Dict[str, Any]]):
"""
Returns the options that are applicable to this particular parser, from the full map of options.
It first uses 'get_id_for_options()' to know the id of this parser, and then simply extracts the contents of
the options... |
def insert_on(self, path, loc = None):
"""Insert self.location in path before its nearest parent directory"""
loc = loc or self.location
if self.project_name == 'setuptools':
try:
version = self.version
except ValueError:
version = ''
... | def function[insert_on, parameter[self, path, loc]]:
constant[Insert self.location in path before its nearest parent directory]
variable[loc] assign[=] <ast.BoolOp object at 0x7da20c76db40>
if compare[name[self].project_name equal[==] constant[setuptools]] begin[:]
<ast.Try object at 0x7... | keyword[def] identifier[insert_on] ( identifier[self] , identifier[path] , identifier[loc] = keyword[None] ):
literal[string]
identifier[loc] = identifier[loc] keyword[or] identifier[self] . identifier[location]
keyword[if] identifier[self] . identifier[project_name] == literal[strin... | def insert_on(self, path, loc=None):
"""Insert self.location in path before its nearest parent directory"""
loc = loc or self.location
if self.project_name == 'setuptools':
try:
version = self.version # depends on [control=['try'], data=[]]
except ValueError:
version... |
def _set_feature(self, name, status):
"""Set feature's inclusion status"""
setattr(self, self._feature_attrname(name), status) | def function[_set_feature, parameter[self, name, status]]:
constant[Set feature's inclusion status]
call[name[setattr], parameter[name[self], call[name[self]._feature_attrname, parameter[name[name]]], name[status]]] | keyword[def] identifier[_set_feature] ( identifier[self] , identifier[name] , identifier[status] ):
literal[string]
identifier[setattr] ( identifier[self] , identifier[self] . identifier[_feature_attrname] ( identifier[name] ), identifier[status] ) | def _set_feature(self, name, status):
"""Set feature's inclusion status"""
setattr(self, self._feature_attrname(name), status) |
def list_data(i):
"""
Input: {
(repo_uoa) - repo UOA
(module_uoa) - module UOA
(data_uoa) - data UOA
(repo_uoa_list) - list of repos to search
(module_uoa_list) - list of module to search
(d... | def function[list_data, parameter[i]]:
constant[
Input: {
(repo_uoa) - repo UOA
(module_uoa) - module UOA
(data_uoa) - data UOA
(repo_uoa_list) - list of repos to search
(module_uoa_list) - list of mo... | keyword[def] identifier[list_data] ( identifier[i] ):
literal[string]
keyword[import] identifier[time]
identifier[start_time] = identifier[time] . identifier[time] ()
identifier[xls] = identifier[i] . identifier[get] ( literal[string] , literal[string] )
keyword[if] identifier[xls] == l... | def list_data(i):
"""
Input: {
(repo_uoa) - repo UOA
(module_uoa) - module UOA
(data_uoa) - data UOA
(repo_uoa_list) - list of repos to search
(module_uoa_list) - list of module to search
(d... |
def search_on(self, *fields, **query):
"""
Search for query on given fields.
Query modifier can be one of these:
* exact
* contains
* startswith
* endswith
* range
* lte
* gte
Args:
\*fields... | def function[search_on, parameter[self]]:
constant[
Search for query on given fields.
Query modifier can be one of these:
* exact
* contains
* startswith
* endswith
* range
* lte
* gte
Args:
... | keyword[def] identifier[search_on] ( identifier[self] ,* identifier[fields] ,** identifier[query] ):
literal[string]
identifier[clone] = identifier[copy] . identifier[deepcopy] ( identifier[self] )
identifier[clone] . identifier[adapter] . identifier[search_on] (* identifier[fields] ,** id... | def search_on(self, *fields, **query):
"""
Search for query on given fields.
Query modifier can be one of these:
* exact
* contains
* startswith
* endswith
* range
* lte
* gte
Args:
\\*fields (s... |
def read_memory(self):
"""
This function read mean value of target`d`
and input vector `x` from history
"""
if self.mem_empty == True:
if self.mem_idx == 0:
m_x = np.zeros(self.n)
m_d = 0
else:
m_x = np.mean(... | def function[read_memory, parameter[self]]:
constant[
This function read mean value of target`d`
and input vector `x` from history
]
if compare[name[self].mem_empty equal[==] constant[True]] begin[:]
if compare[name[self].mem_idx equal[==] constant[0]] begin[:]
... | keyword[def] identifier[read_memory] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[mem_empty] == keyword[True] :
keyword[if] identifier[self] . identifier[mem_idx] == literal[int] :
identifier[m_x] = identifier[np] . identifier[zeros... | def read_memory(self):
"""
This function read mean value of target`d`
and input vector `x` from history
"""
if self.mem_empty == True:
if self.mem_idx == 0:
m_x = np.zeros(self.n)
m_d = 0 # depends on [control=['if'], data=[]]
else:
m_... |
def _construct_role(self, managed_policy_map):
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
"""
execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_... | def function[_construct_role, parameter[self, managed_policy_map]]:
constant[Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
]
variable[execution_role] assign[=] call[name[IAMRole], par... | keyword[def] identifier[_construct_role] ( identifier[self] , identifier[managed_policy_map] ):
literal[string]
identifier[execution_role] = identifier[IAMRole] ( identifier[self] . identifier[logical_id] + literal[string] , identifier[attributes] = identifier[self] . identifier[get_passthrough_res... | def _construct_role(self, managed_policy_map):
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
"""
execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_resource... |
def argpack(args):
"""
Coerce a list of arguments to a tuple.
Parameters
----------
args : tuple or nested tuple
Pack arguments into a tuple, converting ((,...),) or (,) -> (,)
"""
if isinstance(args[0], (tuple, list, ndarray)):
return tupleize(args[0])
elif isinstance(a... | def function[argpack, parameter[args]]:
constant[
Coerce a list of arguments to a tuple.
Parameters
----------
args : tuple or nested tuple
Pack arguments into a tuple, converting ((,...),) or (,) -> (,)
]
if call[name[isinstance], parameter[call[name[args]][constant[0]], tu... | keyword[def] identifier[argpack] ( identifier[args] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[args] [ literal[int] ],( identifier[tuple] , identifier[list] , identifier[ndarray] )):
keyword[return] identifier[tupleize] ( identifier[args] [ literal[int] ])
keyword[el... | def argpack(args):
"""
Coerce a list of arguments to a tuple.
Parameters
----------
args : tuple or nested tuple
Pack arguments into a tuple, converting ((,...),) or (,) -> (,)
"""
if isinstance(args[0], (tuple, list, ndarray)):
return tupleize(args[0]) # depends on [contro... |
def update(self, resource_name, resource, url_prefix, auth, session, send_opts):
"""Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the resource is getting its name changed).
resource (intern.resou... | def function[update, parameter[self, resource_name, resource, url_prefix, auth, session, send_opts]]:
constant[Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the resource is getting its name changed).
... | keyword[def] identifier[update] ( identifier[self] , identifier[resource_name] , identifier[resource] , identifier[url_prefix] , identifier[auth] , identifier[session] , identifier[send_opts] ):
literal[string]
identifier[old_resource] = identifier[copy] . identifier[deepcopy] ( ... | def update(self, resource_name, resource, url_prefix, auth, session, send_opts):
"""Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the resource is getting its name changed).
resource (intern.resource.... |
def find_from(path):
"""Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found.
"""
... | def function[find_from, parameter[path]]:
constant[Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if no... | keyword[def] identifier[find_from] ( identifier[path] ):
literal[string]
identifier[realpath] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[path] )
identifier[config_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[realpath] , literal[stri... | def find_from(path):
"""Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found.
"""
realpa... |
def to_fixed(stype):
""" Returns the instruction sequence for converting the given
type stored in DE,HL to fixed DE,HL.
"""
output = [] # List of instructions
if is_int_type(stype):
output = to_word(stype)
output.append('ex de, hl')
output.append('ld hl, 0') # 'Truncate' t... | def function[to_fixed, parameter[stype]]:
constant[ Returns the instruction sequence for converting the given
type stored in DE,HL to fixed DE,HL.
]
variable[output] assign[=] list[[]]
if call[name[is_int_type], parameter[name[stype]]] begin[:]
variable[output] assign[=] ... | keyword[def] identifier[to_fixed] ( identifier[stype] ):
literal[string]
identifier[output] =[]
keyword[if] identifier[is_int_type] ( identifier[stype] ):
identifier[output] = identifier[to_word] ( identifier[stype] )
identifier[output] . identifier[append] ( literal[string] )
... | def to_fixed(stype):
""" Returns the instruction sequence for converting the given
type stored in DE,HL to fixed DE,HL.
"""
output = [] # List of instructions
if is_int_type(stype):
output = to_word(stype)
output.append('ex de, hl')
output.append('ld hl, 0') # 'Truncate' th... |
def get_environment(id=None, name=None):
"""
Get a specific Environment by name or ID
"""
data = get_environment_raw(id, name)
if data:
return utils.format_json(data) | def function[get_environment, parameter[id, name]]:
constant[
Get a specific Environment by name or ID
]
variable[data] assign[=] call[name[get_environment_raw], parameter[name[id], name[name]]]
if name[data] begin[:]
return[call[name[utils].format_json, parameter[name[data]]]] | keyword[def] identifier[get_environment] ( identifier[id] = keyword[None] , identifier[name] = keyword[None] ):
literal[string]
identifier[data] = identifier[get_environment_raw] ( identifier[id] , identifier[name] )
keyword[if] identifier[data] :
keyword[return] identifier[utils] . identif... | def get_environment(id=None, name=None):
"""
Get a specific Environment by name or ID
"""
data = get_environment_raw(id, name)
if data:
return utils.format_json(data) # depends on [control=['if'], data=[]] |
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
... | def function[read_registry, parameter[self]]:
constant[Extract resolver configuration from the Windows registry.]
variable[lm] assign[=] call[name[_winreg].ConnectRegistry, parameter[constant[None], name[_winreg].HKEY_LOCAL_MACHINE]]
variable[want_scan] assign[=] constant[False]
<ast.Try obj... | keyword[def] identifier[read_registry] ( identifier[self] ):
literal[string]
identifier[lm] = identifier[_winreg] . identifier[ConnectRegistry] ( keyword[None] , identifier[_winreg] . identifier[HKEY_LOCAL_MACHINE] )
identifier[want_scan] = keyword[False]
keyword[try] :
... | def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm, 'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Par... |
def focussed_widget(self):
"""
The widget that currently has the focus within this Frame.
"""
# If the frame has no focus, it can't have a focussed widget.
if not self._has_focus:
return None
try:
layout = self._layouts[self._focus]
re... | def function[focussed_widget, parameter[self]]:
constant[
The widget that currently has the focus within this Frame.
]
if <ast.UnaryOp object at 0x7da1b1d4e110> begin[:]
return[constant[None]]
<ast.Try object at 0x7da1b1d4da20> | keyword[def] identifier[focussed_widget] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_has_focus] :
keyword[return] keyword[None]
keyword[try] :
identifier[layout] = identifier[self] . identifier[_layou... | def focussed_widget(self):
"""
The widget that currently has the focus within this Frame.
"""
# If the frame has no focus, it can't have a focussed widget.
if not self._has_focus:
return None # depends on [control=['if'], data=[]]
try:
layout = self._layouts[self._focus]... |
def create_iterator(self, start=0, step=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... | def function[create_iterator, parameter[self, start, step]]:
constant[
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 n... | keyword[def] identifier[create_iterator] ( identifier[self] , identifier[start] = literal[int] , identifier[step] = literal[int] ):
literal[string]
identifier[key_iterator] =(
identifier[KeyGenerator] ( identifier[self] . identifier[seed] ). identifier[create_iterator] (
identifi... | def create_iterator(self, start=0, step=1):
# type: (int, int) -> Generator[Address, None, None]
'\n Creates an iterator that can be used to progressively generate new\n addresses.\n\n :param start:\n Starting index.\n\n Warning: This method may take awhile to reset if... |
def ext_pillar(hyper_id, pillar, name, key):
'''
Accept the key for the VM on the hyper, if authorized.
'''
vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__)
ok = vk.accept(key)
pillar['virtkey'] = {name: ok}
return {} | def function[ext_pillar, parameter[hyper_id, pillar, name, key]]:
constant[
Accept the key for the VM on the hyper, if authorized.
]
variable[vk] assign[=] call[name[salt].utils.virt.VirtKey, parameter[name[hyper_id], name[name], name[__opts__]]]
variable[ok] assign[=] call[name[vk].acce... | keyword[def] identifier[ext_pillar] ( identifier[hyper_id] , identifier[pillar] , identifier[name] , identifier[key] ):
literal[string]
identifier[vk] = identifier[salt] . identifier[utils] . identifier[virt] . identifier[VirtKey] ( identifier[hyper_id] , identifier[name] , identifier[__opts__] )
iden... | def ext_pillar(hyper_id, pillar, name, key):
"""
Accept the key for the VM on the hyper, if authorized.
"""
vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__)
ok = vk.accept(key)
pillar['virtkey'] = {name: ok}
return {} |
def run_profit(pdb1, pdb2, path1=False, path2=False, path_to_cmd_file=None,
return_pdb_string=False, align_type=None):
"""Takes 2 PDB strings, carries out rmsd superposition using ProFit.
Parameters
----------
pdb1 : str
PDB as string or path
pdb2 : str
PDB as string ... | def function[run_profit, parameter[pdb1, pdb2, path1, path2, path_to_cmd_file, return_pdb_string, align_type]]:
constant[Takes 2 PDB strings, carries out rmsd superposition using ProFit.
Parameters
----------
pdb1 : str
PDB as string or path
pdb2 : str
PDB as string or path
... | keyword[def] identifier[run_profit] ( identifier[pdb1] , identifier[pdb2] , identifier[path1] = keyword[False] , identifier[path2] = keyword[False] , identifier[path_to_cmd_file] = keyword[None] ,
identifier[return_pdb_string] = keyword[False] , identifier[align_type] = keyword[None] ):
literal[string]
i... | def run_profit(pdb1, pdb2, path1=False, path2=False, path_to_cmd_file=None, return_pdb_string=False, align_type=None):
"""Takes 2 PDB strings, carries out rmsd superposition using ProFit.
Parameters
----------
pdb1 : str
PDB as string or path
pdb2 : str
PDB as string or path
pat... |
def log_warning(self, msg):
"""
Log a warning if ``logger`` exists.
Args:
msg: Warning to log.
Warning:
Can raise a ``RuntimeError`` if this was asked in the constructor.
"""
if self.__logger:
self.__logger.warning(msg)
if s... | def function[log_warning, parameter[self, msg]]:
constant[
Log a warning if ``logger`` exists.
Args:
msg: Warning to log.
Warning:
Can raise a ``RuntimeError`` if this was asked in the constructor.
]
if name[self].__logger begin[:]
... | keyword[def] identifier[log_warning] ( identifier[self] , identifier[msg] ):
literal[string]
keyword[if] identifier[self] . identifier[__logger] :
identifier[self] . identifier[__logger] . identifier[warning] ( identifier[msg] )
keyword[if] identifier[self] . identifier[__r... | def log_warning(self, msg):
"""
Log a warning if ``logger`` exists.
Args:
msg: Warning to log.
Warning:
Can raise a ``RuntimeError`` if this was asked in the constructor.
"""
if self.__logger:
self.__logger.warning(msg) # depends on [control=['... |
def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(vie... | def function[path_helper, parameter[self, operations, view, app]]:
constant[Path helper that allows passing a Flask view function.]
variable[rule] assign[=] call[name[self]._rule_for_view, parameter[name[view]]]
call[name[operations].update, parameter[call[name[yaml_utils].load_operations_from_d... | keyword[def] identifier[path_helper] ( identifier[self] , identifier[operations] , identifier[view] , identifier[app] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[rule] = identifier[self] . identifier[_rule_for_view] ( identifier[view] , identifier[app] = identifier[app] )
... | def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(view.view_class, Me... |
def get_used_template(response):
"""
Get the template used in a TemplateResponse.
This returns a tuple of "active choice, all choices"
"""
if not hasattr(response, 'template_name'):
return None, None
template = response.template_name
if template is None:
return None, None
... | def function[get_used_template, parameter[response]]:
constant[
Get the template used in a TemplateResponse.
This returns a tuple of "active choice, all choices"
]
if <ast.UnaryOp object at 0x7da1b02c0f40> begin[:]
return[tuple[[<ast.Constant object at 0x7da1b02c3ee0>, <ast.Constant ... | keyword[def] identifier[get_used_template] ( identifier[response] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[response] , literal[string] ):
keyword[return] keyword[None] , keyword[None]
identifier[template] = identifier[response] . identifier[template_na... | def get_used_template(response):
"""
Get the template used in a TemplateResponse.
This returns a tuple of "active choice, all choices"
"""
if not hasattr(response, 'template_name'):
return (None, None) # depends on [control=['if'], data=[]]
template = response.template_name
if templ... |
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
# Nothing to do.
return
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.alias(py.built... | def function[run, parameter[self, mod]]:
constant[Find all assert statements in *mod* and rewrite them.]
if <ast.UnaryOp object at 0x7da1b1642e90> begin[:]
return[None]
variable[aliases] assign[=] list[[<ast.Call object at 0x7da1b1640e50>, <ast.Call object at 0x7da1b1641330>]]
va... | keyword[def] identifier[run] ( identifier[self] , identifier[mod] ):
literal[string]
keyword[if] keyword[not] identifier[mod] . identifier[body] :
keyword[return]
identifier[aliases] =[ identifier[ast] . identifier[alias] ( identifier[py] ... | def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
# Nothing to do.
return # depends on [control=['if'], data=[]]
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.al... |
def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1.\
document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str):... | def function[get_doc_id, parameter[document_pb, expected_prefix]]:
constant[Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1. document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
... | keyword[def] identifier[get_doc_id] ( identifier[document_pb] , identifier[expected_prefix] ):
literal[string]
identifier[prefix] , identifier[document_id] = identifier[document_pb] . identifier[name] . identifier[rsplit] ( identifier[DOCUMENT_PATH_DELIMITER] , literal[int] )
keyword[if] identifier[p... | def get_doc_id(document_pb, expected_prefix):
"""Parse a document ID from a document protobuf.
Args:
document_pb (google.cloud.proto.firestore.v1beta1. document_pb2.Document): A protobuf for a document that
was created in a ``CreateDocument`` RPC.
expected_prefix (str): T... |
def anonymous(self):
"""
Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.)
"""
if ha... | def function[anonymous, parameter[self]]:
constant[
Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.... | keyword[def] identifier[anonymous] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] . identifier[handler] , literal[string] ):
identifier[anon] = identifier[self] . identifier[handler] . identifier[anonymous]
keyword[if] identifi... | def anonymous(self):
"""
Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.)
"""
if hasattr(se... |
def create_id2collection_info(path, tag):
"""Searchers for JSON files in this repo and returns
a map of collection id ==> (`tag`, dir, collection filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
root, files = triple[0], triple[2]
for filen... | def function[create_id2collection_info, parameter[path, tag]]:
constant[Searchers for JSON files in this repo and returns
a map of collection id ==> (`tag`, dir, collection filepath)
where `tag` is typically the shard name
]
variable[d] assign[=] dictionary[[], []]
for taget[name[tri... | keyword[def] identifier[create_id2collection_info] ( identifier[path] , identifier[tag] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[triple] keyword[in] identifier[os] . identifier[walk] ( identifier[path] ):
identifier[root] , identifier[files] = identifier[triple] [ liter... | def create_id2collection_info(path, tag):
"""Searchers for JSON files in this repo and returns
a map of collection id ==> (`tag`, dir, collection filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
(root, files) = (triple[0], triple[2])
for f... |
def add_config_files_to_archive(directory, filename, config={}):
"""
Adds configuration files to an existing archive
"""
with zipfile.ZipFile(filename, 'a') as zip_file:
for conf in config:
for conf, tree in list(conf.items()):
if 'yaml' in tree:
c... | def function[add_config_files_to_archive, parameter[directory, filename, config]]:
constant[
Adds configuration files to an existing archive
]
with call[name[zipfile].ZipFile, parameter[name[filename], constant[a]]] begin[:]
for taget[name[conf]] in starred[name[config]] begin[:]... | keyword[def] identifier[add_config_files_to_archive] ( identifier[directory] , identifier[filename] , identifier[config] ={}):
literal[string]
keyword[with] identifier[zipfile] . identifier[ZipFile] ( identifier[filename] , literal[string] ) keyword[as] identifier[zip_file] :
keyword[for] ident... | def add_config_files_to_archive(directory, filename, config={}):
"""
Adds configuration files to an existing archive
"""
with zipfile.ZipFile(filename, 'a') as zip_file:
for conf in config:
for (conf, tree) in list(conf.items()):
if 'yaml' in tree:
... |
def get_copyright_metadata(self):
"""Gets the metadata for the copyright.
return: (osid.Metadata) - metadata for the copyright
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
... | def function[get_copyright_metadata, parameter[self]]:
constant[Gets the metadata for the copyright.
return: (osid.Metadata) - metadata for the copyright
*compliance: mandatory -- This method must be implemented.*
]
variable[metadata] assign[=] call[name[dict], parameter[call[n... | keyword[def] identifier[get_copyright_metadata] ( identifier[self] ):
literal[string]
identifier[metadata] = identifier[dict] ( identifier[self] . identifier[_mdata] [ literal[string] ])
identifier[metadata] . identifier[update] ({ literal[string] : identifier[self] . identifier[_... | def get_copyright_metadata(self):
"""Gets the metadata for the copyright.
return: (osid.Metadata) - metadata for the copyright
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
meta... |
def flavor_access_add(flavor_id, project_id, profile=None, **kwargs):
'''
Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_add(flavor... | def function[flavor_access_add, parameter[flavor_id, project_id, profile]]:
constant[
Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID
]
variable[conn] assign[=] call[name[_auth], parameter[n... | keyword[def] identifier[flavor_access_add] ( identifier[flavor_id] , identifier[project_id] , identifier[profile] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[conn] = identifier[_auth] ( identifier[profile] ,** identifier[kwargs] )
keyword[return] identifier[conn] . identifier... | def flavor_access_add(flavor_id, project_id, profile=None, **kwargs):
"""
Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID
"""
conn = _auth(profile, **kwargs)
return conn.flavor_access_add(flavor... |
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie... | def function[_affine_mult, parameter[c, m]]:
constant[Multiply `c` by `m` - can adjust for rectangular shaped `c`.]
if compare[name[m] is constant[None]] begin[:]
return[name[c]]
variable[size] assign[=] call[name[c].flow.size, parameter[]]
<ast.Tuple object at 0x7da1b1e10cd0> as... | keyword[def] identifier[_affine_mult] ( identifier[c] : identifier[FlowField] , identifier[m] : identifier[AffineMatrix] )-> identifier[FlowField] :
literal[string]
keyword[if] identifier[m] keyword[is] keyword[None] : keyword[return] identifier[c]
identifier[size] = identifier[c] . identifier[fl... | def _affine_mult(c: FlowField, m: AffineMatrix) -> FlowField:
"""Multiply `c` by `m` - can adjust for rectangular shaped `c`."""
if m is None:
return c # depends on [control=['if'], data=[]]
size = c.flow.size()
(h, w) = c.size
m[0, 1] *= h / w
m[1, 0] *= w / h
c.flow = c.flow.view(... |
def drop(self):
"""
Remove all data from the database.
"""
Statement = self.get_model('statement')
Tag = self.get_model('tag')
Statement.objects.all().delete()
Tag.objects.all().delete() | def function[drop, parameter[self]]:
constant[
Remove all data from the database.
]
variable[Statement] assign[=] call[name[self].get_model, parameter[constant[statement]]]
variable[Tag] assign[=] call[name[self].get_model, parameter[constant[tag]]]
call[call[name[Stateme... | keyword[def] identifier[drop] ( identifier[self] ):
literal[string]
identifier[Statement] = identifier[self] . identifier[get_model] ( literal[string] )
identifier[Tag] = identifier[self] . identifier[get_model] ( literal[string] )
identifier[Statement] . identifier[objects] . id... | def drop(self):
"""
Remove all data from the database.
"""
Statement = self.get_model('statement')
Tag = self.get_model('tag')
Statement.objects.all().delete()
Tag.objects.all().delete() |
def allocate_series_dataframes(network, series):
"""
Populate time-varying outputs with default values.
Parameters
----------
network : pypsa.Network
series : dict
Dictionary of components and their attributes to populate (see example)
Returns
-------
None
Examples
... | def function[allocate_series_dataframes, parameter[network, series]]:
constant[
Populate time-varying outputs with default values.
Parameters
----------
network : pypsa.Network
series : dict
Dictionary of components and their attributes to populate (see example)
Returns
---... | keyword[def] identifier[allocate_series_dataframes] ( identifier[network] , identifier[series] ):
literal[string]
keyword[for] identifier[component] , identifier[attributes] keyword[in] identifier[iteritems] ( identifier[series] ):
identifier[df] = identifier[network] . identifier[df] ( ident... | def allocate_series_dataframes(network, series):
"""
Populate time-varying outputs with default values.
Parameters
----------
network : pypsa.Network
series : dict
Dictionary of components and their attributes to populate (see example)
Returns
-------
None
Examples
... |
def get_repo_revision():
'''
Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-au... | def function[get_repo_revision, parameter[]]:
constant[
Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-re... | keyword[def] identifier[get_repo_revision] ():
literal[string]
identifier[rev] = literal[int]
identifier[path] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__f... | def get_repo_revision():
"""
Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-au... |
def HeartBeat(self):
"""Terminates a cronjob-run if it has exceeded its maximum runtime.
This is a no-op for cronjobs that allow overruns.
Raises:
LifetimeExceededError: If the cronjob has exceeded its maximum runtime.
"""
# In prod, self.job.lifetime is guaranteed to always be set, and is
... | def function[HeartBeat, parameter[self]]:
constant[Terminates a cronjob-run if it has exceeded its maximum runtime.
This is a no-op for cronjobs that allow overruns.
Raises:
LifetimeExceededError: If the cronjob has exceeded its maximum runtime.
]
if <ast.BoolOp object at 0x7da1b1b69... | keyword[def] identifier[HeartBeat] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[allow_overruns] keyword[or] keyword[not] identifier[self] . identifier[job] . identifier[lifetime] :
keyword[return]
identifier[runtime] = identifier[rdfvalue]... | def HeartBeat(self):
"""Terminates a cronjob-run if it has exceeded its maximum runtime.
This is a no-op for cronjobs that allow overruns.
Raises:
LifetimeExceededError: If the cronjob has exceeded its maximum runtime.
"""
# In prod, self.job.lifetime is guaranteed to always be set, and is
... |
def abort_now ():
"""Force exit of current process without cleanup."""
if os.name == 'posix':
# Unix systems can use signals
import signal
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(1)
os.kill(os.getpid(), signal.SIGKILL)
elif os.name == 'nt':
# NT has os... | def function[abort_now, parameter[]]:
constant[Force exit of current process without cleanup.]
if compare[name[os].name equal[==] constant[posix]] begin[:]
import module[signal]
call[name[os].kill, parameter[call[name[os].getpid, parameter[]], name[signal].SIGTERM]]
... | keyword[def] identifier[abort_now] ():
literal[string]
keyword[if] identifier[os] . identifier[name] == literal[string] :
keyword[import] identifier[signal]
identifier[os] . identifier[kill] ( identifier[os] . identifier[getpid] (), identifier[signal] . identifier[SIGTERM] )
... | def abort_now():
"""Force exit of current process without cleanup."""
if os.name == 'posix':
# Unix systems can use signals
import signal
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(1)
os.kill(os.getpid(), signal.SIGKILL) # depends on [control=['if'], data=[]]
el... |
def call_async(self, fn, *args, **kwargs):
"""
Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. code-block::... | def function[call_async, parameter[self, fn]]:
constant[
Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. co... | keyword[def] identifier[call_async] ( identifier[self] , identifier[fn] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[self] , identifier[CallSpec] ( identifier[fn] , identifier[args] , identifier[kwargs] ))
... | def call_async(self, fn, *args, **kwargs):
"""
Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. code-block:: pyt... |
def id(self) -> typing.Union[str, None]:
"""Identifier for the project."""
return self._project.id if self._project else None | def function[id, parameter[self]]:
constant[Identifier for the project.]
return[<ast.IfExp object at 0x7da20e957b20>] | keyword[def] identifier[id] ( identifier[self] )-> identifier[typing] . identifier[Union] [ identifier[str] , keyword[None] ]:
literal[string]
keyword[return] identifier[self] . identifier[_project] . identifier[id] keyword[if] identifier[self] . identifier[_project] keyword[else] keyword[None... | def id(self) -> typing.Union[str, None]:
"""Identifier for the project."""
return self._project.id if self._project else None |
def do_gdbserver(self):
"""! @brief Handle 'gdbserver' subcommand."""
self._process_commands(self._args.commands)
gdbs = []
try:
# Build dict of session options.
sessionOptions = convert_session_options(self._args.options)
sessionOptions.update({
... | def function[do_gdbserver, parameter[self]]:
constant[! @brief Handle 'gdbserver' subcommand.]
call[name[self]._process_commands, parameter[name[self]._args.commands]]
variable[gdbs] assign[=] list[[]]
<ast.Try object at 0x7da204565840> | keyword[def] identifier[do_gdbserver] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_process_commands] ( identifier[self] . identifier[_args] . identifier[commands] )
identifier[gdbs] =[]
keyword[try] :
identifier[sessionOptions] = iden... | def do_gdbserver(self):
"""! @brief Handle 'gdbserver' subcommand."""
self._process_commands(self._args.commands)
gdbs = []
try:
# Build dict of session options.
sessionOptions = convert_session_options(self._args.options)
sessionOptions.update({'gdbserver_port': self._args.port_... |
def founditem_view(request, item_id):
"""View a founditem.
id: founditem id
"""
founditem = get_object_or_404(FoundItem, id=item_id)
return render(request, "itemreg/item_view.html", {"item": founditem, "type": "found"}) | def function[founditem_view, parameter[request, item_id]]:
constant[View a founditem.
id: founditem id
]
variable[founditem] assign[=] call[name[get_object_or_404], parameter[name[FoundItem]]]
return[call[name[render], parameter[name[request], constant[itemreg/item_view.html], dictionary[[... | keyword[def] identifier[founditem_view] ( identifier[request] , identifier[item_id] ):
literal[string]
identifier[founditem] = identifier[get_object_or_404] ( identifier[FoundItem] , identifier[id] = identifier[item_id] )
keyword[return] identifier[render] ( identifier[request] , literal[string] ,{ l... | def founditem_view(request, item_id):
"""View a founditem.
id: founditem id
"""
founditem = get_object_or_404(FoundItem, id=item_id)
return render(request, 'itemreg/item_view.html', {'item': founditem, 'type': 'found'}) |
def merge(config, revisions, **kwargs):
"""
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
ale... | def function[merge, parameter[config, revisions]]:
constant[
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
]
with call[name[alembic_lock], parameter[call[name[config].registry][constant[sqlalchemy.engine]], call... | keyword[def] identifier[merge] ( identifier[config] , identifier[revisions] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[alembic_lock] (
identifier[config] . identifier[registry] [ literal[string] ], identifier[config] . identifier[alembic_config] ()
) keyword[as] identifie... | def merge(config, revisions, **kwargs):
"""
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
"""
with alembic_lock(config.registry['sqlalchemy.engine'], config.alembic_config()) as alembic_config:
alembic.command.m... |
def css( self, filelist ):
"""This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element."""
if isinstance( filelist, basestring ):
self.link( href=filelist, rel='stylesheet', type='text/css', media='all' )
else:... | def function[css, parameter[self, filelist]]:
constant[This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element.]
if call[name[isinstance], parameter[name[filelist], name[basestring]]] begin[:]
call[name[self].link, param... | keyword[def] identifier[css] ( identifier[self] , identifier[filelist] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[filelist] , identifier[basestring] ):
identifier[self] . identifier[link] ( identifier[href] = identifier[filelist] , identifier[rel] = literal[st... | def css(self, filelist):
"""This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element."""
if isinstance(filelist, basestring):
self.link(href=filelist, rel='stylesheet', type='text/css', media='all') # depends on [control=['if'], data=[]... |
def proveGt(x,tTilde,kw,y):
"""
Generate a zero-knowledge proof that DL(g^kw) == DL(e(x,t)^kw) where
g,e(..) \in Gt.
@return pi = (p,c,u)
"""
# Verify types
assertType(x, G1Element)
assertType(tTilde, G2Element)
# Compute the proof.
beta = pair(x,tTilde)
g = generatorGt()
... | def function[proveGt, parameter[x, tTilde, kw, y]]:
constant[
Generate a zero-knowledge proof that DL(g^kw) == DL(e(x,t)^kw) where
g,e(..) \in Gt.
@return pi = (p,c,u)
]
call[name[assertType], parameter[name[x], name[G1Element]]]
call[name[assertType], parameter[name[tTilde], nam... | keyword[def] identifier[proveGt] ( identifier[x] , identifier[tTilde] , identifier[kw] , identifier[y] ):
literal[string]
identifier[assertType] ( identifier[x] , identifier[G1Element] )
identifier[assertType] ( identifier[tTilde] , identifier[G2Element] )
identifier[beta] = identifier... | def proveGt(x, tTilde, kw, y):
"""
Generate a zero-knowledge proof that DL(g^kw) == DL(e(x,t)^kw) where
g,e(..) \\in Gt.
@return pi = (p,c,u)
"""
# Verify types
assertType(x, G1Element)
assertType(tTilde, G2Element)
# Compute the proof.
beta = pair(x, tTilde)
g = generatorGt(... |
def predict_quantiles(self, Xnew=None, quantiles=(2.5, 97.5), balance=None, **kw):
"""
Inputs:
------------------
balance: bool
Whether to balance or not the model as a whole
"""
if balance is None:
p_balance = self.balance
el... | def function[predict_quantiles, parameter[self, Xnew, quantiles, balance]]:
constant[
Inputs:
------------------
balance: bool
Whether to balance or not the model as a whole
]
if compare[name[balance] is constant[None]] begin[:]
v... | keyword[def] identifier[predict_quantiles] ( identifier[self] , identifier[Xnew] = keyword[None] , identifier[quantiles] =( literal[int] , literal[int] ), identifier[balance] = keyword[None] ,** identifier[kw] ):
literal[string]
keyword[if] identifier[balance] keyword[is] keyword[None] :
... | def predict_quantiles(self, Xnew=None, quantiles=(2.5, 97.5), balance=None, **kw):
"""
Inputs:
------------------
balance: bool
Whether to balance or not the model as a whole
"""
if balance is None:
p_balance = self.balance # depends on [control... |
def _parsed_callback_wrapper(self, callback_parsed, callback_plain, foc, data):
"""Used to by register_catchall_*data() and Thing class (follow, create_point) to present point data as an
object."""
# used by PointDataObjectHandler as reference
if foc == R_FEED:
point_ref = da... | def function[_parsed_callback_wrapper, parameter[self, callback_parsed, callback_plain, foc, data]]:
constant[Used to by register_catchall_*data() and Thing class (follow, create_point) to present point data as an
object.]
if compare[name[foc] equal[==] name[R_FEED]] begin[:]
var... | keyword[def] identifier[_parsed_callback_wrapper] ( identifier[self] , identifier[callback_parsed] , identifier[callback_plain] , identifier[foc] , identifier[data] ):
literal[string]
keyword[if] identifier[foc] == identifier[R_FEED] :
identifier[point_ref] = identifier[data]... | def _parsed_callback_wrapper(self, callback_parsed, callback_plain, foc, data):
"""Used to by register_catchall_*data() and Thing class (follow, create_point) to present point data as an
object."""
# used by PointDataObjectHandler as reference
if foc == R_FEED:
point_ref = data['pid'] # dep... |
def model_enums(vk, model):
"""Fill the model with enums
model['enums'] = {'name': {'item_name': 'item_value'...}, ...}
"""
model['enums'] = {}
# init enums dict
enums_type = [x['@name'] for x in vk['registry']['types']['type']
if x.get('@category') == 'enum']
for name i... | def function[model_enums, parameter[vk, model]]:
constant[Fill the model with enums
model['enums'] = {'name': {'item_name': 'item_value'...}, ...}
]
call[name[model]][constant[enums]] assign[=] dictionary[[], []]
variable[enums_type] assign[=] <ast.ListComp object at 0x7da1b083cb20>
... | keyword[def] identifier[model_enums] ( identifier[vk] , identifier[model] ):
literal[string]
identifier[model] [ literal[string] ]={}
identifier[enums_type] =[ identifier[x] [ literal[string] ] keyword[for] identifier[x] keyword[in] identifier[vk] [ literal[string] ][ literal[string] ][ liter... | def model_enums(vk, model):
"""Fill the model with enums
model['enums'] = {'name': {'item_name': 'item_value'...}, ...}
"""
model['enums'] = {}
# init enums dict
enums_type = [x['@name'] for x in vk['registry']['types']['type'] if x.get('@category') == 'enum']
for name in enums_type:
... |
def receive(self, data):
"""receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP packets in :obj:`dat... | def function[receive, parameter[self, data]]:
constant[receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP... | keyword[def] identifier[receive] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[data] :
identifier[data] = identifier[END]
identifier[self] . identifier[_recv_buffer] += identifier[data]
... | def receive(self, data):
"""receive(data) -> List of decoded messages.
Processes :obj:`data`, which must be a bytes-like object,
and returns a (possibly empty) list with :class:`bytes` objects,
each containing a decoded message.
Any non-terminated SLIP packets in :obj:`data`
... |
def issueServiceJob(self, jobNode):
"""
Issue a service job, putting it on a queue if the maximum number of service
jobs to be scheduled has been reached.
"""
if jobNode.preemptable:
self.preemptableServiceJobsToBeIssued.append(jobNode)
else:
self.... | def function[issueServiceJob, parameter[self, jobNode]]:
constant[
Issue a service job, putting it on a queue if the maximum number of service
jobs to be scheduled has been reached.
]
if name[jobNode].preemptable begin[:]
call[name[self].preemptableServiceJobsToBe... | keyword[def] identifier[issueServiceJob] ( identifier[self] , identifier[jobNode] ):
literal[string]
keyword[if] identifier[jobNode] . identifier[preemptable] :
identifier[self] . identifier[preemptableServiceJobsToBeIssued] . identifier[append] ( identifier[jobNode] )
keywor... | def issueServiceJob(self, jobNode):
"""
Issue a service job, putting it on a queue if the maximum number of service
jobs to be scheduled has been reached.
"""
if jobNode.preemptable:
self.preemptableServiceJobsToBeIssued.append(jobNode) # depends on [control=['if'], data=[]]
... |
def QA_data_calc_marketvalue(data, xdxr):
'使用数据库数据计算复权'
mv = xdxr.query('category!=6').loc[:,
['shares_after',
'liquidity_after']].dropna()
res = pd.concat([data, mv], axis=1)
res = res.assign(
shares=res.shares_afte... | def function[QA_data_calc_marketvalue, parameter[data, xdxr]]:
constant[使用数据库数据计算复权]
variable[mv] assign[=] call[call[call[name[xdxr].query, parameter[constant[category!=6]]].loc][tuple[[<ast.Slice object at 0x7da1b2010220>, <ast.List object at 0x7da1b2010d30>]]].dropna, parameter[]]
variable[re... | keyword[def] identifier[QA_data_calc_marketvalue] ( identifier[data] , identifier[xdxr] ):
literal[string]
identifier[mv] = identifier[xdxr] . identifier[query] ( literal[string] ). identifier[loc] [:,
[ literal[string] ,
literal[string] ]]. identifier[dropna] ()
identifier[res] = identifier[... | def QA_data_calc_marketvalue(data, xdxr):
"""使用数据库数据计算复权"""
mv = xdxr.query('category!=6').loc[:, ['shares_after', 'liquidity_after']].dropna()
res = pd.concat([data, mv], axis=1)
res = res.assign(shares=res.shares_after.fillna(method='ffill'), lshares=res.liquidity_after.fillna(method='ffill'))
ret... |
def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and... | def function[get_yaml_items, parameter[self, dir_path, param]]:
constant[
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
... | keyword[def] identifier[get_yaml_items] ( identifier[self] , identifier[dir_path] , identifier[param] = keyword[None] ):
literal[string]
identifier[result] =[]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[dir_path] ):
keyword[... | def get_yaml_items(self, dir_path, param=None):
"""
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a l... |
def apt_key_exists(keyid):
"""
Check if the given key id exists in apt keyring.
"""
# Command extracted from apt-key source
gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'
with settings(hide('everything'), warn_only=True):
res = r... | def function[apt_key_exists, parameter[keyid]]:
constant[
Check if the given key id exists in apt keyring.
]
variable[gpg_cmd] assign[=] constant[gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg]
with call[name[settings], parameter[call[name[hid... | keyword[def] identifier[apt_key_exists] ( identifier[keyid] ):
literal[string]
identifier[gpg_cmd] = literal[string]
keyword[with] identifier[settings] ( identifier[hide] ( literal[string] ), identifier[warn_only] = keyword[True] ):
identifier[res] = identifier[run] ( literal[string]... | def apt_key_exists(keyid):
"""
Check if the given key id exists in apt keyring.
"""
# Command extracted from apt-key source
gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'
with settings(hide('everything'), warn_only=True):
res = run... |
def _weightfun_spatial_distance(data, params, report):
"""
Creates the weights for the spatial distance method. See func: teneto.derive.derive.
"""
distance = getDistanceFunction(params['distance'])
weights = np.array([distance(data[n, :], data[t, :]) for n in np.arange(
0, data.shape[0]) fo... | def function[_weightfun_spatial_distance, parameter[data, params, report]]:
constant[
Creates the weights for the spatial distance method. See func: teneto.derive.derive.
]
variable[distance] assign[=] call[name[getDistanceFunction], parameter[call[name[params]][constant[distance]]]]
var... | keyword[def] identifier[_weightfun_spatial_distance] ( identifier[data] , identifier[params] , identifier[report] ):
literal[string]
identifier[distance] = identifier[getDistanceFunction] ( identifier[params] [ literal[string] ])
identifier[weights] = identifier[np] . identifier[array] ([ identifier[d... | def _weightfun_spatial_distance(data, params, report):
"""
Creates the weights for the spatial distance method. See func: teneto.derive.derive.
"""
distance = getDistanceFunction(params['distance'])
weights = np.array([distance(data[n, :], data[t, :]) for n in np.arange(0, data.shape[0]) for t in np... |
def find_rings(self, mol, all_atoms):
"""Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic."""
data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
rings = []
aromatic_amino = ... | def function[find_rings, parameter[self, mol, all_atoms]]:
constant[Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic.]
variable[data] assign[=] call[name[namedtuple], parameter[constant[aromatic_ring], constant[atoms orig_atoms ato... | keyword[def] identifier[find_rings] ( identifier[self] , identifier[mol] , identifier[all_atoms] ):
literal[string]
identifier[data] = identifier[namedtuple] ( literal[string] , literal[string] )
identifier[rings] =[]
identifier[aromatic_amino] =[ literal[string] , literal[string]... | def find_rings(self, mol, all_atoms):
"""Find rings and return only aromatic.
Rings have to be sufficiently planar OR be detected by OpenBabel as aromatic."""
data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
rings = []
aromatic_amino = ['TYR', 'TRP', '... |
async def SetStatusMessage(self, message):
'''
message : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='MigrationMaster',
request='SetStatusMessage',
version=1,
params... | <ast.AsyncFunctionDef object at 0x7da1b0ebd4b0> | keyword[async] keyword[def] identifier[SetStatusMessage] ( identifier[self] , identifier[message] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = literal[string] ... | async def SetStatusMessage(self, message):
"""
message : str
Returns -> None
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='MigrationMaster', request='SetStatusMessage', version=1, params=_params)
_params['message'] = message
reply = await self.rpc(msg... |
def add_issues_to_sprint(self, sprint_id, issue_keys):
"""Add the issues in ``issue_keys`` to the ``sprint_id``.
The sprint must be started but not completed.
If a sprint was completed, then have to also edit the history of the
issue so that it was added to the sprint before it was com... | def function[add_issues_to_sprint, parameter[self, sprint_id, issue_keys]]:
constant[Add the issues in ``issue_keys`` to the ``sprint_id``.
The sprint must be started but not completed.
If a sprint was completed, then have to also edit the history of the
issue so that it was added to t... | keyword[def] identifier[add_issues_to_sprint] ( identifier[self] , identifier[sprint_id] , identifier[issue_keys] ):
literal[string]
keyword[if] identifier[self] . identifier[_options] [ literal[string] ]== identifier[GreenHopperResource] . identifier[AGILE_BASE_REST_PATH] :
identifie... | def add_issues_to_sprint(self, sprint_id, issue_keys):
"""Add the issues in ``issue_keys`` to the ``sprint_id``.
The sprint must be started but not completed.
If a sprint was completed, then have to also edit the history of the
issue so that it was added to the sprint before it was complet... |
def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifo,
dyn_range_factor=1., precision=None):
"""
Associate PSDs to segments for a single ifo when using the multi-detector
CLI
"""
... | def function[associate_psds_to_single_ifo_segments, parameter[opt, fd_segments, gwstrain, flen, delta_f, flow, ifo, dyn_range_factor, precision]]:
constant[
Associate PSDs to segments for a single ifo when using the multi-detector
CLI
]
variable[single_det_opt] assign[=] call[name[copy_opts_... | keyword[def] identifier[associate_psds_to_single_ifo_segments] ( identifier[opt] , identifier[fd_segments] , identifier[gwstrain] , identifier[flen] ,
identifier[delta_f] , identifier[flow] , identifier[ifo] ,
identifier[dyn_range_factor] = literal[int] , identifier[precision] = keyword[None] ):
literal[string... | def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen, delta_f, flow, ifo, dyn_range_factor=1.0, precision=None):
"""
Associate PSDs to segments for a single ifo when using the multi-detector
CLI
"""
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
associate_psds_to_segme... |
def writeGlobalFileStream(self, cleanup=False):
"""
Similar to writeGlobalFile, but allows the writing of a stream to the job store.
The yielded file handle does not need to and should not be closed explicitly.
:param bool cleanup: is as in :func:`toil.fileStore.FileStore.writeGlobalFil... | def function[writeGlobalFileStream, parameter[self, cleanup]]:
constant[
Similar to writeGlobalFile, but allows the writing of a stream to the job store.
The yielded file handle does not need to and should not be closed explicitly.
:param bool cleanup: is as in :func:`toil.fileStore.Fil... | keyword[def] identifier[writeGlobalFileStream] ( identifier[self] , identifier[cleanup] = keyword[False] ):
literal[string]
keyword[with] identifier[self] . identifier[jobStore] . identifier[writeFileStream] ( keyword[None] keyword[if] keyword[not] identifier[cleanup] keyword[else] ... | def writeGlobalFileStream(self, cleanup=False):
"""
Similar to writeGlobalFile, but allows the writing of a stream to the job store.
The yielded file handle does not need to and should not be closed explicitly.
:param bool cleanup: is as in :func:`toil.fileStore.FileStore.writeGlobalFile`.
... |
def all_features():
''' Returns dictionary of all features in the module
.. note:: Some of the features (hist4, corr) are relatively expensive to compute
'''
features = {'mean': mean,
'median': median,
'gmean': gmean,
'hmean': hmean,
'vec_... | def function[all_features, parameter[]]:
constant[ Returns dictionary of all features in the module
.. note:: Some of the features (hist4, corr) are relatively expensive to compute
]
variable[features] assign[=] dictionary[[<ast.Constant object at 0x7da1b15f1e70>, <ast.Constant object at 0x7da1... | keyword[def] identifier[all_features] ():
literal[string]
identifier[features] ={ literal[string] : identifier[mean] ,
literal[string] : identifier[median] ,
literal[string] : identifier[gmean] ,
literal[string] : identifier[hmean] ,
literal[string] : identifier[vec_sum] ,
literal[... | def all_features():
""" Returns dictionary of all features in the module
.. note:: Some of the features (hist4, corr) are relatively expensive to compute
"""
features = {'mean': mean, 'median': median, 'gmean': gmean, 'hmean': hmean, 'vec_sum': vec_sum, 'abs_sum': abs_sum, 'abs_energy': abs_energy, 'st... |
def get_dates_link(url):
""" download the dates file from the internet and parse it as a dates file"""
urllib.request.urlretrieve(url, "temp.txt")
dates = get_dates_file("temp.txt")
os.remove("temp.txt")
return dates | def function[get_dates_link, parameter[url]]:
constant[ download the dates file from the internet and parse it as a dates file]
call[name[urllib].request.urlretrieve, parameter[name[url], constant[temp.txt]]]
variable[dates] assign[=] call[name[get_dates_file], parameter[constant[temp.txt]]]
... | keyword[def] identifier[get_dates_link] ( identifier[url] ):
literal[string]
identifier[urllib] . identifier[request] . identifier[urlretrieve] ( identifier[url] , literal[string] )
identifier[dates] = identifier[get_dates_file] ( literal[string] )
identifier[os] . identifier[remove] ( literal[st... | def get_dates_link(url):
""" download the dates file from the internet and parse it as a dates file"""
urllib.request.urlretrieve(url, 'temp.txt')
dates = get_dates_file('temp.txt')
os.remove('temp.txt')
return dates |
def datafile(self):
"""Return an MPR datafile from the /ingest directory of the build filesystem"""
from ambry_sources import MPRowsFile
if self._datafile is None:
if self.urltype == 'partition':
self._datafile = self.partition.datafile
else:
... | def function[datafile, parameter[self]]:
constant[Return an MPR datafile from the /ingest directory of the build filesystem]
from relative_module[ambry_sources] import module[MPRowsFile]
if compare[name[self]._datafile is constant[None]] begin[:]
if compare[name[self].urltype equal[=... | keyword[def] identifier[datafile] ( identifier[self] ):
literal[string]
keyword[from] identifier[ambry_sources] keyword[import] identifier[MPRowsFile]
keyword[if] identifier[self] . identifier[_datafile] keyword[is] keyword[None] :
keyword[if] identifier[self] . ident... | def datafile(self):
"""Return an MPR datafile from the /ingest directory of the build filesystem"""
from ambry_sources import MPRowsFile
if self._datafile is None:
if self.urltype == 'partition':
self._datafile = self.partition.datafile # depends on [control=['if'], data=[]]
els... |
def _create_validate_config(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Create a bcbio.variation configuration input for validation.
"""
ref_call = {"file": str(rm_file), "name": "ref", "type": "grading-ref",
"fix-sample-header": True, "remove-refcalls": True}
a_intervals = ... | def function[_create_validate_config, parameter[vrn_file, rm_file, rm_interval_file, base_dir, data]]:
constant[Create a bcbio.variation configuration input for validation.
]
variable[ref_call] assign[=] dictionary[[<ast.Constant object at 0x7da1b19bb2e0>, <ast.Constant object at 0x7da1b19b90c0>, <a... | keyword[def] identifier[_create_validate_config] ( identifier[vrn_file] , identifier[rm_file] , identifier[rm_interval_file] , identifier[base_dir] , identifier[data] ):
literal[string]
identifier[ref_call] ={ literal[string] : identifier[str] ( identifier[rm_file] ), literal[string] : literal[string] , li... | def _create_validate_config(vrn_file, rm_file, rm_interval_file, base_dir, data):
"""Create a bcbio.variation configuration input for validation.
"""
ref_call = {'file': str(rm_file), 'name': 'ref', 'type': 'grading-ref', 'fix-sample-header': True, 'remove-refcalls': True}
a_intervals = get_analysis_int... |
def get_page_artid_for_publication_info(publication_info, separator):
"""Return the page range or the article id of a publication_info entry.
Args:
publication_info(dict): a publication_info field entry of a record
separator(basestring): optional page range symbol, defaults to a... | def function[get_page_artid_for_publication_info, parameter[publication_info, separator]]:
constant[Return the page range or the article id of a publication_info entry.
Args:
publication_info(dict): a publication_info field entry of a record
separator(basestring): optional page ... | keyword[def] identifier[get_page_artid_for_publication_info] ( identifier[publication_info] , identifier[separator] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[publication_info] :
keyword[return] identifier[publication_info] [ literal[string] ]
k... | def get_page_artid_for_publication_info(publication_info, separator):
"""Return the page range or the article id of a publication_info entry.
Args:
publication_info(dict): a publication_info field entry of a record
separator(basestring): optional page range symbol, defaults to a sin... |
def taskinfo_with_label(label):
"""Return task info dictionary from task label. Internal function,
pretty much only used in migrations since the model methods aren't there."""
task = Task.objects.get(label=label)
info = json.loads(task._func_info)
return info | def function[taskinfo_with_label, parameter[label]]:
constant[Return task info dictionary from task label. Internal function,
pretty much only used in migrations since the model methods aren't there.]
variable[task] assign[=] call[name[Task].objects.get, parameter[]]
variable[info] assign[=... | keyword[def] identifier[taskinfo_with_label] ( identifier[label] ):
literal[string]
identifier[task] = identifier[Task] . identifier[objects] . identifier[get] ( identifier[label] = identifier[label] )
identifier[info] = identifier[json] . identifier[loads] ( identifier[task] . identifier[_func_info] ... | def taskinfo_with_label(label):
"""Return task info dictionary from task label. Internal function,
pretty much only used in migrations since the model methods aren't there."""
task = Task.objects.get(label=label)
info = json.loads(task._func_info)
return info |
def set_value(self, value):
"""Set the value associated with the keyword"""
if not isinstance(value, str):
raise TypeError("A value must be a string, got %s." % value)
self.__value = value | def function[set_value, parameter[self, value]]:
constant[Set the value associated with the keyword]
if <ast.UnaryOp object at 0x7da20c6a9900> begin[:]
<ast.Raise object at 0x7da20c6aa020>
name[self].__value assign[=] name[value] | keyword[def] identifier[set_value] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[str] ):
keyword[raise] identifier[TypeError] ( literal[string] % identifier[value] )
identifier[self... | def set_value(self, value):
"""Set the value associated with the keyword"""
if not isinstance(value, str):
raise TypeError('A value must be a string, got %s.' % value) # depends on [control=['if'], data=[]]
self.__value = value |
def ParsePythonFlags(self, start_line=0):
"""Parse python/swig style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: ... | def function[ParsePythonFlags, parameter[self, start_line]]:
constant[Parse python/swig style flags.]
variable[modname] assign[=] constant[None]
variable[modlist] assign[=] list[[]]
variable[flag] assign[=] constant[None]
for taget[name[line_num]] in starred[call[name[range], par... | keyword[def] identifier[ParsePythonFlags] ( identifier[self] , identifier[start_line] = literal[int] ):
literal[string]
identifier[modname] = keyword[None]
identifier[modlist] =[]
identifier[flag] = keyword[None]
keyword[for] identifier[line_num] keyword[in] identifier[range] ( identifi... | def ParsePythonFlags(self, start_line=0):
"""Parse python/swig style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: # blank
... |
def application(self, environ, start_response):
"""Process a single WSGI request/response cycle.
This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware,
the `__call__` attribute of the Application instance will either become this, or become the outermost
midd... | def function[application, parameter[self, environ, start_response]]:
constant[Process a single WSGI request/response cycle.
This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware,
the `__call__` attribute of the Application instance will either become thi... | keyword[def] identifier[application] ( identifier[self] , identifier[environ] , identifier[start_response] ):
literal[string]
identifier[context] = identifier[environ] [ literal[string] ]= identifier[self] . identifier[RequestContext] ( identifier[environ] = identifier[environ] )
identifier[signals] = ident... | def application(self, environ, start_response):
"""Process a single WSGI request/response cycle.
This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware,
the `__call__` attribute of the Application instance will either become this, or become the outermost
mi... |
def relabel_squeeze(data):
""" Makes relabeling of data if there are unused values. """
palette, index = np.unique(data, return_inverse=True)
data = index.reshape(data.shape)
# realy slow solution
# unq = np.unique(data)
# actual_label = 0
# for lab in unq:
# ... | def function[relabel_squeeze, parameter[data]]:
constant[ Makes relabeling of data if there are unused values. ]
<ast.Tuple object at 0x7da20e963d60> assign[=] call[name[np].unique, parameter[name[data]]]
variable[data] assign[=] call[name[index].reshape, parameter[name[data].shape]]
retur... | keyword[def] identifier[relabel_squeeze] ( identifier[data] ):
literal[string]
identifier[palette] , identifier[index] = identifier[np] . identifier[unique] ( identifier[data] , identifier[return_inverse] = keyword[True] )
identifier[data] = identifier[index] . identifier[reshape] ( identifier[data] .... | def relabel_squeeze(data):
""" Makes relabeling of data if there are unused values. """
(palette, index) = np.unique(data, return_inverse=True)
data = index.reshape(data.shape)
# realy slow solution
# unq = np.unique(data)
# actual_label = 0
# for lab in unq:
# ... |
def sort(self):
"""Sort the data so that x is monotonically increasing and contains
no duplicates.
"""
if 'wavelength' in self.rsr:
# Only one detector apparently:
self.rsr['wavelength'], self.rsr['response'] = \
sort_data(self.rsr['wavelength'], s... | def function[sort, parameter[self]]:
constant[Sort the data so that x is monotonically increasing and contains
no duplicates.
]
if compare[constant[wavelength] in name[self].rsr] begin[:]
<ast.Tuple object at 0x7da1b0c647c0> assign[=] call[name[sort_data], parameter[call[... | keyword[def] identifier[sort] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[rsr] :
identifier[self] . identifier[rsr] [ literal[string] ], identifier[self] . identifier[rsr] [ literal[string] ]= identifier[sort_d... | def sort(self):
"""Sort the data so that x is monotonically increasing and contains
no duplicates.
"""
if 'wavelength' in self.rsr:
# Only one detector apparently:
(self.rsr['wavelength'], self.rsr['response']) = sort_data(self.rsr['wavelength'], self.rsr['response']) # depends ... |
def codes_get_string_length(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the length of the string representation of the key.
If several keys of the same name are present, the maximum length is returned.
:param bytes key: the keyword to get the string representation size of.
:rtyp... | def function[codes_get_string_length, parameter[handle, key]]:
constant[
Get the length of the string representation of the key.
If several keys of the same name are present, the maximum length is returned.
:param bytes key: the keyword to get the string representation size of.
:rtype: int
... | keyword[def] identifier[codes_get_string_length] ( identifier[handle] , identifier[key] ):
literal[string]
identifier[size] = identifier[ffi] . identifier[new] ( literal[string] )
identifier[_codes_get_length] ( identifier[handle] , identifier[key] . identifier[encode] ( identifier[ENC] ), identifier... | def codes_get_string_length(handle, key):
# type: (cffi.FFI.CData, str) -> int
'\n Get the length of the string representation of the key.\n If several keys of the same name are present, the maximum length is returned.\n\n :param bytes key: the keyword to get the string representation size of.\n\n :... |
def report_altitude(self, altitude):
'''possibly report a new altitude'''
master = self.master
if getattr(self.console, 'ElevationMap', None) is not None and self.mpstate.settings.basealt != 0:
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0)*1.0e-7
lon = master.field(... | def function[report_altitude, parameter[self, altitude]]:
constant[possibly report a new altitude]
variable[master] assign[=] name[self].master
if <ast.BoolOp object at 0x7da1b17dcbb0> begin[:]
variable[lat] assign[=] binary_operation[call[name[master].field, parameter[constant[G... | keyword[def] identifier[report_altitude] ( identifier[self] , identifier[altitude] ):
literal[string]
identifier[master] = identifier[self] . identifier[master]
keyword[if] identifier[getattr] ( identifier[self] . identifier[console] , literal[string] , keyword[None] ) keyword[is] keywo... | def report_altitude(self, altitude):
"""possibly report a new altitude"""
master = self.master
if getattr(self.console, 'ElevationMap', None) is not None and self.mpstate.settings.basealt != 0:
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1e-07
lon = master.field('GLOBAL_POSITION_IN... |
def main(argv=None):
"""ben-wait entry point"""
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['... | def function[main, parameter[argv]]:
constant[ben-wait entry point]
variable[arguments] assign[=] call[name[cli_common], parameter[name[__doc__]]]
variable[report] assign[=] call[name[ReportNode], parameter[call[name[arguments]][constant[CAMPAIGN-DIR]]]]
variable[jobs] assign[=] call[nam... | keyword[def] identifier[main] ( identifier[argv] = keyword[None] ):
literal[string]
identifier[arguments] = identifier[cli_common] ( identifier[__doc__] , identifier[argv] = identifier[argv] )
identifier[report] = identifier[ReportNode] ( identifier[arguments] [ literal[string] ])
identifier[jobs... | def main(argv=None):
"""ben-wait entry point"""
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.