code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def register_sub_commands(self, parser):
"""
Add any sub commands to the argument parser.
:param parser: The argument parser object
"""
sub_commands = self.get_sub_commands()
if sub_commands:
sub_parsers = parser.add_subparsers(dest=self.sub_parser_dest_name)... | def function[register_sub_commands, parameter[self, parser]]:
constant[
Add any sub commands to the argument parser.
:param parser: The argument parser object
]
variable[sub_commands] assign[=] call[name[self].get_sub_commands, parameter[]]
if name[sub_commands] begin[:]... | keyword[def] identifier[register_sub_commands] ( identifier[self] , identifier[parser] ):
literal[string]
identifier[sub_commands] = identifier[self] . identifier[get_sub_commands] ()
keyword[if] identifier[sub_commands] :
identifier[sub_parsers] = identifier[parser] . identi... | def register_sub_commands(self, parser):
"""
Add any sub commands to the argument parser.
:param parser: The argument parser object
"""
sub_commands = self.get_sub_commands()
if sub_commands:
sub_parsers = parser.add_subparsers(dest=self.sub_parser_dest_name)
for (na... |
def loadValues(self, values):
"""
Loads the values from the inputed dictionary to the widget.
:param values | <dict>
"""
table = self.tableType()
if table:
schema = table.schema()
else:
schema = None
... | def function[loadValues, parameter[self, values]]:
constant[
Loads the values from the inputed dictionary to the widget.
:param values | <dict>
]
variable[table] assign[=] call[name[self].tableType, parameter[]]
if name[table] begin[:]
variab... | keyword[def] identifier[loadValues] ( identifier[self] , identifier[values] ):
literal[string]
identifier[table] = identifier[self] . identifier[tableType] ()
keyword[if] identifier[table] :
identifier[schema] = identifier[table] . identifier[schema] ()
keyword[... | def loadValues(self, values):
"""
Loads the values from the inputed dictionary to the widget.
:param values | <dict>
"""
table = self.tableType()
if table:
schema = table.schema() # depends on [control=['if'], data=[]]
else:
schema = None
proces... |
def remove_datastore(datastore, service_instance=None):
'''
Removes a datastore. If multiple datastores an error is raised.
datastore
Datastore name
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
... | def function[remove_datastore, parameter[datastore, service_instance]]:
constant[
Removes a datastore. If multiple datastores an error is raised.
datastore
Datastore name
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
... | keyword[def] identifier[remove_datastore] ( identifier[datastore] , identifier[service_instance] = keyword[None] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string] , identifier[datastore] )
identifier[target] = identifier[_get_proxy_target] ( identifier[service_instance] )
i... | def remove_datastore(datastore, service_instance=None):
"""
Removes a datastore. If multiple datastores an error is raised.
datastore
Datastore name
service_instance
Service instance (vim.ServiceInstance) of the vCenter/ESXi host.
Default is None.
.. code-block:: bash
... |
def save(self, force_insert=False, force_update=False, *args, **kwargs):
"""
Makes sure we are in sync with the User field
"""
self.first_name = self.user.first_name
self.last_name = self.user.last_name
self.email = self.user.email
full_name = '%s %s' % (self.firs... | def function[save, parameter[self, force_insert, force_update]]:
constant[
Makes sure we are in sync with the User field
]
name[self].first_name assign[=] name[self].user.first_name
name[self].last_name assign[=] name[self].user.last_name
name[self].email assign[=] name[s... | keyword[def] identifier[save] ( identifier[self] , identifier[force_insert] = keyword[False] , identifier[force_update] = keyword[False] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[first_name] = identifier[self] . identifier[user] . identifier[first_n... | def save(self, force_insert=False, force_update=False, *args, **kwargs):
"""
Makes sure we are in sync with the User field
"""
self.first_name = self.user.first_name
self.last_name = self.user.last_name
self.email = self.user.email
full_name = '%s %s' % (self.first_name, self.last_na... |
def delete(domain, key, user=None):
'''
Delete a default from the system
CLI Example:
.. code-block:: bash
salt '*' macdefaults.delete com.apple.CrashReporter DialogType
salt '*' macdefaults.delete NSGlobalDomain ApplePersistence
domain
The name of the domain to delete f... | def function[delete, parameter[domain, key, user]]:
constant[
Delete a default from the system
CLI Example:
.. code-block:: bash
salt '*' macdefaults.delete com.apple.CrashReporter DialogType
salt '*' macdefaults.delete NSGlobalDomain ApplePersistence
domain
The name... | keyword[def] identifier[delete] ( identifier[domain] , identifier[key] , identifier[user] = keyword[None] ):
literal[string]
identifier[cmd] = literal[string] . identifier[format] ( identifier[domain] , identifier[key] )
keyword[return] identifier[__salt__] [ literal[string] ]( identifier[cmd] , iden... | def delete(domain, key, user=None):
"""
Delete a default from the system
CLI Example:
.. code-block:: bash
salt '*' macdefaults.delete com.apple.CrashReporter DialogType
salt '*' macdefaults.delete NSGlobalDomain ApplePersistence
domain
The name of the domain to delete f... |
def _system_config_file():
"""
Returns the path to the settings.cfg file. On Windows the file is
located in the AppData/Local/envipyengine directory. On Unix, the file
will be located in the ~/.envipyengine directory.
:return: String specifying the full path to the settings.cfg file
"""
if ... | def function[_system_config_file, parameter[]]:
constant[
Returns the path to the settings.cfg file. On Windows the file is
located in the AppData/Local/envipyengine directory. On Unix, the file
will be located in the ~/.envipyengine directory.
:return: String specifying the full path to the se... | keyword[def] identifier[_system_config_file] ():
literal[string]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[config_path] = identifier[os] . identifier[path] . identifier[sep] . identifier[join] ([ identifier[_windows_system_appdata] (),
identifier[... | def _system_config_file():
"""
Returns the path to the settings.cfg file. On Windows the file is
located in the AppData/Local/envipyengine directory. On Unix, the file
will be located in the ~/.envipyengine directory.
:return: String specifying the full path to the settings.cfg file
"""
if ... |
def create_lang_instance(var_map = None):
"""
>>> lang_instance = create_lang_instance()
>>> lang_instance.aml_evaluate(lang_instance.aml_compile('1 = 1'))
True
>>> li = create_lang_instance()
>>> c = li.aml_compile
>>> e = li.aml_evaluate
>>> p = li.aml_translate_python
>>> s = li.aml_translate_sql
>>> u = l... | def function[create_lang_instance, parameter[var_map]]:
constant[
>>> lang_instance = create_lang_instance()
>>> lang_instance.aml_evaluate(lang_instance.aml_compile('1 = 1'))
True
>>> li = create_lang_instance()
>>> c = li.aml_compile
>>> e = li.aml_evaluate
>>> p = li.aml_translate_python
>>> s = li.a... | keyword[def] identifier[create_lang_instance] ( identifier[var_map] = keyword[None] ):
literal[string]
keyword[def] identifier[py_bool_to_lit] ( identifier[py_bool] ):
keyword[return] identifier[parse] ( literal[string] keyword[if] identifier[py_bool] keyword[else] literal[string] , identifier[BooleanL... | def create_lang_instance(var_map=None):
"""
>>> lang_instance = create_lang_instance()
>>> lang_instance.aml_evaluate(lang_instance.aml_compile('1 = 1'))
True
>>> li = create_lang_instance()
>>> c = li.aml_compile
>>> e = li.aml_evaluate
>>> p = li.aml_translate_python
>>> s = li.aml_translate_sql
>>> u = ... |
def reduce_value(value, default=EMPTY_STR):
"""
:return: a single value from lists, tuples or sets with one item;
otherwise, the value itself if not empty or the default if it is.
"""
if hasattr(value, '__len__'):
vlen = len(value)
if vlen == 0:
return default
e... | def function[reduce_value, parameter[value, default]]:
constant[
:return: a single value from lists, tuples or sets with one item;
otherwise, the value itself if not empty or the default if it is.
]
if call[name[hasattr], parameter[name[value], constant[__len__]]] begin[:]
va... | keyword[def] identifier[reduce_value] ( identifier[value] , identifier[default] = identifier[EMPTY_STR] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[value] , literal[string] ):
identifier[vlen] = identifier[len] ( identifier[value] )
keyword[if] identifier[vlen] == ... | def reduce_value(value, default=EMPTY_STR):
"""
:return: a single value from lists, tuples or sets with one item;
otherwise, the value itself if not empty or the default if it is.
"""
if hasattr(value, '__len__'):
vlen = len(value)
if vlen == 0:
return default # depends ... |
def validate_multiple_of(value, divisor, **kwargs):
"""
Given a value and a divisor, validate that the value is divisible by the
divisor.
"""
if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0:
raise ValidationError(
MESSAGES['multiple_of']['invalid'].format(... | def function[validate_multiple_of, parameter[value, divisor]]:
constant[
Given a value and a divisor, validate that the value is divisible by the
divisor.
]
if <ast.UnaryOp object at 0x7da1b0f630d0> begin[:]
<ast.Raise object at 0x7da1b0f614e0> | keyword[def] identifier[validate_multiple_of] ( identifier[value] , identifier[divisor] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[decimal] . identifier[Decimal] ( identifier[str] ( identifier[value] ))% identifier[decimal] . identifier[Decimal] ( identifier[str] ( iden... | def validate_multiple_of(value, divisor, **kwargs):
"""
Given a value and a divisor, validate that the value is divisible by the
divisor.
"""
if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0:
raise ValidationError(MESSAGES['multiple_of']['invalid'].format(divisor, valu... |
def save_gdf_shapefile(gdf, filename=None, folder=None):
"""
Save a GeoDataFrame of place shapes or footprints as an ESRI
shapefile.
Parameters
----------
gdf : GeoDataFrame
the gdf to be saved
filename : string
what to call the shapefile (file extensions are added automatic... | def function[save_gdf_shapefile, parameter[gdf, filename, folder]]:
constant[
Save a GeoDataFrame of place shapes or footprints as an ESRI
shapefile.
Parameters
----------
gdf : GeoDataFrame
the gdf to be saved
filename : string
what to call the shapefile (file extension... | keyword[def] identifier[save_gdf_shapefile] ( identifier[gdf] , identifier[filename] = keyword[None] , identifier[folder] = keyword[None] ):
literal[string]
keyword[if] identifier[folder] keyword[is] keyword[None] :
identifier[folder] = identifier[settings] . identifier[data_folder]
key... | def save_gdf_shapefile(gdf, filename=None, folder=None):
"""
Save a GeoDataFrame of place shapes or footprints as an ESRI
shapefile.
Parameters
----------
gdf : GeoDataFrame
the gdf to be saved
filename : string
what to call the shapefile (file extensions are added automatic... |
def _open(self, mode=None):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
"""
if mode is None:
mode = self.mode
if self.encoding i... | def function[_open, parameter[self, mode]]:
constant[
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
]
if compare[name[mode] is constant[None]] begin[:]
... | keyword[def] identifier[_open] ( identifier[self] , identifier[mode] = keyword[None] ):
literal[string]
keyword[if] identifier[mode] keyword[is] keyword[None] :
identifier[mode] = identifier[self] . identifier[mode]
keyword[if] identifier[self] . identifier[encoding] key... | def _open(self, mode=None):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
"""
if mode is None:
mode = self.mode # depends on [control=['if'], data=['... |
def process_rst_and_summaries(content_generators):
"""
Ensure mathjax script is applied to RST and summaries are
corrected if specified in user settings.
Handles content attached to ArticleGenerator and PageGenerator objects,
since the plugin doesn't know how to handle other Generator types.
F... | def function[process_rst_and_summaries, parameter[content_generators]]:
constant[
Ensure mathjax script is applied to RST and summaries are
corrected if specified in user settings.
Handles content attached to ArticleGenerator and PageGenerator objects,
since the plugin doesn't know how to handl... | keyword[def] identifier[process_rst_and_summaries] ( identifier[content_generators] ):
literal[string]
keyword[for] identifier[generator] keyword[in] identifier[content_generators] :
keyword[if] identifier[isinstance] ( identifier[generator] , identifier[generators] . identifier[ArticlesGener... | def process_rst_and_summaries(content_generators):
"""
Ensure mathjax script is applied to RST and summaries are
corrected if specified in user settings.
Handles content attached to ArticleGenerator and PageGenerator objects,
since the plugin doesn't know how to handle other Generator types.
F... |
def register(linter):
"""required method to auto register this checker """
linter.register_checker(TypeChecker(linter))
linter.register_checker(IterableChecker(linter)) | def function[register, parameter[linter]]:
constant[required method to auto register this checker ]
call[name[linter].register_checker, parameter[call[name[TypeChecker], parameter[name[linter]]]]]
call[name[linter].register_checker, parameter[call[name[IterableChecker], parameter[name[linter]]]]... | keyword[def] identifier[register] ( identifier[linter] ):
literal[string]
identifier[linter] . identifier[register_checker] ( identifier[TypeChecker] ( identifier[linter] ))
identifier[linter] . identifier[register_checker] ( identifier[IterableChecker] ( identifier[linter] )) | def register(linter):
"""required method to auto register this checker """
linter.register_checker(TypeChecker(linter))
linter.register_checker(IterableChecker(linter)) |
def clean_streak(image, stat="pmode1", maxiter=15, sigrej=2.0,
lower=None, upper=None, binwidth=0.3, mask=None,
rpt_clean=0, atol=0.01, verbose=True):
"""
Apply destriping algorithm to input array.
Parameters
----------
image : `StripeArray` object
Arrays a... | def function[clean_streak, parameter[image, stat, maxiter, sigrej, lower, upper, binwidth, mask, rpt_clean, atol, verbose]]:
constant[
Apply destriping algorithm to input array.
Parameters
----------
image : `StripeArray` object
Arrays are modifed in-place.
stat : str
Stati... | keyword[def] identifier[clean_streak] ( identifier[image] , identifier[stat] = literal[string] , identifier[maxiter] = literal[int] , identifier[sigrej] = literal[int] ,
identifier[lower] = keyword[None] , identifier[upper] = keyword[None] , identifier[binwidth] = literal[int] , identifier[mask] = keyword[None] ,
i... | def clean_streak(image, stat='pmode1', maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, rpt_clean=0, atol=0.01, verbose=True):
"""
Apply destriping algorithm to input array.
Parameters
----------
image : `StripeArray` object
Arrays are modifed in-place.
stat : s... |
def _on_connection_finished(self, success, result, failure_reason, context):
"""Callback called when the connection attempt to a BLE device has finished.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A bool indicating that the operation is... | def function[_on_connection_finished, parameter[self, success, result, failure_reason, context]]:
constant[Callback called when the connection attempt to a BLE device has finished.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A bool indic... | keyword[def] identifier[_on_connection_finished] ( identifier[self] , identifier[success] , identifier[result] , identifier[failure_reason] , identifier[context] ):
literal[string]
identifier[connection_id] = identifier[context] [ literal[string] ]
keyword[if] keyword[not] identifier[su... | def _on_connection_finished(self, success, result, failure_reason, context):
"""Callback called when the connection attempt to a BLE device has finished.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A bool indicating that the operation is suc... |
def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) | def function[getZoom, parameter[self, resolution]]:
constant[Return the zoom level for a given resolution]
assert[compare[name[resolution] in name[self].RESOLUTIONS]]
return[call[name[self].RESOLUTIONS.index, parameter[name[resolution]]]] | keyword[def] identifier[getZoom] ( identifier[self] , identifier[resolution] ):
literal[string]
keyword[assert] identifier[resolution] keyword[in] identifier[self] . identifier[RESOLUTIONS]
keyword[return] identifier[self] . identifier[RESOLUTIONS] . identifier[index] ( identifier[res... | def getZoom(self, resolution):
"""Return the zoom level for a given resolution"""
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) |
def export(self):
"""
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation ... | def function[export, parameter[self]]:
constant[
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The seria... | keyword[def] identifier[export] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[C] , literal[string] ):
keyword[raise] identifier[NotImplementedError] ( literal[string] )
identifier[minor_status] = identifier[ffi] . identifie... | def export(self):
"""
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation of t... |
def get_transport_target(cls, instance, timeout, retries):
'''
Generate a Transport target object based on the instance's configuration
'''
if "ip_address" not in instance:
raise Exception("An IP address needs to be specified")
ip_address = instance["ip_address"]
... | def function[get_transport_target, parameter[cls, instance, timeout, retries]]:
constant[
Generate a Transport target object based on the instance's configuration
]
if compare[constant[ip_address] <ast.NotIn object at 0x7da2590d7190> name[instance]] begin[:]
<ast.Raise object at ... | keyword[def] identifier[get_transport_target] ( identifier[cls] , identifier[instance] , identifier[timeout] , identifier[retries] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[instance] :
keyword[raise] identifier[Exception] ( literal[string] ... | def get_transport_target(cls, instance, timeout, retries):
"""
Generate a Transport target object based on the instance's configuration
"""
if 'ip_address' not in instance:
raise Exception('An IP address needs to be specified') # depends on [control=['if'], data=[]]
ip_address = ins... |
def add_header(input_array, codec, length, param):
"""Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the prepended encoded byte array"""
... | def function[add_header, parameter[input_array, codec, length, param]]:
constant[Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the pre... | keyword[def] identifier[add_header] ( identifier[input_array] , identifier[codec] , identifier[length] , identifier[param] ):
literal[string]
keyword[return] identifier[struct] . identifier[pack] ( identifier[mmtf] . identifier[utils] . identifier[constants] . identifier[NUM_DICT] [ literal[int] ], identi... | def add_header(input_array, codec, length, param):
"""Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the prepended encoded byte array"""
... |
def aggregate_series(self, key, aggregate, start=None, end=None,
interval=None, namespace=None, cache=None,
percentile=None):
"""Get a time series of gauge aggregates"""
return self.make_context(key=key, aggregate=aggregate, start=start,
... | def function[aggregate_series, parameter[self, key, aggregate, start, end, interval, namespace, cache, percentile]]:
constant[Get a time series of gauge aggregates]
return[call[call[name[self].make_context, parameter[]].aggregate_series, parameter[]]] | keyword[def] identifier[aggregate_series] ( identifier[self] , identifier[key] , identifier[aggregate] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ,
identifier[interval] = keyword[None] , identifier[namespace] = keyword[None] , identifier[cache] = keyword[None] ,
identifier[percentile] = k... | def aggregate_series(self, key, aggregate, start=None, end=None, interval=None, namespace=None, cache=None, percentile=None):
"""Get a time series of gauge aggregates"""
return self.make_context(key=key, aggregate=aggregate, start=start, end=end, interval=interval, namespace=namespace, cache=cache, percentile=p... |
def timeout_queue_add(self, item, cache_time=0):
"""
Add a item to be run at a future time.
This must be a Module, I3statusModule or a Task
"""
# add the info to the add queue. We do this so that actually adding
# the module is done in the core thread.
self.timeo... | def function[timeout_queue_add, parameter[self, item, cache_time]]:
constant[
Add a item to be run at a future time.
This must be a Module, I3statusModule or a Task
]
call[name[self].timeout_add_queue.append, parameter[tuple[[<ast.Name object at 0x7da1b1d8c730>, <ast.Name object ... | keyword[def] identifier[timeout_queue_add] ( identifier[self] , identifier[item] , identifier[cache_time] = literal[int] ):
literal[string]
identifier[self] . identifier[timeout_add_queue] . identifier[append] (( identifier[item] , identifier[cache_time] ))
... | def timeout_queue_add(self, item, cache_time=0):
"""
Add a item to be run at a future time.
This must be a Module, I3statusModule or a Task
"""
# add the info to the add queue. We do this so that actually adding
# the module is done in the core thread.
self.timeout_add_queue.app... |
def print_generic(self, msg, prefix=None):
"""
Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string
"""
if prefix is None:
self._log(msg, Logger.INFO)... | def function[print_generic, parameter[self, msg, prefix]]:
constant[
Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string
]
if compare[name[prefix] is constant[No... | keyword[def] identifier[print_generic] ( identifier[self] , identifier[msg] , identifier[prefix] = keyword[None] ):
literal[string]
keyword[if] identifier[prefix] keyword[is] keyword[None] :
identifier[self] . identifier[_log] ( identifier[msg] , identifier[Logger] . identifier[INFO... | def print_generic(self, msg, prefix=None):
"""
Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string
"""
if prefix is None:
self._log(msg, Logger.INFO) # depends ... |
def fullName(self):
"""A full name, intended to uniquely identify a parameter"""
# join with '_' if both are set (cannot put '.', because it is used as
# **kwargs)
if self.parentName and self.name:
return self.parentName + '_' + self.name
# otherwise just use the one ... | def function[fullName, parameter[self]]:
constant[A full name, intended to uniquely identify a parameter]
if <ast.BoolOp object at 0x7da1b1c3c670> begin[:]
return[binary_operation[binary_operation[name[self].parentName + constant[_]] + name[self].name]]
return[<ast.BoolOp object at 0x7da1b1c... | keyword[def] identifier[fullName] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[parentName] keyword[and] identifier[self] . identifier[name] :
keyword[return] identifier[self] . identifier[parentName] + literal[string] + identifie... | def fullName(self):
"""A full name, intended to uniquely identify a parameter"""
# join with '_' if both are set (cannot put '.', because it is used as
# **kwargs)
if self.parentName and self.name:
return self.parentName + '_' + self.name # depends on [control=['if'], data=[]]
# otherwise j... |
def has_callbacks(self, name):
"""
Returns True if there are callbacks attached to the specified
event name.
Returns False if not
"""
r = self.event_listeners.get(name)
if not r:
return False
return len(r) > 0 | def function[has_callbacks, parameter[self, name]]:
constant[
Returns True if there are callbacks attached to the specified
event name.
Returns False if not
]
variable[r] assign[=] call[name[self].event_listeners.get, parameter[name[name]]]
if <ast.UnaryOp object... | keyword[def] identifier[has_callbacks] ( identifier[self] , identifier[name] ):
literal[string]
identifier[r] = identifier[self] . identifier[event_listeners] . identifier[get] ( identifier[name] )
keyword[if] keyword[not] identifier[r] :
keyword[return] keyword[False]
... | def has_callbacks(self, name):
"""
Returns True if there are callbacks attached to the specified
event name.
Returns False if not
"""
r = self.event_listeners.get(name)
if not r:
return False # depends on [control=['if'], data=[]]
return len(r) > 0 |
def extract_content(image_path, member_name, return_hash=False):
'''extract_content will extract content from an image using cat.
If hash=True, a hash sum is returned instead
'''
if member_name.startswith('./'):
member_name = member_name.replace('.','',1)
if return_hash:
hashy = hash... | def function[extract_content, parameter[image_path, member_name, return_hash]]:
constant[extract_content will extract content from an image using cat.
If hash=True, a hash sum is returned instead
]
if call[name[member_name].startswith, parameter[constant[./]]] begin[:]
variable[m... | keyword[def] identifier[extract_content] ( identifier[image_path] , identifier[member_name] , identifier[return_hash] = keyword[False] ):
literal[string]
keyword[if] identifier[member_name] . identifier[startswith] ( literal[string] ):
identifier[member_name] = identifier[member_name] . identifie... | def extract_content(image_path, member_name, return_hash=False):
"""extract_content will extract content from an image using cat.
If hash=True, a hash sum is returned instead
"""
if member_name.startswith('./'):
member_name = member_name.replace('.', '', 1) # depends on [control=['if'], data=[]... |
def get_catalogs_by_query(self, catalog_query):
"""Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
``CatalogList``
r... | def function[get_catalogs_by_query, parameter[self, catalog_query]]:
constant[Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
... | keyword[def] identifier[get_catalogs_by_query] ( identifier[self] , identifier[catalog_query] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_ca... | def get_catalogs_by_query(self, catalog_query):
"""Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
``CatalogList``
raise... |
def tgread_object(self):
"""Reads a Telegram object."""
constructor_id = self.read_int(signed=False)
clazz = tlobjects.get(constructor_id, None)
if clazz is None:
# The class was None, but there's still a
# chance of it being a manually parsed value like bool!
... | def function[tgread_object, parameter[self]]:
constant[Reads a Telegram object.]
variable[constructor_id] assign[=] call[name[self].read_int, parameter[]]
variable[clazz] assign[=] call[name[tlobjects].get, parameter[name[constructor_id], constant[None]]]
if compare[name[clazz] is consta... | keyword[def] identifier[tgread_object] ( identifier[self] ):
literal[string]
identifier[constructor_id] = identifier[self] . identifier[read_int] ( identifier[signed] = keyword[False] )
identifier[clazz] = identifier[tlobjects] . identifier[get] ( identifier[constructor_id] , keyword[None]... | def tgread_object(self):
"""Reads a Telegram object."""
constructor_id = self.read_int(signed=False)
clazz = tlobjects.get(constructor_id, None)
if clazz is None:
# The class was None, but there's still a
# chance of it being a manually parsed value like bool!
value = constructor... |
def RemoveObject(self, path):
'''Remove a D-Bus object from the mock
As with AddObject, this will *not* emit the InterfacesRemoved signal if
it’s an ObjectManager instance.
'''
try:
objects[path].remove_from_connection()
del objects[path]
except K... | def function[RemoveObject, parameter[self, path]]:
constant[Remove a D-Bus object from the mock
As with AddObject, this will *not* emit the InterfacesRemoved signal if
it’s an ObjectManager instance.
]
<ast.Try object at 0x7da20c993f10> | keyword[def] identifier[RemoveObject] ( identifier[self] , identifier[path] ):
literal[string]
keyword[try] :
identifier[objects] [ identifier[path] ]. identifier[remove_from_connection] ()
keyword[del] identifier[objects] [ identifier[path] ]
keyword[except] id... | def RemoveObject(self, path):
"""Remove a D-Bus object from the mock
As with AddObject, this will *not* emit the InterfacesRemoved signal if
it’s an ObjectManager instance.
"""
try:
objects[path].remove_from_connection()
del objects[path] # depends on [control=['try'], ... |
def indexInfo(self, index):
""" Returns information about a specific
planetary time.
"""
entry = self.table[index]
info = {
# Default is diurnal
'mode': 'Day',
'ruler': self.dayRuler(),
'dayRuler': self.dayRuler(),
... | def function[indexInfo, parameter[self, index]]:
constant[ Returns information about a specific
planetary time.
]
variable[entry] assign[=] call[name[self].table][name[index]]
variable[info] assign[=] dictionary[[<ast.Constant object at 0x7da1b2346e30>, <ast.Constant o... | keyword[def] identifier[indexInfo] ( identifier[self] , identifier[index] ):
literal[string]
identifier[entry] = identifier[self] . identifier[table] [ identifier[index] ]
identifier[info] ={
literal[string] : literal[string] ,
literal[string] : identifier[self] ... | def indexInfo(self, index):
""" Returns information about a specific
planetary time.
"""
entry = self.table[index]
# Default is diurnal
info = {'mode': 'Day', 'ruler': self.dayRuler(), 'dayRuler': self.dayRuler(), 'nightRuler': self.nightRuler(), 'hourRuler': entry[2], 'hourNu... |
def simxGetUIHandle(clientID, uiName, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if (sys.version_info[0] == 3) and (type(uiName) is str):
uiName=uiName.encode('utf-8')
return c_GetUIHandle(clientID, u... | def function[simxGetUIHandle, parameter[clientID, uiName, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[handle] assign[=] call[name[ct].c_int, parameter[]]
if <ast.BoolOp object at 0x7da207f032e0> begin[:]
... | keyword[def] identifier[simxGetUIHandle] ( identifier[clientID] , identifier[uiName] , identifier[operationMode] ):
literal[string]
identifier[handle] = identifier[ct] . identifier[c_int] ()
keyword[if] ( identifier[sys] . identifier[version_info] [ literal[int] ]== literal[int] ) keyword[and] ( iden... | def simxGetUIHandle(clientID, uiName, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
handle = ct.c_int()
if sys.version_info[0] == 3 and type(uiName) is str:
uiName = uiName.encode('utf-8') # depends on [control=['if'], data=[]]... |
def extract_public_key(args):
""" Load an ECDSA private key and extract the embedded public key as raw binary data. """
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print("%s public key extracted to %s" % (args.keyfile.name, args.public_key... | def function[extract_public_key, parameter[args]]:
constant[ Load an ECDSA private key and extract the embedded public key as raw binary data. ]
variable[sk] assign[=] call[name[_load_ecdsa_signing_key], parameter[name[args]]]
variable[vk] assign[=] call[name[sk].get_verifying_key, parameter[]]
... | keyword[def] identifier[extract_public_key] ( identifier[args] ):
literal[string]
identifier[sk] = identifier[_load_ecdsa_signing_key] ( identifier[args] )
identifier[vk] = identifier[sk] . identifier[get_verifying_key] ()
identifier[args] . identifier[public_keyfile] . identifier[write] ( identi... | def extract_public_key(args):
""" Load an ECDSA private key and extract the embedded public key as raw binary data. """
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print('%s public key extracted to %s' % (args.keyfile.name, args.public_key... |
def parse_expression(val, acceptable_types, name=None, raise_type=ValueError):
"""Attempts to parse the given `val` as a python expression of the specified `acceptable_types`.
:param string val: A string containing a python expression.
:param acceptable_types: The acceptable types of the parsed object.
:type a... | def function[parse_expression, parameter[val, acceptable_types, name, raise_type]]:
constant[Attempts to parse the given `val` as a python expression of the specified `acceptable_types`.
:param string val: A string containing a python expression.
:param acceptable_types: The acceptable types of the parsed ... | keyword[def] identifier[parse_expression] ( identifier[val] , identifier[acceptable_types] , identifier[name] = keyword[None] , identifier[raise_type] = identifier[ValueError] ):
literal[string]
keyword[def] identifier[format_type] ( identifier[typ] ):
keyword[return] identifier[typ] . identifier[__name... | def parse_expression(val, acceptable_types, name=None, raise_type=ValueError):
"""Attempts to parse the given `val` as a python expression of the specified `acceptable_types`.
:param string val: A string containing a python expression.
:param acceptable_types: The acceptable types of the parsed object.
:type... |
def fraction_correct_values(indices, x_values, y_values, x_cutoff = 1.0, y_cutoff = 1.0, ignore_null_values = False):
'''
An approximation to the metric used in the Kellogg et al. paper: "The fraction correct is defined as the number of mutations categorized correctly divided by the total number of mutations in... | def function[fraction_correct_values, parameter[indices, x_values, y_values, x_cutoff, y_cutoff, ignore_null_values]]:
constant[
An approximation to the metric used in the Kellogg et al. paper: "The fraction correct is defined as the number of mutations categorized correctly divided by the total number of m... | keyword[def] identifier[fraction_correct_values] ( identifier[indices] , identifier[x_values] , identifier[y_values] , identifier[x_cutoff] = literal[int] , identifier[y_cutoff] = literal[int] , identifier[ignore_null_values] = keyword[False] ):
literal[string]
identifier[num_points] = identifier[len] ( id... | def fraction_correct_values(indices, x_values, y_values, x_cutoff=1.0, y_cutoff=1.0, ignore_null_values=False):
"""
An approximation to the metric used in the Kellogg et al. paper: "The fraction correct is defined as the number of mutations categorized correctly divided by the total number of mutations in the b... |
def handle_namespace_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``.
:raises: RedefinedNamespaceError
:raises: pybel.resources.exc.ResourceError
"""
namespace = tokens['name']
self.ra... | def function[handle_namespace_url, parameter[self, line, position, tokens]]:
constant[Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``.
:raises: RedefinedNamespaceError
:raises: pybel.resources.exc.ResourceError
]
variable[namespace] assign[=] call[name[tokens]][constant... | keyword[def] identifier[handle_namespace_url] ( identifier[self] , identifier[line] : identifier[str] , identifier[position] : identifier[int] , identifier[tokens] : identifier[ParseResults] )-> identifier[ParseResults] :
literal[string]
identifier[namespace] = identifier[tokens] [ literal[string] ... | def handle_namespace_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``.
:raises: RedefinedNamespaceError
:raises: pybel.resources.exc.ResourceError
"""
namespace = tokens['name']
self.raise_for_rede... |
def set_subject(self, subject):
"""
Set the subject of this certificate.
:param subject: The subject.
:type subject: :py:class:`X509Name`
:return: ``None``
"""
self._set_name(_lib.X509_set_subject_name, subject)
self._subject_invalidator.clear() | def function[set_subject, parameter[self, subject]]:
constant[
Set the subject of this certificate.
:param subject: The subject.
:type subject: :py:class:`X509Name`
:return: ``None``
]
call[name[self]._set_name, parameter[name[_lib].X509_set_subject_name, name[s... | keyword[def] identifier[set_subject] ( identifier[self] , identifier[subject] ):
literal[string]
identifier[self] . identifier[_set_name] ( identifier[_lib] . identifier[X509_set_subject_name] , identifier[subject] )
identifier[self] . identifier[_subject_invalidator] . identifier[clear] (... | def set_subject(self, subject):
"""
Set the subject of this certificate.
:param subject: The subject.
:type subject: :py:class:`X509Name`
:return: ``None``
"""
self._set_name(_lib.X509_set_subject_name, subject)
self._subject_invalidator.clear() |
def _check_times(self, min_times, max_times, step):
'''
Make sure that the arguments are valid
:raises: KittyException if not valid
'''
kassert.is_int(min_times)
kassert.is_int(max_times)
kassert.is_int(step)
if not((min_times >= 0) and (max_times > 0) an... | def function[_check_times, parameter[self, min_times, max_times, step]]:
constant[
Make sure that the arguments are valid
:raises: KittyException if not valid
]
call[name[kassert].is_int, parameter[name[min_times]]]
call[name[kassert].is_int, parameter[name[max_times]]]
... | keyword[def] identifier[_check_times] ( identifier[self] , identifier[min_times] , identifier[max_times] , identifier[step] ):
literal[string]
identifier[kassert] . identifier[is_int] ( identifier[min_times] )
identifier[kassert] . identifier[is_int] ( identifier[max_times] )
iden... | def _check_times(self, min_times, max_times, step):
"""
Make sure that the arguments are valid
:raises: KittyException if not valid
"""
kassert.is_int(min_times)
kassert.is_int(max_times)
kassert.is_int(step)
if not (min_times >= 0 and max_times > 0 and (max_times >= min_tim... |
def symbolic(self, mtx):
"""
Perform symbolic object (symbolic LU decomposition) computation for a given
sparsity pattern.
"""
self.free_symbolic()
indx = self._getIndx(mtx)
if not assumeSortedIndices:
# row/column indices cannot be assumed to be sor... | def function[symbolic, parameter[self, mtx]]:
constant[
Perform symbolic object (symbolic LU decomposition) computation for a given
sparsity pattern.
]
call[name[self].free_symbolic, parameter[]]
variable[indx] assign[=] call[name[self]._getIndx, parameter[name[mtx]]]
... | keyword[def] identifier[symbolic] ( identifier[self] , identifier[mtx] ):
literal[string]
identifier[self] . identifier[free_symbolic] ()
identifier[indx] = identifier[self] . identifier[_getIndx] ( identifier[mtx] )
keyword[if] keyword[not] identifier[assumeSortedIndices] :
... | def symbolic(self, mtx):
"""
Perform symbolic object (symbolic LU decomposition) computation for a given
sparsity pattern.
"""
self.free_symbolic()
indx = self._getIndx(mtx)
if not assumeSortedIndices:
# row/column indices cannot be assumed to be sorted
mtx.sort_i... |
def get_sources(self, skydir=None, distance=None, cuts=None,
minmax_ts=None, minmax_npred=None,
exclude=None, square=False, coordsys='CEL',
names=None):
"""Retrieve list of source objects satisfying the following
selections:
* Angular ... | def function[get_sources, parameter[self, skydir, distance, cuts, minmax_ts, minmax_npred, exclude, square, coordsys, names]]:
constant[Retrieve list of source objects satisfying the following
selections:
* Angular separation from ``skydir`` or ROI center (if
``skydir`` is None) le... | keyword[def] identifier[get_sources] ( identifier[self] , identifier[skydir] = keyword[None] , identifier[distance] = keyword[None] , identifier[cuts] = keyword[None] ,
identifier[minmax_ts] = keyword[None] , identifier[minmax_npred] = keyword[None] ,
identifier[exclude] = keyword[None] , identifier[square] = keywo... | def get_sources(self, skydir=None, distance=None, cuts=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, coordsys='CEL', names=None):
"""Retrieve list of source objects satisfying the following
selections:
* Angular separation from ``skydir`` or ROI center (if
``skyd... |
def line_to_variables(source, line, inherit_permission, parent):
"""
Returns a list of variables declared in the provided line of code. The
line of code should be provided as a string.
"""
vartype, kind, strlen, proto, rest = parse_type(line,parent.strings,parent.settings)
attribs = []
inten... | def function[line_to_variables, parameter[source, line, inherit_permission, parent]]:
constant[
Returns a list of variables declared in the provided line of code. The
line of code should be provided as a string.
]
<ast.Tuple object at 0x7da18c4cc8b0> assign[=] call[name[parse_type], paramete... | keyword[def] identifier[line_to_variables] ( identifier[source] , identifier[line] , identifier[inherit_permission] , identifier[parent] ):
literal[string]
identifier[vartype] , identifier[kind] , identifier[strlen] , identifier[proto] , identifier[rest] = identifier[parse_type] ( identifier[line] , identi... | def line_to_variables(source, line, inherit_permission, parent):
"""
Returns a list of variables declared in the provided line of code. The
line of code should be provided as a string.
"""
(vartype, kind, strlen, proto, rest) = parse_type(line, parent.strings, parent.settings)
attribs = []
i... |
def scores(factors):
""" Computes the score of temperaments
and elements.
"""
temperaments = {
const.CHOLERIC: 0,
const.MELANCHOLIC: 0,
const.SANGUINE: 0,
const.PHLEGMATIC: 0
}
qualities = {
const.HOT: 0,
const.COLD: 0,
... | def function[scores, parameter[factors]]:
constant[ Computes the score of temperaments
and elements.
]
variable[temperaments] assign[=] dictionary[[<ast.Attribute object at 0x7da1b0f39ab0>, <ast.Attribute object at 0x7da1b0f3b070>, <ast.Attribute object at 0x7da1b0f3a320>, <ast.Attribute ob... | keyword[def] identifier[scores] ( identifier[factors] ):
literal[string]
identifier[temperaments] ={
identifier[const] . identifier[CHOLERIC] : literal[int] ,
identifier[const] . identifier[MELANCHOLIC] : literal[int] ,
identifier[const] . identifier[SANGUINE] : literal[int] ,
identifie... | def scores(factors):
""" Computes the score of temperaments
and elements.
"""
temperaments = {const.CHOLERIC: 0, const.MELANCHOLIC: 0, const.SANGUINE: 0, const.PHLEGMATIC: 0}
qualities = {const.HOT: 0, const.COLD: 0, const.DRY: 0, const.HUMID: 0}
for factor in factors:
element = fac... |
def can_modify(self, user=None):
"""Determines whether the submission can be modified.
Returns a boolean value.
The 'user' parameter is optional and additionally checks whether
the given user is authorized to perform these actions.
This function checks the submission states and ... | def function[can_modify, parameter[self, user]]:
constant[Determines whether the submission can be modified.
Returns a boolean value.
The 'user' parameter is optional and additionally checks whether
the given user is authorized to perform these actions.
This function checks the ... | keyword[def] identifier[can_modify] ( identifier[self] , identifier[user] = keyword[None] ):
literal[string]
keyword[if] identifier[user] keyword[and] keyword[not] identifier[self] . identifier[user_can_modify] ( identifier[user] ):
keyword[return] keyword[False... | def can_modify(self, user=None):
"""Determines whether the submission can be modified.
Returns a boolean value.
The 'user' parameter is optional and additionally checks whether
the given user is authorized to perform these actions.
This function checks the submission states and assi... |
def get_avg_price_fifo(self) -> Decimal:
"""
Calculates the average price paid for the security.
security = Commodity
Returns Decimal value.
"""
balance = self.get_quantity()
if not balance:
return Decimal(0)
paid = Decimal(0)
accounts... | def function[get_avg_price_fifo, parameter[self]]:
constant[
Calculates the average price paid for the security.
security = Commodity
Returns Decimal value.
]
variable[balance] assign[=] call[name[self].get_quantity, parameter[]]
if <ast.UnaryOp object at 0x7da1b1... | keyword[def] identifier[get_avg_price_fifo] ( identifier[self] )-> identifier[Decimal] :
literal[string]
identifier[balance] = identifier[self] . identifier[get_quantity] ()
keyword[if] keyword[not] identifier[balance] :
keyword[return] identifier[Decimal] ( literal[int] )
... | def get_avg_price_fifo(self) -> Decimal:
"""
Calculates the average price paid for the security.
security = Commodity
Returns Decimal value.
"""
balance = self.get_quantity()
if not balance:
return Decimal(0) # depends on [control=['if'], data=[]]
paid = Decimal(... |
def get_hits(self):
"""Return a list with number of hit cache lines per memory hierarchy level."""
return [self.stats[cache_level]['HIT_count']/self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] | def function[get_hits, parameter[self]]:
constant[Return a list with number of hit cache lines per memory hierarchy level.]
return[<ast.ListComp object at 0x7da1b26ae3e0>] | keyword[def] identifier[get_hits] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[self] . identifier[stats] [ identifier[cache_level] ][ literal[string] ]/ identifier[self] . identifier[first_dim_factor]
keyword[for] identifier[cache_level] keyword[in] identifier[ran... | def get_hits(self):
"""Return a list with number of hit cache lines per memory hierarchy level."""
return [self.stats[cache_level]['HIT_count'] / self.first_dim_factor for cache_level in range(len(self.machine['memory hierarchy']))] |
def _get_params(self, validator_parameter, name_prefix):
"""Retrieves additional user-supplied params for the job and validates them.
Args:
validator_parameter: name of the request parameter which supplies
validator for this parameter set.
name_prefix: common prefix for all parameter names ... | def function[_get_params, parameter[self, validator_parameter, name_prefix]]:
constant[Retrieves additional user-supplied params for the job and validates them.
Args:
validator_parameter: name of the request parameter which supplies
validator for this parameter set.
name_prefix: common ... | keyword[def] identifier[_get_params] ( identifier[self] , identifier[validator_parameter] , identifier[name_prefix] ):
literal[string]
identifier[params_validator] = identifier[self] . identifier[request] . identifier[get] ( identifier[validator_parameter] )
identifier[user_params] ={}
keyword[f... | def _get_params(self, validator_parameter, name_prefix):
"""Retrieves additional user-supplied params for the job and validates them.
Args:
validator_parameter: name of the request parameter which supplies
validator for this parameter set.
name_prefix: common prefix for all parameter names ... |
def load(self):
"""
- should not be empty
- yaml itself should be valid (should we grab more than 1 yaml error at a time?)
- we should have whitelist of fields the can set at each level, and start
getting objects out of those, processing grammar if necessary, validating other s... | def function[load, parameter[self]]:
constant[
- should not be empty
- yaml itself should be valid (should we grab more than 1 yaml error at a time?)
- we should have whitelist of fields the can set at each level, and start
getting objects out of those, processing grammar if ne... | keyword[def] identifier[load] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[config_text] , identifier[str] ):
identifier[self] . identifier[config_text] = identifier[self] . identifier[config_text] . identifier[d... | def load(self):
"""
- should not be empty
- yaml itself should be valid (should we grab more than 1 yaml error at a time?)
- we should have whitelist of fields the can set at each level, and start
getting objects out of those, processing grammar if necessary, validating other setti... |
def centerLatLon(self):
"""
Get the center lat/lon of model
"""
# GET CENTROID FROM GSSHA GRID
gssha_grid = self.getGrid()
min_x, max_x, min_y, max_y = gssha_grid.bounds()
x_ext, y_ext = transform(gssha_grid.proj,
Proj(init='epsg:... | def function[centerLatLon, parameter[self]]:
constant[
Get the center lat/lon of model
]
variable[gssha_grid] assign[=] call[name[self].getGrid, parameter[]]
<ast.Tuple object at 0x7da18f09d180> assign[=] call[name[gssha_grid].bounds, parameter[]]
<ast.Tuple object at 0x7... | keyword[def] identifier[centerLatLon] ( identifier[self] ):
literal[string]
identifier[gssha_grid] = identifier[self] . identifier[getGrid] ()
identifier[min_x] , identifier[max_x] , identifier[min_y] , identifier[max_y] = identifier[gssha_grid] . identifier[bounds] ()
i... | def centerLatLon(self):
"""
Get the center lat/lon of model
"""
# GET CENTROID FROM GSSHA GRID
gssha_grid = self.getGrid()
(min_x, max_x, min_y, max_y) = gssha_grid.bounds()
(x_ext, y_ext) = transform(gssha_grid.proj, Proj(init='epsg:4326'), [min_x, max_x, min_x, max_x], [min_y, max_... |
def setDefaults(self, instance):
"""Only call during object initialization, this function sets fields
to schema defaults. It's adapted from the original to support
IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter
does not find a suitable field, or that field's value is Falseish,
th... | def function[setDefaults, parameter[self, instance]]:
constant[Only call during object initialization, this function sets fields
to schema defaults. It's adapted from the original to support
IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter
does not find a suitable field, or that fi... | keyword[def] identifier[setDefaults] ( identifier[self] , identifier[instance] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[self] . identifier[values] ():
identifier[value] = keyword[None]
keyword[if] identifier[shasattr] ( identifier[field... | def setDefaults(self, instance):
"""Only call during object initialization, this function sets fields
to schema defaults. It's adapted from the original to support
IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter
does not find a suitable field, or that field's value is Falseish,
th... |
def binarize(netin, threshold_type, threshold_level, sign='pos', axis='time'):
"""
Binarizes a network, returning the network. General wrapper function for different binarization functions.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
thresh... | def function[binarize, parameter[netin, threshold_type, threshold_level, sign, axis]]:
constant[
Binarizes a network, returning the network. General wrapper function for different binarization functions.
Parameters
----------
netin : array or dict
Network (graphlet or contact representa... | keyword[def] identifier[binarize] ( identifier[netin] , identifier[threshold_type] , identifier[threshold_level] , identifier[sign] = literal[string] , identifier[axis] = literal[string] ):
literal[string]
keyword[if] identifier[threshold_type] == literal[string] :
identifier[netout] = identifier... | def binarize(netin, threshold_type, threshold_level, sign='pos', axis='time'):
"""
Binarizes a network, returning the network. General wrapper function for different binarization functions.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
thresh... |
def gender(self):
''' Tries to scrape the correct gender for a given word from wordreference.com '''
elements = self.tree.xpath('//table[@class="WRD"]')
if len(elements):
elements = self.tree.xpath('//table[@class="WRD"]')[0]
if len(elements):
if '/iten/' in self.page.url:
elements = elements.xpat... | def function[gender, parameter[self]]:
constant[ Tries to scrape the correct gender for a given word from wordreference.com ]
variable[elements] assign[=] call[name[self].tree.xpath, parameter[constant[//table[@class="WRD"]]]]
if call[name[len], parameter[name[elements]]] begin[:]
... | keyword[def] identifier[gender] ( identifier[self] ):
literal[string]
identifier[elements] = identifier[self] . identifier[tree] . identifier[xpath] ( literal[string] )
keyword[if] identifier[len] ( identifier[elements] ):
identifier[elements] = identifier[self] . identifier[tree] . identifier[xpath] ... | def gender(self):
""" Tries to scrape the correct gender for a given word from wordreference.com """
elements = self.tree.xpath('//table[@class="WRD"]')
if len(elements):
elements = self.tree.xpath('//table[@class="WRD"]')[0]
if len(elements):
if '/iten/' in self.page.url:
... |
def decode_body(cls, header, f):
"""Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises... | def function[decode_body, parameter[cls, header, f]]:
constant[Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a r... | keyword[def] identifier[decode_body] ( identifier[cls] , identifier[header] , identifier[f] ):
literal[string]
keyword[assert] identifier[header] . identifier[packet_type] == identifier[MqttControlPacketType] . identifier[pingreq]
keyword[if] identifier[header] . identifier[remaining_l... | def decode_body(cls, header, f):
"""Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
... |
def execute(self, context):
"""
Execute sqoop job
"""
self.hook = SqoopHook(
conn_id=self.conn_id,
verbose=self.verbose,
num_mappers=self.num_mappers,
hcatalog_database=self.hcatalog_database,
hcatalog_table=self.hcatalog_table,... | def function[execute, parameter[self, context]]:
constant[
Execute sqoop job
]
name[self].hook assign[=] call[name[SqoopHook], parameter[]]
if compare[name[self].cmd_type equal[==] constant[export]] begin[:]
call[name[self].hook.export_table, parameter[]] | keyword[def] identifier[execute] ( identifier[self] , identifier[context] ):
literal[string]
identifier[self] . identifier[hook] = identifier[SqoopHook] (
identifier[conn_id] = identifier[self] . identifier[conn_id] ,
identifier[verbose] = identifier[self] . identifier[verbose] ,
... | def execute(self, context):
"""
Execute sqoop job
"""
self.hook = SqoopHook(conn_id=self.conn_id, verbose=self.verbose, num_mappers=self.num_mappers, hcatalog_database=self.hcatalog_database, hcatalog_table=self.hcatalog_table, properties=self.properties)
if self.cmd_type == 'export':
... |
def samples_nb(message, wpm, framerate=FRAMERATE, word_spaced=False):
"""
Calculate the number of samples for a given word at a given framerate (samples / seconds)
>>> samples_nb('SOS', 15)
23814
"""
return int(duration(message, wpm, output='float', word_spaced=word_spaced) / 1000.0 * framerate... | def function[samples_nb, parameter[message, wpm, framerate, word_spaced]]:
constant[
Calculate the number of samples for a given word at a given framerate (samples / seconds)
>>> samples_nb('SOS', 15)
23814
]
return[call[name[int], parameter[binary_operation[binary_operation[call[name[durat... | keyword[def] identifier[samples_nb] ( identifier[message] , identifier[wpm] , identifier[framerate] = identifier[FRAMERATE] , identifier[word_spaced] = keyword[False] ):
literal[string]
keyword[return] identifier[int] ( identifier[duration] ( identifier[message] , identifier[wpm] , identifier[output] = li... | def samples_nb(message, wpm, framerate=FRAMERATE, word_spaced=False):
"""
Calculate the number of samples for a given word at a given framerate (samples / seconds)
>>> samples_nb('SOS', 15)
23814
"""
return int(duration(message, wpm, output='float', word_spaced=word_spaced) / 1000.0 * framerate... |
def chars(self, font, block):
"""
Analyses characters in single font or all fonts.
"""
if font:
font_files = self._getFont(font)
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
blocks = ... | def function[chars, parameter[self, font, block]]:
constant[
Analyses characters in single font or all fonts.
]
if name[font] begin[:]
variable[font_files] assign[=] call[name[self]._getFont, parameter[name[font]]]
variable[code_points] assign[=] call[name[self]._... | keyword[def] identifier[chars] ( identifier[self] , identifier[font] , identifier[block] ):
literal[string]
keyword[if] identifier[font] :
identifier[font_files] = identifier[self] . identifier[_getFont] ( identifier[font] )
keyword[else] :
identifier[font_files]... | def chars(self, font, block):
"""
Analyses characters in single font or all fonts.
"""
if font:
font_files = self._getFont(font) # depends on [control=['if'], data=[]]
else:
font_files = fc.query()
code_points = self._getFontChars(font_files)
if not block:
bl... |
def serialize(self, resources):
"""Serialize resource(s) according to json-api spec."""
serialized = {
'meta': {
'sqlalchemy_jsonapi_version': '4.0.9'
},
'jsonapi': {
'version': '1.0'
}
}
# Determine multiple... | def function[serialize, parameter[self, resources]]:
constant[Serialize resource(s) according to json-api spec.]
variable[serialized] assign[=] dictionary[[<ast.Constant object at 0x7da1b0cf5b10>, <ast.Constant object at 0x7da1b0cf50c0>], [<ast.Dict object at 0x7da1b0cf5b40>, <ast.Dict object at 0x7da1b... | keyword[def] identifier[serialize] ( identifier[self] , identifier[resources] ):
literal[string]
identifier[serialized] ={
literal[string] :{
literal[string] : literal[string]
},
literal[string] :{
literal[string] : literal[string]
}
}
... | def serialize(self, resources):
"""Serialize resource(s) according to json-api spec."""
serialized = {'meta': {'sqlalchemy_jsonapi_version': '4.0.9'}, 'jsonapi': {'version': '1.0'}}
# Determine multiple resources by checking for SQLAlchemy query count.
if hasattr(resources, 'count'):
serialized[... |
def _yass_vars(self):
""" Global variables """
utc = arrow.utcnow()
return {
"NAME": __title__,
"VERSION": __version__,
"URL": __uri__,
"GENERATOR": "%s %s" % (__title__, __version__),
"YEAR": utc.year
} | def function[_yass_vars, parameter[self]]:
constant[ Global variables ]
variable[utc] assign[=] call[name[arrow].utcnow, parameter[]]
return[dictionary[[<ast.Constant object at 0x7da20cabcd00>, <ast.Constant object at 0x7da20cabe890>, <ast.Constant object at 0x7da20cabd840>, <ast.Constant object at ... | keyword[def] identifier[_yass_vars] ( identifier[self] ):
literal[string]
identifier[utc] = identifier[arrow] . identifier[utcnow] ()
keyword[return] {
literal[string] : identifier[__title__] ,
literal[string] : identifier[__version__] ,
literal[string] : identif... | def _yass_vars(self):
""" Global variables """
utc = arrow.utcnow()
return {'NAME': __title__, 'VERSION': __version__, 'URL': __uri__, 'GENERATOR': '%s %s' % (__title__, __version__), 'YEAR': utc.year} |
def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
"""Convert a word into discrete features in self.crf_features,
including word before and word after."""
sentence_features = []
prefixes = ('-1', '0', '+1')
... | def function[_sentence_to_features, parameter[self, sentence]]:
constant[Convert a word into discrete features in self.crf_features,
including word before and word after.]
variable[sentence_features] assign[=] list[[]]
variable[prefixes] assign[=] tuple[[<ast.Constant object at 0x7da1b0b... | keyword[def] identifier[_sentence_to_features] ( identifier[self] , identifier[sentence] : identifier[list] ):
literal[string]
identifier[sentence_features] =[]
identifier[prefixes] =( literal[string] , literal[string] , literal[string] )
keyword[for] identifier[word_idx] key... | def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
'Convert a word into discrete features in self.crf_features,\n including word before and word after.'
sentence_features = []
prefixes = ('-1', '0', '+1')
for word_idx in ran... |
def set_file_type(self, doc, type_value):
"""
Raises OrderError if no package or file defined.
Raises CardinalityError if more than one type set.
Raises SPDXValueError if type is unknown.
"""
type_dict = {
'SOURCE': file.FileType.SOURCE,
'BINARY': ... | def function[set_file_type, parameter[self, doc, type_value]]:
constant[
Raises OrderError if no package or file defined.
Raises CardinalityError if more than one type set.
Raises SPDXValueError if type is unknown.
]
variable[type_dict] assign[=] dictionary[[<ast.Constant... | keyword[def] identifier[set_file_type] ( identifier[self] , identifier[doc] , identifier[type_value] ):
literal[string]
identifier[type_dict] ={
literal[string] : identifier[file] . identifier[FileType] . identifier[SOURCE] ,
literal[string] : identifier[file] . identifier[FileTyp... | def set_file_type(self, doc, type_value):
"""
Raises OrderError if no package or file defined.
Raises CardinalityError if more than one type set.
Raises SPDXValueError if type is unknown.
"""
type_dict = {'SOURCE': file.FileType.SOURCE, 'BINARY': file.FileType.BINARY, 'ARCHIVE': ... |
def get_session(self, token_path=None):
""" Create a requests Session object
:param Path token_path: (Only oauth) full path to where the token
should be load from
:return: A ready to use requests session
:rtype: OAuth2Session
"""
# TODO: remove token_path in fut... | def function[get_session, parameter[self, token_path]]:
constant[ Create a requests Session object
:param Path token_path: (Only oauth) full path to where the token
should be load from
:return: A ready to use requests session
:rtype: OAuth2Session
]
if compare[n... | keyword[def] identifier[get_session] ( identifier[self] , identifier[token_path] = keyword[None] ):
literal[string]
keyword[if] identifier[token_path] keyword[is] keyword[not] keyword[None] :
identifier[warnings] . identifier[warn] ( literal[string]
literal[s... | def get_session(self, token_path=None):
""" Create a requests Session object
:param Path token_path: (Only oauth) full path to where the token
should be load from
:return: A ready to use requests session
:rtype: OAuth2Session
"""
# TODO: remove token_path in future vers... |
def get_ruptures_within(dstore, bbox):
"""
Extract the ruptures within the given bounding box, a string
minlon,minlat,maxlon,maxlat.
Example:
http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46
"""
minlon, minlat, maxlon, maxlat = map(float, bbox.split(','))
hypo = dstore['... | def function[get_ruptures_within, parameter[dstore, bbox]]:
constant[
Extract the ruptures within the given bounding box, a string
minlon,minlat,maxlon,maxlat.
Example:
http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46
]
<ast.Tuple object at 0x7da18f58de10> assign[=] ... | keyword[def] identifier[get_ruptures_within] ( identifier[dstore] , identifier[bbox] ):
literal[string]
identifier[minlon] , identifier[minlat] , identifier[maxlon] , identifier[maxlat] = identifier[map] ( identifier[float] , identifier[bbox] . identifier[split] ( literal[string] ))
identifier[hypo] =... | def get_ruptures_within(dstore, bbox):
"""
Extract the ruptures within the given bounding box, a string
minlon,minlat,maxlon,maxlat.
Example:
http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46
"""
(minlon, minlat, maxlon, maxlat) = map(float, bbox.split(','))
hypo = dstore... |
def fix_opcode_names(opmap):
"""
Python stupidly named some OPCODES with a + which prevents using opcode name
directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
can then use opcode_23.SLICE_3. Later Python's fix this.
"""
return dict([(k.replace('+', '_'), v)
... | def function[fix_opcode_names, parameter[opmap]]:
constant[
Python stupidly named some OPCODES with a + which prevents using opcode name
directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
can then use opcode_23.SLICE_3. Later Python's fix this.
]
return[call[name[dic... | keyword[def] identifier[fix_opcode_names] ( identifier[opmap] ):
literal[string]
keyword[return] identifier[dict] ([( identifier[k] . identifier[replace] ( literal[string] , literal[string] ), identifier[v] )
keyword[for] ( identifier[k] , identifier[v] ) keyword[in] identifier[opmap] . identifier[i... | def fix_opcode_names(opmap):
"""
Python stupidly named some OPCODES with a + which prevents using opcode name
directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
can then use opcode_23.SLICE_3. Later Python's fix this.
"""
return dict([(k.replace('+', '_'), v) for (k, v) ... |
def get_projects(uid, include_shared_projects=True, projects_ids_list_filter=None, **kwargs):
"""
Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those projects whi... | def function[get_projects, parameter[uid, include_shared_projects, projects_ids_list_filter]]:
constant[
Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those p... | keyword[def] identifier[get_projects] ( identifier[uid] , identifier[include_shared_projects] = keyword[True] , identifier[projects_ids_list_filter] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[req_user_id] = identifier[kwargs] . identifier[get] ( literal[string] )
i... | def get_projects(uid, include_shared_projects=True, projects_ids_list_filter=None, **kwargs):
"""
Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those projects whi... |
def create_app(self, apps_path, name):
"""
Create Trionyx app in given path
:param str path: path to create app in.
:param str name: name of app
:raises FileExistsError:
"""
app_path = os.path.join(apps_path, name.lower())
shutil.copytree(self.app_path, ... | def function[create_app, parameter[self, apps_path, name]]:
constant[
Create Trionyx app in given path
:param str path: path to create app in.
:param str name: name of app
:raises FileExistsError:
]
variable[app_path] assign[=] call[name[os].path.join, parameter[... | keyword[def] identifier[create_app] ( identifier[self] , identifier[apps_path] , identifier[name] ):
literal[string]
identifier[app_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[apps_path] , identifier[name] . identifier[lower] ())
identifier[shutil] . identifi... | def create_app(self, apps_path, name):
"""
Create Trionyx app in given path
:param str path: path to create app in.
:param str name: name of app
:raises FileExistsError:
"""
app_path = os.path.join(apps_path, name.lower())
shutil.copytree(self.app_path, app_path)
... |
def __validate(self, target, value, oldvalue, initiator):
""" Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return: :raise ValidateError:
... | def function[__validate, parameter[self, target, value, oldvalue, initiator]]:
constant[ Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return:... | keyword[def] identifier[__validate] ( identifier[self] , identifier[target] , identifier[value] , identifier[oldvalue] , identifier[initiator] ):
literal[string]
keyword[if] identifier[value] == identifier[oldvalue] :
keyword[return] identifier[value]
keyword[if] identifi... | def __validate(self, target, value, oldvalue, initiator):
""" Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return: :raise ValidateError:
... |
def get_descriptions(fastas):
"""
get the description for each ORF
"""
id2desc = {}
for fasta in fastas:
for seq in parse_fasta(fasta):
header = seq[0].split('>')[1].split(' ')
id = header[0]
if len(header) > 1:
desc = ' '.join(header[1:])... | def function[get_descriptions, parameter[fastas]]:
constant[
get the description for each ORF
]
variable[id2desc] assign[=] dictionary[[], []]
for taget[name[fasta]] in starred[name[fastas]] begin[:]
for taget[name[seq]] in starred[call[name[parse_fasta], parameter[name[... | keyword[def] identifier[get_descriptions] ( identifier[fastas] ):
literal[string]
identifier[id2desc] ={}
keyword[for] identifier[fasta] keyword[in] identifier[fastas] :
keyword[for] identifier[seq] keyword[in] identifier[parse_fasta] ( identifier[fasta] ):
identifier[heade... | def get_descriptions(fastas):
"""
get the description for each ORF
"""
id2desc = {}
for fasta in fastas:
for seq in parse_fasta(fasta):
header = seq[0].split('>')[1].split(' ')
id = header[0]
if len(header) > 1:
desc = ' '.join(header[1:])... |
def imshow(image, backend=IMSHOW_BACKEND_DEFAULT):
"""
Shows an image in a window.
dtype support::
* ``uint8``: yes; not tested
* ``uint16``: ?
* ``uint32``: ?
* ``uint64``: ?
* ``int8``: ?
* ``int16``: ?
* ``int32``: ?
* ``int64``: ?
... | def function[imshow, parameter[image, backend]]:
constant[
Shows an image in a window.
dtype support::
* ``uint8``: yes; not tested
* ``uint16``: ?
* ``uint32``: ?
* ``uint64``: ?
* ``int8``: ?
* ``int16``: ?
* ``int32``: ?
* ``int64``: ?... | keyword[def] identifier[imshow] ( identifier[image] , identifier[backend] = identifier[IMSHOW_BACKEND_DEFAULT] ):
literal[string]
identifier[do_assert] ( identifier[backend] keyword[in] [ literal[string] , literal[string] ], literal[string] %( identifier[backend] ,))
keyword[if] identifier[backend]... | def imshow(image, backend=IMSHOW_BACKEND_DEFAULT):
"""
Shows an image in a window.
dtype support::
* ``uint8``: yes; not tested
* ``uint16``: ?
* ``uint32``: ?
* ``uint64``: ?
* ``int8``: ?
* ``int16``: ?
* ``int32``: ?
* ``int64``: ?
... |
def algo_exp(x, m, t, b):
"""mono-exponential curve."""
return m*np.exp(-t*x)+b | def function[algo_exp, parameter[x, m, t, b]]:
constant[mono-exponential curve.]
return[binary_operation[binary_operation[name[m] * call[name[np].exp, parameter[binary_operation[<ast.UnaryOp object at 0x7da1afe19930> * name[x]]]]] + name[b]]] | keyword[def] identifier[algo_exp] ( identifier[x] , identifier[m] , identifier[t] , identifier[b] ):
literal[string]
keyword[return] identifier[m] * identifier[np] . identifier[exp] (- identifier[t] * identifier[x] )+ identifier[b] | def algo_exp(x, m, t, b):
"""mono-exponential curve."""
return m * np.exp(-t * x) + b |
def many(func):
"""
Create a callable that applies ``func`` to every value in a sequence.
If the value is not a sequence then an empty list is returned.
:type func: `callable`
:param func: Callable to be applied to the first result.
"""
def _many(result):
if _isSequenceTypeNotText... | def function[many, parameter[func]]:
constant[
Create a callable that applies ``func`` to every value in a sequence.
If the value is not a sequence then an empty list is returned.
:type func: `callable`
:param func: Callable to be applied to the first result.
]
def function[_many,... | keyword[def] identifier[many] ( identifier[func] ):
literal[string]
keyword[def] identifier[_many] ( identifier[result] ):
keyword[if] identifier[_isSequenceTypeNotText] ( identifier[result] ):
keyword[return] identifier[map] ( identifier[func] , identifier[result] )
keywo... | def many(func):
"""
Create a callable that applies ``func`` to every value in a sequence.
If the value is not a sequence then an empty list is returned.
:type func: `callable`
:param func: Callable to be applied to the first result.
"""
def _many(result):
if _isSequenceTypeNotTex... |
def enable_one_shot_all_breakpoints(self):
"""
Enables for one shot all disabled breakpoints in all processes.
@see:
enable_one_shot_code_breakpoint,
enable_one_shot_page_breakpoint,
enable_one_shot_hardware_breakpoint
"""
# disable code brea... | def function[enable_one_shot_all_breakpoints, parameter[self]]:
constant[
Enables for one shot all disabled breakpoints in all processes.
@see:
enable_one_shot_code_breakpoint,
enable_one_shot_page_breakpoint,
enable_one_shot_hardware_breakpoint
]
... | keyword[def] identifier[enable_one_shot_all_breakpoints] ( identifier[self] ):
literal[string]
keyword[for] ( identifier[pid] , identifier[bp] ) keyword[in] identifier[self] . identifier[get_all_code_breakpoints] ():
keyword[if] identifier[bp] . identifier[is_disabled] ():
... | def enable_one_shot_all_breakpoints(self):
"""
Enables for one shot all disabled breakpoints in all processes.
@see:
enable_one_shot_code_breakpoint,
enable_one_shot_page_breakpoint,
enable_one_shot_hardware_breakpoint
"""
# disable code breakpoints f... |
def select(self, query='', next_token=None, consistent_read=False, max_items=None):
"""
Returns a set of Attributes for item names within domain_name that match the query.
The query must be expressed in using the SELECT style syntax rather than the
original SimpleDB query language.
... | def function[select, parameter[self, query, next_token, consistent_read, max_items]]:
constant[
Returns a set of Attributes for item names within domain_name that match the query.
The query must be expressed in using the SELECT style syntax rather than the
original SimpleDB query languag... | keyword[def] identifier[select] ( identifier[self] , identifier[query] = literal[string] , identifier[next_token] = keyword[None] , identifier[consistent_read] = keyword[False] , identifier[max_items] = keyword[None] ):
literal[string]
keyword[return] identifier[SelectResultSet] ( identifier[self]... | def select(self, query='', next_token=None, consistent_read=False, max_items=None):
"""
Returns a set of Attributes for item names within domain_name that match the query.
The query must be expressed in using the SELECT style syntax rather than the
original SimpleDB query language.
... |
def Open(self, path=None, read_only=True, **unused_kwargs):
"""Opens the storage.
Args:
path (Optional[str]): path to the storage file.
read_only (Optional[bool]): True if the file should be opened in
read-only mode.
Raises:
IOError: if the storage file is already opened or if ... | def function[Open, parameter[self, path, read_only]]:
constant[Opens the storage.
Args:
path (Optional[str]): path to the storage file.
read_only (Optional[bool]): True if the file should be opened in
read-only mode.
Raises:
IOError: if the storage file is already opened or... | keyword[def] identifier[Open] ( identifier[self] , identifier[path] = keyword[None] , identifier[read_only] = keyword[True] ,** identifier[unused_kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_open] :
keyword[raise] identifier[IOError] ( literal[string] )
keyword[if... | def Open(self, path=None, read_only=True, **unused_kwargs):
"""Opens the storage.
Args:
path (Optional[str]): path to the storage file.
read_only (Optional[bool]): True if the file should be opened in
read-only mode.
Raises:
IOError: if the storage file is already opened or if ... |
def adrinverter(v_dc, p_dc, inverter, vtol=0.10):
r'''
Converts DC power and voltage to AC power using Anton Driesse's
Grid-Connected PV Inverter efficiency model
Parameters
----------
v_dc : numeric
A scalar or pandas series of DC voltages, in volts, which are provided
as input... | def function[adrinverter, parameter[v_dc, p_dc, inverter, vtol]]:
constant[
Converts DC power and voltage to AC power using Anton Driesse's
Grid-Connected PV Inverter efficiency model
Parameters
----------
v_dc : numeric
A scalar or pandas series of DC voltages, in volts, which are ... | keyword[def] identifier[adrinverter] ( identifier[v_dc] , identifier[p_dc] , identifier[inverter] , identifier[vtol] = literal[int] ):
literal[string]
identifier[p_nom] = identifier[inverter] [ literal[string] ]
identifier[v_nom] = identifier[inverter] [ literal[string] ]
identifier[pac_max] = i... | def adrinverter(v_dc, p_dc, inverter, vtol=0.1):
"""
Converts DC power and voltage to AC power using Anton Driesse's
Grid-Connected PV Inverter efficiency model
Parameters
----------
v_dc : numeric
A scalar or pandas series of DC voltages, in volts, which are provided
as input t... |
def read(self, file_path): # type: (str) -> Timezone
"""
Read a zoneinfo structure from the given path.
:param file_path: The path of a zoneinfo file.
"""
if not os.path.exists(file_path):
raise InvalidZoneinfoFile("The tzinfo file does not exist")
with ope... | def function[read, parameter[self, file_path]]:
constant[
Read a zoneinfo structure from the given path.
:param file_path: The path of a zoneinfo file.
]
if <ast.UnaryOp object at 0x7da1b1d36860> begin[:]
<ast.Raise object at 0x7da1b1d374f0>
with call[name[open],... | keyword[def] identifier[read] ( identifier[self] , identifier[file_path] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[file_path] ):
keyword[raise] identifier[InvalidZoneinfoFile] ( literal[string] )
keyword... | def read(self, file_path): # type: (str) -> Timezone
'\n Read a zoneinfo structure from the given path.\n\n :param file_path: The path of a zoneinfo file.\n '
if not os.path.exists(file_path):
raise InvalidZoneinfoFile('The tzinfo file does not exist') # depends on [control=['if']... |
def _add(self, adr, metadata):
"""Add an address.
"""
with self._address_lock:
metadata["receive_time"] = datetime.utcnow()
self._addresses[adr] = metadata | def function[_add, parameter[self, adr, metadata]]:
constant[Add an address.
]
with name[self]._address_lock begin[:]
call[name[metadata]][constant[receive_time]] assign[=] call[name[datetime].utcnow, parameter[]]
call[name[self]._addresses][name[adr]] assign[=] n... | keyword[def] identifier[_add] ( identifier[self] , identifier[adr] , identifier[metadata] ):
literal[string]
keyword[with] identifier[self] . identifier[_address_lock] :
identifier[metadata] [ literal[string] ]= identifier[datetime] . identifier[utcnow] ()
identifier[self... | def _add(self, adr, metadata):
"""Add an address.
"""
with self._address_lock:
metadata['receive_time'] = datetime.utcnow()
self._addresses[adr] = metadata # depends on [control=['with'], data=[]] |
def metadata_id(item):
"""Extracts the identifier from a Slack item.
This identifier will be the mix of two fields because Slack
messages does not have any unique identifier. In this case,
'ts' and 'user' values (or 'bot_id' when the message is sent by a bot)
are combined becaus... | def function[metadata_id, parameter[item]]:
constant[Extracts the identifier from a Slack item.
This identifier will be the mix of two fields because Slack
messages does not have any unique identifier. In this case,
'ts' and 'user' values (or 'bot_id' when the message is sent by a bot)
... | keyword[def] identifier[metadata_id] ( identifier[item] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[item] :
identifier[nick] = identifier[item] [ literal[string] ]
keyword[elif] literal[string] keyword[in] identifier[item] :
identif... | def metadata_id(item):
"""Extracts the identifier from a Slack item.
This identifier will be the mix of two fields because Slack
messages does not have any unique identifier. In this case,
'ts' and 'user' values (or 'bot_id' when the message is sent by a bot)
are combined because th... |
def occurrence(request, event_id, occurrence_id):
"""
:param request: Django request object.
:param event_id: The `id` associated with the occurrence's event.
:param occurrence_id: The `id` associated with the occurrence.
:param is_preview: Should the listing page be generated as a preview? This
... | def function[occurrence, parameter[request, event_id, occurrence_id]]:
constant[
:param request: Django request object.
:param event_id: The `id` associated with the occurrence's event.
:param occurrence_id: The `id` associated with the occurrence.
:param is_preview: Should the listing page be g... | keyword[def] identifier[occurrence] ( identifier[request] , identifier[event_id] , identifier[occurrence_id] ):
literal[string]
identifier[warnings] . identifier[warn] (
literal[string]
literal[string]
, identifier[DeprecationWarning]
)
keyword[try] :
identifier[occ... | def occurrence(request, event_id, occurrence_id):
"""
:param request: Django request object.
:param event_id: The `id` associated with the occurrence's event.
:param occurrence_id: The `id` associated with the occurrence.
:param is_preview: Should the listing page be generated as a preview? This
... |
def parse_search_url(url):
"""Parses a search URL."""
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in SEARCH_SCHEMES:
config["ENGINE"] = SEARCH_SCHEMES[url.scheme]
if url.scheme in USES_URL:
... | def function[parse_search_url, parameter[url]]:
constant[Parses a search URL.]
variable[config] assign[=] dictionary[[], []]
variable[url] assign[=] call[name[urlparse].urlparse, parameter[name[url]]]
variable[path] assign[=] call[name[url].path][<ast.Slice object at 0x7da1b28fcac0>]
... | keyword[def] identifier[parse_search_url] ( identifier[url] ):
literal[string]
identifier[config] ={}
identifier[url] = identifier[urlparse] . identifier[urlparse] ( identifier[url] )
identifier[path] = identifier[url] . identifier[path] [ literal[int] :]
identifier[path] = identifie... | def parse_search_url(url):
"""Parses a search URL."""
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in SEARCH_SCHEMES:
config['ENGINE'] = SEARCH_SCHEMES[url.scheme] # depends on [control=['if'], data=[... |
def get_cached_files(url, server_name="", document_root=None):
"""
Given a URL, return a list of paths of all cached variations of that file.
Doesn't include the original file.
"""
import glob
url_info = process_url(url, server_name, document_root, check_security=False)
# get path to cache... | def function[get_cached_files, parameter[url, server_name, document_root]]:
constant[
Given a URL, return a list of paths of all cached variations of that file.
Doesn't include the original file.
]
import module[glob]
variable[url_info] assign[=] call[name[process_url], parameter[name[u... | keyword[def] identifier[get_cached_files] ( identifier[url] , identifier[server_name] = literal[string] , identifier[document_root] = keyword[None] ):
literal[string]
keyword[import] identifier[glob]
identifier[url_info] = identifier[process_url] ( identifier[url] , identifier[server_name] , identif... | def get_cached_files(url, server_name='', document_root=None):
"""
Given a URL, return a list of paths of all cached variations of that file.
Doesn't include the original file.
"""
import glob
url_info = process_url(url, server_name, document_root, check_security=False)
# get path to cache ... |
def __get_query_agg_cardinality(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregat... | def function[__get_query_agg_cardinality, parameter[cls, field, agg_id]]:
constant[
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation ... | keyword[def] identifier[__get_query_agg_cardinality] ( identifier[cls] , identifier[field] , identifier[agg_id] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[agg_id] :
identifier[agg_id] = identifier[cls] . identifier[AGGREGATION_ID]
identifier[quer... | def __get_query_agg_cardinality(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregation ... |
def finalize(self):
"""
Get the base64-encoded signature itself.
Can only be called once.
"""
signature = self.signer.finalize()
sig_r, sig_s = decode_dss_signature(signature)
sig_b64 = encode_signature(sig_r, sig_s)
return sig_b64 | def function[finalize, parameter[self]]:
constant[
Get the base64-encoded signature itself.
Can only be called once.
]
variable[signature] assign[=] call[name[self].signer.finalize, parameter[]]
<ast.Tuple object at 0x7da207f9a1d0> assign[=] call[name[decode_dss_signature... | keyword[def] identifier[finalize] ( identifier[self] ):
literal[string]
identifier[signature] = identifier[self] . identifier[signer] . identifier[finalize] ()
identifier[sig_r] , identifier[sig_s] = identifier[decode_dss_signature] ( identifier[signature] )
identifier[sig_b64] = ... | def finalize(self):
"""
Get the base64-encoded signature itself.
Can only be called once.
"""
signature = self.signer.finalize()
(sig_r, sig_s) = decode_dss_signature(signature)
sig_b64 = encode_signature(sig_r, sig_s)
return sig_b64 |
def json_get_default(json: JsonValue, path: str,
default: Any, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the ... | def function[json_get_default, parameter[json, path, default, expected_type]]:
constant[Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the provided default value:
... | keyword[def] identifier[json_get_default] ( identifier[json] : identifier[JsonValue] , identifier[path] : identifier[str] ,
identifier[default] : identifier[Any] , identifier[expected_type] : identifier[Any] = identifier[ANY] )-> identifier[Any] :
literal[string]
keyword[try] :
keyword[return] i... | def json_get_default(json: JsonValue, path: str, default: Any, expected_type: Any=ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the provided default value:... |
def is_usable(host, port, timeout=3):
"""测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3)
"""
try:
proxies = {
'http': 'http://%s:%s' % (h... | def function[is_usable, parameter[host, port, timeout]]:
constant[测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3)
]
<ast.Try object at 0x7da1b26a54b0> | keyword[def] identifier[is_usable] ( identifier[host] , identifier[port] , identifier[timeout] = literal[int] ):
literal[string]
keyword[try] :
identifier[proxies] ={
literal[string] : literal[string] %( identifier[host] , identifier[port] ),
literal[string] : literal[string] %( ... | def is_usable(host, port, timeout=3):
"""测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3)
"""
try:
proxies = {'http': 'http://%s:%s' % (host, port), '... |
def get(self, key, default=None, *, section=DataStoreDocumentSection.Data):
""" Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The ... | def function[get, parameter[self, key, default]]:
constant[ Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the ... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ,*, identifier[section] = identifier[DataStoreDocumentSection] . identifier[Data] ):
literal[string]
identifier[key_notation] = literal[string] . identifier[join] ([ identifier[section] , identif... | def get(self, key, default=None, *, section=DataStoreDocumentSection.Data):
""" Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key ... |
def EncodeMessages(self,
message_list,
result,
destination=None,
timestamp=None,
api_version=3):
"""Accepts a list of messages and encodes for transmission.
This function signs and then encrypts the payload... | def function[EncodeMessages, parameter[self, message_list, result, destination, timestamp, api_version]]:
constant[Accepts a list of messages and encodes for transmission.
This function signs and then encrypts the payload.
Args:
message_list: A MessageList rdfvalue containing a list of GrrMessa... | keyword[def] identifier[EncodeMessages] ( identifier[self] ,
identifier[message_list] ,
identifier[result] ,
identifier[destination] = keyword[None] ,
identifier[timestamp] = keyword[None] ,
identifier[api_version] = literal[int] ):
literal[string]
keyword[if] identifier[api_version] keyword[not] k... | def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3):
"""Accepts a list of messages and encodes for transmission.
This function signs and then encrypts the payload.
Args:
message_list: A MessageList rdfvalue containing a list of GrrMessages.
result:... |
def search(self, query, method="lucene", start=None,
rows=None, access_token=None):
"""Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edism... | def function[search, parameter[self, query, method, start, rows, access_token]]:
constant[Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax... | keyword[def] identifier[search] ( identifier[self] , identifier[query] , identifier[method] = literal[string] , identifier[start] = keyword[None] ,
identifier[rows] = keyword[None] , identifier[access_token] = keyword[None] ):
literal[string]
keyword[if] identifier[access_token] keyword[is] key... | def search(self, query, method='lucene', start=None, rows=None, access_token=None):
"""Search the ORCID database.
Parameters
----------
:param query: string
Query in line with the chosen method.
:param method: string
One of 'lucene', 'edismax', 'dismax'
... |
def _make_request(self, action):
"""
Perform the request
:param action: action name
:return: a dict containing the request result
:rtype: dict
"""
if isinstance(action, list):
kwargs = {'actions': action}
action = 'send'
else:
... | def function[_make_request, parameter[self, action]]:
constant[
Perform the request
:param action: action name
:return: a dict containing the request result
:rtype: dict
]
if call[name[isinstance], parameter[name[action], name[list]]] begin[:]
vari... | keyword[def] identifier[_make_request] ( identifier[self] , identifier[action] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[action] , identifier[list] ):
identifier[kwargs] ={ literal[string] : identifier[action] }
identifier[action] = literal[string... | def _make_request(self, action):
"""
Perform the request
:param action: action name
:return: a dict containing the request result
:rtype: dict
"""
if isinstance(action, list):
kwargs = {'actions': action}
action = 'send' # depends on [control=['if'], data... |
def occurrence_halved_fingerprint(
word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG
):
"""Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number... | def function[occurrence_halved_fingerprint, parameter[word, n_bits, most_common]]:
constant[Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number ... | keyword[def] identifier[occurrence_halved_fingerprint] (
identifier[word] , identifier[n_bits] = literal[int] , identifier[most_common] = identifier[MOST_COMMON_LETTERS_CG]
):
literal[string]
keyword[return] identifier[OccurrenceHalved] (). identifier[fingerprint] ( identifier[word] , identifier[n_bits]... | def occurrence_halved_fingerprint(word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG):
"""Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bi... |
def from_canstrat(cls, filename, source='canstrat'):
"""
Eat a Canstrat DAT file and make a striplog.
"""
with open(filename) as f:
dat = f.read()
data = parse_canstrat(dat)
list_of_Intervals = []
for d in data[7]: # 7 is the 'card type' for litholo... | def function[from_canstrat, parameter[cls, filename, source]]:
constant[
Eat a Canstrat DAT file and make a striplog.
]
with call[name[open], parameter[name[filename]]] begin[:]
variable[dat] assign[=] call[name[f].read, parameter[]]
variable[data] assign[=] call[... | keyword[def] identifier[from_canstrat] ( identifier[cls] , identifier[filename] , identifier[source] = literal[string] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] ) keyword[as] identifier[f] :
identifier[dat] = identifier[f] . identifier[read] ()
... | def from_canstrat(cls, filename, source='canstrat'):
"""
Eat a Canstrat DAT file and make a striplog.
"""
with open(filename) as f:
dat = f.read() # depends on [control=['with'], data=['f']]
data = parse_canstrat(dat)
list_of_Intervals = []
for d in data[7]: # 7 is the 'car... |
def _join_url_dir(self, url, *args):
"""
Join a URL with multiple directories
"""
for path in args:
url = url.rstrip('/') + '/'
url = urljoin(url, path.lstrip('/'))
return url | def function[_join_url_dir, parameter[self, url]]:
constant[
Join a URL with multiple directories
]
for taget[name[path]] in starred[name[args]] begin[:]
variable[url] assign[=] binary_operation[call[name[url].rstrip, parameter[constant[/]]] + constant[/]]
... | keyword[def] identifier[_join_url_dir] ( identifier[self] , identifier[url] ,* identifier[args] ):
literal[string]
keyword[for] identifier[path] keyword[in] identifier[args] :
identifier[url] = identifier[url] . identifier[rstrip] ( literal[string] )+ literal[string]
i... | def _join_url_dir(self, url, *args):
"""
Join a URL with multiple directories
"""
for path in args:
url = url.rstrip('/') + '/'
url = urljoin(url, path.lstrip('/')) # depends on [control=['for'], data=['path']]
return url |
def prep_models(aryPrfTc, varSdSmthTmp=2.0, lgcPrint=True):
"""
Prepare pRF model time courses.
Parameters
----------
aryPrfTc : np.array
4D numpy array with pRF time course models, with following dimensions:
`aryPrfTc[x-position, y-position, SD, volume]`.
varSdSmthTmp : float
... | def function[prep_models, parameter[aryPrfTc, varSdSmthTmp, lgcPrint]]:
constant[
Prepare pRF model time courses.
Parameters
----------
aryPrfTc : np.array
4D numpy array with pRF time course models, with following dimensions:
`aryPrfTc[x-position, y-position, SD, volume]`.
... | keyword[def] identifier[prep_models] ( identifier[aryPrfTc] , identifier[varSdSmthTmp] = literal[int] , identifier[lgcPrint] = keyword[True] ):
literal[string]
keyword[if] identifier[lgcPrint] :
identifier[print] ( literal[string] )
keyword[def] identifier[funcSmthTmp] ( identifie... | def prep_models(aryPrfTc, varSdSmthTmp=2.0, lgcPrint=True):
"""
Prepare pRF model time courses.
Parameters
----------
aryPrfTc : np.array
4D numpy array with pRF time course models, with following dimensions:
`aryPrfTc[x-position, y-position, SD, volume]`.
varSdSmthTmp : float
... |
def rebuild(self, image, root_pass=None, authorized_keys=None, **kwargs):
"""
Rebuilding an Instance deletes all existing Disks and Configs and deploys
a new :any:`Image` to it. This can be used to reset an existing
Instance or to install an Image on an empty Instance.
:param i... | def function[rebuild, parameter[self, image, root_pass, authorized_keys]]:
constant[
Rebuilding an Instance deletes all existing Disks and Configs and deploys
a new :any:`Image` to it. This can be used to reset an existing
Instance or to install an Image on an empty Instance.
:... | keyword[def] identifier[rebuild] ( identifier[self] , identifier[image] , identifier[root_pass] = keyword[None] , identifier[authorized_keys] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[ret_pass] = keyword[None]
keyword[if] keyword[not] identifier[root_pass] :
... | def rebuild(self, image, root_pass=None, authorized_keys=None, **kwargs):
"""
Rebuilding an Instance deletes all existing Disks and Configs and deploys
a new :any:`Image` to it. This can be used to reset an existing
Instance or to install an Image on an empty Instance.
:param image... |
def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5 | def function[calc_mass, parameter[nu_max, delta_nu, teff]]:
constant[ asteroseismic scaling relations ]
variable[NU_MAX] assign[=] constant[3140.0]
variable[DELTA_NU] assign[=] constant[135.03]
variable[TEFF] assign[=] constant[5777.0]
return[binary_operation[binary_operation[binary_... | keyword[def] identifier[calc_mass] ( identifier[nu_max] , identifier[delta_nu] , identifier[teff] ):
literal[string]
identifier[NU_MAX] = literal[int]
identifier[DELTA_NU] = literal[int]
identifier[TEFF] = literal[int]
keyword[return] ( identifier[nu_max] / identifier[NU_MAX] )** literal[... | def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max / NU_MAX) ** 3 * (delta_nu / DELTA_NU) ** (-4) * (teff / TEFF) ** 1.5 |
def get(self, default=None):
"""Extract the smallest item from queue.
Return default if queue is empty."""
if not self.__data:
return default
return heapq.heappop(self.__data) | def function[get, parameter[self, default]]:
constant[Extract the smallest item from queue.
Return default if queue is empty.]
if <ast.UnaryOp object at 0x7da18f09da50> begin[:]
return[name[default]]
return[call[name[heapq].heappop, parameter[name[self].__data]]] | keyword[def] identifier[get] ( identifier[self] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__data] :
keyword[return] identifier[default]
keyword[return] identifier[heapq] . identifier[heappop] ( identifi... | def get(self, default=None):
"""Extract the smallest item from queue.
Return default if queue is empty."""
if not self.__data:
return default # depends on [control=['if'], data=[]]
return heapq.heappop(self.__data) |
def create(dataset, transformers):
"""
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformer... | def function[create, parameter[dataset, transformers]]:
constant[
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Trans... | keyword[def] identifier[create] ( identifier[dataset] , identifier[transformers] ):
literal[string]
identifier[err_msg] = literal[string]
identifier[cls] = identifier[transformers] . identifier[__class__]
identifier[_raise_error_if_not_sframe] ( identifier[dataset] , literal[string] )
... | def create(dataset, transformers):
"""
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformer... |
async def get_data(self, raw: bool=True) -> AnyStr:
"""The request body data."""
try:
body_future = asyncio.ensure_future(self.body)
raw_data = await asyncio.wait_for(body_future, timeout=self.body_timeout)
except asyncio.TimeoutError:
body_future.cancel()
... | <ast.AsyncFunctionDef object at 0x7da20e793910> | keyword[async] keyword[def] identifier[get_data] ( identifier[self] , identifier[raw] : identifier[bool] = keyword[True] )-> identifier[AnyStr] :
literal[string]
keyword[try] :
identifier[body_future] = identifier[asyncio] . identifier[ensure_future] ( identifier[self] . identifier[bo... | async def get_data(self, raw: bool=True) -> AnyStr:
"""The request body data."""
try:
body_future = asyncio.ensure_future(self.body)
raw_data = await asyncio.wait_for(body_future, timeout=self.body_timeout) # depends on [control=['try'], data=[]]
except asyncio.TimeoutError:
body_fu... |
def area(self):
r"""The area of the current surface.
For surfaces in :math:`\mathbf{R}^2`, this computes the area via
Green's theorem. Using the vector field :math:`\mathbf{F} =
\left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2`
Green's theorem says twice th... | def function[area, parameter[self]]:
constant[The area of the current surface.
For surfaces in :math:`\mathbf{R}^2`, this computes the area via
Green's theorem. Using the vector field :math:`\mathbf{F} =
\left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2`
Gre... | keyword[def] identifier[area] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_dimension] != literal[int] :
keyword[raise] identifier[NotImplementedError] (
literal[string] ,
literal[string] ,
identifier[self] . i... | def area(self):
"""The area of the current surface.
For surfaces in :math:`\\mathbf{R}^2`, this computes the area via
Green's theorem. Using the vector field :math:`\\mathbf{F} =
\\left[-y, x\\right]^T`, since :math:`\\partial_x(x) - \\partial_y(-y) = 2`
Green's theorem says twice t... |
def is_left(point0, point1, point2):
""" Tests if a point is Left|On|Right of an infinite line.
Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html
.. note:: This implementation only works in 2-dimensional space.
:param point0: Point P0
:param point1: Point P1
:param... | def function[is_left, parameter[point0, point1, point2]]:
constant[ Tests if a point is Left|On|Right of an infinite line.
Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html
.. note:: This implementation only works in 2-dimensional space.
:param point0: Point P0
:pa... | keyword[def] identifier[is_left] ( identifier[point0] , identifier[point1] , identifier[point2] ):
literal[string]
keyword[return] (( identifier[point1] [ literal[int] ]- identifier[point0] [ literal[int] ])*( identifier[point2] [ literal[int] ]- identifier[point0] [ literal[int] ]))-(( identifier[point2] ... | def is_left(point0, point1, point2):
""" Tests if a point is Left|On|Right of an infinite line.
Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html
.. note:: This implementation only works in 2-dimensional space.
:param point0: Point P0
:param point1: Point P1
:param... |
def get_all_parts(self, max_parts=None, part_number_marker=None):
"""
Return the uploaded parts of this MultiPart Upload. This is
a lower-level method that requires you to manually page through
results. To simplify this process, you can just use the
object itself as an iterator... | def function[get_all_parts, parameter[self, max_parts, part_number_marker]]:
constant[
Return the uploaded parts of this MultiPart Upload. This is
a lower-level method that requires you to manually page through
results. To simplify this process, you can just use the
object itse... | keyword[def] identifier[get_all_parts] ( identifier[self] , identifier[max_parts] = keyword[None] , identifier[part_number_marker] = keyword[None] ):
literal[string]
identifier[self] . identifier[_parts] =[]
identifier[query_args] = literal[string] % identifier[self] . identifier[id]
... | def get_all_parts(self, max_parts=None, part_number_marker=None):
"""
Return the uploaded parts of this MultiPart Upload. This is
a lower-level method that requires you to manually page through
results. To simplify this process, you can just use the
object itself as an iterator and... |
def b_vdm(B, lat):
"""
Converts a magnetic field value (input in units of tesla) to a virtual
dipole moment (VDM) or a virtual axial dipole moment (VADM); output
in units of Am^2)
Parameters
----------
B: local magnetic field strength in tesla
lat: latitude of site in degrees
Retur... | def function[b_vdm, parameter[B, lat]]:
constant[
Converts a magnetic field value (input in units of tesla) to a virtual
dipole moment (VDM) or a virtual axial dipole moment (VADM); output
in units of Am^2)
Parameters
----------
B: local magnetic field strength in tesla
lat: latitud... | keyword[def] identifier[b_vdm] ( identifier[B] , identifier[lat] ):
literal[string]
identifier[fact] =(( literal[int] )** literal[int] )* literal[int]
identifier[colat] = identifier[np] . identifier[radians] ( literal[int] - identifier[lat] )
keyword[return] identifier[fact] * identifier[B... | def b_vdm(B, lat):
"""
Converts a magnetic field value (input in units of tesla) to a virtual
dipole moment (VDM) or a virtual axial dipole moment (VADM); output
in units of Am^2)
Parameters
----------
B: local magnetic field strength in tesla
lat: latitude of site in degrees
Retur... |
def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | def function[create_metadata_response, parameter[self, uri, http_method, body, headers]]:
constant[Create metadata response
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da1b175f100>], [<ast.Constant object at 0x7da1b175e830>]]
return[tuple[[<ast.Name object at 0x7da1b... | keyword[def] identifier[create_metadata_response] ( identifier[self] , identifier[uri] , identifier[http_method] = literal[string] , identifier[body] = keyword[None] ,
identifier[headers] = keyword[None] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string]
... | def create_metadata_response(self, uri, http_method='GET', body=None, headers=None):
"""Create metadata response
"""
headers = {'Content-Type': 'application/json'}
return (headers, json.dumps(self.claims), 200) |
def get_nameserver_detail_output_show_nameserver_nameserver_connected_via_ag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_nam... | def function[get_nameserver_detail_output_show_nameserver_nameserver_connected_via_ag, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_nameserver_detail] assign[=] call[name[ET].Element, paramete... | keyword[def] identifier[get_nameserver_detail_output_show_nameserver_nameserver_connected_via_ag] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_nameserver_detail] = identifier[ET] . ... | def get_nameserver_detail_output_show_nameserver_nameserver_connected_via_ag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_nameserver_detail = ET.Element('get_nameserver_detail')
config = get_nameserver_detail
output = ET.SubElement(get_nameserver_detail, 'out... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.