code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def upload_urls(self, project, files, run=None, entity=None, description=None):
"""Generate temporary resumeable upload urls
Args:
project (str): The project to download
files (list or dict): The filenames to upload
run (str, optional): The run to upload to
... | def function[upload_urls, parameter[self, project, files, run, entity, description]]:
constant[Generate temporary resumeable upload urls
Args:
project (str): The project to download
files (list or dict): The filenames to upload
run (str, optional): The run to upload ... | keyword[def] identifier[upload_urls] ( identifier[self] , identifier[project] , identifier[files] , identifier[run] = keyword[None] , identifier[entity] = keyword[None] , identifier[description] = keyword[None] ):
literal[string]
identifier[query] = identifier[gql] ( literal[string] )
iden... | def upload_urls(self, project, files, run=None, entity=None, description=None):
"""Generate temporary resumeable upload urls
Args:
project (str): The project to download
files (list or dict): The filenames to upload
run (str, optional): The run to upload to
e... |
def extension(names):
"""Makes a function to be an extension."""
for name in names:
if not NAME_PATTERN.match(name):
raise ValueError('invalid extension name: %s' % name)
def decorator(f, names=names):
return Extension(f, names=names)
return decorator | def function[extension, parameter[names]]:
constant[Makes a function to be an extension.]
for taget[name[name]] in starred[name[names]] begin[:]
if <ast.UnaryOp object at 0x7da1b2875ba0> begin[:]
<ast.Raise object at 0x7da1b28751b0>
def function[decorator, parameter[f... | keyword[def] identifier[extension] ( identifier[names] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[names] :
keyword[if] keyword[not] identifier[NAME_PATTERN] . identifier[match] ( identifier[name] ):
keyword[raise] identifier[ValueError] ( literal[str... | def extension(names):
"""Makes a function to be an extension."""
for name in names:
if not NAME_PATTERN.match(name):
raise ValueError('invalid extension name: %s' % name) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['name']]
def decorator(f, names=names)... |
def get_project_children(self, project_id, name_contains=None):
"""
Get direct files and folders of a project.
:param project_id: str: uuid of the project to list contents
:param name_contains: str: filter children based on a pattern
:return: [File|Folder]: list of Files/Folders ... | def function[get_project_children, parameter[self, project_id, name_contains]]:
constant[
Get direct files and folders of a project.
:param project_id: str: uuid of the project to list contents
:param name_contains: str: filter children based on a pattern
:return: [File|Folder]: ... | keyword[def] identifier[get_project_children] ( identifier[self] , identifier[project_id] , identifier[name_contains] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_create_array_response] (
identifier[self] . identifier[data_service] . identifier[get_pro... | def get_project_children(self, project_id, name_contains=None):
"""
Get direct files and folders of a project.
:param project_id: str: uuid of the project to list contents
:param name_contains: str: filter children based on a pattern
:return: [File|Folder]: list of Files/Folders cont... |
def format(self, record):
"""Format the log record."""
levelname = getattr(record, 'levelname', None)
record.levelcolor = ''
record.endlevelcolor = ''
if levelname:
level_color = getattr(self.TermColors, levelname, '')
record.levelcolor = level_color
... | def function[format, parameter[self, record]]:
constant[Format the log record.]
variable[levelname] assign[=] call[name[getattr], parameter[name[record], constant[levelname], constant[None]]]
name[record].levelcolor assign[=] constant[]
name[record].endlevelcolor assign[=] constant[]
... | keyword[def] identifier[format] ( identifier[self] , identifier[record] ):
literal[string]
identifier[levelname] = identifier[getattr] ( identifier[record] , literal[string] , keyword[None] )
identifier[record] . identifier[levelcolor] = literal[string]
identifier[record] . ident... | def format(self, record):
"""Format the log record."""
levelname = getattr(record, 'levelname', None)
record.levelcolor = ''
record.endlevelcolor = ''
if levelname:
level_color = getattr(self.TermColors, levelname, '')
record.levelcolor = level_color
record.endlevelcolor = se... |
def maybe_get_static_value(x, dtype=None):
"""Helper which tries to return a static value.
Given `x`, extract it's value statically, optionally casting to a specific
dtype. If this is not possible, None is returned.
Args:
x: `Tensor` for which to extract a value statically.
dtype: Optional dtype to ca... | def function[maybe_get_static_value, parameter[x, dtype]]:
constant[Helper which tries to return a static value.
Given `x`, extract it's value statically, optionally casting to a specific
dtype. If this is not possible, None is returned.
Args:
x: `Tensor` for which to extract a value statically.
... | keyword[def] identifier[maybe_get_static_value] ( identifier[x] , identifier[dtype] = keyword[None] ):
literal[string]
keyword[if] identifier[x] keyword[is] keyword[None] :
keyword[return] identifier[x]
keyword[try] :
identifier[x_] = identifier[tf] . identifier[get_static_value] ( identif... | def maybe_get_static_value(x, dtype=None):
"""Helper which tries to return a static value.
Given `x`, extract it's value statically, optionally casting to a specific
dtype. If this is not possible, None is returned.
Args:
x: `Tensor` for which to extract a value statically.
dtype: Optional dtype to ... |
def revoke(self):
"""LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the respon... | def function[revoke, parameter[self]]:
constant[LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoke... | keyword[def] identifier[revoke] ( identifier[self] ):
literal[string]
identifier[self] . identifier[client] . identifier[post] ( identifier[self] . identifier[client] . identifier[get_url] ( literal[string] ),
identifier[json] ={ literal[string] : identifier[self] . identifier[id] })
... | def revoke(self):
"""LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... |
def needs_serialization(self):
"""
Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all.
"""
return any(field.is_set_on(self) for field in six.itervalues(se... | def function[needs_serialization, parameter[self]]:
constant[
Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all.
]
return[call[name[any], parameter[<ast.Gene... | keyword[def] identifier[needs_serialization] ( identifier[self] ):
literal[string]
keyword[return] identifier[any] ( identifier[field] . identifier[is_set_on] ( identifier[self] ) keyword[for] identifier[field] keyword[in] identifier[six] . identifier[itervalues] ( identifier[self] . identifier... | def needs_serialization(self):
"""
Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all.
"""
return any((field.is_set_on(self) for field in six.itervalues(self.fiel... |
def sym_gen(seq_len):
"""
Build NN symbol depending on the length of the input sequence
"""
sentence_shape = train_iter.provide_data[0][1]
char_sentence_shape = train_iter.provide_data[1][1]
entities_shape = train_iter.provide_label[0][1]
X_sent = mx.symbol.Variable(train_iter.provide_data[... | def function[sym_gen, parameter[seq_len]]:
constant[
Build NN symbol depending on the length of the input sequence
]
variable[sentence_shape] assign[=] call[call[name[train_iter].provide_data][constant[0]]][constant[1]]
variable[char_sentence_shape] assign[=] call[call[name[train_iter].p... | keyword[def] identifier[sym_gen] ( identifier[seq_len] ):
literal[string]
identifier[sentence_shape] = identifier[train_iter] . identifier[provide_data] [ literal[int] ][ literal[int] ]
identifier[char_sentence_shape] = identifier[train_iter] . identifier[provide_data] [ literal[int] ][ literal[int] ]... | def sym_gen(seq_len):
"""
Build NN symbol depending on the length of the input sequence
"""
sentence_shape = train_iter.provide_data[0][1]
char_sentence_shape = train_iter.provide_data[1][1]
entities_shape = train_iter.provide_label[0][1]
X_sent = mx.symbol.Variable(train_iter.provide_data[0... |
def _add_child(self, collection, set, child):
"""Adds 'child' to 'collection', first checking 'set' to see if it's
already present."""
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
... | def function[_add_child, parameter[self, collection, set, child]]:
constant[Adds 'child' to 'collection', first checking 'set' to see if it's
already present.]
variable[added] assign[=] constant[None]
for taget[name[c]] in starred[name[child]] begin[:]
if compare[name[c] ... | keyword[def] identifier[_add_child] ( identifier[self] , identifier[collection] , identifier[set] , identifier[child] ):
literal[string]
identifier[added] = keyword[None]
keyword[for] identifier[c] keyword[in] identifier[child] :
keyword[if] identifier[c] keyword[not] k... | def _add_child(self, collection, set, child):
"""Adds 'child' to 'collection', first checking 'set' to see if it's
already present."""
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1 # depends on [control=['if'], da... |
def update_message_dict(message_dict,action):
"""
Update the g_ok_java_messages dict structure by
1. add the new java ignored messages stored in message_dict if action == 1
2. remove the java ignored messages stired in message_dict if action == 2.
Parameters
----------
message_dict : Pyth... | def function[update_message_dict, parameter[message_dict, action]]:
constant[
Update the g_ok_java_messages dict structure by
1. add the new java ignored messages stored in message_dict if action == 1
2. remove the java ignored messages stired in message_dict if action == 2.
Parameters
----... | keyword[def] identifier[update_message_dict] ( identifier[message_dict] , identifier[action] ):
literal[string]
keyword[global] identifier[g_ok_java_messages]
identifier[allKeys] = identifier[g_ok_java_messages] . identifier[keys] ()
keyword[for] identifier[key] keyword[in] identifier[mess... | def update_message_dict(message_dict, action):
"""
Update the g_ok_java_messages dict structure by
1. add the new java ignored messages stored in message_dict if action == 1
2. remove the java ignored messages stired in message_dict if action == 2.
Parameters
----------
message_dict : Pyt... |
def get_long_description():
"""Extract description from README.md, for PyPI's usage"""
try:
fpath = os.path.join(os.path.dirname(__file__), "README.md")
with io.open(fpath, encoding="utf-8") as f:
readme = f.read()
desc = readme.partition("<!-- start_ppi_description -->")... | def function[get_long_description, parameter[]]:
constant[Extract description from README.md, for PyPI's usage]
<ast.Try object at 0x7da1b21c73a0> | keyword[def] identifier[get_long_description] ():
literal[string]
keyword[try] :
identifier[fpath] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), literal[string] )
keyword[with] identifier[io] . i... | def get_long_description():
"""Extract description from README.md, for PyPI's usage"""
try:
fpath = os.path.join(os.path.dirname(__file__), 'README.md')
with io.open(fpath, encoding='utf-8') as f:
readme = f.read()
desc = readme.partition('<!-- start_ppi_description -->')... |
def add_dynamic_gateway(self, networks):
"""
A dynamic gateway object creates a router object that is
attached to a DHCP interface. You can associate networks with
this gateway address to identify networks for routing on this
interface.
::
route = en... | def function[add_dynamic_gateway, parameter[self, networks]]:
constant[
A dynamic gateway object creates a router object that is
attached to a DHCP interface. You can associate networks with
this gateway address to identify networks for routing on this
interface.
::
... | keyword[def] identifier[add_dynamic_gateway] ( identifier[self] , identifier[networks] ):
literal[string]
identifier[routing_node_gateway] = identifier[RoutingNodeGateway] ( identifier[dynamic_classid] = literal[string] ,
identifier[destinations] = identifier[networks] keyword[or] [])
... | def add_dynamic_gateway(self, networks):
"""
A dynamic gateway object creates a router object that is
attached to a DHCP interface. You can associate networks with
this gateway address to identify networks for routing on this
interface.
::
route = engine... |
def get_value(self, field, quick):
# type: (Field, bool) -> Any
""" Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quic... | def function[get_value, parameter[self, field, quick]]:
constant[ Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quick mode, th... | keyword[def] identifier[get_value] ( identifier[self] , identifier[field] , identifier[quick] ):
literal[string]
keyword[if] identifier[callable] ( identifier[field] . identifier[default] ):
identifier[default] = identifier[field] . identifier[default] ( identifier[self] )
k... | def get_value(self, field, quick):
# type: (Field, bool) -> Any
" Ask user the question represented by this instance.\n\n Args:\n field (Field):\n The field we're asking the user to provide the value for.\n quick (bool):\n Enable quick mode. In quick mo... |
def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in p... | def function[read_stats, parameter[self]]:
constant[ Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
]
name[self].tx_statistics assign[=] call[name[TgnObjectsDict], parameter[]]
for tag... | keyword[def] identifier[read_stats] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tx_statistics] = identifier[TgnObjectsDict] ()
keyword[for] identifier[port] keyword[in] identifier[self] . identifier[session] . identifier[ports] . identifier[values] ():
... | def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in port.streams.value... |
def get_contents_sig(self):
"""
A helper method for get_cachedir_bsig.
It computes and returns the signature for this
node's contents.
"""
try:
return self.contentsig
except AttributeError:
pass
executor = self.get_executor()
... | def function[get_contents_sig, parameter[self]]:
constant[
A helper method for get_cachedir_bsig.
It computes and returns the signature for this
node's contents.
]
<ast.Try object at 0x7da2041da830>
variable[executor] assign[=] call[name[self].get_executor, parameter... | keyword[def] identifier[get_contents_sig] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[contentsig]
keyword[except] identifier[AttributeError] :
keyword[pass]
identifier[executor] = identifier[sel... | def get_contents_sig(self):
"""
A helper method for get_cachedir_bsig.
It computes and returns the signature for this
node's contents.
"""
try:
return self.contentsig # depends on [control=['try'], data=[]]
except AttributeError:
pass # depends on [control=... |
def generate_warning_text(self):
"""
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
"""
self.warning_text = ""
if self.s in list(self.pmag_results_data['spe... | def function[generate_warning_text, parameter[self]]:
constant[
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
]
name[self].warning_text assign[=] constant[]
... | keyword[def] identifier[generate_warning_text] ( identifier[self] ):
literal[string]
identifier[self] . identifier[warning_text] = literal[string]
keyword[if] identifier[self] . identifier[s] keyword[in] identifier[list] ( identifier[self] . identifier[pmag_results_data] [ literal[stri... | def generate_warning_text(self):
"""
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
"""
self.warning_text = ''
if self.s in list(self.pmag_results_data['specimens'].key... |
def in_collision_other(self, other_manager,
return_names=False, return_data=False):
"""
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
... | def function[in_collision_other, parameter[self, other_manager, return_names, return_data]]:
constant[
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
Another c... | keyword[def] identifier[in_collision_other] ( identifier[self] , identifier[other_manager] ,
identifier[return_names] = keyword[False] , identifier[return_data] = keyword[False] ):
literal[string]
identifier[cdata] = identifier[fcl] . identifier[CollisionData] ()
keyword[if] identifier[r... | def in_collision_other(self, other_manager, return_names=False, return_data=False):
"""
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
Another collision manager ob... |
def _dsp2dot_option(arg):
"""Used to convert the :dmap: option to auto directives."""
# noinspection PyUnusedLocal
def map_args(*args, **kwargs):
from schedula.utils.base import Base
a = inspect.signature(Base.plot).bind(None, *args, **kwargs).arguments
a.popitem(last=False)
... | def function[_dsp2dot_option, parameter[arg]]:
constant[Used to convert the :dmap: option to auto directives.]
def function[map_args, parameter[]]:
from relative_module[schedula.utils.base] import module[Base]
variable[a] assign[=] call[call[name[inspect].signature, parameter[nam... | keyword[def] identifier[_dsp2dot_option] ( identifier[arg] ):
literal[string]
keyword[def] identifier[map_args] (* identifier[args] ,** identifier[kwargs] ):
keyword[from] identifier[schedula] . identifier[utils] . identifier[base] keyword[import] identifier[Base]
identifier[a]... | def _dsp2dot_option(arg):
"""Used to convert the :dmap: option to auto directives."""
# noinspection PyUnusedLocal
def map_args(*args, **kwargs):
from schedula.utils.base import Base
a = inspect.signature(Base.plot).bind(None, *args, **kwargs).arguments
a.popitem(last=False)
... |
def start_datetime(self) -> Optional[datetime.datetime]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.intervals[0].start | def function[start_datetime, parameter[self]]:
constant[
Returns the start date of the set of intervals, or ``None`` if empty.
]
if <ast.UnaryOp object at 0x7da1b18e6650> begin[:]
return[constant[None]]
return[call[name[self].intervals][constant[0]].start] | keyword[def] identifier[start_datetime] ( identifier[self] )-> identifier[Optional] [ identifier[datetime] . identifier[datetime] ]:
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[intervals] :
keyword[return] keyword[None]
keyword[return] identifie... | def start_datetime(self) -> Optional[datetime.datetime]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None # depends on [control=['if'], data=[]]
return self.intervals[0].start |
def delete_api_key(self, api_key, **kwargs): # noqa: E501
"""Delete API key. # noqa: E501
An endpoint for deleting the API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes ... | def function[delete_api_key, parameter[self, api_key]]:
constant[Delete API key. # noqa: E501
An endpoint for deleting the API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method mak... | keyword[def] identifier[delete_api_key] ( identifier[self] , identifier[api_key] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[... | def delete_api_key(self, api_key, **kwargs): # noqa: E501
"Delete API key. # noqa: E501\n\n An endpoint for deleting the API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501\n This method makes a s... |
def addParts(self, part_id, parent_id, part_relationship=None):
"""
This will add a has_part (or subproperty) relationship between
a parent_id and the supplied part.
By default the relationship will be BFO:has_part,
but any relationship could be given here.
:param part_id... | def function[addParts, parameter[self, part_id, parent_id, part_relationship]]:
constant[
This will add a has_part (or subproperty) relationship between
a parent_id and the supplied part.
By default the relationship will be BFO:has_part,
but any relationship could be given here.
... | keyword[def] identifier[addParts] ( identifier[self] , identifier[part_id] , identifier[parent_id] , identifier[part_relationship] = keyword[None] ):
literal[string]
keyword[if] identifier[part_relationship] keyword[is] keyword[None] :
identifier[part_relationship] = identifier[self... | def addParts(self, part_id, parent_id, part_relationship=None):
"""
This will add a has_part (or subproperty) relationship between
a parent_id and the supplied part.
By default the relationship will be BFO:has_part,
but any relationship could be given here.
:param part_id:
... |
def get_old_sha(diff_part):
"""
Returns the SHA for the original file that was changed in a diff part.
"""
r = re.compile(r'index ([a-fA-F\d]*)')
return r.search(diff_part).groups()[0] | def function[get_old_sha, parameter[diff_part]]:
constant[
Returns the SHA for the original file that was changed in a diff part.
]
variable[r] assign[=] call[name[re].compile, parameter[constant[index ([a-fA-F\d]*)]]]
return[call[call[call[name[r].search, parameter[name[diff_part]]].groups,... | keyword[def] identifier[get_old_sha] ( identifier[diff_part] ):
literal[string]
identifier[r] = identifier[re] . identifier[compile] ( literal[string] )
keyword[return] identifier[r] . identifier[search] ( identifier[diff_part] ). identifier[groups] ()[ literal[int] ] | def get_old_sha(diff_part):
"""
Returns the SHA for the original file that was changed in a diff part.
"""
r = re.compile('index ([a-fA-F\\d]*)')
return r.search(diff_part).groups()[0] |
def on_electrode_states_set(self, states):
'''
Render and draw updated **static** electrode actuations layer on
canvas.
'''
if (self.canvas_slave.electrode_states
.equals(states['electrode_states'])):
return
self.canvas_slave.electrode_states ... | def function[on_electrode_states_set, parameter[self, states]]:
constant[
Render and draw updated **static** electrode actuations layer on
canvas.
]
if call[name[self].canvas_slave.electrode_states.equals, parameter[call[name[states]][constant[electrode_states]]]] begin[:]
... | keyword[def] identifier[on_electrode_states_set] ( identifier[self] , identifier[states] ):
literal[string]
keyword[if] ( identifier[self] . identifier[canvas_slave] . identifier[electrode_states]
. identifier[equals] ( identifier[states] [ literal[string] ])):
keyword[return]... | def on_electrode_states_set(self, states):
"""
Render and draw updated **static** electrode actuations layer on
canvas.
"""
if self.canvas_slave.electrode_states.equals(states['electrode_states']):
return # depends on [control=['if'], data=[]]
self.canvas_slave.electrode_sta... |
def get_nowait(self):
"""Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
"""
new_get = Future()
with self._lock:
if not self._get.done():
raise QueueEmpty
get, self._get = self._... | def function[get_nowait, parameter[self]]:
constant[Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
]
variable[new_get] assign[=] call[name[Future], parameter[]]
with name[self]._lock begin[:]
if <ast.Un... | keyword[def] identifier[get_nowait] ( identifier[self] ):
literal[string]
identifier[new_get] = identifier[Future] ()
keyword[with] identifier[self] . identifier[_lock] :
keyword[if] keyword[not] identifier[self] . identifier[_get] . identifier[done] ():
k... | def get_nowait(self):
"""Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
"""
new_get = Future()
with self._lock:
if not self._get.done():
raise QueueEmpty # depends on [control=['if'], data=[]]
(get, se... |
def get_fields(brain_or_object):
"""Get the list of fields from the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: List of fields
:rtype: list
"""
obj = get_object(brain_or_object)
... | def function[get_fields, parameter[brain_or_object]]:
constant[Get the list of fields from the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: List of fields
:rtype: list
]
varia... | keyword[def] identifier[get_fields] ( identifier[brain_or_object] ):
literal[string]
identifier[obj] = identifier[get_object] ( identifier[brain_or_object] )
keyword[if] identifier[is_root] ( identifier[obj] ):
keyword[return] {}
identifier[schema] = identifier[get_schema] ( identi... | def get_fields(brain_or_object):
"""Get the list of fields from the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: List of fields
:rtype: list
"""
obj = get_object(brain_or_object)
... |
def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise Va... | def function[format_spec_to_regex, parameter[field_name, format_spec]]:
constant[Make an attempt at converting a format spec to a regular expression.]
variable[regex_match] assign[=] call[name[fmt_spec_regex].match, parameter[call[name[format_spec].replace, parameter[constant[\], constant[]]]]]
... | keyword[def] identifier[format_spec_to_regex] ( identifier[field_name] , identifier[format_spec] ):
literal[string]
identifier[regex_match] = identifier[fmt_spec_regex] . identifier[match] ( identifier[format_spec] . identifier[replace] ( literal[string] , literal[string] ))
keywo... | def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise ValueError("Invalid fo... |
def tablify(*args):
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
"""
table = []
args = [listify(arg) for arg in args]
for row in zip(*args):
r = []
for x in row:
r += listify(x)
table += [r]
return table
return [sum([listif... | def function[tablify, parameter[]]:
constant[
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
]
variable[table] assign[=] list[[]]
variable[args] assign[=] <ast.ListComp object at 0x7da18c4ce650>
for taget[name[row]] in starred[call[name[zip], parameter[<ast.... | keyword[def] identifier[tablify] (* identifier[args] ):
literal[string]
identifier[table] =[]
identifier[args] =[ identifier[listify] ( identifier[arg] ) keyword[for] identifier[arg] keyword[in] identifier[args] ]
keyword[for] identifier[row] keyword[in] identifier[zip] (* identifier[args] ... | def tablify(*args):
"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
"""
table = []
args = [listify(arg) for arg in args]
for row in zip(*args):
r = []
for x in row:
r += listify(x) # depends on [control=['for'], data=['x']]
table += [... |
def _import_plugins(self) -> None:
"""
Import and register plugin in the plugin manager.
The pluggy library is used as plugin manager.
"""
logger.debug('Importing plugins')
self._pm = pluggy.PluginManager('sirbot')
self._pm.add_hookspecs(hookspecs)
for p... | def function[_import_plugins, parameter[self]]:
constant[
Import and register plugin in the plugin manager.
The pluggy library is used as plugin manager.
]
call[name[logger].debug, parameter[constant[Importing plugins]]]
name[self]._pm assign[=] call[name[pluggy].PluginM... | keyword[def] identifier[_import_plugins] ( identifier[self] )-> keyword[None] :
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[_pm] = identifier[pluggy] . identifier[PluginManager] ( literal[string] )
identifier[self] . ide... | def _import_plugins(self) -> None:
"""
Import and register plugin in the plugin manager.
The pluggy library is used as plugin manager.
"""
logger.debug('Importing plugins')
self._pm = pluggy.PluginManager('sirbot')
self._pm.add_hookspecs(hookspecs)
for plugin in self.config[... |
def _parse_image_name(self, image, retry=True):
'''starting with an image string in either of the following formats:
job_id|collection
job_id|collection|job_name
Parse the job_name, job_id, and collection uri from it. If the user
provides the first option, we use th... | def function[_parse_image_name, parameter[self, image, retry]]:
constant[starting with an image string in either of the following formats:
job_id|collection
job_id|collection|job_name
Parse the job_name, job_id, and collection uri from it. If the user
provides the f... | keyword[def] identifier[_parse_image_name] ( identifier[self] , identifier[image] , identifier[retry] = keyword[True] ):
literal[string]
keyword[try] :
identifier[job_id] , identifier[collection] , identifier[job_name] = identifier[image] . identifier[split] ( literal[string] )
... | def _parse_image_name(self, image, retry=True):
"""starting with an image string in either of the following formats:
job_id|collection
job_id|collection|job_name
Parse the job_name, job_id, and collection uri from it. If the user
provides the first option, we use the jo... |
async def generate_psk(self, security_key):
"""Generate and set a psk from the security key."""
if not self._psk:
PatchedDTLSSecurityStore.IDENTITY = 'Client_identity'.encode(
'utf-8')
PatchedDTLSSecurityStore.KEY = security_key.encode('utf-8')
comman... | <ast.AsyncFunctionDef object at 0x7da18ede69b0> | keyword[async] keyword[def] identifier[generate_psk] ( identifier[self] , identifier[security_key] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_psk] :
identifier[PatchedDTLSSecurityStore] . identifier[IDENTITY] = literal[string] . identifier[encode] (
... | async def generate_psk(self, security_key):
"""Generate and set a psk from the security key."""
if not self._psk:
PatchedDTLSSecurityStore.IDENTITY = 'Client_identity'.encode('utf-8')
PatchedDTLSSecurityStore.KEY = security_key.encode('utf-8')
command = Gateway().generate_psk(self._psk_i... |
def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.li... | def function[evaluate_inline, parameter[self, groups]]:
constant[Evaluate inline comments on their own lines.]
if name[self].lines begin[:]
if <ast.BoolOp object at 0x7da2054a56f0> begin[:]
<ast.AugAssign object at 0x7da18c4ccd30>
name[self].leading assign[=] ... | keyword[def] identifier[evaluate_inline] ( identifier[self] , identifier[groups] ):
literal[string]
keyword[if] identifier[self] . identifier[lines] :
keyword[if] (
identifier[self] . identifier[group_comments] keyword[and]
identifier[sel... | def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if self.group_comments and self.line_num == self.prev_line + 1 and (groups['leading_space... |
def report_by_type_stats(sect, stats, _):
"""make a report of
* percentage of different types documented
* percentage of different types with a bad name
"""
# percentage of different types documented and/or with a bad name
nice_stats = {}
for node_type in ("module", "class", "method", "func... | def function[report_by_type_stats, parameter[sect, stats, _]]:
constant[make a report of
* percentage of different types documented
* percentage of different types with a bad name
]
variable[nice_stats] assign[=] dictionary[[], []]
for taget[name[node_type]] in starred[tuple[[<ast.C... | keyword[def] identifier[report_by_type_stats] ( identifier[sect] , identifier[stats] , identifier[_] ):
literal[string]
identifier[nice_stats] ={}
keyword[for] identifier[node_type] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] ):
keyword[try] :
... | def report_by_type_stats(sect, stats, _):
"""make a report of
* percentage of different types documented
* percentage of different types with a bad name
"""
# percentage of different types documented and/or with a bad name
nice_stats = {}
for node_type in ('module', 'class', 'method', 'func... |
def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode... | def function[_generate_barcode_ids, parameter[info_iter]]:
constant[Create unique barcode IDs assigned to sequences
]
variable[bc_type] assign[=] constant[SampleSheet]
variable[barcodes] assign[=] call[name[list], parameter[call[name[set], parameter[<ast.ListComp object at 0x7da1b17b4a60>]]]... | keyword[def] identifier[_generate_barcode_ids] ( identifier[info_iter] ):
literal[string]
identifier[bc_type] = literal[string]
identifier[barcodes] = identifier[list] ( identifier[set] ([ identifier[x] [- literal[int] ] keyword[for] identifier[x] keyword[in] identifier[info_iter] ]))
identif... | def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = 'SampleSheet'
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for (i, bc) in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i + 1) # depends on ... |
def drawPath(self, pointList):
"""
Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the original layer size WITHOUT downsamp... | def function[drawPath, parameter[self, pointList]]:
constant[
Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the ori... | keyword[def] identifier[drawPath] ( identifier[self] , identifier[pointList] ):
literal[string]
identifier[self] . identifier[drawLine] ( identifier[pointList] [ literal[int] ][ literal[int] ], identifier[pointList] [ literal[int] ][ literal[int] ], identifier[pointList] [ literal[int] ][ literal[int] ], ident... | def drawPath(self, pointList):
"""
Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the original layer size WITHOUT downsa... |
def prepare_argparser():
"""Prepare argparser object. New options will be added in this function first."""
description = "%(prog)s -- Gene Set Enrichment Analysis in Python"
epilog = "For command line options of each command, type: %(prog)s COMMAND -h"
# top-level parser
argparser = ap.ArgumentPars... | def function[prepare_argparser, parameter[]]:
constant[Prepare argparser object. New options will be added in this function first.]
variable[description] assign[=] constant[%(prog)s -- Gene Set Enrichment Analysis in Python]
variable[epilog] assign[=] constant[For command line options of each co... | keyword[def] identifier[prepare_argparser] ():
literal[string]
identifier[description] = literal[string]
identifier[epilog] = literal[string]
identifier[argparser] = identifier[ap] . identifier[ArgumentParser] ( identifier[description] = identifier[description] , identifier[epilog] = iden... | def prepare_argparser():
"""Prepare argparser object. New options will be added in this function first."""
description = '%(prog)s -- Gene Set Enrichment Analysis in Python'
epilog = 'For command line options of each command, type: %(prog)s COMMAND -h'
# top-level parser
argparser = ap.ArgumentParse... |
def transformer_moe_8k():
"""Hyper parameters specifics for long sequence generation."""
hparams = transformer_moe_base()
hparams.batch_size = 8192
hparams.max_length = 0 # max_length == batch_size
hparams.eval_drop_long_sequences = True
hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat... | def function[transformer_moe_8k, parameter[]]:
constant[Hyper parameters specifics for long sequence generation.]
variable[hparams] assign[=] call[name[transformer_moe_base], parameter[]]
name[hparams].batch_size assign[=] constant[8192]
name[hparams].max_length assign[=] constant[0]
... | keyword[def] identifier[transformer_moe_8k] ():
literal[string]
identifier[hparams] = identifier[transformer_moe_base] ()
identifier[hparams] . identifier[batch_size] = literal[int]
identifier[hparams] . identifier[max_length] = literal[int]
identifier[hparams] . identifier[eval_drop_long_sequences... | def transformer_moe_8k():
"""Hyper parameters specifics for long sequence generation."""
hparams = transformer_moe_base()
hparams.batch_size = 8192
hparams.max_length = 0 # max_length == batch_size
hparams.eval_drop_long_sequences = True
hparams.min_length_bucket = 256 # Avoid cyclic problems ... |
def on_open(self, ws):
"""
Callback executed when a connection is opened to the server.
Handles streaming of audio to the server.
:param ws: Websocket client
"""
self.callback.on_connected()
# Send initialization message
init_data = self.build_start_mess... | def function[on_open, parameter[self, ws]]:
constant[
Callback executed when a connection is opened to the server.
Handles streaming of audio to the server.
:param ws: Websocket client
]
call[name[self].callback.on_connected, parameter[]]
variable[init_data] assi... | keyword[def] identifier[on_open] ( identifier[self] , identifier[ws] ):
literal[string]
identifier[self] . identifier[callback] . identifier[on_connected] ()
identifier[init_data] = identifier[self] . identifier[build_start_message] ( identifier[self] . identifier[options] )
... | def on_open(self, ws):
"""
Callback executed when a connection is opened to the server.
Handles streaming of audio to the server.
:param ws: Websocket client
"""
self.callback.on_connected()
# Send initialization message
init_data = self.build_start_message(self.options)... |
def chunks(arr, size):
"""Splits a list into chunks
:param arr: list to split
:type arr: :class:`list`
:param size: number of elements in each chunk
:type size: :class:`int`
:return: generator object
:rtype: :class:`generator`
"""
for i in _range(0, len(arr), size):
yield ar... | def function[chunks, parameter[arr, size]]:
constant[Splits a list into chunks
:param arr: list to split
:type arr: :class:`list`
:param size: number of elements in each chunk
:type size: :class:`int`
:return: generator object
:rtype: :class:`generator`
]
for taget[name[i]] ... | keyword[def] identifier[chunks] ( identifier[arr] , identifier[size] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[_range] ( literal[int] , identifier[len] ( identifier[arr] ), identifier[size] ):
keyword[yield] identifier[arr] [ identifier[i] : identifier[i] + identifie... | def chunks(arr, size):
"""Splits a list into chunks
:param arr: list to split
:type arr: :class:`list`
:param size: number of elements in each chunk
:type size: :class:`int`
:return: generator object
:rtype: :class:`generator`
"""
for i in _range(0, len(arr), size):
yield ar... |
def _merge_dicts(*args):
'''
Shallow copy and merge dicts together, giving precedence to last in.
'''
ret = dict()
for arg in args:
ret.update(arg)
return ret | def function[_merge_dicts, parameter[]]:
constant[
Shallow copy and merge dicts together, giving precedence to last in.
]
variable[ret] assign[=] call[name[dict], parameter[]]
for taget[name[arg]] in starred[name[args]] begin[:]
call[name[ret].update, parameter[name[arg]]... | keyword[def] identifier[_merge_dicts] (* identifier[args] ):
literal[string]
identifier[ret] = identifier[dict] ()
keyword[for] identifier[arg] keyword[in] identifier[args] :
identifier[ret] . identifier[update] ( identifier[arg] )
keyword[return] identifier[ret] | def _merge_dicts(*args):
"""
Shallow copy and merge dicts together, giving precedence to last in.
"""
ret = dict()
for arg in args:
ret.update(arg) # depends on [control=['for'], data=['arg']]
return ret |
def load(self, filename):
"""
Updates the setting from config file in JSON format.
:param filename: filename of the local JSON settings file. If None, the local config file is used.
"""
if filename is None:
filename = LOCALCONFIG
with open(filename, 'r') as fi... | def function[load, parameter[self, filename]]:
constant[
Updates the setting from config file in JSON format.
:param filename: filename of the local JSON settings file. If None, the local config file is used.
]
if compare[name[filename] is constant[None]] begin[:]
... | keyword[def] identifier[load] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[None] :
identifier[filename] = identifier[LOCALCONFIG]
keyword[with] identifier[open] ( identifier[filename] , literal[string] )... | def load(self, filename):
"""
Updates the setting from config file in JSON format.
:param filename: filename of the local JSON settings file. If None, the local config file is used.
"""
if filename is None:
filename = LOCALCONFIG # depends on [control=['if'], data=['filename']]
... |
def plot_fit(self, **kwargs):
""" Plots the fit of the model
Returns
----------
None (plots data and the fit)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
if self.latent_variables.estimated is ... | def function[plot_fit, parameter[self]]:
constant[ Plots the fit of the model
Returns
----------
None (plots data and the fit)
]
import module[matplotlib.pyplot] as alias[plt]
import module[seaborn] as alias[sns]
variable[figsize] assign[=] call[name[kwargs].get,... | keyword[def] identifier[plot_fit] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
keyword[import] identifier[seaborn] keyword[as] identifier[sns]
identifier[figsize] = ide... | def plot_fit(self, **kwargs):
""" Plots the fit of the model
Returns
----------
None (plots data and the fit)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize', (10, 7))
if self.latent_variables.estimated is False:
raise... |
def change_numbering(self, new_index=None):
"""Change numbering to a new index.
Changes the numbering of index and all dependent numbering
(bond_with...) to a new_index.
The user has to make sure that the new_index consists of distinct
elements.
Args:
... | def function[change_numbering, parameter[self, new_index]]:
constant[Change numbering to a new index.
Changes the numbering of index and all dependent numbering
(bond_with...) to a new_index.
The user has to make sure that the new_index consists of distinct
elements.
... | keyword[def] identifier[change_numbering] ( identifier[self] , identifier[new_index] = keyword[None] ):
literal[string]
keyword[if] ( identifier[new_index] keyword[is] keyword[None] ):
identifier[new_index] = identifier[range] ( identifier[len] ( identifier[self] ))
keyword[... | def change_numbering(self, new_index=None):
"""Change numbering to a new index.
Changes the numbering of index and all dependent numbering
(bond_with...) to a new_index.
The user has to make sure that the new_index consists of distinct
elements.
Args:
ne... |
def uemify(self, reference, hypothesis, uem=None, collar=0.,
skip_overlap=False, returns_uem=False, returns_timeline=False):
"""Crop 'reference' and 'hypothesis' to 'uem' support
Parameters
----------
reference, hypothesis : Annotation
Reference and hypothesis... | def function[uemify, parameter[self, reference, hypothesis, uem, collar, skip_overlap, returns_uem, returns_timeline]]:
constant[Crop 'reference' and 'hypothesis' to 'uem' support
Parameters
----------
reference, hypothesis : Annotation
Reference and hypothesis annotations.
... | keyword[def] identifier[uemify] ( identifier[self] , identifier[reference] , identifier[hypothesis] , identifier[uem] = keyword[None] , identifier[collar] = literal[int] ,
identifier[skip_overlap] = keyword[False] , identifier[returns_uem] = keyword[False] , identifier[returns_timeline] = keyword[False] ):
... | def uemify(self, reference, hypothesis, uem=None, collar=0.0, skip_overlap=False, returns_uem=False, returns_timeline=False):
"""Crop 'reference' and 'hypothesis' to 'uem' support
Parameters
----------
reference, hypothesis : Annotation
Reference and hypothesis annotations.
... |
def _get_warped_array(
input_file=None,
indexes=None,
dst_bounds=None,
dst_shape=None,
dst_crs=None,
resampling=None,
src_nodata=None,
dst_nodata=None
):
"""Extract a numpy array from a raster file."""
try:
return _rasterio_read(
input_file=input_file,
... | def function[_get_warped_array, parameter[input_file, indexes, dst_bounds, dst_shape, dst_crs, resampling, src_nodata, dst_nodata]]:
constant[Extract a numpy array from a raster file.]
<ast.Try object at 0x7da1b012f9a0> | keyword[def] identifier[_get_warped_array] (
identifier[input_file] = keyword[None] ,
identifier[indexes] = keyword[None] ,
identifier[dst_bounds] = keyword[None] ,
identifier[dst_shape] = keyword[None] ,
identifier[dst_crs] = keyword[None] ,
identifier[resampling] = keyword[None] ,
identifier[src_nodata] = ke... | def _get_warped_array(input_file=None, indexes=None, dst_bounds=None, dst_shape=None, dst_crs=None, resampling=None, src_nodata=None, dst_nodata=None):
"""Extract a numpy array from a raster file."""
try:
return _rasterio_read(input_file=input_file, indexes=indexes, dst_bounds=dst_bounds, dst_shape=dst_... |
def as_file(self):
"""If obj[%data_key_name] exists, return name of a file with base64
decoded obj[%data_key_name] content otherwise obj[%file_key_name]."""
use_data_if_no_file = not self._file and self._data
if use_data_if_no_file:
if self._base64_file_content:
... | def function[as_file, parameter[self]]:
constant[If obj[%data_key_name] exists, return name of a file with base64
decoded obj[%data_key_name] content otherwise obj[%file_key_name].]
variable[use_data_if_no_file] assign[=] <ast.BoolOp object at 0x7da20c6c4e50>
if name[use_data_if_no_file]... | keyword[def] identifier[as_file] ( identifier[self] ):
literal[string]
identifier[use_data_if_no_file] = keyword[not] identifier[self] . identifier[_file] keyword[and] identifier[self] . identifier[_data]
keyword[if] identifier[use_data_if_no_file] :
keyword[if] identifi... | def as_file(self):
"""If obj[%data_key_name] exists, return name of a file with base64
decoded obj[%data_key_name] content otherwise obj[%file_key_name]."""
use_data_if_no_file = not self._file and self._data
if use_data_if_no_file:
if self._base64_file_content:
if isinstance(sel... |
def _q(self, number, precision='.00001'):
"""quantiztion of BSSEval values"""
if np.isinf(number):
return np.nan
else:
return D(D(number).quantize(D(precision))) | def function[_q, parameter[self, number, precision]]:
constant[quantiztion of BSSEval values]
if call[name[np].isinf, parameter[name[number]]] begin[:]
return[name[np].nan] | keyword[def] identifier[_q] ( identifier[self] , identifier[number] , identifier[precision] = literal[string] ):
literal[string]
keyword[if] identifier[np] . identifier[isinf] ( identifier[number] ):
keyword[return] identifier[np] . identifier[nan]
keyword[else] :
... | def _q(self, number, precision='.00001'):
"""quantiztion of BSSEval values"""
if np.isinf(number):
return np.nan # depends on [control=['if'], data=[]]
else:
return D(D(number).quantize(D(precision))) |
def obfuscate(
obfuscate_globals=False, shadow_funcname=False, reserved_keywords=()):
"""
An example, barebone name obfuscation ruleset
obfuscate_globals
If true, identifier names on the global scope will also be
obfuscated. Default is False.
shadow_funcname
If True, ob... | def function[obfuscate, parameter[obfuscate_globals, shadow_funcname, reserved_keywords]]:
constant[
An example, barebone name obfuscation ruleset
obfuscate_globals
If true, identifier names on the global scope will also be
obfuscated. Default is False.
shadow_funcname
If T... | keyword[def] identifier[obfuscate] (
identifier[obfuscate_globals] = keyword[False] , identifier[shadow_funcname] = keyword[False] , identifier[reserved_keywords] =()):
literal[string]
keyword[def] identifier[name_obfuscation_rules] ():
identifier[inst] = identifier[Obfuscator] (
ident... | def obfuscate(obfuscate_globals=False, shadow_funcname=False, reserved_keywords=()):
"""
An example, barebone name obfuscation ruleset
obfuscate_globals
If true, identifier names on the global scope will also be
obfuscated. Default is False.
shadow_funcname
If True, obfuscated ... |
def cleanString(someText):
"""
remove special characters and spaces from string
and convert to lowercase
"""
ret = ''
if someText is not None:
ret = filter(unicode.isalnum, someText.lower())
return ret | def function[cleanString, parameter[someText]]:
constant[
remove special characters and spaces from string
and convert to lowercase
]
variable[ret] assign[=] constant[]
if compare[name[someText] is_not constant[None]] begin[:]
variable[ret] assign[=] call[name[filter]... | keyword[def] identifier[cleanString] ( identifier[someText] ):
literal[string]
identifier[ret] = literal[string]
keyword[if] identifier[someText] keyword[is] keyword[not] keyword[None] :
identifier[ret] = identifier[filter] ( identifier[unicode] . identifier[isalnum] , identifier[someTex... | def cleanString(someText):
"""
remove special characters and spaces from string
and convert to lowercase
"""
ret = ''
if someText is not None:
ret = filter(unicode.isalnum, someText.lower()) # depends on [control=['if'], data=['someText']]
return ret |
def _AugAssign(self, t):
""" +=,-=,*=,/=,**=, etc. operations
"""
self._fill()
self._dispatch(t.node)
self._write(' '+t.op+' ')
self._dispatch(t.expr)
if not self._do_indent:
self._write(';') | def function[_AugAssign, parameter[self, t]]:
constant[ +=,-=,*=,/=,**=, etc. operations
]
call[name[self]._fill, parameter[]]
call[name[self]._dispatch, parameter[name[t].node]]
call[name[self]._write, parameter[binary_operation[binary_operation[constant[ ] + name[t].op] + const... | keyword[def] identifier[_AugAssign] ( identifier[self] , identifier[t] ):
literal[string]
identifier[self] . identifier[_fill] ()
identifier[self] . identifier[_dispatch] ( identifier[t] . identifier[node] )
identifier[self] . identifier[_write] ( literal[string] + identifier[t] ... | def _AugAssign(self, t):
""" +=,-=,*=,/=,**=, etc. operations
"""
self._fill()
self._dispatch(t.node)
self._write(' ' + t.op + ' ')
self._dispatch(t.expr)
if not self._do_indent:
self._write(';') # depends on [control=['if'], data=[]] |
def new(self, interchange_level=1, sys_ident='', vol_ident='', set_size=1,
seqnum=1, log_block_size=2048, vol_set_ident=' ', pub_ident_str='',
preparer_ident_str='', app_ident_str='', copyright_file='',
abstract_file='', bibli_file='', vol_expire_date=None, app_use='',
jo... | def function[new, parameter[self, interchange_level, sys_ident, vol_ident, set_size, seqnum, log_block_size, vol_set_ident, pub_ident_str, preparer_ident_str, app_ident_str, copyright_file, abstract_file, bibli_file, vol_expire_date, app_use, joliet, rock_ridge, xa, udf]]:
constant[
Create a new ISO fro... | keyword[def] identifier[new] ( identifier[self] , identifier[interchange_level] = literal[int] , identifier[sys_ident] = literal[string] , identifier[vol_ident] = literal[string] , identifier[set_size] = literal[int] ,
identifier[seqnum] = literal[int] , identifier[log_block_size] = literal[int] , identifier[vol_set... | def new(self, interchange_level=1, sys_ident='', vol_ident='', set_size=1, seqnum=1, log_block_size=2048, vol_set_ident=' ', pub_ident_str='', preparer_ident_str='', app_ident_str='', copyright_file='', abstract_file='', bibli_file='', vol_expire_date=None, app_use='', joliet=None, rock_ridge=None, xa=False, udf=None):... |
async def set_presence(self, status: str = "online", ignore_cache: bool = False):
"""
Set the online status of the user. See also: `API reference`_
Args:
status: The online status of the user. Allowed values: "online", "offline", "unavailable".
ignore_cache: Whether or n... | <ast.AsyncFunctionDef object at 0x7da1b0b30c10> | keyword[async] keyword[def] identifier[set_presence] ( identifier[self] , identifier[status] : identifier[str] = literal[string] , identifier[ignore_cache] : identifier[bool] = keyword[False] ):
literal[string]
keyword[await] identifier[self] . identifier[ensure_registered] ()
keyword[if... | async def set_presence(self, status: str='online', ignore_cache: bool=False):
"""
Set the online status of the user. See also: `API reference`_
Args:
status: The online status of the user. Allowed values: "online", "offline", "unavailable".
ignore_cache: Whether or not to se... |
def delete_country_by_id(cls, country_id, **kwargs):
"""Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id,... | def function[delete_country_by_id, parameter[cls, country_id]]:
constant[Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_... | keyword[def] identifier[delete_country_by_id] ( identifier[cls] , identifier[country_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] ide... | def delete_country_by_id(cls, country_id, **kwargs):
"""Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id, asy... |
def parse(readDataInstance, nDebugEntries):
"""
Returns a new L{ImageDebugDirectories} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{ImageDebugDirectories} object.
@type nDebugEntries: in... | def function[parse, parameter[readDataInstance, nDebugEntries]]:
constant[
Returns a new L{ImageDebugDirectories} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{ImageDebugDirectories} object.
... | keyword[def] identifier[parse] ( identifier[readDataInstance] , identifier[nDebugEntries] ):
literal[string]
identifier[dbgEntries] = identifier[ImageDebugDirectories] ()
identifier[dataLength] = identifier[len] ( identifier[readDataInstance] )
identifier[toRead] = identifier[nDe... | def parse(readDataInstance, nDebugEntries):
"""
Returns a new L{ImageDebugDirectories} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{ImageDebugDirectories} object.
@type nDebugEntries: int
... |
def merge_dict(dict1, dict2):
# type: (dict, dict) -> dict
"""Recursively merge dictionaries: dict2 on to dict1. This differs
from dict.update() in that values that are dicts are recursively merged.
Note that only dict value types are merged, not lists, etc.
:param dict dict1: dictionary to merge t... | def function[merge_dict, parameter[dict1, dict2]]:
constant[Recursively merge dictionaries: dict2 on to dict1. This differs
from dict.update() in that values that are dicts are recursively merged.
Note that only dict value types are merged, not lists, etc.
:param dict dict1: dictionary to merge to
... | keyword[def] identifier[merge_dict] ( identifier[dict1] , identifier[dict2] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[dict1] , identifier[dict] ) keyword[or] keyword[not] identifier[isinstance] ( identifier[dict2] , identifier[dict] ):
keyword[raise] ide... | def merge_dict(dict1, dict2):
# type: (dict, dict) -> dict
'Recursively merge dictionaries: dict2 on to dict1. This differs\n from dict.update() in that values that are dicts are recursively merged.\n Note that only dict value types are merged, not lists, etc.\n\n :param dict dict1: dictionary to merge... |
def _reset(self):
"""
Reset the state of mail object.
"""
log.debug("Reset all variables")
self._attachments = []
self._text_plain = []
self._text_html = []
self._defects = []
self._defects_categories = set()
self._has_defects = False | def function[_reset, parameter[self]]:
constant[
Reset the state of mail object.
]
call[name[log].debug, parameter[constant[Reset all variables]]]
name[self]._attachments assign[=] list[[]]
name[self]._text_plain assign[=] list[[]]
name[self]._text_html assign[=] ... | keyword[def] identifier[_reset] ( identifier[self] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[_attachments] =[]
identifier[self] . identifier[_text_plain] =[]
identifier[self] . identifier[_text_html] =[]
... | def _reset(self):
"""
Reset the state of mail object.
"""
log.debug('Reset all variables')
self._attachments = []
self._text_plain = []
self._text_html = []
self._defects = []
self._defects_categories = set()
self._has_defects = False |
def get(self, **kwargs):
"""
:param texteRecherche:
:param numAmend:
:param idArticle:
:param idAuteur:
:param idDossierLegislatif:
:param idExamen:
:param idExamens:
:param periodeParlementaire:
:param dateDebut:
:param dateFin:
... | def function[get, parameter[self]]:
constant[
:param texteRecherche:
:param numAmend:
:param idArticle:
:param idAuteur:
:param idDossierLegislatif:
:param idExamen:
:param idExamens:
:param periodeParlementaire:
:param dateDebut:
:... | keyword[def] identifier[get] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[params] = identifier[self] . identifier[default_params] . identifier[copy] ()
identifier[params] . identifier[update] ( identifier[kwargs] )
identifier[start] = identifier[time] .... | def get(self, **kwargs):
"""
:param texteRecherche:
:param numAmend:
:param idArticle:
:param idAuteur:
:param idDossierLegislatif:
:param idExamen:
:param idExamens:
:param periodeParlementaire:
:param dateDebut:
:param dateFin:
... |
def fromMessage(cls, message):
"""Generate a ServerError instance, extracting the error text
and the error code from the message."""
error_text = message.getArg(
OPENID_NS, 'error', '<no error message supplied>')
error_code = message.getArg(OPENID_NS, 'error_code')
re... | def function[fromMessage, parameter[cls, message]]:
constant[Generate a ServerError instance, extracting the error text
and the error code from the message.]
variable[error_text] assign[=] call[name[message].getArg, parameter[name[OPENID_NS], constant[error], constant[<no error message supplied>... | keyword[def] identifier[fromMessage] ( identifier[cls] , identifier[message] ):
literal[string]
identifier[error_text] = identifier[message] . identifier[getArg] (
identifier[OPENID_NS] , literal[string] , literal[string] )
identifier[error_code] = identifier[message] . identifier... | def fromMessage(cls, message):
"""Generate a ServerError instance, extracting the error text
and the error code from the message."""
error_text = message.getArg(OPENID_NS, 'error', '<no error message supplied>')
error_code = message.getArg(OPENID_NS, 'error_code')
return cls(error_text, error_co... |
def is_bootstrapped(metadata):
"""Return True if cihai is correctly bootstrapped."""
fields = UNIHAN_FIELDS + DEFAULT_COLUMNS
if TABLE_NAME in metadata.tables.keys():
table = metadata.tables[TABLE_NAME]
if set(fields) == set(c.name for c in table.columns):
return True
el... | def function[is_bootstrapped, parameter[metadata]]:
constant[Return True if cihai is correctly bootstrapped.]
variable[fields] assign[=] binary_operation[name[UNIHAN_FIELDS] + name[DEFAULT_COLUMNS]]
if compare[name[TABLE_NAME] in call[name[metadata].tables.keys, parameter[]]] begin[:]
... | keyword[def] identifier[is_bootstrapped] ( identifier[metadata] ):
literal[string]
identifier[fields] = identifier[UNIHAN_FIELDS] + identifier[DEFAULT_COLUMNS]
keyword[if] identifier[TABLE_NAME] keyword[in] identifier[metadata] . identifier[tables] . identifier[keys] ():
identifier[table]... | def is_bootstrapped(metadata):
"""Return True if cihai is correctly bootstrapped."""
fields = UNIHAN_FIELDS + DEFAULT_COLUMNS
if TABLE_NAME in metadata.tables.keys():
table = metadata.tables[TABLE_NAME]
if set(fields) == set((c.name for c in table.columns)):
return True # depend... |
def do_set(self, line):
"""set [parameter [value]] set (without parameters): Display the value of all
session variables.
set <session variable>: Display the value of a single session variable. set
<session variable> <value>: Set the value of a session variable.
"""
sess... | def function[do_set, parameter[self, line]]:
constant[set [parameter [value]] set (without parameters): Display the value of all
session variables.
set <session variable>: Display the value of a single session variable. set
<session variable> <value>: Set the value of a session variable... | keyword[def] identifier[do_set] ( identifier[self] , identifier[line] ):
literal[string]
identifier[session_parameter] , identifier[value] = identifier[self] . identifier[_split_args] ( identifier[line] , literal[int] , literal[int] )
keyword[if] identifier[value] keyword[is] keyword[No... | def do_set(self, line):
"""set [parameter [value]] set (without parameters): Display the value of all
session variables.
set <session variable>: Display the value of a single session variable. set
<session variable> <value>: Set the value of a session variable.
"""
(session_par... |
def getApplicationsTransitionStateNameFromEnum(self, state):
"""Returns a string for an application transition state"""
fn = self.function_table.getApplicationsTransitionStateNameFromEnum
result = fn(state)
return result | def function[getApplicationsTransitionStateNameFromEnum, parameter[self, state]]:
constant[Returns a string for an application transition state]
variable[fn] assign[=] name[self].function_table.getApplicationsTransitionStateNameFromEnum
variable[result] assign[=] call[name[fn], parameter[name[st... | keyword[def] identifier[getApplicationsTransitionStateNameFromEnum] ( identifier[self] , identifier[state] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[getApplicationsTransitionStateNameFromEnum]
identifier[result] = identifier[fn] ( iden... | def getApplicationsTransitionStateNameFromEnum(self, state):
"""Returns a string for an application transition state"""
fn = self.function_table.getApplicationsTransitionStateNameFromEnum
result = fn(state)
return result |
def get_account(self, headers=None, prefix=None, delimiter=None,
marker=None, end_marker=None, limit=None, query=None,
cdn=False, decode_json=True):
"""
GETs the account and returns the results. This is done to list
the containers for the account. Some use... | def function[get_account, parameter[self, headers, prefix, delimiter, marker, end_marker, limit, query, cdn, decode_json]]:
constant[
GETs the account and returns the results. This is done to list
the containers for the account. Some useful headers are also
returned:
===========... | keyword[def] identifier[get_account] ( identifier[self] , identifier[headers] = keyword[None] , identifier[prefix] = keyword[None] , identifier[delimiter] = keyword[None] ,
identifier[marker] = keyword[None] , identifier[end_marker] = keyword[None] , identifier[limit] = keyword[None] , identifier[query] = keyword[No... | def get_account(self, headers=None, prefix=None, delimiter=None, marker=None, end_marker=None, limit=None, query=None, cdn=False, decode_json=True):
"""
GETs the account and returns the results. This is done to list
the containers for the account. Some useful headers are also
returned:
... |
def xml_marshal_complete_multipart_upload(uploaded_parts):
"""
Marshal's complete multipart upload request based on *uploaded_parts*.
:param uploaded_parts: List of all uploaded parts, ordered by part number.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CompleteMultipartUpload', {'x... | def function[xml_marshal_complete_multipart_upload, parameter[uploaded_parts]]:
constant[
Marshal's complete multipart upload request based on *uploaded_parts*.
:param uploaded_parts: List of all uploaded parts, ordered by part number.
:return: Marshalled XML data.
]
variable[root] assi... | keyword[def] identifier[xml_marshal_complete_multipart_upload] ( identifier[uploaded_parts] ):
literal[string]
identifier[root] = identifier[s3_xml] . identifier[Element] ( literal[string] ,{ literal[string] : identifier[_S3_NAMESPACE] })
keyword[for] identifier[uploaded_part] keyword[in] identifie... | def xml_marshal_complete_multipart_upload(uploaded_parts):
"""
Marshal's complete multipart upload request based on *uploaded_parts*.
:param uploaded_parts: List of all uploaded parts, ordered by part number.
:return: Marshalled XML data.
"""
root = s3_xml.Element('CompleteMultipartUpload', {'x... |
def drop_account(self, account_cookie):
"""删除一个account
Arguments:
account_cookie {[type]} -- [description]
Raises:
RuntimeError -- [description]
"""
if account_cookie in self.account_list:
res = self.account_list.remove(account_cookie)
... | def function[drop_account, parameter[self, account_cookie]]:
constant[删除一个account
Arguments:
account_cookie {[type]} -- [description]
Raises:
RuntimeError -- [description]
]
if compare[name[account_cookie] in name[self].account_list] begin[:]
... | keyword[def] identifier[drop_account] ( identifier[self] , identifier[account_cookie] ):
literal[string]
keyword[if] identifier[account_cookie] keyword[in] identifier[self] . identifier[account_list] :
identifier[res] = identifier[self] . identifier[account_list] . identifier[remov... | def drop_account(self, account_cookie):
"""删除一个account
Arguments:
account_cookie {[type]} -- [description]
Raises:
RuntimeError -- [description]
"""
if account_cookie in self.account_list:
res = self.account_list.remove(account_cookie)
self.cash.... |
def connect_edges(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent.
"""
paths = []
for start, end ... | def function[connect_edges, parameter[graph]]:
constant[
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent.
]
... | keyword[def] identifier[connect_edges] ( identifier[graph] ):
literal[string]
identifier[paths] =[]
keyword[for] identifier[start] , identifier[end] keyword[in] identifier[graph] . identifier[array] ( identifier[graph] . identifier[kdims] ):
identifier[start_ds] = identifier[graph] . ident... | def connect_edges(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent.
"""
paths = []
for (start, end... |
def _setup_variant_regions(data, out_dir):
"""Ensure we have variant regions for calling, using transcript if not present.
Respects noalt_calling by removing additional contigs to improve
speeds.
"""
vr_file = dd.get_variant_regions(data)
if not vr_file:
vr_file = regions.get_sv_bed(dat... | def function[_setup_variant_regions, parameter[data, out_dir]]:
constant[Ensure we have variant regions for calling, using transcript if not present.
Respects noalt_calling by removing additional contigs to improve
speeds.
]
variable[vr_file] assign[=] call[name[dd].get_variant_regions, par... | keyword[def] identifier[_setup_variant_regions] ( identifier[data] , identifier[out_dir] ):
literal[string]
identifier[vr_file] = identifier[dd] . identifier[get_variant_regions] ( identifier[data] )
keyword[if] keyword[not] identifier[vr_file] :
identifier[vr_file] = identifier[regions] . ... | def _setup_variant_regions(data, out_dir):
"""Ensure we have variant regions for calling, using transcript if not present.
Respects noalt_calling by removing additional contigs to improve
speeds.
"""
vr_file = dd.get_variant_regions(data)
if not vr_file:
vr_file = regions.get_sv_bed(dat... |
def import_sql_table(connection_url, table, username, password, columns=None, optimize=True, fetch_mode=None):
"""
Import SQL table to H2OFrame in memory.
Assumes that the SQL table is not being updated and is stable.
Runs multiple SELECT SQL queries concurrently for parallel ingestion.
Be sure to ... | def function[import_sql_table, parameter[connection_url, table, username, password, columns, optimize, fetch_mode]]:
constant[
Import SQL table to H2OFrame in memory.
Assumes that the SQL table is not being updated and is stable.
Runs multiple SELECT SQL queries concurrently for parallel ingestion.... | keyword[def] identifier[import_sql_table] ( identifier[connection_url] , identifier[table] , identifier[username] , identifier[password] , identifier[columns] = keyword[None] , identifier[optimize] = keyword[True] , identifier[fetch_mode] = keyword[None] ):
literal[string]
identifier[assert_is_type] ( iden... | def import_sql_table(connection_url, table, username, password, columns=None, optimize=True, fetch_mode=None):
"""
Import SQL table to H2OFrame in memory.
Assumes that the SQL table is not being updated and is stable.
Runs multiple SELECT SQL queries concurrently for parallel ingestion.
Be sure to ... |
def posterior_step(logposts, dim):
"""Finds the last time a chain made a jump > dim/2.
Parameters
----------
logposts : array
1D array of values that are proportional to the log posterior values.
dim : int
The dimension of the parameter space.
Returns
-------
int
... | def function[posterior_step, parameter[logposts, dim]]:
constant[Finds the last time a chain made a jump > dim/2.
Parameters
----------
logposts : array
1D array of values that are proportional to the log posterior values.
dim : int
The dimension of the parameter space.
Ret... | keyword[def] identifier[posterior_step] ( identifier[logposts] , identifier[dim] ):
literal[string]
keyword[if] identifier[logposts] . identifier[ndim] > literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[criteria] = identifier[dim] / literal[int]
iden... | def posterior_step(logposts, dim):
"""Finds the last time a chain made a jump > dim/2.
Parameters
----------
logposts : array
1D array of values that are proportional to the log posterior values.
dim : int
The dimension of the parameter space.
Returns
-------
int
... |
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
"""
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dic... | def function[clone_g0_inputs_on_ngpus, parameter[self, inputs, outputs, g0_inputs]]:
constant[
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
... | keyword[def] identifier[clone_g0_inputs_on_ngpus] ( identifier[self] , identifier[inputs] , identifier[outputs] , identifier[g0_inputs] ):
literal[string]
keyword[assert] identifier[len] ( identifier[inputs] )== identifier[len] ( identifier[outputs] ),(
literal[string] )
identifier[inputs] [ li... | def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
"""
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dic... |
def resize(img, size, interpolation=Image.BILINEAR):
r"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an i... | def function[resize, parameter[img, size, interpolation]]:
constant[Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. ... | keyword[def] identifier[resize] ( identifier[img] , identifier[size] , identifier[interpolation] = identifier[Image] . identifier[BILINEAR] ):
literal[string]
keyword[if] keyword[not] identifier[_is_pil_image] ( identifier[img] ):
keyword[raise] identifier[TypeError] ( literal[string] . identif... | def resize(img, size, interpolation=Image.BILINEAR):
"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an in... |
def csv_row_to_transaction(index, row, source_encoding="latin1",
date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","):
"""
Parses a row of strings to a ``Transaction`` object.
Args:
index: The index of this row in the original CSV file. Used for
sorting... | def function[csv_row_to_transaction, parameter[index, row, source_encoding, date_format, thousand_sep, decimal_sep]]:
constant[
Parses a row of strings to a ``Transaction`` object.
Args:
index: The index of this row in the original CSV file. Used for
sorting ``Transactio... | keyword[def] identifier[csv_row_to_transaction] ( identifier[index] , identifier[row] , identifier[source_encoding] = literal[string] ,
identifier[date_format] = literal[string] , identifier[thousand_sep] = literal[string] , identifier[decimal_sep] = literal[string] ):
literal[string]
identifier[x... | def csv_row_to_transaction(index, row, source_encoding='latin1', date_format='%d-%m-%Y', thousand_sep='.', decimal_sep=','):
"""
Parses a row of strings to a ``Transaction`` object.
Args:
index: The index of this row in the original CSV file. Used for
sorting ``Transaction``... |
def create_build_graph(self, target_roots, build_root=None):
"""Construct and return a `BuildGraph` given a set of input specs.
:param TargetRoots target_roots: The targets root of the request.
:param string build_root: The build root.
:returns: A tuple of (BuildGraph, AddressMapper).
"""
logge... | def function[create_build_graph, parameter[self, target_roots, build_root]]:
constant[Construct and return a `BuildGraph` given a set of input specs.
:param TargetRoots target_roots: The targets root of the request.
:param string build_root: The build root.
:returns: A tuple of (BuildGraph, Address... | keyword[def] identifier[create_build_graph] ( identifier[self] , identifier[target_roots] , identifier[build_root] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[target_roots] )
identifier[graph] = identifier[LegacyBuildGraph] . identifier[crea... | def create_build_graph(self, target_roots, build_root=None):
"""Construct and return a `BuildGraph` given a set of input specs.
:param TargetRoots target_roots: The targets root of the request.
:param string build_root: The build root.
:returns: A tuple of (BuildGraph, AddressMapper).
"""
logge... |
def on_connect(self, user):
""" Todo connect """
self.user = user
self.logger.info("connected as %s", user)
if not isinstance(self.con_connect, type(None)):
self.con_connect(user) | def function[on_connect, parameter[self, user]]:
constant[ Todo connect ]
name[self].user assign[=] name[user]
call[name[self].logger.info, parameter[constant[connected as %s], name[user]]]
if <ast.UnaryOp object at 0x7da1b0a9f0d0> begin[:]
call[name[self].con_connect, pa... | keyword[def] identifier[on_connect] ( identifier[self] , identifier[user] ):
literal[string]
identifier[self] . identifier[user] = identifier[user]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[user] )
keyword[if] keyword[not] identifier[isinstance] ( ... | def on_connect(self, user):
""" Todo connect """
self.user = user
self.logger.info('connected as %s', user)
if not isinstance(self.con_connect, type(None)):
self.con_connect(user) # depends on [control=['if'], data=[]] |
def outline(self, face_ids=None, **kwargs):
"""
Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watertight mesh as... | def function[outline, parameter[self, face_ids]]:
constant[
Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watert... | keyword[def] identifier[outline] ( identifier[self] , identifier[face_ids] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[path] . identifier[exchange] . identifier[misc] keyword[import] identifier[faces_to_path]
keyword[from] . identifier[path] . id... | def outline(self, face_ids=None, **kwargs):
"""
Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watertight mesh as the... |
def convert_type(self, type):
"""Convert type to SQL
"""
# Default dialect
mapping = {
'any': sa.Text,
'array': None,
'boolean': sa.Boolean,
'date': sa.Date,
'datetime': sa.DateTime,
'duration': None,
'g... | def function[convert_type, parameter[self, type]]:
constant[Convert type to SQL
]
variable[mapping] assign[=] dictionary[[<ast.Constant object at 0x7da1b26ac2b0>, <ast.Constant object at 0x7da1b26ad7b0>, <ast.Constant object at 0x7da1b26aceb0>, <ast.Constant object at 0x7da1b26af4f0>, <ast.Const... | keyword[def] identifier[convert_type] ( identifier[self] , identifier[type] ):
literal[string]
identifier[mapping] ={
literal[string] : identifier[sa] . identifier[Text] ,
literal[string] : keyword[None] ,
literal[string] : identifier[sa] . identifier[Boolean] ,... | def convert_type(self, type):
"""Convert type to SQL
"""
# Default dialect
mapping = {'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'geojson': None, 'geopoint': None, 'integer': sa.Integer, 'number': sa.Float, 'object': None, 'strin... |
def compute_mem_overhead(self):
"""Returns memory overhead."""
self.mem_overhead = (self._process.memory_info().rss -
builtins.initial_rss_size) | def function[compute_mem_overhead, parameter[self]]:
constant[Returns memory overhead.]
name[self].mem_overhead assign[=] binary_operation[call[name[self]._process.memory_info, parameter[]].rss - name[builtins].initial_rss_size] | keyword[def] identifier[compute_mem_overhead] ( identifier[self] ):
literal[string]
identifier[self] . identifier[mem_overhead] =( identifier[self] . identifier[_process] . identifier[memory_info] (). identifier[rss] -
identifier[builtins] . identifier[initial_rss_size] ) | def compute_mem_overhead(self):
"""Returns memory overhead."""
self.mem_overhead = self._process.memory_info().rss - builtins.initial_rss_size |
def should_raptorize(self, req, resp):
""" Determine if this request should be raptorized. Boolean. """
if resp.status != "200 OK":
return False
content_type = resp.headers.get('Content-Type', 'text/plain').lower()
if not 'html' in content_type:
return False
... | def function[should_raptorize, parameter[self, req, resp]]:
constant[ Determine if this request should be raptorized. Boolean. ]
if compare[name[resp].status not_equal[!=] constant[200 OK]] begin[:]
return[constant[False]]
variable[content_type] assign[=] call[call[name[resp].headers.ge... | keyword[def] identifier[should_raptorize] ( identifier[self] , identifier[req] , identifier[resp] ):
literal[string]
keyword[if] identifier[resp] . identifier[status] != literal[string] :
keyword[return] keyword[False]
identifier[content_type] = identifier[resp] . identif... | def should_raptorize(self, req, resp):
""" Determine if this request should be raptorized. Boolean. """
if resp.status != '200 OK':
return False # depends on [control=['if'], data=[]]
content_type = resp.headers.get('Content-Type', 'text/plain').lower()
if not 'html' in content_type:
r... |
def map(requests, stream=True, pool=None, size=1, exception_handler=None):
"""Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param size: Specifies the number of workers to... | def function[map, parameter[requests, stream, pool, size, exception_handler]]:
constant[Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param size: Specifies the number... | keyword[def] identifier[map] ( identifier[requests] , identifier[stream] = keyword[True] , identifier[pool] = keyword[None] , identifier[size] = literal[int] , identifier[exception_handler] = keyword[None] ):
literal[string]
identifier[pool] = identifier[pool] keyword[if] identifier[pool] keyword[else]... | def map(requests, stream=True, pool=None, size=1, exception_handler=None):
"""Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param size: Specifies the number of workers to... |
def closing(self, cancelable=False):
"""Exit tasks"""
if self.already_closed or self.is_starting_up:
return True
if cancelable and CONF.get('main', 'prompt_on_exit'):
reply = QMessageBox.critical(self, 'Spyder',
'Do you reall... | def function[closing, parameter[self, cancelable]]:
constant[Exit tasks]
if <ast.BoolOp object at 0x7da18bcc87f0> begin[:]
return[constant[True]]
if <ast.BoolOp object at 0x7da18bcc8eb0> begin[:]
variable[reply] assign[=] call[name[QMessageBox].critical, parameter[name[se... | keyword[def] identifier[closing] ( identifier[self] , identifier[cancelable] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[already_closed] keyword[or] identifier[self] . identifier[is_starting_up] :
keyword[return] keyword[True]
keyword... | def closing(self, cancelable=False):
"""Exit tasks"""
if self.already_closed or self.is_starting_up:
return True # depends on [control=['if'], data=[]]
if cancelable and CONF.get('main', 'prompt_on_exit'):
reply = QMessageBox.critical(self, 'Spyder', 'Do you really want to exit?', QMessageB... |
def make_tempfile (self, want='handle', resolution='try_unlink', suffix='', **kwargs):
"""Get a context manager that creates and cleans up a uniquely-named temporary
file with a name similar to this path.
This function returns a context manager that creates a secure
temporary file with ... | def function[make_tempfile, parameter[self, want, resolution, suffix]]:
constant[Get a context manager that creates and cleans up a uniquely-named temporary
file with a name similar to this path.
This function returns a context manager that creates a secure
temporary file with a path si... | keyword[def] identifier[make_tempfile] ( identifier[self] , identifier[want] = literal[string] , identifier[resolution] = literal[string] , identifier[suffix] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[want] keyword[not] keyword[in] ( literal[string] , lit... | def make_tempfile(self, want='handle', resolution='try_unlink', suffix='', **kwargs):
"""Get a context manager that creates and cleans up a uniquely-named temporary
file with a name similar to this path.
This function returns a context manager that creates a secure
temporary file with a pat... |
def select(self, selector):
'''Transforms each element of a sequence into a new form.
Each element is transformed through a selector function to produce a
value for each value in the source sequence. The generated sequence is
lazily evaluated.
Args:
selector... | def function[select, parameter[self, selector]]:
constant[Transforms each element of a sequence into a new form.
Each element is transformed through a selector function to produce a
value for each value in the source sequence. The generated sequence is
lazily evaluated.
Args:
... | keyword[def] identifier[select] ( identifier[self] , identifier[selector] ):
literal[string]
keyword[return] identifier[self] . identifier[_create] ( identifier[self] . identifier[_pool] . identifier[imap_unordered] ( identifier[selector] , identifier[iter] ( identifier[self] ),
identi... | def select(self, selector):
"""Transforms each element of a sequence into a new form.
Each element is transformed through a selector function to produce a
value for each value in the source sequence. The generated sequence is
lazily evaluated.
Args:
selector: A unary fu... |
def _open_xarray_dataset(self, val, chunks=CHUNK_SIZE):
"""Read the band in blocks."""
dask_arr = from_sds(val, chunks=chunks)
attrs = val.attributes()
return xr.DataArray(dask_arr, dims=('y', 'x'),
attrs=attrs) | def function[_open_xarray_dataset, parameter[self, val, chunks]]:
constant[Read the band in blocks.]
variable[dask_arr] assign[=] call[name[from_sds], parameter[name[val]]]
variable[attrs] assign[=] call[name[val].attributes, parameter[]]
return[call[name[xr].DataArray, parameter[name[dask_a... | keyword[def] identifier[_open_xarray_dataset] ( identifier[self] , identifier[val] , identifier[chunks] = identifier[CHUNK_SIZE] ):
literal[string]
identifier[dask_arr] = identifier[from_sds] ( identifier[val] , identifier[chunks] = identifier[chunks] )
identifier[attrs] = identifier[val] ... | def _open_xarray_dataset(self, val, chunks=CHUNK_SIZE):
"""Read the band in blocks."""
dask_arr = from_sds(val, chunks=chunks)
attrs = val.attributes()
return xr.DataArray(dask_arr, dims=('y', 'x'), attrs=attrs) |
def message_checksum(msg):
'''calculate a 8-bit checksum of the key fields of a message, so we
can detect incompatible XML changes'''
from .mavcrc import x25crc
crc = x25crc()
crc.accumulate_str(msg.name + ' ')
# in order to allow for extensions the crc does not include
# any field extens... | def function[message_checksum, parameter[msg]]:
constant[calculate a 8-bit checksum of the key fields of a message, so we
can detect incompatible XML changes]
from relative_module[mavcrc] import module[x25crc]
variable[crc] assign[=] call[name[x25crc], parameter[]]
call[name[crc].accu... | keyword[def] identifier[message_checksum] ( identifier[msg] ):
literal[string]
keyword[from] . identifier[mavcrc] keyword[import] identifier[x25crc]
identifier[crc] = identifier[x25crc] ()
identifier[crc] . identifier[accumulate_str] ( identifier[msg] . identifier[name] + literal[string] )
... | def message_checksum(msg):
"""calculate a 8-bit checksum of the key fields of a message, so we
can detect incompatible XML changes"""
from .mavcrc import x25crc
crc = x25crc()
crc.accumulate_str(msg.name + ' ')
# in order to allow for extensions the crc does not include
# any field extens... |
def new_tx(self, *args, **kwargs):
""" Let's obtain a new txbuffer
:returns int txid: id of the new txbuffer
"""
builder = self.transactionbuilder_class(
*args, blockchain_instance=self, **kwargs
)
self._txbuffers.append(builder)
return builder | def function[new_tx, parameter[self]]:
constant[ Let's obtain a new txbuffer
:returns int txid: id of the new txbuffer
]
variable[builder] assign[=] call[name[self].transactionbuilder_class, parameter[<ast.Starred object at 0x7da1b0109750>]]
call[name[self]._txbuffers.append... | keyword[def] identifier[new_tx] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[builder] = identifier[self] . identifier[transactionbuilder_class] (
* identifier[args] , identifier[blockchain_instance] = identifier[self] ,** identifier[kwargs]
... | def new_tx(self, *args, **kwargs):
""" Let's obtain a new txbuffer
:returns int txid: id of the new txbuffer
"""
builder = self.transactionbuilder_class(*args, blockchain_instance=self, **kwargs)
self._txbuffers.append(builder)
return builder |
def get_all_scores(self, motifs, dbmotifs, match, metric, combine,
pval=False, parallel=True, trim=None, ncpus=None):
"""Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instan... | def function[get_all_scores, parameter[self, motifs, dbmotifs, match, metric, combine, pval, parallel, trim, ncpus]]:
constant[Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instances.
dbmotifs ... | keyword[def] identifier[get_all_scores] ( identifier[self] , identifier[motifs] , identifier[dbmotifs] , identifier[match] , identifier[metric] , identifier[combine] ,
identifier[pval] = keyword[False] , identifier[parallel] = keyword[True] , identifier[trim] = keyword[None] , identifier[ncpus] = keyword[None] ):
... | def get_all_scores(self, motifs, dbmotifs, match, metric, combine, pval=False, parallel=True, trim=None, ncpus=None):
"""Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instances.
dbmotifs : list
... |
def fetch(channels, start, end, type=None, dtype=None, allow_tape=None,
connection=None, host=None, port=None, pad=None, scaled=True,
verbose=False, series_class=TimeSeries):
# host and port keywords are used by the decorator only
# pylint: disable=unused-argument
"""Fetch a dict of data... | def function[fetch, parameter[channels, start, end, type, dtype, allow_tape, connection, host, port, pad, scaled, verbose, series_class]]:
constant[Fetch a dict of data series from NDS2
This method sits underneath `TimeSeries.fetch` and related methods,
and isn't really designed to be called directly.
... | keyword[def] identifier[fetch] ( identifier[channels] , identifier[start] , identifier[end] , identifier[type] = keyword[None] , identifier[dtype] = keyword[None] , identifier[allow_tape] = keyword[None] ,
identifier[connection] = keyword[None] , identifier[host] = keyword[None] , identifier[port] = keyword[None] , ... | def fetch(channels, start, end, type=None, dtype=None, allow_tape=None, connection=None, host=None, port=None, pad=None, scaled=True, verbose=False, series_class=TimeSeries):
# host and port keywords are used by the decorator only
# pylint: disable=unused-argument
"Fetch a dict of data series from NDS2\n\n ... |
def CreateDefaultPartition(client, ad_group_id):
"""Creates a default partition.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID for an ad group.
"""
ad_group_criterion_service = client.GetService('AdGroupCriterionService',
version='v... | def function[CreateDefaultPartition, parameter[client, ad_group_id]]:
constant[Creates a default partition.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID for an ad group.
]
variable[ad_group_criterion_service] assign[=] call[name[client].GetService, parameter[constant[... | keyword[def] identifier[CreateDefaultPartition] ( identifier[client] , identifier[ad_group_id] ):
literal[string]
identifier[ad_group_criterion_service] = identifier[client] . identifier[GetService] ( literal[string] ,
identifier[version] = literal[string] )
identifier[operations] =[{
literal[string]... | def CreateDefaultPartition(client, ad_group_id):
"""Creates a default partition.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID for an ad group.
"""
ad_group_criterion_service = client.GetService('AdGroupCriterionService', version='v201809')
# Make sure that caseValue and p... |
def save(self, filename=None):
""" Saves the runtime configuration to disk.
Parameters
----------
filename: str or None, default=None
writeable path to configuration filename.
If None, use default location and filename.
"""
if not filename:
... | def function[save, parameter[self, filename]]:
constant[ Saves the runtime configuration to disk.
Parameters
----------
filename: str or None, default=None
writeable path to configuration filename.
If None, use default location and filename.
]
if ... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[filename] :
identifier[filename] = identifier[self] . identifier[DEFAULT_CONFIG_FILE_NAME]
keyword[else] :
identifier[... | def save(self, filename=None):
""" Saves the runtime configuration to disk.
Parameters
----------
filename: str or None, default=None
writeable path to configuration filename.
If None, use default location and filename.
"""
if not filename:
filena... |
def get_tokenizer(fhp # type: Optional[field_formats.FieldHashingProperties]
):
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
""" Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that... | def function[get_tokenizer, parameter[fhp]]:
constant[ Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that takes a string and tokenises based on those properties.
]
def function[dummy, parameter[word, ignore]... | keyword[def] identifier[get_tokenizer] ( identifier[fhp]
):
literal[string]
keyword[def] identifier[dummy] ( identifier[word] , identifier[ignore] = keyword[None] ):
literal[string]
keyword[return] ( literal[string] keyword[for] identifier[i] keyword[in] identifier[range] ( ... | def get_tokenizer(fhp): # type: Optional[field_formats.FieldHashingProperties]
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
' Get tokeniser function from the hash settings.\n\n This function takes a FieldHashingProperties object. It returns a\n function that takes a string an... |
def install(name=None, sources=None, saltenv='base', **kwargs):
'''
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package name... | def function[install, parameter[name, sources, saltenv]]:
constant[
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package ... | keyword[def] identifier[install] ( identifier[name] = keyword[None] , identifier[sources] = keyword[None] , identifier[saltenv] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[salt] . identifier[utils] . identifier[data] . identifier[is_true] ( identifier[kwargs] . ident... | def install(name=None, sources=None, saltenv='base', **kwargs):
"""
Install the passed package. Can install packages from the following
sources:
* Locally (package already exists on the minion
* HTTP/HTTPS server
* FTP server
* Salt master
Returns a dict containing the new package name... |
def login(
cls, username=None, password=None, requests_session=None,
rate_limit=None
):
"""Get a session that has authenticated with okcupid.com.
If no username and password is supplied, the ones stored in
:class:`okcupyd.settings` will be used.
:param userna... | def function[login, parameter[cls, username, password, requests_session, rate_limit]]:
constant[Get a session that has authenticated with okcupid.com.
If no username and password is supplied, the ones stored in
:class:`okcupyd.settings` will be used.
:param username: The username to log... | keyword[def] identifier[login] (
identifier[cls] , identifier[username] = keyword[None] , identifier[password] = keyword[None] , identifier[requests_session] = keyword[None] ,
identifier[rate_limit] = keyword[None]
):
literal[string]
identifier[requests_session] = identifier[requests_session] k... | def login(cls, username=None, password=None, requests_session=None, rate_limit=None):
"""Get a session that has authenticated with okcupid.com.
If no username and password is supplied, the ones stored in
:class:`okcupyd.settings` will be used.
:param username: The username to log in with.
... |
def start(self):
'''Start the timer and store the start time, this can only be executed
once per instance
It returns the timer instance so it can be chained when instantiating
the timer instance like this:
``timer = Timer('application_name').start()``'''
assert self._sta... | def function[start, parameter[self]]:
constant[Start the timer and store the start time, this can only be executed
once per instance
It returns the timer instance so it can be chained when instantiating
the timer instance like this:
``timer = Timer('application_name').start()``]... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[assert] identifier[self] . identifier[_start] keyword[is] keyword[None] ,(
literal[string] )
identifier[self] . identifier[_last] = identifier[self] . identifier[_start] = identifier[time] . identifier... | def start(self):
"""Start the timer and store the start time, this can only be executed
once per instance
It returns the timer instance so it can be chained when instantiating
the timer instance like this:
``timer = Timer('application_name').start()``"""
assert self._start is No... |
def show_qos_queue(self, queue, **_params):
"""Fetches information of a certain queue."""
return self.get(self.qos_queue_path % (queue),
params=_params) | def function[show_qos_queue, parameter[self, queue]]:
constant[Fetches information of a certain queue.]
return[call[name[self].get, parameter[binary_operation[name[self].qos_queue_path <ast.Mod object at 0x7da2590d6920> name[queue]]]]] | keyword[def] identifier[show_qos_queue] ( identifier[self] , identifier[queue] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[self] . identifier[qos_queue_path] %( identifier[queue] ),
identifier[params] = identifier[_params] ) | def show_qos_queue(self, queue, **_params):
"""Fetches information of a certain queue."""
return self.get(self.qos_queue_path % queue, params=_params) |
def alt_names(names: str) -> Callable[..., Any]:
"""Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
"""
names_split = names.split()
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
... | def function[alt_names, parameter[names]]:
constant[Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
]
variable[names_split] assign[=] call[name[names].split, parameter[]]
def function[decorato... | keyword[def] identifier[alt_names] ( identifier[names] : identifier[str] )-> identifier[Callable] [..., identifier[Any] ]:
literal[string]
identifier[names_split] = identifier[names] . identifier[split] ()
keyword[def] identifier[decorator] ( identifier[func] : identifier[Callable] [..., identifier[... | def alt_names(names: str) -> Callable[..., Any]:
"""Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
"""
names_split = names.split()
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
... |
def _update(self):
"""Update the display of button after querying data from interface"""
self.clear()
self._set_boutons_communs()
if self.interface:
self.addSeparator()
l_actions = self.interface.get_actions_toolbar()
self._set_boutons_interface(l_acti... | def function[_update, parameter[self]]:
constant[Update the display of button after querying data from interface]
call[name[self].clear, parameter[]]
call[name[self]._set_boutons_communs, parameter[]]
if name[self].interface begin[:]
call[name[self].addSeparator, paramete... | keyword[def] identifier[_update] ( identifier[self] ):
literal[string]
identifier[self] . identifier[clear] ()
identifier[self] . identifier[_set_boutons_communs] ()
keyword[if] identifier[self] . identifier[interface] :
identifier[self] . identifier[addSeparator] ()... | def _update(self):
"""Update the display of button after querying data from interface"""
self.clear()
self._set_boutons_communs()
if self.interface:
self.addSeparator()
l_actions = self.interface.get_actions_toolbar()
self._set_boutons_interface(l_actions) # depends on [control=... |
def plot_by_correct(self, y, is_correct):
""" Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False)
Arguments:
y (int): the selected class
is_correct (boolean):... | def function[plot_by_correct, parameter[self, y, is_correct]]:
constant[ Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False)
Arguments:
y (int): the selected class
... | keyword[def] identifier[plot_by_correct] ( identifier[self] , identifier[y] , identifier[is_correct] ):
literal[string]
keyword[return] identifier[self] . identifier[plot_val_with_title] ( identifier[self] . identifier[most_by_correct] ( identifier[y] , identifier[is_correct] ), identifier[y] ) | def plot_by_correct(self, y, is_correct):
""" Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False)
Arguments:
y (int): the selected class
is_correct (boolean): a b... |
def link(target, link_to):
"""
Create a link to a target file or a folder.
For simplicity sake, both target and link_to must be absolute path and must
include the filename of the file or folder.
Also do not include any trailing slash.
e.g. link('/path/to/file', '/path/to/link')
But not: l... | def function[link, parameter[target, link_to]]:
constant[
Create a link to a target file or a folder.
For simplicity sake, both target and link_to must be absolute path and must
include the filename of the file or folder.
Also do not include any trailing slash.
e.g. link('/path/to/file', '... | keyword[def] identifier[link] ( identifier[target] , identifier[link_to] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[target] , identifier[str] )
keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[target] )
keyword[assert] identifier[i... | def link(target, link_to):
"""
Create a link to a target file or a folder.
For simplicity sake, both target and link_to must be absolute path and must
include the filename of the file or folder.
Also do not include any trailing slash.
e.g. link('/path/to/file', '/path/to/link')
But not: l... |
def register_as_type(self, locator, object_factory):
"""
Registers a component using its type (a constructor function).
:param locator: a locator to identify component to be created.
:param object_factory: a component type.
"""
if locator == None:
raise Exce... | def function[register_as_type, parameter[self, locator, object_factory]]:
constant[
Registers a component using its type (a constructor function).
:param locator: a locator to identify component to be created.
:param object_factory: a component type.
]
if compare[name[l... | keyword[def] identifier[register_as_type] ( identifier[self] , identifier[locator] , identifier[object_factory] ):
literal[string]
keyword[if] identifier[locator] == keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[if] identifier[object_facto... | def register_as_type(self, locator, object_factory):
"""
Registers a component using its type (a constructor function).
:param locator: a locator to identify component to be created.
:param object_factory: a component type.
"""
if locator == None:
raise Exception('Locat... |
def url_for(endpoint, default="senaite.jsonapi.get", **values):
"""Looks up the API URL for the given endpoint
:param endpoint: The name of the registered route (aka endpoint)
:type endpoint: string
:returns: External URL for this endpoint
:rtype: string/None
"""
try:
return router... | def function[url_for, parameter[endpoint, default]]:
constant[Looks up the API URL for the given endpoint
:param endpoint: The name of the registered route (aka endpoint)
:type endpoint: string
:returns: External URL for this endpoint
:rtype: string/None
]
<ast.Try object at 0x7da1b2539... | keyword[def] identifier[url_for] ( identifier[endpoint] , identifier[default] = literal[string] ,** identifier[values] ):
literal[string]
keyword[try] :
keyword[return] identifier[router] . identifier[url_for] ( identifier[endpoint] , identifier[force_external] = keyword[True] , identifier[value... | def url_for(endpoint, default='senaite.jsonapi.get', **values):
"""Looks up the API URL for the given endpoint
:param endpoint: The name of the registered route (aka endpoint)
:type endpoint: string
:returns: External URL for this endpoint
:rtype: string/None
"""
try:
return router.... |
def unindent(buffer, from_row, to_row, count=1):
"""
Unindent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text):
remove = ' ' * count
if text.startswith(remove):
return... | def function[unindent, parameter[buffer, from_row, to_row, count]]:
constant[
Unindent text of a :class:`.Buffer` object.
]
variable[current_row] assign[=] name[buffer].document.cursor_position_row
variable[line_range] assign[=] call[name[range], parameter[name[from_row], name[to_row]]]
... | keyword[def] identifier[unindent] ( identifier[buffer] , identifier[from_row] , identifier[to_row] , identifier[count] = literal[int] ):
literal[string]
identifier[current_row] = identifier[buffer] . identifier[document] . identifier[cursor_position_row]
identifier[line_range] = identifier[range] ( i... | def unindent(buffer, from_row, to_row, count=1):
"""
Unindent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text):
remove = ' ' * count
if text.startswith(remove):
return... |
def render_import_image(self, use_auth=None):
"""
Configure the import_image plugin
"""
# import_image is a multi-phase plugin
if self.user_params.imagestream_name.value is None:
self.pt.remove_plugin('exit_plugins', 'import_image',
'... | def function[render_import_image, parameter[self, use_auth]]:
constant[
Configure the import_image plugin
]
if compare[name[self].user_params.imagestream_name.value is constant[None]] begin[:]
call[name[self].pt.remove_plugin, parameter[constant[exit_plugins], constant[im... | keyword[def] identifier[render_import_image] ( identifier[self] , identifier[use_auth] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[user_params] . identifier[imagestream_name] . identifier[value] keyword[is] keyword[None] :
identifier[self] .... | def render_import_image(self, use_auth=None):
"""
Configure the import_image plugin
"""
# import_image is a multi-phase plugin
if self.user_params.imagestream_name.value is None:
self.pt.remove_plugin('exit_plugins', 'import_image', 'imagestream not in user parameters') # depends on... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.