code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def check_datafile_present_and_download(path, backup_url=None):
"""Check whether the file is present, otherwise download.
"""
path = Path(path)
if path.is_file(): return True
if backup_url is None: return False
logg.info('try downloading from url\n' + backup_url + '\n' +
'... this ... | def function[check_datafile_present_and_download, parameter[path, backup_url]]:
constant[Check whether the file is present, otherwise download.
]
variable[path] assign[=] call[name[Path], parameter[name[path]]]
if call[name[path].is_file, parameter[]] begin[:]
return[constant[True]]
... | keyword[def] identifier[check_datafile_present_and_download] ( identifier[path] , identifier[backup_url] = keyword[None] ):
literal[string]
identifier[path] = identifier[Path] ( identifier[path] )
keyword[if] identifier[path] . identifier[is_file] (): keyword[return] keyword[True]
keyword[if] ... | def check_datafile_present_and_download(path, backup_url=None):
"""Check whether the file is present, otherwise download.
"""
path = Path(path)
if path.is_file():
return True # depends on [control=['if'], data=[]]
if backup_url is None:
return False # depends on [control=['if'], da... |
def calculate(*args, **kwargs):
'''
Calculates and returns a requested quantity from quantities passed in as
keyword arguments.
Parameters
----------
\*args : string
Names of quantities to be calculated.
assumptions : tuple, optional
Strings specifying which assumptions to enable. Overrides the default
... | def function[calculate, parameter[]]:
constant[
Calculates and returns a requested quantity from quantities passed in as
keyword arguments.
Parameters
----------
\*args : string
Names of quantities to be calculated.
assumptions : tuple, optional
Strings specifying which assumptions to enable. Override... | keyword[def] identifier[calculate] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[solver] = identifier[FluidSolver] (** identifier[k... | def calculate(*args, **kwargs):
"""
Calculates and returns a requested quantity from quantities passed in as
keyword arguments.
Parameters
----------
\\*args : string
Names of quantities to be calculated.
assumptions : tuple, optional
Strings specifying which assumptions to enable. Overrides the default
... |
def full_name(self):
"""Get the name of the day of the week.
Returns
-------
StringValue
The name of the day of the week
"""
import ibis.expr.operations as ops
return ops.DayOfWeekName(self.op().arg).to_expr() | def function[full_name, parameter[self]]:
constant[Get the name of the day of the week.
Returns
-------
StringValue
The name of the day of the week
]
import module[ibis.expr.operations] as alias[ops]
return[call[call[name[ops].DayOfWeekName, parameter[call[na... | keyword[def] identifier[full_name] ( identifier[self] ):
literal[string]
keyword[import] identifier[ibis] . identifier[expr] . identifier[operations] keyword[as] identifier[ops]
keyword[return] identifier[ops] . identifier[DayOfWeekName] ( identifier[self] . identifier[op] (). identi... | def full_name(self):
"""Get the name of the day of the week.
Returns
-------
StringValue
The name of the day of the week
"""
import ibis.expr.operations as ops
return ops.DayOfWeekName(self.op().arg).to_expr() |
def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(
lambda dt: ms_since_epoch(datetime.combine(
... | def function[status_codes_by_date_stats, parameter[]]:
constant[
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
]
def function[date_counter, parameter[queryset]]:
return[call[name[dict], parameter[call[nam... | keyword[def] identifier[status_codes_by_date_stats] ():
literal[string]
keyword[def] identifier[date_counter] ( identifier[queryset] ):
keyword[return] identifier[dict] ( identifier[Counter] ( identifier[map] (
keyword[lambda] identifier[dt] : identifier[ms_since_epoch] ( identifier[d... | def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(lambda dt: ms_since_epoch(datetime.combine(make_naive(dt), datetime.min... |
def get_installed_version(self):
"""Return dependency status (string)"""
if self.check():
return '%s (%s)' % (self.installed_version, self.OK)
else:
return '%s (%s)' % (self.installed_version, self.NOK) | def function[get_installed_version, parameter[self]]:
constant[Return dependency status (string)]
if call[name[self].check, parameter[]] begin[:]
return[binary_operation[constant[%s (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b20437f0>, <ast.Attribute object at... | keyword[def] identifier[get_installed_version] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[check] ():
keyword[return] literal[string] %( identifier[self] . identifier[installed_version] , identifier[self] . identifier[OK] )
keyword[els... | def get_installed_version(self):
"""Return dependency status (string)"""
if self.check():
return '%s (%s)' % (self.installed_version, self.OK) # depends on [control=['if'], data=[]]
else:
return '%s (%s)' % (self.installed_version, self.NOK) |
def setup(self, pin, value):
"""Set the input or output mode for a specified pin. Mode should be
either GPIO.OUT or GPIO.IN.
"""
self._validate_pin(pin)
# Set bit to 1 for input or 0 for output.
if value == GPIO.IN:
self.iodir[int(pin/8)] |= 1 << (int(pin%8))... | def function[setup, parameter[self, pin, value]]:
constant[Set the input or output mode for a specified pin. Mode should be
either GPIO.OUT or GPIO.IN.
]
call[name[self]._validate_pin, parameter[name[pin]]]
if compare[name[value] equal[==] name[GPIO].IN] begin[:]
<ast.Au... | keyword[def] identifier[setup] ( identifier[self] , identifier[pin] , identifier[value] ):
literal[string]
identifier[self] . identifier[_validate_pin] ( identifier[pin] )
keyword[if] identifier[value] == identifier[GPIO] . identifier[IN] :
identifier[self] . identif... | def setup(self, pin, value):
"""Set the input or output mode for a specified pin. Mode should be
either GPIO.OUT or GPIO.IN.
"""
self._validate_pin(pin)
# Set bit to 1 for input or 0 for output.
if value == GPIO.IN:
self.iodir[int(pin / 8)] |= 1 << int(pin % 8) # depends on [co... |
def sgn(x):
"""
Return the sign of x.
Return a positive integer if x > 0, 0 if x == 0, and a negative integer if
x < 0. Raise ValueError if x is a NaN.
This function is equivalent to cmp(x, 0), but more efficient.
"""
x = BigFloat._implicit_convert(x)
if is_nan(x):
raise Valu... | def function[sgn, parameter[x]]:
constant[
Return the sign of x.
Return a positive integer if x > 0, 0 if x == 0, and a negative integer if
x < 0. Raise ValueError if x is a NaN.
This function is equivalent to cmp(x, 0), but more efficient.
]
variable[x] assign[=] call[name[BigFl... | keyword[def] identifier[sgn] ( identifier[x] ):
literal[string]
identifier[x] = identifier[BigFloat] . identifier[_implicit_convert] ( identifier[x] )
keyword[if] identifier[is_nan] ( identifier[x] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier... | def sgn(x):
"""
Return the sign of x.
Return a positive integer if x > 0, 0 if x == 0, and a negative integer if
x < 0. Raise ValueError if x is a NaN.
This function is equivalent to cmp(x, 0), but more efficient.
"""
x = BigFloat._implicit_convert(x)
if is_nan(x):
raise Valu... |
def shutdown(self):
"""Wait for all threads to complete"""
# cleanup
self.started = False
try:
# nice way of doing things - let's wait until all items
# in the queue are processed
for t in self._threads:
t.join()
finally:
... | def function[shutdown, parameter[self]]:
constant[Wait for all threads to complete]
name[self].started assign[=] constant[False]
<ast.Try object at 0x7da1b287f4f0> | keyword[def] identifier[shutdown] ( identifier[self] ):
literal[string]
identifier[self] . identifier[started] = keyword[False]
keyword[try] :
keyword[for] identifier[t] keyword[in] identifier[self] . identifier[_threads] :
ident... | def shutdown(self):
"""Wait for all threads to complete"""
# cleanup
self.started = False
try:
# nice way of doing things - let's wait until all items
# in the queue are processed
for t in self._threads:
t.join() # depends on [control=['for'], data=['t']] # depends ... |
def get_fields(Model,
parent_field="",
model_stack=None,
stack_limit=2,
excludes=['permissions', 'comment', 'content_type']):
"""
Given a Model, return a list of lists of strings with important stuff:
...
['test_user__user__customuser', 'custo... | def function[get_fields, parameter[Model, parent_field, model_stack, stack_limit, excludes]]:
constant[
Given a Model, return a list of lists of strings with important stuff:
...
['test_user__user__customuser', 'customuser', 'User', 'RelatedObject']
['test_user__unique_id', 'unique_id', 'TestUse... | keyword[def] identifier[get_fields] ( identifier[Model] ,
identifier[parent_field] = literal[string] ,
identifier[model_stack] = keyword[None] ,
identifier[stack_limit] = literal[int] ,
identifier[excludes] =[ literal[string] , literal[string] , literal[string] ]):
literal[string]
identifier[out_fields... | def get_fields(Model, parent_field='', model_stack=None, stack_limit=2, excludes=['permissions', 'comment', 'content_type']):
"""
Given a Model, return a list of lists of strings with important stuff:
...
['test_user__user__customuser', 'customuser', 'User', 'RelatedObject']
['test_user__unique_id',... |
def user(context, institute_id, user_name, user_mail, admin):
"""Add a user to the database."""
adapter = context.obj['adapter']
institutes = []
for institute in institute_id:
institute_obj = adapter.institute(institute_id=institute)
if not institute_obj:
LOG.warning("Insti... | def function[user, parameter[context, institute_id, user_name, user_mail, admin]]:
constant[Add a user to the database.]
variable[adapter] assign[=] call[name[context].obj][constant[adapter]]
variable[institutes] assign[=] list[[]]
for taget[name[institute]] in starred[name[institute_id]... | keyword[def] identifier[user] ( identifier[context] , identifier[institute_id] , identifier[user_name] , identifier[user_mail] , identifier[admin] ):
literal[string]
identifier[adapter] = identifier[context] . identifier[obj] [ literal[string] ]
identifier[institutes] =[]
keyword[for] identifie... | def user(context, institute_id, user_name, user_mail, admin):
"""Add a user to the database."""
adapter = context.obj['adapter']
institutes = []
for institute in institute_id:
institute_obj = adapter.institute(institute_id=institute)
if not institute_obj:
LOG.warning('Institu... |
def _get_simpx_plane(self):
"""
Locate the plane for simpx of on wulff_cv, by comparing the center of
the simpx triangle with the plane functions.
"""
on_wulff = [False] * len(self.miller_list)
surface_area = [0.0] * len(self.miller_list)
for simpx in self.wulff_c... | def function[_get_simpx_plane, parameter[self]]:
constant[
Locate the plane for simpx of on wulff_cv, by comparing the center of
the simpx triangle with the plane functions.
]
variable[on_wulff] assign[=] binary_operation[list[[<ast.Constant object at 0x7da18dc04d30>]] * call[nam... | keyword[def] identifier[_get_simpx_plane] ( identifier[self] ):
literal[string]
identifier[on_wulff] =[ keyword[False] ]* identifier[len] ( identifier[self] . identifier[miller_list] )
identifier[surface_area] =[ literal[int] ]* identifier[len] ( identifier[self] . identifier[miller_list] ... | def _get_simpx_plane(self):
"""
Locate the plane for simpx of on wulff_cv, by comparing the center of
the simpx triangle with the plane functions.
"""
on_wulff = [False] * len(self.miller_list)
surface_area = [0.0] * len(self.miller_list)
for simpx in self.wulff_cv_simp:
... |
def export_img(visio_filename, image_filename, pagenum=None, pagename=None):
""" Exports images from visio file """
# visio requires absolute path
image_pathname = os.path.abspath(image_filename)
if not os.path.isdir(os.path.dirname(image_pathname)):
msg = 'Could not write image file: %s' % ima... | def function[export_img, parameter[visio_filename, image_filename, pagenum, pagename]]:
constant[ Exports images from visio file ]
variable[image_pathname] assign[=] call[name[os].path.abspath, parameter[name[image_filename]]]
if <ast.UnaryOp object at 0x7da18c4ce320> begin[:]
va... | keyword[def] identifier[export_img] ( identifier[visio_filename] , identifier[image_filename] , identifier[pagenum] = keyword[None] , identifier[pagename] = keyword[None] ):
literal[string]
identifier[image_pathname] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[image_filename... | def export_img(visio_filename, image_filename, pagenum=None, pagename=None):
""" Exports images from visio file """
# visio requires absolute path
image_pathname = os.path.abspath(image_filename)
if not os.path.isdir(os.path.dirname(image_pathname)):
msg = 'Could not write image file: %s' % imag... |
def _metrics_options(p):
""" Add options specific to metrics subcommand. """
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument(
'--start', type=date_parse,
help='Start date (requires --end, overrides --days)')
p.add_argument(
'--end', ty... | def function[_metrics_options, parameter[p]]:
constant[ Add options specific to metrics subcommand. ]
call[name[_default_options], parameter[name[p]]]
call[name[p].add_argument, parameter[constant[--start]]]
call[name[p].add_argument, parameter[constant[--end]]]
call[name[p].add_... | keyword[def] identifier[_metrics_options] ( identifier[p] ):
literal[string]
identifier[_default_options] ( identifier[p] , identifier[blacklist] =[ literal[string] , literal[string] , literal[string] , literal[string] ])
identifier[p] . identifier[add_argument] (
literal[string] , identifier[ty... | def _metrics_options(p):
""" Add options specific to metrics subcommand. """
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument('--start', type=date_parse, help='Start date (requires --end, overrides --days)')
p.add_argument('--end', type=date_parse, help='End da... |
def read_data(self, **kwargs):
'''
Read the datafile specified in Sample.datafile and
return the resulting object.
Does NOT assign the data to self.data
It's advised not to use this method, but instead to access
the data through the FCMeasurement.data attribute.
... | def function[read_data, parameter[self]]:
constant[
Read the datafile specified in Sample.datafile and
return the resulting object.
Does NOT assign the data to self.data
It's advised not to use this method, but instead to access
the data through the FCMeasurement.data at... | keyword[def] identifier[read_data] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[meta] , identifier[data] = identifier[parse_fcs] ( identifier[self] . identifier[datafile] ,** identifier[kwargs] )
keyword[return] identifier[data] | def read_data(self, **kwargs):
"""
Read the datafile specified in Sample.datafile and
return the resulting object.
Does NOT assign the data to self.data
It's advised not to use this method, but instead to access
the data through the FCMeasurement.data attribute.
"""
... |
def set_defaults(self, config_file):
"""Set defaults.
"""
self.defaults = Defaults(config_file)
self.locations = Locations(self.defaults)
self.python = Python()
self.setuptools = Setuptools()
self.scp = SCP()
self.scms = SCMFactory()
self.urlparser... | def function[set_defaults, parameter[self, config_file]]:
constant[Set defaults.
]
name[self].defaults assign[=] call[name[Defaults], parameter[name[config_file]]]
name[self].locations assign[=] call[name[Locations], parameter[name[self].defaults]]
name[self].python assign[=] cal... | keyword[def] identifier[set_defaults] ( identifier[self] , identifier[config_file] ):
literal[string]
identifier[self] . identifier[defaults] = identifier[Defaults] ( identifier[config_file] )
identifier[self] . identifier[locations] = identifier[Locations] ( identifier[self] . identifier[... | def set_defaults(self, config_file):
"""Set defaults.
"""
self.defaults = Defaults(config_file)
self.locations = Locations(self.defaults)
self.python = Python()
self.setuptools = Setuptools()
self.scp = SCP()
self.scms = SCMFactory()
self.urlparser = URLParser()
self.skipcomm... |
def get_host_map(root):
''' Gets a mapping between CM hostId and Nagios host information
The key is the CM hostId
The value is an object containing the Nagios hostname and host address
'''
hosts_map = {}
for host in root.get_all_hosts():
hosts_map[host.hostId] = {"hostname": NAGIOS_HOSTNAME_FOR... | def function[get_host_map, parameter[root]]:
constant[ Gets a mapping between CM hostId and Nagios host information
The key is the CM hostId
The value is an object containing the Nagios hostname and host address
]
variable[hosts_map] assign[=] dictionary[[], []]
for taget[name[hos... | keyword[def] identifier[get_host_map] ( identifier[root] ):
literal[string]
identifier[hosts_map] ={}
keyword[for] identifier[host] keyword[in] identifier[root] . identifier[get_all_hosts] ():
identifier[hosts_map] [ identifier[host] . identifier[hostId] ]={ literal[string] : identifier[NAGIOS_HOSTN... | def get_host_map(root):
""" Gets a mapping between CM hostId and Nagios host information
The key is the CM hostId
The value is an object containing the Nagios hostname and host address
"""
hosts_map = {}
for host in root.get_all_hosts():
hosts_map[host.hostId] = {'hostname': NAGIOS_HO... |
def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
... | def function[save_checkpoint, parameter[model, filename, optimizer, meta]]:
constant[Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are... | keyword[def] identifier[save_checkpoint] ( identifier[model] , identifier[filename] , identifier[optimizer] = keyword[None] , identifier[meta] = keyword[None] ):
literal[string]
keyword[if] identifier[meta] keyword[is] keyword[None] :
identifier[meta] ={}
keyword[elif] keyword[not] ident... | def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
... |
def add_profiler(self, id, profiler):
""" Add a profiler for RDD `id` """
if not self.profilers:
if self.profile_dump_path:
atexit.register(self.dump_profiles, self.profile_dump_path)
else:
atexit.register(self.show_profiles)
self.profiler... | def function[add_profiler, parameter[self, id, profiler]]:
constant[ Add a profiler for RDD `id` ]
if <ast.UnaryOp object at 0x7da18dc9bd30> begin[:]
if name[self].profile_dump_path begin[:]
call[name[atexit].register, parameter[name[self].dump_profiles, name[self... | keyword[def] identifier[add_profiler] ( identifier[self] , identifier[id] , identifier[profiler] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[profilers] :
keyword[if] identifier[self] . identifier[profile_dump_path] :
identifier[atexit] ... | def add_profiler(self, id, profiler):
""" Add a profiler for RDD `id` """
if not self.profilers:
if self.profile_dump_path:
atexit.register(self.dump_profiles, self.profile_dump_path) # depends on [control=['if'], data=[]]
else:
atexit.register(self.show_profiles) # dep... |
def refresh_waiting_tasks(self):
"""
Refresh the state of all WAITING tasks. This will, for example, update
Catching Timer Events whose waiting time has passed.
"""
assert not self.read_only
for my_task in self.get_tasks(Task.WAITING):
my_task.task_spec._updat... | def function[refresh_waiting_tasks, parameter[self]]:
constant[
Refresh the state of all WAITING tasks. This will, for example, update
Catching Timer Events whose waiting time has passed.
]
assert[<ast.UnaryOp object at 0x7da1b01ba6b0>]
for taget[name[my_task]] in starred[cal... | keyword[def] identifier[refresh_waiting_tasks] ( identifier[self] ):
literal[string]
keyword[assert] keyword[not] identifier[self] . identifier[read_only]
keyword[for] identifier[my_task] keyword[in] identifier[self] . identifier[get_tasks] ( identifier[Task] . identifier[WAITING] ):... | def refresh_waiting_tasks(self):
"""
Refresh the state of all WAITING tasks. This will, for example, update
Catching Timer Events whose waiting time has passed.
"""
assert not self.read_only
for my_task in self.get_tasks(Task.WAITING):
my_task.task_spec._update(my_task) # de... |
def maybe(cls, val: Optional[T]) -> 'Option[T]':
"""
Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``.
Args:
val: Some value.
Returns:
``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`.
Examples:
>>> O... | def function[maybe, parameter[cls, val]]:
constant[
Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``.
Args:
val: Some value.
Returns:
``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`.
Examples:
>>> Op... | keyword[def] identifier[maybe] ( identifier[cls] , identifier[val] : identifier[Optional] [ identifier[T] ])-> literal[string] :
literal[string]
keyword[return] identifier[cast] ( literal[string] , identifier[NONE] ) keyword[if] identifier[val] keyword[is] keyword[None] keyword[else] identifi... | def maybe(cls, val: Optional[T]) -> 'Option[T]':
"""
Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``.
Args:
val: Some value.
Returns:
``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`.
Examples:
>>> Optio... |
def addValueToField(self, i, value=None):
"""Add 'value' to the field i.
Parameters:
--------------------------------------------------------------------
value: value to be added
i: value is added to field i
"""
assert(len(self.fields)>i)
if value is None:
value = ... | def function[addValueToField, parameter[self, i, value]]:
constant[Add 'value' to the field i.
Parameters:
--------------------------------------------------------------------
value: value to be added
i: value is added to field i
]
assert[compare[call[name[len], parameter... | keyword[def] identifier[addValueToField] ( identifier[self] , identifier[i] , identifier[value] = keyword[None] ):
literal[string]
keyword[assert] ( identifier[len] ( identifier[self] . identifier[fields] )> identifier[i] )
keyword[if] identifier[value] keyword[is] keyword[None] :
identifie... | def addValueToField(self, i, value=None):
"""Add 'value' to the field i.
Parameters:
--------------------------------------------------------------------
value: value to be added
i: value is added to field i
"""
assert len(self.fields) > i
if value is None:
value ... |
def cancelMarketData(self, contracts=None):
"""
Cancel streaming market data for contract
https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm
"""
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance... | def function[cancelMarketData, parameter[self, contracts]]:
constant[
Cancel streaming market data for contract
https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm
]
if compare[name[contracts] equal[==] constant[None]] begin[:]
varia... | keyword[def] identifier[cancelMarketData] ( identifier[self] , identifier[contracts] = keyword[None] ):
literal[string]
keyword[if] identifier[contracts] == keyword[None] :
identifier[contracts] = identifier[list] ( identifier[self] . identifier[contracts] . identifier[values] ())
... | def cancelMarketData(self, contracts=None):
"""
Cancel streaming market data for contract
https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm
"""
if contracts == None:
contracts = list(self.contracts.values()) # depends on [control=['if'], data=['c... |
def setRandomParams(self):
"""
set random hyperparameters
"""
params = SP.randn(self.getNumberParams())
self.setParams(params) | def function[setRandomParams, parameter[self]]:
constant[
set random hyperparameters
]
variable[params] assign[=] call[name[SP].randn, parameter[call[name[self].getNumberParams, parameter[]]]]
call[name[self].setParams, parameter[name[params]]] | keyword[def] identifier[setRandomParams] ( identifier[self] ):
literal[string]
identifier[params] = identifier[SP] . identifier[randn] ( identifier[self] . identifier[getNumberParams] ())
identifier[self] . identifier[setParams] ( identifier[params] ) | def setRandomParams(self):
"""
set random hyperparameters
"""
params = SP.randn(self.getNumberParams())
self.setParams(params) |
def db_remove(name, user=None, password=None, host=None, port=None):
'''
Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI ... | def function[db_remove, parameter[name, user, password, host, port]]:
constant[
Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect t... | keyword[def] identifier[db_remove] ( identifier[name] , identifier[user] = keyword[None] , identifier[password] = keyword[None] , identifier[host] = keyword[None] , identifier[port] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[db_exists] ( identifier[name] , identifier[user] , i... | def db_remove(name, user=None, password=None, host=None, port=None):
"""
Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI ... |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = ToggleButton(self.get_context(), None,
d.style or "@attr/buttonStyleToggle") | def function[create_widget, parameter[self]]:
constant[ Create the underlying widget.
]
variable[d] assign[=] name[self].declaration
name[self].widget assign[=] call[name[ToggleButton], parameter[call[name[self].get_context, parameter[]], constant[None], <ast.BoolOp object at 0x7da1b1b1... | keyword[def] identifier[create_widget] ( identifier[self] ):
literal[string]
identifier[d] = identifier[self] . identifier[declaration]
identifier[self] . identifier[widget] = identifier[ToggleButton] ( identifier[self] . identifier[get_context] (), keyword[None] ,
identifier[d] ... | def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = ToggleButton(self.get_context(), None, d.style or '@attr/buttonStyleToggle') |
def add(self, properties):
"""
Add a faked HBA resource.
Parameters:
properties (dict):
Resource properties.
Special handling and requirements for certain properties:
* 'element-id' will be auto-generated with a unique value across
... | def function[add, parameter[self, properties]]:
constant[
Add a faked HBA resource.
Parameters:
properties (dict):
Resource properties.
Special handling and requirements for certain properties:
* 'element-id' will be auto-generated with a unique ... | keyword[def] identifier[add] ( identifier[self] , identifier[properties] ):
literal[string]
identifier[new_hba] = identifier[super] ( identifier[FakedHbaManager] , identifier[self] ). identifier[add] ( identifier[properties] )
identifier[partition] = identifier[self] . identifier[parent] ... | def add(self, properties):
"""
Add a faked HBA resource.
Parameters:
properties (dict):
Resource properties.
Special handling and requirements for certain properties:
* 'element-id' will be auto-generated with a unique value across
all ... |
def parse_from_args(self, l):
"""Secondary customization point, called from getFromKwargs to turn
a validated value into a single property value"""
if self.multiple:
return [self.parse_from_arg(arg) for arg in l]
return self.parse_from_arg(l[0]) | def function[parse_from_args, parameter[self, l]]:
constant[Secondary customization point, called from getFromKwargs to turn
a validated value into a single property value]
if name[self].multiple begin[:]
return[<ast.ListComp object at 0x7da1b20981f0>]
return[call[name[self].parse... | keyword[def] identifier[parse_from_args] ( identifier[self] , identifier[l] ):
literal[string]
keyword[if] identifier[self] . identifier[multiple] :
keyword[return] [ identifier[self] . identifier[parse_from_arg] ( identifier[arg] ) keyword[for] identifier[arg] keyword[in] identifi... | def parse_from_args(self, l):
"""Secondary customization point, called from getFromKwargs to turn
a validated value into a single property value"""
if self.multiple:
return [self.parse_from_arg(arg) for arg in l] # depends on [control=['if'], data=[]]
return self.parse_from_arg(l[0]) |
def recording_command(event):
'''Run the actual command to record the a/v material.
'''
conf = config('capture')
# Prepare command line
cmd = conf['command']
cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp())))
cmd = cmd.replace('{{dir}}', event.directory())
cmd = cm... | def function[recording_command, parameter[event]]:
constant[Run the actual command to record the a/v material.
]
variable[conf] assign[=] call[name[config], parameter[constant[capture]]]
variable[cmd] assign[=] call[name[conf]][constant[command]]
variable[cmd] assign[=] call[name[cmd... | keyword[def] identifier[recording_command] ( identifier[event] ):
literal[string]
identifier[conf] = identifier[config] ( literal[string] )
identifier[cmd] = identifier[conf] [ literal[string] ]
identifier[cmd] = identifier[cmd] . identifier[replace] ( literal[string] , identifier[str] ( ide... | def recording_command(event):
"""Run the actual command to record the a/v material.
"""
conf = config('capture')
# Prepare command line
cmd = conf['command']
cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp())))
cmd = cmd.replace('{{dir}}', event.directory())
cmd = cm... |
def ping():
'''
Is the chassis responding?
:return: Returns False if the chassis didn't respond, True otherwise.
'''
r = __salt__['dracr.system_info'](host=DETAILS['host'],
admin_username=DETAILS['admin_username'],
admin_p... | def function[ping, parameter[]]:
constant[
Is the chassis responding?
:return: Returns False if the chassis didn't respond, True otherwise.
]
variable[r] assign[=] call[call[name[__salt__]][constant[dracr.system_info]], parameter[]]
if compare[call[name[r].get, parameter[constant[r... | keyword[def] identifier[ping] ():
literal[string]
identifier[r] = identifier[__salt__] [ literal[string] ]( identifier[host] = identifier[DETAILS] [ literal[string] ],
identifier[admin_username] = identifier[DETAILS] [ literal[string] ],
identifier[admin_password] = identifier[DETAILS] [ literal[... | def ping():
"""
Is the chassis responding?
:return: Returns False if the chassis didn't respond, True otherwise.
"""
r = __salt__['dracr.system_info'](host=DETAILS['host'], admin_username=DETAILS['admin_username'], admin_password=DETAILS['admin_password'])
if r.get('retcode', 0) == 1:
... |
def _next_cTn_id(self):
"""Return the next available unique ID (int) for p:cTn element."""
cTn_id_strs = self.xpath('/p:sld/p:timing//p:cTn/@id')
ids = [int(id_str) for id_str in cTn_id_strs]
return max(ids) + 1 | def function[_next_cTn_id, parameter[self]]:
constant[Return the next available unique ID (int) for p:cTn element.]
variable[cTn_id_strs] assign[=] call[name[self].xpath, parameter[constant[/p:sld/p:timing//p:cTn/@id]]]
variable[ids] assign[=] <ast.ListComp object at 0x7da20c76d0f0>
return[b... | keyword[def] identifier[_next_cTn_id] ( identifier[self] ):
literal[string]
identifier[cTn_id_strs] = identifier[self] . identifier[xpath] ( literal[string] )
identifier[ids] =[ identifier[int] ( identifier[id_str] ) keyword[for] identifier[id_str] keyword[in] identifier[cTn_id_strs] ]
... | def _next_cTn_id(self):
"""Return the next available unique ID (int) for p:cTn element."""
cTn_id_strs = self.xpath('/p:sld/p:timing//p:cTn/@id')
ids = [int(id_str) for id_str in cTn_id_strs]
return max(ids) + 1 |
def first(self):
"""
First chunk
"""
return self.values[tuple(zeros(len(self.values.shape)))] | def function[first, parameter[self]]:
constant[
First chunk
]
return[call[name[self].values][call[name[tuple], parameter[call[name[zeros], parameter[call[name[len], parameter[name[self].values.shape]]]]]]]] | keyword[def] identifier[first] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[values] [ identifier[tuple] ( identifier[zeros] ( identifier[len] ( identifier[self] . identifier[values] . identifier[shape] )))] | def first(self):
"""
First chunk
"""
return self.values[tuple(zeros(len(self.values.shape)))] |
def _path_hash(path, transform, kwargs):
"""
Generate a hash of source file path + transform + args
"""
sortedargs = ["%s:%r:%s" % (key, value, type(value))
for key, value in sorted(iteritems(kwargs))]
srcinfo = "{path}:{transform}:{{{kwargs}}}".format(path=os.path.abspath(path),
... | def function[_path_hash, parameter[path, transform, kwargs]]:
constant[
Generate a hash of source file path + transform + args
]
variable[sortedargs] assign[=] <ast.ListComp object at 0x7da1b1279b40>
variable[srcinfo] assign[=] call[constant[{path}:{transform}:{{{kwargs}}}].format, param... | keyword[def] identifier[_path_hash] ( identifier[path] , identifier[transform] , identifier[kwargs] ):
literal[string]
identifier[sortedargs] =[ literal[string] %( identifier[key] , identifier[value] , identifier[type] ( identifier[value] ))
keyword[for] identifier[key] , identifier[value] keyword[i... | def _path_hash(path, transform, kwargs):
"""
Generate a hash of source file path + transform + args
"""
sortedargs = ['%s:%r:%s' % (key, value, type(value)) for (key, value) in sorted(iteritems(kwargs))]
srcinfo = '{path}:{transform}:{{{kwargs}}}'.format(path=os.path.abspath(path), transform=transfo... |
def main(argv=None):
"""Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a string, then treat string as
... | def function[main, parameter[argv]]:
constant[Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a str... | keyword[def] identifier[main] ( identifier[argv] = keyword[None] ):
literal[string]
keyword[if] identifier[argv] keyword[is] keyword[None] :
identifier[argv] = identifier[sys] . identifier[argv] [ literal[int] :]
identifier[args] = identifier[_get_parser] (). identifier[parse_args] ( ident... | def main(argv=None):
"""Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a string, then treat string as
... |
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
ACCOUNTS_FORBIDDEN_USERNAMES list.
"""
try:
get_user_model().objects.get(
username__iexact=sel... | def function[clean_username, parameter[self]]:
constant[
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
ACCOUNTS_FORBIDDEN_USERNAMES list.
]
<ast.Try object at 0x7da18f00ca30>
if compare[call[cal... | keyword[def] identifier[clean_username] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[get_user_model] (). identifier[objects] . identifier[get] (
identifier[username__iexact] = identifier[self] . identifier[cleaned_data] [ literal[string] ])
keyw... | def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
ACCOUNTS_FORBIDDEN_USERNAMES list.
"""
try:
get_user_model().objects.get(username__iexact=self.cleaned_data['username']) ... |
def normal_h3(size: int = 10000) -> HistogramND:
"""A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
data3 = np.random.normal(0, 1, (size,))
return h3([da... | def function[normal_h3, parameter[size]]:
constant[A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points
]
variable[data1] assign[=] call[name[np].random.normal, parameter[constant[0], constant[1], tuple[[<ast.Name object at 0x7da20c794d60>]]]]
... | keyword[def] identifier[normal_h3] ( identifier[size] : identifier[int] = literal[int] )-> identifier[HistogramND] :
literal[string]
identifier[data1] = identifier[np] . identifier[random] . identifier[normal] ( literal[int] , literal[int] ,( identifier[size] ,))
identifier[data2] = identifier[np] . i... | def normal_h3(size: int=10000) -> HistogramND:
"""A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
data3 = np.random.normal(0, 1, (size,))
return h3([data... |
def erase_sector(self, address):
"""!
@brief Erase one sector.
@exception FlashEraseFailure
"""
assert self._active_operation == self.Operation.ERASE
# update core register to execute the erase_sector subroutine
result = self._call_function_and_wait(self... | def function[erase_sector, parameter[self, address]]:
constant[!
@brief Erase one sector.
@exception FlashEraseFailure
]
assert[compare[name[self]._active_operation equal[==] name[self].Operation.ERASE]]
variable[result] assign[=] call[name[self]._call_function_and_w... | keyword[def] identifier[erase_sector] ( identifier[self] , identifier[address] ):
literal[string]
keyword[assert] identifier[self] . identifier[_active_operation] == identifier[self] . identifier[Operation] . identifier[ERASE]
identifier[result] = identifier[self] . identifier[... | def erase_sector(self, address):
"""!
@brief Erase one sector.
@exception FlashEraseFailure
"""
assert self._active_operation == self.Operation.ERASE
# update core register to execute the erase_sector subroutine
result = self._call_function_and_wait(self.flash_algo['pc_e... |
def crop(self, min, max):
"""
Crop a region by removing coordinates outside bounds.
Follows normal slice indexing conventions.
Parameters
----------
min : tuple
Minimum or starting bounds for each axis.
max : tuple
Maximum or ending boun... | def function[crop, parameter[self, min, max]]:
constant[
Crop a region by removing coordinates outside bounds.
Follows normal slice indexing conventions.
Parameters
----------
min : tuple
Minimum or starting bounds for each axis.
max : tuple
... | keyword[def] identifier[crop] ( identifier[self] , identifier[min] , identifier[max] ):
literal[string]
identifier[new] =[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[self] . identifier[coordinates] keyword[if] identifier[all] ( identifier[c] >= identifier[min] ) keyword[a... | def crop(self, min, max):
"""
Crop a region by removing coordinates outside bounds.
Follows normal slice indexing conventions.
Parameters
----------
min : tuple
Minimum or starting bounds for each axis.
max : tuple
Maximum or ending bounds f... |
def _on_github_user(self, future, access_token, response):
"""Invoked as a callback when self.github_request returns the response
to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token for the user's use
:p... | def function[_on_github_user, parameter[self, future, access_token, response]]:
constant[Invoked as a callback when self.github_request returns the response
to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token fo... | keyword[def] identifier[_on_github_user] ( identifier[self] , identifier[future] , identifier[access_token] , identifier[response] ):
literal[string]
identifier[response] [ literal[string] ]= identifier[access_token]
identifier[future] . identifier[set_result] ( identifier[response] ) | def _on_github_user(self, future, access_token, response):
"""Invoked as a callback when self.github_request returns the response
to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token for the user's use
:param... |
def api_url(self):
'''return the api url of self'''
return pathjoin(Bin.path, self.name, url=self.service.url) | def function[api_url, parameter[self]]:
constant[return the api url of self]
return[call[name[pathjoin], parameter[name[Bin].path, name[self].name]]] | keyword[def] identifier[api_url] ( identifier[self] ):
literal[string]
keyword[return] identifier[pathjoin] ( identifier[Bin] . identifier[path] , identifier[self] . identifier[name] , identifier[url] = identifier[self] . identifier[service] . identifier[url] ) | def api_url(self):
"""return the api url of self"""
return pathjoin(Bin.path, self.name, url=self.service.url) |
def on_train_begin(self, **kwargs:Any)->None:
"Initialize inner arguments."
self.wait, self.opt = 0, self.learn.opt
super().on_train_begin(**kwargs) | def function[on_train_begin, parameter[self]]:
constant[Initialize inner arguments.]
<ast.Tuple object at 0x7da1b1dd9330> assign[=] tuple[[<ast.Constant object at 0x7da1b1ddae30>, <ast.Attribute object at 0x7da1b1ddb2e0>]]
call[call[name[super], parameter[]].on_train_begin, parameter[]] | keyword[def] identifier[on_train_begin] ( identifier[self] ,** identifier[kwargs] : identifier[Any] )-> keyword[None] :
literal[string]
identifier[self] . identifier[wait] , identifier[self] . identifier[opt] = literal[int] , identifier[self] . identifier[learn] . identifier[opt]
identifi... | def on_train_begin(self, **kwargs: Any) -> None:
"""Initialize inner arguments."""
(self.wait, self.opt) = (0, self.learn.opt)
super().on_train_begin(**kwargs) |
def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
"""
pal = widget.palette()
pal.setColor(pal.Base, color)
widget.setPalette(pal) | def function[_set_widget_background_color, parameter[widget, color]]:
constant[
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
]
variable[pal] assign[=] call[name[widget].palette, parameter[]]
call... | keyword[def] identifier[_set_widget_background_color] ( identifier[widget] , identifier[color] ):
literal[string]
identifier[pal] = identifier[widget] . identifier[palette] ()
identifier[pal] . identifier[setColor] ( identifier[pal] . identifier[Base] , identifier[color] )
identif... | def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
"""
pal = widget.palette()
pal.setColor(pal.Base, color)
widget.setPalette(pal) |
def nb_r_deriv(r, data_row):
"""
Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells
"""
n = len(data_row)
d = sum(digamma(data_row + r)) - n*digamma(r) + n*np.log(r/(r+np... | def function[nb_r_deriv, parameter[r, data_row]]:
constant[
Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells
]
variable[n] assign[=] call[name[len], parameter[name[... | keyword[def] identifier[nb_r_deriv] ( identifier[r] , identifier[data_row] ):
literal[string]
identifier[n] = identifier[len] ( identifier[data_row] )
identifier[d] = identifier[sum] ( identifier[digamma] ( identifier[data_row] + identifier[r] ))- identifier[n] * identifier[digamma] ( identifier[r] )+... | def nb_r_deriv(r, data_row):
"""
Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells
"""
n = len(data_row)
d = sum(digamma(data_row + r)) - n * digamma(r) + n * np.log(r /... |
def set_timestamp(self, time: Union[str, datetime.datetime] = None,
now: bool = False) -> None:
"""
Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
... | def function[set_timestamp, parameter[self, time, now]]:
constant[
Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
now: bool
Defaults to :class:`False`.
... | keyword[def] identifier[set_timestamp] ( identifier[self] , identifier[time] : identifier[Union] [ identifier[str] , identifier[datetime] . identifier[datetime] ]= keyword[None] ,
identifier[now] : identifier[bool] = keyword[False] )-> keyword[None] :
literal[string]
keyword[if] identifier[now] :... | def set_timestamp(self, time: Union[str, datetime.datetime]=None, now: bool=False) -> None:
"""
Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
now: bool
Defaul... |
def get_mean_values(self, C, sites, rup, dists, a1100):
"""
Returns the mean values for a specific IMT
"""
if isinstance(a1100, np.ndarray):
# Site model defined
temp_vs30 = sites.vs30
temp_z2pt5 = sites.z2pt5
else:
# Default site a... | def function[get_mean_values, parameter[self, C, sites, rup, dists, a1100]]:
constant[
Returns the mean values for a specific IMT
]
if call[name[isinstance], parameter[name[a1100], name[np].ndarray]] begin[:]
variable[temp_vs30] assign[=] name[sites].vs30
... | keyword[def] identifier[get_mean_values] ( identifier[self] , identifier[C] , identifier[sites] , identifier[rup] , identifier[dists] , identifier[a1100] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[a1100] , identifier[np] . identifier[ndarray] ):
identi... | def get_mean_values(self, C, sites, rup, dists, a1100):
"""
Returns the mean values for a specific IMT
"""
if isinstance(a1100, np.ndarray):
# Site model defined
temp_vs30 = sites.vs30
temp_z2pt5 = sites.z2pt5 # depends on [control=['if'], data=[]]
else:
# De... |
def update_probs(self):
"""Update the internal probability values given the counts."""
# We deal with the prior probsfirst
# This is a fixed assumed value for systematic error
syst_error = 0.05
prior_probs = {'syst': {}, 'rand': {}}
for source, (p, n) in self.prior_counts... | def function[update_probs, parameter[self]]:
constant[Update the internal probability values given the counts.]
variable[syst_error] assign[=] constant[0.05]
variable[prior_probs] assign[=] dictionary[[<ast.Constant object at 0x7da207f00ca0>, <ast.Constant object at 0x7da207f01ed0>], [<ast.Dict ... | keyword[def] identifier[update_probs] ( identifier[self] ):
literal[string]
identifier[syst_error] = literal[int]
identifier[prior_probs] ={ literal[string] :{}, literal[string] :{}}
keyword[for] identifier[source] ,( identifier[p] , identifier[n] ) keyword[in]... | def update_probs(self):
"""Update the internal probability values given the counts."""
# We deal with the prior probsfirst
# This is a fixed assumed value for systematic error
syst_error = 0.05
prior_probs = {'syst': {}, 'rand': {}}
for (source, (p, n)) in self.prior_counts.items():
# Sk... |
def parse_JSON(self, JSON_string):
"""
Parses a `pyowm.alertapi30.trigger.Trigger` instance out of raw JSON
data. As per OWM documentation, start and end times are expressed with
respect to the moment when you create/update the Trigger. By design,
PyOWM will only allow users to s... | def function[parse_JSON, parameter[self, JSON_string]]:
constant[
Parses a `pyowm.alertapi30.trigger.Trigger` instance out of raw JSON
data. As per OWM documentation, start and end times are expressed with
respect to the moment when you create/update the Trigger. By design,
PyOWM... | keyword[def] identifier[parse_JSON] ( identifier[self] , identifier[JSON_string] ):
literal[string]
keyword[if] identifier[JSON_string] keyword[is] keyword[None] :
keyword[raise] identifier[parse_response_error] . identifier[ParseResponseError] ( literal[string] )
identifi... | def parse_JSON(self, JSON_string):
"""
Parses a `pyowm.alertapi30.trigger.Trigger` instance out of raw JSON
data. As per OWM documentation, start and end times are expressed with
respect to the moment when you create/update the Trigger. By design,
PyOWM will only allow users to speci... |
def argmin(self):
"""
Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates.
"""
return tuple(centres[index] for centres, index in
zip(self.centres(), numpy.unravel_... | def function[argmin, parameter[self]]:
constant[
Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates.
]
return[call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da20c6aa290>]]] | keyword[def] identifier[argmin] ( identifier[self] ):
literal[string]
keyword[return] identifier[tuple] ( identifier[centres] [ identifier[index] ] keyword[for] identifier[centres] , identifier[index] keyword[in]
identifier[zip] ( identifier[self] . identifier[centres] (), identifier[n... | def argmin(self):
"""
Return the co-ordinates of the bin centre containing the
minimum value. Same as numpy.argmin(), converting the
indexes to bin co-ordinates.
"""
return tuple((centres[index] for (centres, index) in zip(self.centres(), numpy.unravel_index(self.array.argmin(),... |
def update_graph(self, dep_id=None, success=True):
"""dep_id just finished. Update our dependency
graph and submit any jobs that just became runable.
Called with dep_id=None to update entire graph for hwm, but without finishing
a task.
"""
# print ("\n\n***********")
... | def function[update_graph, parameter[self, dep_id, success]]:
constant[dep_id just finished. Update our dependency
graph and submit any jobs that just became runable.
Called with dep_id=None to update entire graph for hwm, but without finishing
a task.
]
variable[jobs] a... | keyword[def] identifier[update_graph] ( identifier[self] , identifier[dep_id] = keyword[None] , identifier[success] = keyword[True] ):
literal[string]
identifier[jobs] = identifier[self] . identifier[graph] . identifier[pop] ( ... | def update_graph(self, dep_id=None, success=True):
"""dep_id just finished. Update our dependency
graph and submit any jobs that just became runable.
Called with dep_id=None to update entire graph for hwm, but without finishing
a task.
"""
# print ("\n\n***********")
# pprin... |
def getComponent(self, innerFlag=False):
"""Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component n... | def function[getComponent, parameter[self, innerFlag]]:
constant[Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
]
if compare[name[self]._currentIdx is constant[None]] begin... | keyword[def] identifier[getComponent] ( identifier[self] , identifier[innerFlag] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[_currentIdx] keyword[is] keyword[None] :
keyword[raise] identifier[error] . identifier[PyAsn1Error] ( literal[string] )
... | def getComponent(self, innerFlag=False):
"""Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component not chosen') ... |
def walk_up(bottom):
""" mimic os.walk, but walk 'up' instead of down the directory tree
:param bottom:
:return:
"""
import os
from os import path
bottom = path.realpath(bottom)
# get files in current dir
try:
names = os.listdir(bottom)
except Exception as e:
r... | def function[walk_up, parameter[bottom]]:
constant[ mimic os.walk, but walk 'up' instead of down the directory tree
:param bottom:
:return:
]
import module[os]
from relative_module[os] import module[path]
variable[bottom] assign[=] call[name[path].realpath, parameter[name[bottom]]]
... | keyword[def] identifier[walk_up] ( identifier[bottom] ):
literal[string]
keyword[import] identifier[os]
keyword[from] identifier[os] keyword[import] identifier[path]
identifier[bottom] = identifier[path] . identifier[realpath] ( identifier[bottom] )
keyword[try] :
ident... | def walk_up(bottom):
""" mimic os.walk, but walk 'up' instead of down the directory tree
:param bottom:
:return:
"""
import os
from os import path
bottom = path.realpath(bottom)
# get files in current dir
try:
names = os.listdir(bottom) # depends on [control=['try'], data=[... |
def write_gexf(docgraph, output_file):
"""
takes a document graph, converts it into GEXF format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) | def function[write_gexf, parameter[docgraph, output_file]]:
constant[
takes a document graph, converts it into GEXF format and writes it to
a file.
]
variable[dg_copy] assign[=] call[name[deepcopy], parameter[name[docgraph]]]
call[name[remove_root_metadata], parameter[name[dg_copy]]]... | keyword[def] identifier[write_gexf] ( identifier[docgraph] , identifier[output_file] ):
literal[string]
identifier[dg_copy] = identifier[deepcopy] ( identifier[docgraph] )
identifier[remove_root_metadata] ( identifier[dg_copy] )
identifier[layerset2str] ( identifier[dg_copy] )
identifier[att... | def write_gexf(docgraph, output_file):
"""
takes a document graph, converts it into GEXF format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) |
def get_authorization_url(self):
"""Get the authorization Url for the current client."""
return self._format_url(
OAUTH2_ROOT + 'authorize',
query = {
'response_type': 'code',
'client_id': self.client.get('client_id', ''),
'redirect... | def function[get_authorization_url, parameter[self]]:
constant[Get the authorization Url for the current client.]
return[call[name[self]._format_url, parameter[binary_operation[name[OAUTH2_ROOT] + constant[authorize]]]]] | keyword[def] identifier[get_authorization_url] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_format_url] (
identifier[OAUTH2_ROOT] + literal[string] ,
identifier[query] ={
literal[string] : literal[string] ,
literal[string]... | def get_authorization_url(self):
"""Get the authorization Url for the current client."""
return self._format_url(OAUTH2_ROOT + 'authorize', query={'response_type': 'code', 'client_id': self.client.get('client_id', ''), 'redirect_uri': self.client.get('redirect_uri', '')}) |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose['key'] != layer_purpose_aggrega... | def function[get_next_step, parameter[self]]:
constant[Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
]
variable[layer_purpose] assign[=] call[name[self].parent.step_kw_purpose.selected_purpose, par... | keyword[def] identifier[get_next_step] ( identifier[self] ):
literal[string]
identifier[layer_purpose] = identifier[self] . identifier[parent] . identifier[step_kw_purpose] . identifier[selected_purpose] ()
keyword[if] identifier[layer_purpose] [ literal[string] ]!= identifier[layer_purpo... | def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose['key'] != layer_purpose_aggregation['key']:... |
def regenerate(self):
"""Regenerate the session id.
This function creates a new session id and stores all information
associated with the current id in that new id. It then destroys the
old session id. This is useful for preventing session fixation attacks
and should be done whe... | def function[regenerate, parameter[self]]:
constant[Regenerate the session id.
This function creates a new session id and stores all information
associated with the current id in that new id. It then destroys the
old session id. This is useful for preventing session fixation attacks
... | keyword[def] identifier[regenerate] ( identifier[self] ):
literal[string]
identifier[oldhash] = identifier[self] . identifier[session_hash]
identifier[self] . identifier[new_session_id] ()
keyword[try] :
identifier[self] . identifier[rdb] . identifier[rename] ( iden... | def regenerate(self):
"""Regenerate the session id.
This function creates a new session id and stores all information
associated with the current id in that new id. It then destroys the
old session id. This is useful for preventing session fixation attacks
and should be done wheneve... |
def request(self):
""" Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received."""
headers = {'Accept': 'application/json'}
# Use API Key if possible
if self.api_key:
headers['X-API-KEY'] = self.api_key
ret... | def function[request, parameter[self]]:
constant[ Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received.]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da204565570>], [<ast.Constant object at 0x7da204564e20>]]
if name... | keyword[def] identifier[request] ( identifier[self] ):
literal[string]
identifier[headers] ={ literal[string] : literal[string] }
keyword[if] identifier[self] . identifier[api_key] :
identifier[headers] [ literal[string] ]= identifier[self] . identifier[api_key]
... | def request(self):
""" Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received."""
headers = {'Accept': 'application/json'}
# Use API Key if possible
if self.api_key:
headers['X-API-KEY'] = self.api_key
return (requests, headers) #... |
def returnModPositions(peptide, indexStart=1, removeModString='UNIMOD:'):
"""Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino acids positions of t... | def function[returnModPositions, parameter[peptide, indexStart, removeModString]]:
constant[Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino a... | keyword[def] identifier[returnModPositions] ( identifier[peptide] , identifier[indexStart] = literal[int] , identifier[removeModString] = literal[string] ):
literal[string]
identifier[unidmodPositionDict] = identifier[dict] ()
keyword[while] identifier[peptide] . identifier[find] ( literal[string] )!... | def returnModPositions(peptide, indexStart=1, removeModString='UNIMOD:'):
"""Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino acids positions of t... |
def update_kwargs(self, request, **kwargs):
"""
Adds variables to the context that are expected by the
base cms templates.
* **navigation** - The side navigation for this bundle and user.
* **dashboard** - The list of dashboard links for this user.
* **object_header** - ... | def function[update_kwargs, parameter[self, request]]:
constant[
Adds variables to the context that are expected by the
base cms templates.
* **navigation** - The side navigation for this bundle and user.
* **dashboard** - The list of dashboard links for this user.
* **o... | keyword[def] identifier[update_kwargs] ( identifier[self] , identifier[request] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] = identifier[super] ( identifier[CMSRender] , identifier[self] ). identifier[update_kwargs] ( identifier[request] ,** identifier[kwargs] )
... | def update_kwargs(self, request, **kwargs):
"""
Adds variables to the context that are expected by the
base cms templates.
* **navigation** - The side navigation for this bundle and user.
* **dashboard** - The list of dashboard links for this user.
* **object_header** - If n... |
def disconnect_all(self):
"""
Disconnect all nodes
:return:
"""
rhs = 'b:' + self.definition['node_class'].__label__
rel = _rel_helper(lhs='a', rhs=rhs, ident='r', **self.definition)
q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r'
self.sourc... | def function[disconnect_all, parameter[self]]:
constant[
Disconnect all nodes
:return:
]
variable[rhs] assign[=] binary_operation[constant[b:] + call[name[self].definition][constant[node_class]].__label__]
variable[rel] assign[=] call[name[_rel_helper], parameter[]]
... | keyword[def] identifier[disconnect_all] ( identifier[self] ):
literal[string]
identifier[rhs] = literal[string] + identifier[self] . identifier[definition] [ literal[string] ]. identifier[__label__]
identifier[rel] = identifier[_rel_helper] ( identifier[lhs] = literal[string] , identifier... | def disconnect_all(self):
"""
Disconnect all nodes
:return:
"""
rhs = 'b:' + self.definition['node_class'].__label__
rel = _rel_helper(lhs='a', rhs=rhs, ident='r', **self.definition)
q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r'
self.source.cypher(q) |
def readfmt(self, fmt):
"""Read a specified object, using a struct format string."""
size = struct.calcsize(fmt)
blob = self.read(size)
obj, = struct.unpack(fmt, blob)
return obj | def function[readfmt, parameter[self, fmt]]:
constant[Read a specified object, using a struct format string.]
variable[size] assign[=] call[name[struct].calcsize, parameter[name[fmt]]]
variable[blob] assign[=] call[name[self].read, parameter[name[size]]]
<ast.Tuple object at 0x7da1b1240c... | keyword[def] identifier[readfmt] ( identifier[self] , identifier[fmt] ):
literal[string]
identifier[size] = identifier[struct] . identifier[calcsize] ( identifier[fmt] )
identifier[blob] = identifier[self] . identifier[read] ( identifier[size] )
identifier[obj] ,= identifier[struc... | def readfmt(self, fmt):
"""Read a specified object, using a struct format string."""
size = struct.calcsize(fmt)
blob = self.read(size)
(obj,) = struct.unpack(fmt, blob)
return obj |
def _read_or_calc_samples(
sampler,
modelidx=0,
n_samples=100,
last_step=False,
e_range=None,
e_npoints=100,
threads=None,
):
"""Get samples from blob or compute them from chain and sampler.modelfn
"""
if not e_range:
# return the results saved in blobs
modelx, m... | def function[_read_or_calc_samples, parameter[sampler, modelidx, n_samples, last_step, e_range, e_npoints, threads]]:
constant[Get samples from blob or compute them from chain and sampler.modelfn
]
if <ast.UnaryOp object at 0x7da1b0c52050> begin[:]
<ast.Tuple object at 0x7da1b0c521a0... | keyword[def] identifier[_read_or_calc_samples] (
identifier[sampler] ,
identifier[modelidx] = literal[int] ,
identifier[n_samples] = literal[int] ,
identifier[last_step] = keyword[False] ,
identifier[e_range] = keyword[None] ,
identifier[e_npoints] = literal[int] ,
identifier[threads] = keyword[None] ,
):
... | def _read_or_calc_samples(sampler, modelidx=0, n_samples=100, last_step=False, e_range=None, e_npoints=100, threads=None):
"""Get samples from blob or compute them from chain and sampler.modelfn
"""
if not e_range:
# return the results saved in blobs
(modelx, model) = _process_blob(sampler, ... |
def do_lsfolders(self, subcmd, opts):
"""${cmd_name}: list the sub folders of the maildir.
${cmd_usage}
"""
client = MdClient(self.maildir, filesystem=self.filesystem)
client.lsfolders(stream=self.stdout) | def function[do_lsfolders, parameter[self, subcmd, opts]]:
constant[${cmd_name}: list the sub folders of the maildir.
${cmd_usage}
]
variable[client] assign[=] call[name[MdClient], parameter[name[self].maildir]]
call[name[client].lsfolders, parameter[]] | keyword[def] identifier[do_lsfolders] ( identifier[self] , identifier[subcmd] , identifier[opts] ):
literal[string]
identifier[client] = identifier[MdClient] ( identifier[self] . identifier[maildir] , identifier[filesystem] = identifier[self] . identifier[filesystem] )
identifier[client] .... | def do_lsfolders(self, subcmd, opts):
"""${cmd_name}: list the sub folders of the maildir.
${cmd_usage}
"""
client = MdClient(self.maildir, filesystem=self.filesystem)
client.lsfolders(stream=self.stdout) |
def list_views(app, appbuilder):
"""
List all registered views
"""
_appbuilder = import_application(app, appbuilder)
echo_header("List of registered views")
for view in _appbuilder.baseviews:
click.echo(
"View:{0} | Route:{1} | Perms:{2}".format(
view.__cl... | def function[list_views, parameter[app, appbuilder]]:
constant[
List all registered views
]
variable[_appbuilder] assign[=] call[name[import_application], parameter[name[app], name[appbuilder]]]
call[name[echo_header], parameter[constant[List of registered views]]]
for taget[... | keyword[def] identifier[list_views] ( identifier[app] , identifier[appbuilder] ):
literal[string]
identifier[_appbuilder] = identifier[import_application] ( identifier[app] , identifier[appbuilder] )
identifier[echo_header] ( literal[string] )
keyword[for] identifier[view] keyword[in] identifi... | def list_views(app, appbuilder):
"""
List all registered views
"""
_appbuilder = import_application(app, appbuilder)
echo_header('List of registered views')
for view in _appbuilder.baseviews:
click.echo('View:{0} | Route:{1} | Perms:{2}'.format(view.__class__.__name__, view.route_bas... |
def _send(self, message):
"""A helper method that does the actual sending."""
charset='UTF-8'
params = {
'action' : 'sendsms',
'user' : self.get_username(),
'password' : self.get_password(),
'from' : message.from_phone,
'to' : ",".join(message.to... | def function[_send, parameter[self, message]]:
constant[A helper method that does the actual sending.]
variable[charset] assign[=] constant[UTF-8]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da20c6e7dc0>, <ast.Constant object at 0x7da20c6e6890>, <ast.Constant object at 0x7d... | keyword[def] identifier[_send] ( identifier[self] , identifier[message] ):
literal[string]
identifier[charset] = literal[string]
identifier[params] ={
literal[string] : literal[string] ,
literal[string] : identifier[self] . identifier[get_username] (),
literal[s... | def _send(self, message):
"""A helper method that does the actual sending."""
charset = 'UTF-8'
params = {'action': 'sendsms', 'user': self.get_username(), 'password': self.get_password(), 'from': message.from_phone, 'to': ','.join(message.to), 'text': message.body, 'clientcharset': charset, 'detectcharset'... |
def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` s... | def function[colorspace, parameter[im, bw, replace_alpha]]:
constant[
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_an... | keyword[def] identifier[colorspace] ( identifier[im] , identifier[bw] = keyword[False] , identifier[replace_alpha] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[im] . identifier[mode] == literal[string] :
identifier[im] = identifier[im] . identifier[p... | def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` s... |
def configurations(self):
"""
Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations.
:rtype: yagocd.resources.configuration.ConfigurationManager
"""
if self._configuration_manager is None:
self._configuration_manager = ... | def function[configurations, parameter[self]]:
constant[
Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations.
:rtype: yagocd.resources.configuration.ConfigurationManager
]
if compare[name[self]._configuration_manager is constant[... | keyword[def] identifier[configurations] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_configuration_manager] keyword[is] keyword[None] :
identifier[self] . identifier[_configuration_manager] = identifier[ConfigurationManager] ( identifier[session] ... | def configurations(self):
"""
Property for accessing :class:`ConfigurationManager` instance, which is used to manage configurations.
:rtype: yagocd.resources.configuration.ConfigurationManager
"""
if self._configuration_manager is None:
self._configuration_manager = Configuratio... |
def disable(self):
"""
Disable the button, if in non-expert mode.
"""
w.ActButton.disable(self)
g = get_root(self).globals
if self._expert:
self.config(bg=g.COL['start'])
else:
self.config(bg=g.COL['startD']) | def function[disable, parameter[self]]:
constant[
Disable the button, if in non-expert mode.
]
call[name[w].ActButton.disable, parameter[name[self]]]
variable[g] assign[=] call[name[get_root], parameter[name[self]]].globals
if name[self]._expert begin[:]
c... | keyword[def] identifier[disable] ( identifier[self] ):
literal[string]
identifier[w] . identifier[ActButton] . identifier[disable] ( identifier[self] )
identifier[g] = identifier[get_root] ( identifier[self] ). identifier[globals]
keyword[if] identifier[self] . identifier[_exper... | def disable(self):
"""
Disable the button, if in non-expert mode.
"""
w.ActButton.disable(self)
g = get_root(self).globals
if self._expert:
self.config(bg=g.COL['start']) # depends on [control=['if'], data=[]]
else:
self.config(bg=g.COL['startD']) |
def convert_param(self, method, param, value):
"""Converts the parameter using the function 'convert' function of the
validation rules. Same parameters as the `validate_param` method, so
it might have just been added there. But lumping together the two
functionalities would make overwrit... | def function[convert_param, parameter[self, method, param, value]]:
constant[Converts the parameter using the function 'convert' function of the
validation rules. Same parameters as the `validate_param` method, so
it might have just been added there. But lumping together the two
function... | keyword[def] identifier[convert_param] ( identifier[self] , identifier[method] , identifier[param] , identifier[value] ):
literal[string]
identifier[rules] = identifier[self] . identifier[_get_validation] ( identifier[method] , identifier[param] )
keyword[if] keyword[not] identifier[rule... | def convert_param(self, method, param, value):
"""Converts the parameter using the function 'convert' function of the
validation rules. Same parameters as the `validate_param` method, so
it might have just been added there. But lumping together the two
functionalities would make overwriting ... |
def validate(opts):
"""
Client-facing validate method. Checks to see if the passed in opts
argument is either a list or a namespace containing the attribute
'extensions' and runs validations on it accordingly. If opts is neither
of those things, this will raise a ValueError
:param opts: either ... | def function[validate, parameter[opts]]:
constant[
Client-facing validate method. Checks to see if the passed in opts
argument is either a list or a namespace containing the attribute
'extensions' and runs validations on it accordingly. If opts is neither
of those things, this will raise a Value... | keyword[def] identifier[validate] ( identifier[opts] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[opts] , literal[string] ):
keyword[return] identifier[_validate] ( identifier[opts] . identifier[extensions] )
keyword[elif] identifier[isinstance] ( identifier[opts] , iden... | def validate(opts):
"""
Client-facing validate method. Checks to see if the passed in opts
argument is either a list or a namespace containing the attribute
'extensions' and runs validations on it accordingly. If opts is neither
of those things, this will raise a ValueError
:param opts: either ... |
def close_connection(self, connection: str) -> None:
""" Close the connection"""
if connection not in self.connections:
raise ConnectionNotOpen(connection)
self.connections.pop(connection).close() | def function[close_connection, parameter[self, connection]]:
constant[ Close the connection]
if compare[name[connection] <ast.NotIn object at 0x7da2590d7190> name[self].connections] begin[:]
<ast.Raise object at 0x7da1b1cc3b50>
call[call[name[self].connections.pop, parameter[name[connect... | keyword[def] identifier[close_connection] ( identifier[self] , identifier[connection] : identifier[str] )-> keyword[None] :
literal[string]
keyword[if] identifier[connection] keyword[not] keyword[in] identifier[self] . identifier[connections] :
keyword[raise] identifier[Connection... | def close_connection(self, connection: str) -> None:
""" Close the connection"""
if connection not in self.connections:
raise ConnectionNotOpen(connection) # depends on [control=['if'], data=['connection']]
self.connections.pop(connection).close() |
def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else... | def function[_has_expired, parameter[self]]:
constant[ Has this HIT expired yet? ]
variable[expired] assign[=] constant[False]
if call[name[hasattr], parameter[name[self], constant[Expiration]]] begin[:]
variable[now] assign[=] call[name[datetime].datetime.utcnow, parameter[]]
... | keyword[def] identifier[_has_expired] ( identifier[self] ):
literal[string]
identifier[expired] = keyword[False]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[now] = identifier[datetime] . identifier[datetime] . identifier[utcnow] ()
... | def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = now >= expiration # depends on [control=['if'], data=[]... |
def update_scoped_package(self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version):
"""UpdateScopedPackage.
[Preview API]
:param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details:
:param str... | def function[update_scoped_package, parameter[self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version]]:
constant[UpdateScopedPackage.
[Preview API]
:param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_... | keyword[def] identifier[update_scoped_package] ( identifier[self] , identifier[package_version_details] , identifier[feed_id] , identifier[package_scope] , identifier[unscoped_package_name] , identifier[package_version] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifie... | def update_scoped_package(self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version):
"""UpdateScopedPackage.
[Preview API]
:param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details:
:param str fee... |
def get_appliances(self, location_id):
"""Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
"""
url = "https://api.neur.io/v1/appliances"
headers = self.__gen... | def function[get_appliances, parameter[self, location_id]]:
constant[Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
]
variable[url] assign[=] constant[h... | keyword[def] identifier[get_appliances] ( identifier[self] , identifier[location_id] ):
literal[string]
identifier[url] = literal[string]
identifier[headers] = identifier[self] . identifier[__gen_headers] ()
identifier[headers] [ literal[string] ]= literal[string]
identifier[params] ={
... | def get_appliances(self, location_id):
"""Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
"""
url = 'https://api.neur.io/v1/appliances'
headers = self.__gen_... |
def run(**kwargs):
'''
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param... | def function[run, parameter[]]:
constant[
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the ... | keyword[def] identifier[run] (** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[ret] ={
literal[string] : identifier[list] ( identifier[kwargs] ),
literal[stri... | def run(**kwargs):
"""
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param... |
def dsync_files(self, source, target):
'''Sync directory to directory.'''
src_s3_url = S3URL.is_valid(source)
dst_s3_url = S3URL.is_valid(target)
source_list = self.relative_dir_walk(source)
if len(source_list) == 0 or '.' in source_list:
raise Failure('Sync command need to sync directory to ... | def function[dsync_files, parameter[self, source, target]]:
constant[Sync directory to directory.]
variable[src_s3_url] assign[=] call[name[S3URL].is_valid, parameter[name[source]]]
variable[dst_s3_url] assign[=] call[name[S3URL].is_valid, parameter[name[target]]]
variable[source_list] a... | keyword[def] identifier[dsync_files] ( identifier[self] , identifier[source] , identifier[target] ):
literal[string]
identifier[src_s3_url] = identifier[S3URL] . identifier[is_valid] ( identifier[source] )
identifier[dst_s3_url] = identifier[S3URL] . identifier[is_valid] ( identifier[target] )
i... | def dsync_files(self, source, target):
"""Sync directory to directory."""
src_s3_url = S3URL.is_valid(source)
dst_s3_url = S3URL.is_valid(target)
source_list = self.relative_dir_walk(source)
if len(source_list) == 0 or '.' in source_list:
raise Failure('Sync command need to sync directory to... |
def get_resource(self, resource_name, name):
# pylint: disable=too-many-locals, too-many-nested-blocks
"""Get a specific resource by name"""
try:
logger.info("Trying to get %s: '%s'", resource_name, name)
services_list = False
if resource_name == 'host' and '... | def function[get_resource, parameter[self, resource_name, name]]:
constant[Get a specific resource by name]
<ast.Try object at 0x7da20c795870> | keyword[def] identifier[get_resource] ( identifier[self] , identifier[resource_name] , identifier[name] ):
literal[string]
keyword[try] :
identifier[logger] . identifier[info] ( literal[string] , identifier[resource_name] , identifier[name] )
identifier[services_list] = ... | def get_resource(self, resource_name, name):
# pylint: disable=too-many-locals, too-many-nested-blocks
'Get a specific resource by name'
try:
logger.info("Trying to get %s: '%s'", resource_name, name)
services_list = False
if resource_name == 'host' and '/' in name:
split... |
def view_dupl_sources_time(token, dstore):
"""
Display the time spent computing duplicated sources
"""
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for source_id, records in items:
if len(records) > 1: # dupl
... | def function[view_dupl_sources_time, parameter[token, dstore]]:
constant[
Display the time spent computing duplicated sources
]
variable[info] assign[=] call[name[dstore]][constant[source_info]]
variable[items] assign[=] call[name[sorted], parameter[call[call[name[group_array], parameter... | keyword[def] identifier[view_dupl_sources_time] ( identifier[token] , identifier[dstore] ):
literal[string]
identifier[info] = identifier[dstore] [ literal[string] ]
identifier[items] = identifier[sorted] ( identifier[group_array] ( identifier[info] . identifier[value] , literal[string] ). identifier[... | def view_dupl_sources_time(token, dstore):
"""
Display the time spent computing duplicated sources
"""
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for (source_id, records) in items:
if len(records) > 1: # dupl
... |
def late_filling(target, pressure='pore.pressure',
Pc_star='pore.pc_star',
Swp_star=0.2, eta=3):
r"""
Calculates the fraction of a pore or throat filled with invading fluid
based on the capillary pressure in the invading phase. The invading phase
volume is calculated f... | def function[late_filling, parameter[target, pressure, Pc_star, Swp_star, eta]]:
constant[
Calculates the fraction of a pore or throat filled with invading fluid
based on the capillary pressure in the invading phase. The invading phase
volume is calculated from:
.. math::
S_{nw... | keyword[def] identifier[late_filling] ( identifier[target] , identifier[pressure] = literal[string] ,
identifier[Pc_star] = literal[string] ,
identifier[Swp_star] = literal[int] , identifier[eta] = literal[int] ):
literal[string]
identifier[element] = identifier[pressure] . identifier[split] ( literal[st... | def late_filling(target, pressure='pore.pressure', Pc_star='pore.pc_star', Swp_star=0.2, eta=3):
"""
Calculates the fraction of a pore or throat filled with invading fluid
based on the capillary pressure in the invading phase. The invading phase
volume is calculated from:
.. math::
... |
def is_identity_matrix(mat,
ignore_phase=False,
rtol=RTOL_DEFAULT,
atol=ATOL_DEFAULT):
"""Test if an array is an identity matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.arr... | def function[is_identity_matrix, parameter[mat, ignore_phase, rtol, atol]]:
constant[Test if an array is an identity matrix.]
if compare[name[atol] is constant[None]] begin[:]
variable[atol] assign[=] name[ATOL_DEFAULT]
if compare[name[rtol] is constant[None]] begin[:]
... | keyword[def] identifier[is_identity_matrix] ( identifier[mat] ,
identifier[ignore_phase] = keyword[False] ,
identifier[rtol] = identifier[RTOL_DEFAULT] ,
identifier[atol] = identifier[ATOL_DEFAULT] ):
literal[string]
keyword[if] identifier[atol] keyword[is] keyword[None] :
identifier[atol] =... | def is_identity_matrix(mat, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is an identity matrix."""
if atol is None:
atol = ATOL_DEFAULT # depends on [control=['if'], data=['atol']]
if rtol is None:
rtol = RTOL_DEFAULT # depends on [control=['if'], data=['r... |
def checkIPFromAlias(alias=None):
'''
Method that checks if the given alias is currently connected to Skype and returns its IP address.
:param alias: Alias to be searched.
:return: Python structure for the Json received. It has the following structure:
{
"type": "i3visio.ip",
... | def function[checkIPFromAlias, parameter[alias]]:
constant[
Method that checks if the given alias is currently connected to Skype and returns its IP address.
:param alias: Alias to be searched.
:return: Python structure for the Json received. It has the following structure:
{
"t... | keyword[def] identifier[checkIPFromAlias] ( identifier[alias] = keyword[None] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : ... | def checkIPFromAlias(alias=None):
"""
Method that checks if the given alias is currently connected to Skype and returns its IP address.
:param alias: Alias to be searched.
:return: Python structure for the Json received. It has the following structure:
{
"type": "i3visio.ip",
... |
def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp):
"""邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_addr {[type]} -- [description]
... | def function[QA_util_send_mail, parameter[msg, title, from_user, from_password, to_addr, smtp]]:
constant[邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_... | keyword[def] identifier[QA_util_send_mail] ( identifier[msg] , identifier[title] , identifier[from_user] , identifier[from_password] , identifier[to_addr] , identifier[smtp] ):
literal[string]
identifier[msg] = identifier[MIMEText] ( identifier[msg] , literal[string] , literal[string] )
identifier[ms... | def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp):
"""邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_addr {[type]} -- [description]
... |
def monthdatescalendar(cls, year, month):
""" Returns a list of week in a month. A week is a list of NepDate objects """
weeks = []
week = []
for day in NepCal.itermonthdates(year, month):
week.append(day)
if len(week) == 7:
weeks.append(week)
... | def function[monthdatescalendar, parameter[cls, year, month]]:
constant[ Returns a list of week in a month. A week is a list of NepDate objects ]
variable[weeks] assign[=] list[[]]
variable[week] assign[=] list[[]]
for taget[name[day]] in starred[call[name[NepCal].itermonthdates, paramet... | keyword[def] identifier[monthdatescalendar] ( identifier[cls] , identifier[year] , identifier[month] ):
literal[string]
identifier[weeks] =[]
identifier[week] =[]
keyword[for] identifier[day] keyword[in] identifier[NepCal] . identifier[itermonthdates] ( identifier[year] , ident... | def monthdatescalendar(cls, year, month):
""" Returns a list of week in a month. A week is a list of NepDate objects """
weeks = []
week = []
for day in NepCal.itermonthdates(year, month):
week.append(day)
if len(week) == 7:
weeks.append(week)
week = [] # depends... |
def trim_decimals(s, precision=-3):
"""
Convert from scientific notation using precision
"""
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
# If pre... | def function[trim_decimals, parameter[s, precision]]:
constant[
Convert from scientific notation using precision
]
variable[encoded] assign[=] call[name[s].encode, parameter[constant[ascii], constant[ignore]]]
variable[str_val] assign[=] constant[]
if name[six].PY3 begin[... | keyword[def] identifier[trim_decimals] ( identifier[s] , identifier[precision] =- literal[int] ):
literal[string]
identifier[encoded] = identifier[s] . identifier[encode] ( literal[string] , literal[string] )
identifier[str_val] = literal[string]
keyword[if] identifier[six] . id... | def trim_decimals(s, precision=-3):
"""
Convert from scientific notation using precision
"""
encoded = s.encode('ascii', 'ignore')
str_val = ''
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision] # depends on [control=['if'], data=[]]
# If preci... |
def rmlst(databasepath, credentials):
"""
Get the most up-to-date profiles and alleles from pubmlst. Note that you will need the necessary access token
and secret for this to work
:param databasepath: path to use to save the database
:param credentials: path to folder containing ... | def function[rmlst, parameter[databasepath, credentials]]:
constant[
Get the most up-to-date profiles and alleles from pubmlst. Note that you will need the necessary access token
and secret for this to work
:param databasepath: path to use to save the database
:param credentials:... | keyword[def] identifier[rmlst] ( identifier[databasepath] , identifier[credentials] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
identifier[completefile] = identifier[os] . identifier[path] . identifier[join] ( identifier[databasepath] , literal[st... | def rmlst(databasepath, credentials):
"""
Get the most up-to-date profiles and alleles from pubmlst. Note that you will need the necessary access token
and secret for this to work
:param databasepath: path to use to save the database
:param credentials: path to folder containing acce... |
def find_by_uuid(self, si, uuid, is_vm=True, path=None, data_center=None):
"""
Finds vm/host by his uuid in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param uuid: the object uuid
:param path: the path to find the object ('dc' or 'dc/f... | def function[find_by_uuid, parameter[self, si, uuid, is_vm, path, data_center]]:
constant[
Finds vm/host by his uuid in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param uuid: the object uuid
:param path: the path to find the object ('... | keyword[def] identifier[find_by_uuid] ( identifier[self] , identifier[si] , identifier[uuid] , identifier[is_vm] = keyword[True] , identifier[path] = keyword[None] , identifier[data_center] = keyword[None] ):
literal[string]
keyword[if] identifier[uuid] keyword[is] keyword[None] :
... | def find_by_uuid(self, si, uuid, is_vm=True, path=None, data_center=None):
"""
Finds vm/host by his uuid in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param uuid: the object uuid
:param path: the path to find the object ('dc' or 'dc/folde... |
def WriteClientStats(self, client_id,
stats):
"""Stores a ClientStats instance."""
if client_id not in self.ReadAllClientIDs():
raise db.UnknownClientError(client_id)
self.client_stats[client_id][rdfvalue.RDFDatetime.Now()] = stats | def function[WriteClientStats, parameter[self, client_id, stats]]:
constant[Stores a ClientStats instance.]
if compare[name[client_id] <ast.NotIn object at 0x7da2590d7190> call[name[self].ReadAllClientIDs, parameter[]]] begin[:]
<ast.Raise object at 0x7da2054a58d0>
call[call[name[self].c... | keyword[def] identifier[WriteClientStats] ( identifier[self] , identifier[client_id] ,
identifier[stats] ):
literal[string]
keyword[if] identifier[client_id] keyword[not] keyword[in] identifier[self] . identifier[ReadAllClientIDs] ():
keyword[raise] identifier[db] . identifier[UnknownClientErr... | def WriteClientStats(self, client_id, stats):
"""Stores a ClientStats instance."""
if client_id not in self.ReadAllClientIDs():
raise db.UnknownClientError(client_id) # depends on [control=['if'], data=['client_id']]
self.client_stats[client_id][rdfvalue.RDFDatetime.Now()] = stats |
def process(self, context, data):
"""
Will modify the context.target_backend attribute based on the requester identifier.
:param context: request context
:param data: the internal request
"""
context.target_backend = self.requester_mapping[data.requester]
return s... | def function[process, parameter[self, context, data]]:
constant[
Will modify the context.target_backend attribute based on the requester identifier.
:param context: request context
:param data: the internal request
]
name[context].target_backend assign[=] call[name[self].... | keyword[def] identifier[process] ( identifier[self] , identifier[context] , identifier[data] ):
literal[string]
identifier[context] . identifier[target_backend] = identifier[self] . identifier[requester_mapping] [ identifier[data] . identifier[requester] ]
keyword[return] identifier[super... | def process(self, context, data):
"""
Will modify the context.target_backend attribute based on the requester identifier.
:param context: request context
:param data: the internal request
"""
context.target_backend = self.requester_mapping[data.requester]
return super().proce... |
def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
... | def function[summary, parameter[self, raw]]:
constant[
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the m... | keyword[def] identifier[summary] ( identifier[self] , identifier[raw] ):
literal[string]
keyword[try] :
identifier[taxonomies] =[]
keyword[if] identifier[raw] . identifier[get] ( literal[string] ):
identifier[final_level] = keyword[None]
... | def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
... |
def shv(command, capture=False, ignore_error=False, cwd=None):
"""Run the given command inside the virtual environment, if available:
"""
_setVirtualEnv()
try:
command = "%s; %s" % (options.virtualenv.activate_cmd, command)
except AttributeError:
pass
return bash(command, capture... | def function[shv, parameter[command, capture, ignore_error, cwd]]:
constant[Run the given command inside the virtual environment, if available:
]
call[name[_setVirtualEnv], parameter[]]
<ast.Try object at 0x7da1b0037c40>
return[call[name[bash], parameter[name[command]]]] | keyword[def] identifier[shv] ( identifier[command] , identifier[capture] = keyword[False] , identifier[ignore_error] = keyword[False] , identifier[cwd] = keyword[None] ):
literal[string]
identifier[_setVirtualEnv] ()
keyword[try] :
identifier[command] = literal[string] %( identifier[options] ... | def shv(command, capture=False, ignore_error=False, cwd=None):
"""Run the given command inside the virtual environment, if available:
"""
_setVirtualEnv()
try:
command = '%s; %s' % (options.virtualenv.activate_cmd, command) # depends on [control=['try'], data=[]]
except AttributeError:
... |
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''get the name list of the topics, and print it
'''
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
... | def function[show_list, parameter[timeout_in_sec, out, host, sub_port]]:
constant[get the name list of the topics, and print it
]
class class[TopicNameStore, parameter[]] begin[:]
def function[__init__, parameter[self]]:
name[self]._topic_names assign[=] call[... | keyword[def] identifier[show_list] ( identifier[timeout_in_sec] , identifier[out] = identifier[sys] . identifier[stdout] , identifier[host] = identifier[jps] . identifier[env] . identifier[get_master_host] (), identifier[sub_port] = identifier[jps] . identifier[DEFAULT_SUB_PORT] ):
literal[string]
keyword[... | def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
"""get the name list of the topics, and print it
"""
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
... |
def run(tests=(), reporter=None, stop_after=None):
"""
Run the tests that are loaded by each of the strings provided.
Arguments:
tests (iterable):
the collection of tests (specified as `str` s) to run
reporter (Reporter):
a `Reporter` to use for the run. If unpro... | def function[run, parameter[tests, reporter, stop_after]]:
constant[
Run the tests that are loaded by each of the strings provided.
Arguments:
tests (iterable):
the collection of tests (specified as `str` s) to run
reporter (Reporter):
a `Reporter` to use for... | keyword[def] identifier[run] ( identifier[tests] =(), identifier[reporter] = keyword[None] , identifier[stop_after] = keyword[None] ):
literal[string]
keyword[if] identifier[reporter] keyword[is] keyword[None] :
identifier[reporter] = identifier[Counter] ()
keyword[if] identifier[stop_af... | def run(tests=(), reporter=None, stop_after=None):
"""
Run the tests that are loaded by each of the strings provided.
Arguments:
tests (iterable):
the collection of tests (specified as `str` s) to run
reporter (Reporter):
a `Reporter` to use for the run. If unpro... |
def calibration_stimulus(self, mode):
"""Gets the stimulus model for calibration
:param mode: Type of stimulus to get: tone or noise
:type mode: str
:returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>`
"""
if mode == 'tone':
return self... | def function[calibration_stimulus, parameter[self, mode]]:
constant[Gets the stimulus model for calibration
:param mode: Type of stimulus to get: tone or noise
:type mode: str
:returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>`
]
if compare[name[m... | keyword[def] identifier[calibration_stimulus] ( identifier[self] , identifier[mode] ):
literal[string]
keyword[if] identifier[mode] == literal[string] :
keyword[return] identifier[self] . identifier[tone_calibrator] . identifier[stimulus]
keyword[elif] identifier[mode] == ... | def calibration_stimulus(self, mode):
"""Gets the stimulus model for calibration
:param mode: Type of stimulus to get: tone or noise
:type mode: str
:returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>`
"""
if mode == 'tone':
return self.tone_calibr... |
def get_option(self, key):
"""Returns current value of specified option.
:param key: key of the option
"""
# Backwards compatibility
if key == "rtmpdump":
key = "rtmp-rtmpdump"
elif key == "rtmpdump-proxy":
key = "rtmp-proxy"
elif key == ... | def function[get_option, parameter[self, key]]:
constant[Returns current value of specified option.
:param key: key of the option
]
if compare[name[key] equal[==] constant[rtmpdump]] begin[:]
variable[key] assign[=] constant[rtmp-rtmpdump]
if compare[name[key] e... | keyword[def] identifier[get_option] ( identifier[self] , identifier[key] ):
literal[string]
keyword[if] identifier[key] == literal[string] :
identifier[key] = literal[string]
keyword[elif] identifier[key] == literal[string] :
identifier[key] = literal[... | def get_option(self, key):
"""Returns current value of specified option.
:param key: key of the option
"""
# Backwards compatibility
if key == 'rtmpdump':
key = 'rtmp-rtmpdump' # depends on [control=['if'], data=['key']]
elif key == 'rtmpdump-proxy':
key = 'rtmp-proxy'... |
def telegram(self, client_key=None, tgid=None, key=None):
"""Create Telegram Templates which can be used to send telegrams
:param client_key: Client Key Nationstates Gave you
:param tgid: TGID from api template
:param key: Key from api Template
"""
return Tele... | def function[telegram, parameter[self, client_key, tgid, key]]:
constant[Create Telegram Templates which can be used to send telegrams
:param client_key: Client Key Nationstates Gave you
:param tgid: TGID from api template
:param key: Key from api Template
]
retur... | keyword[def] identifier[telegram] ( identifier[self] , identifier[client_key] = keyword[None] , identifier[tgid] = keyword[None] , identifier[key] = keyword[None] ):
literal[string]
keyword[return] identifier[Telegram] ( identifier[self] , identifier[client_key] , identifier[tgid] , identifier[key... | def telegram(self, client_key=None, tgid=None, key=None):
"""Create Telegram Templates which can be used to send telegrams
:param client_key: Client Key Nationstates Gave you
:param tgid: TGID from api template
:param key: Key from api Template
"""
return Telegram(sel... |
def flavor_access_list(name, projects, **kwargs):
'''
Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-share:
nova... | def function[flavor_access_list, parameter[name, projects]]:
constant[
Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-sh... | keyword[def] identifier[flavor_access_list] ( identifier[name] , identifier[projects] ,** identifier[kwargs] ):
literal[string]
identifier[dry_run] = identifier[__opts__] [ literal[string] ]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[False] , literal[string] : li... | def flavor_access_list(name, projects, **kwargs):
"""
Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-share:
nova... |
def to_joint_gaussian(self):
"""
The linear Gaussian Bayesian Networks are an alternative
representation for the class of multivariate Gaussian distributions.
This method returns an equivalent joint Gaussian distribution.
Returns
-------
GaussianDistribution: An ... | def function[to_joint_gaussian, parameter[self]]:
constant[
The linear Gaussian Bayesian Networks are an alternative
representation for the class of multivariate Gaussian distributions.
This method returns an equivalent joint Gaussian distribution.
Returns
-------
... | keyword[def] identifier[to_joint_gaussian] ( identifier[self] ):
literal[string]
identifier[variables] = identifier[nx] . identifier[topological_sort] ( identifier[self] )
identifier[mean] = identifier[np] . identifier[zeros] ( identifier[len] ( identifier[variables] ))
identifier... | def to_joint_gaussian(self):
"""
The linear Gaussian Bayesian Networks are an alternative
representation for the class of multivariate Gaussian distributions.
This method returns an equivalent joint Gaussian distribution.
Returns
-------
GaussianDistribution: An equi... |
def constraints_since(self, other):
"""
Returns the constraints that have been accumulated since `other`.
:param other: a prior PathHistory object
:returns: a list of constraints
"""
constraints = [ ]
cur = self
while cur is not other and cur is not None... | def function[constraints_since, parameter[self, other]]:
constant[
Returns the constraints that have been accumulated since `other`.
:param other: a prior PathHistory object
:returns: a list of constraints
]
variable[constraints] assign[=] list[[]]
variable[cur] ... | keyword[def] identifier[constraints_since] ( identifier[self] , identifier[other] ):
literal[string]
identifier[constraints] =[]
identifier[cur] = identifier[self]
keyword[while] identifier[cur] keyword[is] keyword[not] identifier[other] keyword[and] identifier[cur] keywo... | def constraints_since(self, other):
"""
Returns the constraints that have been accumulated since `other`.
:param other: a prior PathHistory object
:returns: a list of constraints
"""
constraints = []
cur = self
while cur is not other and cur is not None:
constrai... |
def sampleByKey(self, withReplacement, fractions, seed=None):
"""
Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map.
>>> fractio... | def function[sampleByKey, parameter[self, withReplacement, fractions, seed]]:
constant[
Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map... | keyword[def] identifier[sampleByKey] ( identifier[self] , identifier[withReplacement] , identifier[fractions] , identifier[seed] = keyword[None] ):
literal[string]
keyword[for] identifier[fraction] keyword[in] identifier[fractions] . identifier[values] ():
keyword[assert] identifie... | def sampleByKey(self, withReplacement, fractions, seed=None):
"""
Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map.
>>> fractions =... |
def find(self, objects):
"""Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatc... | def function[find, parameter[self, objects]]:
constant[Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises gro... | keyword[def] identifier[find] ( identifier[self] , identifier[objects] ):
literal[string]
identifier[matches] = identifier[list] ( identifier[self] . identifier[__call__] ( identifier[objects] ))
keyword[if] keyword[not] identifier[matches] :
keyword[raise] identifier[excep... | def find(self, objects):
"""Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatchesE... |
def delete(self, **kwds):
"""
Endpoint: /photo/<id>/delete.json
Deletes this photo.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.photo.delete(self, **kwds)
self._delete_fields()
return result | def function[delete, parameter[self]]:
constant[
Endpoint: /photo/<id>/delete.json
Deletes this photo.
Returns True if successful.
Raises a TroveboxError if not.
]
variable[result] assign[=] call[name[self]._client.photo.delete, parameter[name[self]]]
cal... | keyword[def] identifier[delete] ( identifier[self] ,** identifier[kwds] ):
literal[string]
identifier[result] = identifier[self] . identifier[_client] . identifier[photo] . identifier[delete] ( identifier[self] ,** identifier[kwds] )
identifier[self] . identifier[_delete_fields] ()
... | def delete(self, **kwds):
"""
Endpoint: /photo/<id>/delete.json
Deletes this photo.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.photo.delete(self, **kwds)
self._delete_fields()
return result |
def cross_entropy_reward_loss(logits, actions, rewards, name=None):
"""Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholder
The agent action... | def function[cross_entropy_reward_loss, parameter[logits, actions, rewards, name]]:
constant[Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholde... | keyword[def] identifier[cross_entropy_reward_loss] ( identifier[logits] , identifier[actions] , identifier[rewards] , identifier[name] = keyword[None] ):
literal[string]
identifier[cross_entropy] = identifier[tf] . identifier[nn] . identifier[sparse_softmax_cross_entropy_with_logits] ( identifier[labels] =... | def cross_entropy_reward_loss(logits, actions, rewards, name=None):
"""Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholder
The agent action... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.