code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def minimize(self, time, variables, **kwargs):
"""
Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
by some op... | def function[minimize, parameter[self, time, variables]]:
constant[
Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
... | keyword[def] identifier[minimize] ( identifier[self] , identifier[time] , identifier[variables] ,** identifier[kwargs] ):
literal[string]
... | def minimize(self, time, variables, **kwargs):
"""
Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
by some optimi... |
def perform(self):
"""Runs through all of the steps in the chain and runs each of them in sequence.
:return: The value from the lat "do" step performed
"""
last_value = None
last_step = None
while self.items.qsize():
item = self.items.get()
if ... | def function[perform, parameter[self]]:
constant[Runs through all of the steps in the chain and runs each of them in sequence.
:return: The value from the lat "do" step performed
]
variable[last_value] assign[=] constant[None]
variable[last_step] assign[=] constant[None]
... | keyword[def] identifier[perform] ( identifier[self] ):
literal[string]
identifier[last_value] = keyword[None]
identifier[last_step] = keyword[None]
keyword[while] identifier[self] . identifier[items] . identifier[qsize] ():
identifier[item] = identifier[self] . i... | def perform(self):
"""Runs through all of the steps in the chain and runs each of them in sequence.
:return: The value from the lat "do" step performed
"""
last_value = None
last_step = None
while self.items.qsize():
item = self.items.get()
if item.flag == self.do:
... |
def json(
self,
*,
include: 'SetStr' = None,
exclude: 'SetStr' = None,
by_alias: bool = False,
skip_defaults: bool = False,
encoder: Optional[Callable[[Any], Any]] = None,
**dumps_kwargs: Any,
) -> str:
"""
Generate a JSON representatio... | def function[json, parameter[self]]:
constant[
Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`.
`encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`.
]
variable[encoder] ass... | keyword[def] identifier[json] (
identifier[self] ,
*,
identifier[include] : literal[string] = keyword[None] ,
identifier[exclude] : literal[string] = keyword[None] ,
identifier[by_alias] : identifier[bool] = keyword[False] ,
identifier[skip_defaults] : identifier[bool] = keyword[False] ,
identifier[encoder] : i... | def json(self, *, include: 'SetStr'=None, exclude: 'SetStr'=None, by_alias: bool=False, skip_defaults: bool=False, encoder: Optional[Callable[[Any], Any]]=None, **dumps_kwargs: Any) -> str:
"""
Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`.
`encoder`... |
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename... | def function[total_statements, parameter[self, filename]]:
constant[
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
]
if compare[name[filename] is_not constant[None]] begin[:]... | keyword[def] identifier[total_statements] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[not] keyword[None] :
identifier[statements] = identifier[self] . identifier[_get_lines_by_filename] ( identifi... | def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
... |
def hide_routemap_holder_route_map_content_set_extcommunity_rt_ASN_NN_rt(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.S... | def function[hide_routemap_holder_route_map_content_set_extcommunity_rt_ASN_NN_rt, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[hide_routemap_holder] assign[=] call[name[ET].SubElement, parameter[... | keyword[def] identifier[hide_routemap_holder_route_map_content_set_extcommunity_rt_ASN_NN_rt] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[hide_routemap_holder] = identifier[ET] . ident... | def hide_routemap_holder_route_map_content_set_extcommunity_rt_ASN_NN_rt(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
hide_routemap_holder = ET.SubElement(config, 'hide-routemap-holder', xmlns='urn:brocade.com:mgmt:brocade-ip-policy')
route_map = ET.SubElement(hide_r... |
def error(self, s, pos):
"""Show text and a caret under that. For example:
x = 2y + z
^
"""
print("Lexical error:")
print("%s" % s[:pos+10]) # + 10 for trailing context
print("%s^" % (" "*(pos-1)))
for t in self.rv: print(t)
raise SystemExit | def function[error, parameter[self, s, pos]]:
constant[Show text and a caret under that. For example:
x = 2y + z
^
]
call[name[print], parameter[constant[Lexical error:]]]
call[name[print], parameter[binary_operation[constant[%s] <ast.Mod object at 0x7da2590d6920> call[name[s]][<ast.Slice o... | keyword[def] identifier[error] ( identifier[self] , identifier[s] , identifier[pos] ):
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] % identifier[s] [: identifier[pos] + literal[int] ])
identifier[print] ( literal[string] %( literal[stri... | def error(self, s, pos):
"""Show text and a caret under that. For example:
x = 2y + z
^
"""
print('Lexical error:')
print('%s' % s[:pos + 10]) # + 10 for trailing context
print('%s^' % (' ' * (pos - 1)))
for t in self.rv:
print(t) # depends on [control=['for'], data=['t']]
raise S... |
def as_dict(self):
"""
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
# print("in as_dict", type(self.x), type(self.c), type(self.xc))
i... | def function[as_dict, parameter[self]]:
constant[
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
]
variable[d] assign[=] dictionary[[<ast.Constant object at 0x7da20c992080>, <ast.Constant object at 0x7da20c990d30>], [<ast.Attribute object at 0x7da... | keyword[def] identifier[as_dict] ( identifier[self] ):
literal[string]
identifier[d] ={ literal[string] : identifier[self] . identifier[__class__] . identifier[__module__] ,
literal[string] : identifier[self] . identifier[__class__] . identifier[__name__] }
keyword[if] i... | def as_dict(self):
"""
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
"""
d = {'@module': self.__class__.__module__, '@class': self.__class__.__name__}
# print("in as_dict", type(self.x), type(self.c), type(self.xc))
if self.x is not None:
... |
def clear_input_score_start_range(self):
"""Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.g... | def function[clear_input_score_start_range, parameter[self]]:
constant[Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
]
if <ast.BoolO... | keyword[def] identifier[clear_input_score_start_range] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[get_input_score_start_range_metadata] (). identifier[is_read_only] () keyword[or]
identifier[self] . identifier[get_input_score_start_range_met... | def clear_input_score_start_range(self):
"""Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.grading.G... |
def parse_bookmark_data (data):
"""Return iterator for bookmarks of the form (url, name, line number).
Bookmarks are not sorted.
"""
name = None
lineno = 0
for line in data.splitlines():
lineno += 1
line = line.strip()
if line.startswith("NAME="):
name = line[... | def function[parse_bookmark_data, parameter[data]]:
constant[Return iterator for bookmarks of the form (url, name, line number).
Bookmarks are not sorted.
]
variable[name] assign[=] constant[None]
variable[lineno] assign[=] constant[0]
for taget[name[line]] in starred[call[name[d... | keyword[def] identifier[parse_bookmark_data] ( identifier[data] ):
literal[string]
identifier[name] = keyword[None]
identifier[lineno] = literal[int]
keyword[for] identifier[line] keyword[in] identifier[data] . identifier[splitlines] ():
identifier[lineno] += literal[int]
... | def parse_bookmark_data(data):
"""Return iterator for bookmarks of the form (url, name, line number).
Bookmarks are not sorted.
"""
name = None
lineno = 0
for line in data.splitlines():
lineno += 1
line = line.strip()
if line.startswith('NAME='):
name = line[5... |
def project_update(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fupdate
"""
return DXHTTPRequest('/%s/update' % object_id, inp... | def function[project_update, parameter[object_id, input_params, always_retry]]:
constant[
Invokes the /project-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fupdate
]
return[call[name[DXHTTPRequest], parame... | keyword[def] identifier[project_update] ( identifier[object_id] , identifier[input_params] ={}, identifier[always_retry] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[DXHTTPRequest] ( literal[string] % identifier[object_id] , identifier[input_params] , identifier[alw... | def project_update(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fupdate
"""
return DXHTTPRequest('/%s/update' % object_id, inp... |
def javascript_tag(self, *args):
"""
Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset
"""
tags = []
for arg in args:
asset_path = self.asset_url_for('{0}.js'... | def function[javascript_tag, parameter[self]]:
constant[
Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset
]
variable[tags] assign[=] list[[]]
for taget[name[arg]] in star... | keyword[def] identifier[javascript_tag] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[tags] =[]
keyword[for] identifier[arg] keyword[in] identifier[args] :
identifier[asset_path] = identifier[self] . identifier[asset_url_for] ( literal[string] . iden... | def javascript_tag(self, *args):
"""
Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset
"""
tags = []
for arg in args:
asset_path = self.asset_url_for('{0}.js'.format(arg))
... |
def forward_until(self, condition):
"""Forward until one of the provided matches is found.
The returned string contains all characters found *before the condition
was met. In other words, the condition will be true for the remainder
of the buffer.
:param condition: set of valid... | def function[forward_until, parameter[self, condition]]:
constant[Forward until one of the provided matches is found.
The returned string contains all characters found *before the condition
was met. In other words, the condition will be true for the remainder
of the buffer.
:pa... | keyword[def] identifier[forward_until] ( identifier[self] , identifier[condition] ):
literal[string]
identifier[c] = identifier[TokenWithPosition] ( literal[string] , identifier[self] . identifier[peek] (). identifier[position] )
keyword[while] identifier[self] . identifier[hasNext] () ke... | def forward_until(self, condition):
"""Forward until one of the provided matches is found.
The returned string contains all characters found *before the condition
was met. In other words, the condition will be true for the remainder
of the buffer.
:param condition: set of valid str... |
def to_dict(self):
"""Return a dict all all data about the release"""
data = model_to_dict(self, exclude=['id'])
data['title'] = unicode(self)
data['slug'] = self.slug
data['release_date'] = self.release_date.date().isoformat()
data['created'] = self.created.isoformat()
... | def function[to_dict, parameter[self]]:
constant[Return a dict all all data about the release]
variable[data] assign[=] call[name[model_to_dict], parameter[name[self]]]
call[name[data]][constant[title]] assign[=] call[name[unicode], parameter[name[self]]]
call[name[data]][constant[slug]]... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
identifier[data] = identifier[model_to_dict] ( identifier[self] , identifier[exclude] =[ literal[string] ])
identifier[data] [ literal[string] ]= identifier[unicode] ( identifier[self] )
identifier[data] [ lite... | def to_dict(self):
"""Return a dict all all data about the release"""
data = model_to_dict(self, exclude=['id'])
data['title'] = unicode(self)
data['slug'] = self.slug
data['release_date'] = self.release_date.date().isoformat()
data['created'] = self.created.isoformat()
data['modified'] = se... |
def _on_error(self, websock, e):
'''
Raises BrowsingException in the thread that created this instance.
'''
if isinstance(e, (
websocket.WebSocketConnectionClosedException,
ConnectionResetError)):
self.logger.error('websocket closed, did chrome die?')
... | def function[_on_error, parameter[self, websock, e]]:
constant[
Raises BrowsingException in the thread that created this instance.
]
if call[name[isinstance], parameter[name[e], tuple[[<ast.Attribute object at 0x7da1b1e92710>, <ast.Name object at 0x7da1b1e90be0>]]]] begin[:]
... | keyword[def] identifier[_on_error] ( identifier[self] , identifier[websock] , identifier[e] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[e] ,(
identifier[websocket] . identifier[WebSocketConnectionClosedException] ,
identifier[ConnectionResetError] )):
... | def _on_error(self, websock, e):
"""
Raises BrowsingException in the thread that created this instance.
"""
if isinstance(e, (websocket.WebSocketConnectionClosedException, ConnectionResetError)):
self.logger.error('websocket closed, did chrome die?') # depends on [control=['if'], data=[... |
def do_disable_commands(self, _):
"""Disable the Application Management commands"""
message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME,
self.CMD_CAT_APP_MGMT)
self.disa... | def function[do_disable_commands, parameter[self, _]]:
constant[Disable the Application Management commands]
variable[message_to_print] assign[=] call[constant[{} is not available while {} commands are disabled].format, parameter[name[COMMAND_NAME], name[self].CMD_CAT_APP_MGMT]]
call[name[self].... | keyword[def] identifier[do_disable_commands] ( identifier[self] , identifier[_] ):
literal[string]
identifier[message_to_print] = literal[string] . identifier[format] ( identifier[COMMAND_NAME] ,
identifier[self] . identifier[CMD_CAT_APP_MGMT] )
identifier[self] . identifier[disab... | def do_disable_commands(self, _):
"""Disable the Application Management commands"""
message_to_print = '{} is not available while {} commands are disabled'.format(COMMAND_NAME, self.CMD_CAT_APP_MGMT)
self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print)
self.poutput('The Application Management ... |
def geometry_hash(geometry):
"""
Get an MD5 for a geometry object
Parameters
------------
geometry : object
Returns
------------
MD5 : str
"""
if hasattr(geometry, 'md5'):
# for most of our trimesh objects
md5 = geometry.md5()
elif hasattr(geometry, 'tostrin... | def function[geometry_hash, parameter[geometry]]:
constant[
Get an MD5 for a geometry object
Parameters
------------
geometry : object
Returns
------------
MD5 : str
]
if call[name[hasattr], parameter[name[geometry], constant[md5]]] begin[:]
variable[md5... | keyword[def] identifier[geometry_hash] ( identifier[geometry] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[geometry] , literal[string] ):
identifier[md5] = identifier[geometry] . identifier[md5] ()
keyword[elif] identifier[hasattr] ( identifier[geometry] , literal[st... | def geometry_hash(geometry):
"""
Get an MD5 for a geometry object
Parameters
------------
geometry : object
Returns
------------
MD5 : str
"""
if hasattr(geometry, 'md5'):
# for most of our trimesh objects
md5 = geometry.md5() # depends on [control=['if'], data... |
def load_plugins(self):
"""Refresh the list of available collectors and auditors
Returns:
`None`
"""
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.collectors']['plugins']:
cls = entry_point.load()
if cls.enabled():
self.log... | def function[load_plugins, parameter[self]]:
constant[Refresh the list of available collectors and auditors
Returns:
`None`
]
for taget[name[entry_point]] in starred[call[call[name[CINQ_PLUGINS]][constant[cloud_inquisitor.plugins.collectors]]][constant[plugins]]] begin[:]
... | keyword[def] identifier[load_plugins] ( identifier[self] ):
literal[string]
keyword[for] identifier[entry_point] keyword[in] identifier[CINQ_PLUGINS] [ literal[string] ][ literal[string] ]:
identifier[cls] = identifier[entry_point] . identifier[load] ()
keyword[if] ide... | def load_plugins(self):
"""Refresh the list of available collectors and auditors
Returns:
`None`
"""
for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.collectors']['plugins']:
cls = entry_point.load()
if cls.enabled():
self.log.debug('Collector lo... |
def describe_snapshots(kwargs=None, call=None):
'''
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, <AWS Account ID>. Mul... | def function[describe_snapshots, parameter[kwargs, call]]:
constant[
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, ... | keyword[def] identifier[describe_snapshots] ( identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
identifier[log] . identifier[error] (
literal[string]
literal[string]
)
key... | def describe_snapshots(kwargs=None, call=None):
"""
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, <AWS Account ID>. Mul... |
def candidates(self):
"""A list of candidate addresses (as dictionaries) from a geocode
operation"""
# convert x['location'] to a point from a json point struct
def cditer():
for candidate in self._json_struct['candidates']:
newcandidate = candidate.copy()
... | def function[candidates, parameter[self]]:
constant[A list of candidate addresses (as dictionaries) from a geocode
operation]
def function[cditer, parameter[]]:
for taget[name[candidate]] in starred[call[name[self]._json_struct][constant[candidates]]] begin[:]
... | keyword[def] identifier[candidates] ( identifier[self] ):
literal[string]
keyword[def] identifier[cditer] ():
keyword[for] identifier[candidate] keyword[in] identifier[self] . identifier[_json_struct] [ literal[string] ]:
identifier[newcandidate] = identif... | def candidates(self):
"""A list of candidate addresses (as dictionaries) from a geocode
operation"""
# convert x['location'] to a point from a json point struct
def cditer():
for candidate in self._json_struct['candidates']:
newcandidate = candidate.copy()
newcand... |
def zfill(self, width):
"""Pad a numeric string with zeros on the left, to fill a field of the specified width.
The string is never truncated.
:param int width: Length of output string.
"""
if not self.value_no_colors:
result = self.value_no_colors.zfill(width)
... | def function[zfill, parameter[self, width]]:
constant[Pad a numeric string with zeros on the left, to fill a field of the specified width.
The string is never truncated.
:param int width: Length of output string.
]
if <ast.UnaryOp object at 0x7da18bcc8820> begin[:]
... | keyword[def] identifier[zfill] ( identifier[self] , identifier[width] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[value_no_colors] :
identifier[result] = identifier[self] . identifier[value_no_colors] . identifier[zfill] ( identifier[width] )
ke... | def zfill(self, width):
"""Pad a numeric string with zeros on the left, to fill a field of the specified width.
The string is never truncated.
:param int width: Length of output string.
"""
if not self.value_no_colors:
result = self.value_no_colors.zfill(width) # depends on [c... |
def to_json(val, allow_pickle=False, pretty=False):
r"""
Converts a python object to a JSON string using the utool convention
Args:
val (object):
Returns:
str: json_str
References:
http://stackoverflow.com/questions/11561932/why-does-json-dumpslistnp
CommandLine:
... | def function[to_json, parameter[val, allow_pickle, pretty]]:
constant[
Converts a python object to a JSON string using the utool convention
Args:
val (object):
Returns:
str: json_str
References:
http://stackoverflow.com/questions/11561932/why-does-json-dumpslistnp
... | keyword[def] identifier[to_json] ( identifier[val] , identifier[allow_pickle] = keyword[False] , identifier[pretty] = keyword[False] ):
literal[string]
identifier[UtoolJSONEncoder] = identifier[make_utool_json_encoder] ( identifier[allow_pickle] )
identifier[json_kw] ={}
identifier[json_kw] [ lit... | def to_json(val, allow_pickle=False, pretty=False):
"""
Converts a python object to a JSON string using the utool convention
Args:
val (object):
Returns:
str: json_str
References:
http://stackoverflow.com/questions/11561932/why-does-json-dumpslistnp
CommandLine:
... |
def Take(self: Iterable, n):
"""
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
for i, e in enumerate(self):
if i == n:
break
yield e | def function[Take, parameter[self, n]]:
constant[
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
]
for taget[tuple[[<ast.Name object at 0x7da1b0f51960>, <ast.Name object at 0x7da1b0f52e00>]]] in starred[call[... | keyword[def] identifier[Take] ( identifier[self] : identifier[Iterable] , identifier[n] ):
literal[string]
keyword[for] identifier[i] , identifier[e] keyword[in] identifier[enumerate] ( identifier[self] ):
keyword[if] identifier[i] == identifier[n] :
keyword[break]
keyw... | def Take(self: Iterable, n):
"""
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
for (i, e) in enumerate(self):
if i == n:
break # depends on [control=['if'], data=[]]
yield e # depen... |
def unix_time(self, end_datetime=None, start_datetime=None):
"""
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
"""
start_datetime = self._parse_start_datetime(start_datetime)
end_... | def function[unix_time, parameter[self, end_datetime, start_datetime]]:
constant[
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
]
variable[start_datetime] assign[=] call[name[self]._parse... | keyword[def] identifier[unix_time] ( identifier[self] , identifier[end_datetime] = keyword[None] , identifier[start_datetime] = keyword[None] ):
literal[string]
identifier[start_datetime] = identifier[self] . identifier[_parse_start_datetime] ( identifier[start_datetime] )
identifier[end_d... | def unix_time(self, end_datetime=None, start_datetime=None):
"""
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
"""
start_datetime = self._parse_start_datetime(start_datetime)
end_datetime = s... |
def blocking(func, *args, **kwargs):
"""Run a function that uses blocking IO.
The function is run in the IO thread pool.
"""
pool = get_io_pool()
fut = pool.submit(func, *args, **kwargs)
return fut.result() | def function[blocking, parameter[func]]:
constant[Run a function that uses blocking IO.
The function is run in the IO thread pool.
]
variable[pool] assign[=] call[name[get_io_pool], parameter[]]
variable[fut] assign[=] call[name[pool].submit, parameter[name[func], <ast.Starred object at... | keyword[def] identifier[blocking] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[pool] = identifier[get_io_pool] ()
identifier[fut] = identifier[pool] . identifier[submit] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] )
keyword[return] ... | def blocking(func, *args, **kwargs):
"""Run a function that uses blocking IO.
The function is run in the IO thread pool.
"""
pool = get_io_pool()
fut = pool.submit(func, *args, **kwargs)
return fut.result() |
def from_ascii_hex(text: str) -> int:
"""Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 012... | def function[from_ascii_hex, parameter[text]]:
constant[Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
... | keyword[def] identifier[from_ascii_hex] ( identifier[text] : identifier[str] )-> identifier[int] :
literal[string]
identifier[value] = literal[int]
keyword[for] identifier[index] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[text] )):
identifier[char_ord] = i... | def from_ascii_hex(text: str) -> int:
"""Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 012... |
def graphdata(data):
"""returns ratings and episode number
to be used for making graphs"""
data = jh.get_ratings(data)
num = 1
rating_final = []
episode_final = []
for k,v in data.iteritems():
rating=[]
epinum=[]
for r in v:
if r != None:
r... | def function[graphdata, parameter[data]]:
constant[returns ratings and episode number
to be used for making graphs]
variable[data] assign[=] call[name[jh].get_ratings, parameter[name[data]]]
variable[num] assign[=] constant[1]
variable[rating_final] assign[=] list[[]]
variabl... | keyword[def] identifier[graphdata] ( identifier[data] ):
literal[string]
identifier[data] = identifier[jh] . identifier[get_ratings] ( identifier[data] )
identifier[num] = literal[int]
identifier[rating_final] =[]
identifier[episode_final] =[]
keyword[for] identifier[k] , identifier[v... | def graphdata(data):
"""returns ratings and episode number
to be used for making graphs"""
data = jh.get_ratings(data)
num = 1
rating_final = []
episode_final = []
for (k, v) in data.iteritems():
rating = []
epinum = []
for r in v:
if r != None:
... |
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^... | def function[read_input, parameter[self]]:
constant[Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-buildin... | keyword[def] identifier[read_input] ( identifier[self] ):
literal[string]
identifier[uwg_param_file_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[uwgParamDir] , identifier[self] . identifier[uwgParamFileName] )
keyword[if] keyword[not]... | def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
... |
def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputTe... | def function[run, parameter[self]]:
constant[
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
]
variable[count] assign[=] dictionary[[], []]
for ta... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[count] ={}
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[input] ():
keyword[for] identifier[line] keyword[in] identifier[f] . identifier[open] ( literal[string]... | def run(self):
"""
1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText`
2. write the count into the :py:meth:`~.WordCount.output` target
"""
count = {}
# NOTE: self.input() actually returns an element for the InputText.output() t... |
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
... | def function[_deleted_files, parameter[]]:
constant[
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
]
variable[deleted_files] assign[=] list[[]]
for taget[name[proc]... | keyword[def] identifier[_deleted_files] ():
literal[string]
identifier[deleted_files] =[]
keyword[for] identifier[proc] keyword[in] identifier[psutil] . identifier[process_iter] ():
keyword[try] :
identifier[pinfo] = identifier[proc] . identifier[as_dict] ( identifier[attrs] ... | def _deleted_files():
"""
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
"""
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
... |
def get_unique_field_values(dcm_file_list, field_name):
"""Return a set of unique field values from a list of DICOM files
Parameters
----------
dcm_file_list: iterable of DICOM file paths
field_name: str
Name of the field from where to get each value
Returns
-------
Set of field ... | def function[get_unique_field_values, parameter[dcm_file_list, field_name]]:
constant[Return a set of unique field values from a list of DICOM files
Parameters
----------
dcm_file_list: iterable of DICOM file paths
field_name: str
Name of the field from where to get each value
Return... | keyword[def] identifier[get_unique_field_values] ( identifier[dcm_file_list] , identifier[field_name] ):
literal[string]
identifier[field_values] = identifier[set] ()
keyword[for] identifier[dcm] keyword[in] identifier[dcm_file_list] :
identifier[field_values] . identifier[add] ( identifi... | def get_unique_field_values(dcm_file_list, field_name):
"""Return a set of unique field values from a list of DICOM files
Parameters
----------
dcm_file_list: iterable of DICOM file paths
field_name: str
Name of the field from where to get each value
Returns
-------
Set of field ... |
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
r... | def function[_put, parameter[self]]:
constant[Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
]
if compare[constant[timeout] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin[:]
call[name[kwargs]][... | keyword[def] identifier[_put] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] :
identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[timeout]
identi... | def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout # depends on [control=['if'], data=['kwargs']]
req = self.session.... |
def append(self, item):
"""Adds a new item to the end of the collection."""
if len(self) == 0:
# Special case, we make this the current item
self.index = 0
self.items.append(item) | def function[append, parameter[self, item]]:
constant[Adds a new item to the end of the collection.]
if compare[call[name[len], parameter[name[self]]] equal[==] constant[0]] begin[:]
name[self].index assign[=] constant[0]
call[name[self].items.append, parameter[name[item]]] | keyword[def] identifier[append] ( identifier[self] , identifier[item] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] )== literal[int] :
identifier[self] . identifier[index] = literal[int]
identifier[self] . identifier[items] . identifier[append] ... | def append(self, item):
"""Adds a new item to the end of the collection."""
if len(self) == 0:
# Special case, we make this the current item
self.index = 0 # depends on [control=['if'], data=[]]
self.items.append(item) |
def match_filter(self, idx_list, pattern, dict_type=False,
dict_key='name'):
"""Return Matched items in indexed files.
:param idx_list:
:return list
"""
if dict_type is False:
return self._return_deque([
obj for obj in idx_list
... | def function[match_filter, parameter[self, idx_list, pattern, dict_type, dict_key]]:
constant[Return Matched items in indexed files.
:param idx_list:
:return list
]
if compare[name[dict_type] is constant[False]] begin[:]
return[call[name[self]._return_deque, parameter[<a... | keyword[def] identifier[match_filter] ( identifier[self] , identifier[idx_list] , identifier[pattern] , identifier[dict_type] = keyword[False] ,
identifier[dict_key] = literal[string] ):
literal[string]
keyword[if] identifier[dict_type] keyword[is] keyword[False] :
keyword[return]... | def match_filter(self, idx_list, pattern, dict_type=False, dict_key='name'):
"""Return Matched items in indexed files.
:param idx_list:
:return list
"""
if dict_type is False:
return self._return_deque([obj for obj in idx_list if re.search(pattern, obj)]) # depends on [control=... |
def refresh_existing_encodings(self):
"""
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
"""
update = False
for msg in self.proto_analyzer.messages:
i = next((i for i, d in enumerate(self.decodings) if d.name ==... | def function[refresh_existing_encodings, parameter[self]]:
constant[
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
]
variable[update] assign[=] constant[False]
for taget[name[msg]] in starred[name[self].proto_analyzer.messa... | keyword[def] identifier[refresh_existing_encodings] ( identifier[self] ):
literal[string]
identifier[update] = keyword[False]
keyword[for] identifier[msg] keyword[in] identifier[self] . identifier[proto_analyzer] . identifier[messages] :
identifier[i] = identifier[next] (... | def refresh_existing_encodings(self):
"""
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
"""
update = False
for msg in self.proto_analyzer.messages:
i = next((i for (i, d) in enumerate(self.decodings) if d.name == msg.decoder.na... |
def sync_status(self):
"""Synchronize DOI status DataCite MDS.
:returns: `True` if is sync successfully.
"""
status = None
try:
try:
self.api.doi_get(self.pid.pid_value)
status = PIDStatus.REGISTERED
except DataCiteGoneErr... | def function[sync_status, parameter[self]]:
constant[Synchronize DOI status DataCite MDS.
:returns: `True` if is sync successfully.
]
variable[status] assign[=] constant[None]
<ast.Try object at 0x7da18f721150>
if compare[name[status] is constant[None]] begin[:]
... | keyword[def] identifier[sync_status] ( identifier[self] ):
literal[string]
identifier[status] = keyword[None]
keyword[try] :
keyword[try] :
identifier[self] . identifier[api] . identifier[doi_get] ( identifier[self] . identifier[pid] . identifier[pid_value] ... | def sync_status(self):
"""Synchronize DOI status DataCite MDS.
:returns: `True` if is sync successfully.
"""
status = None
try:
try:
self.api.doi_get(self.pid.pid_value)
status = PIDStatus.REGISTERED # depends on [control=['try'], data=[]]
except Dat... |
def _MultiStream(cls, fds):
"""Effectively streams data from multiple opened BlobImage objects.
Args:
fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects.
Yields:
Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd
is an object from the fds argument... | def function[_MultiStream, parameter[cls, fds]]:
constant[Effectively streams data from multiple opened BlobImage objects.
Args:
fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects.
Yields:
Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd
is ... | keyword[def] identifier[_MultiStream] ( identifier[cls] , identifier[fds] ):
literal[string]
identifier[broken_fds] = identifier[set] ()
identifier[missing_blobs_fd_pairs] =[]
keyword[for] identifier[chunk_fd_pairs] keyword[in] identifier[collection] . identifier[Batch] (
identifier[cls]... | def _MultiStream(cls, fds):
"""Effectively streams data from multiple opened BlobImage objects.
Args:
fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects.
Yields:
Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd
is an object from the fds argument... |
def length(self):
"""Array of vector lengths"""
return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray) | def function[length, parameter[self]]:
constant[Array of vector lengths]
return[call[call[name[np].sqrt, parameter[call[name[np].sum, parameter[binary_operation[name[self] ** constant[2]]]]]].view, parameter[name[np].ndarray]]] | keyword[def] identifier[length] ( identifier[self] ):
literal[string]
keyword[return] identifier[np] . identifier[sqrt] ( identifier[np] . identifier[sum] ( identifier[self] ** literal[int] , identifier[axis] = literal[int] )). identifier[view] ( identifier[np] . identifier[ndarray] ) | def length(self):
"""Array of vector lengths"""
return np.sqrt(np.sum(self ** 2, axis=1)).view(np.ndarray) |
def returner(ret):
'''
Send a message to Nagios with the data
'''
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
... | def function[returner, parameter[ret]]:
constant[
Send a message to Nagios with the data
]
variable[_options] assign[=] call[name[_get_options], parameter[name[ret]]]
call[name[log].debug, parameter[constant[_options %s], name[_options]]]
call[name[_options]][constant[hostname]] ... | keyword[def] identifier[returner] ( identifier[ret] ):
literal[string]
identifier[_options] = identifier[_get_options] ( identifier[ret] )
identifier[log] . identifier[debug] ( literal[string] , identifier[_options] )
identifier[_options] [ literal[string] ]= identifier[ret] . identifier[get] ( ... | def returner(ret):
"""
Send a message to Nagios with the data
"""
_options = _get_options(ret)
log.debug('_options %s', _options)
_options['hostname'] = ret.get('id')
if 'url' not in _options or _options['url'] == '':
log.error('nagios_nrdp.url not defined in salt config')
re... |
def get_anime(self, anime_id, title_language='canonical'):
"""Fetches the Anime Object of the given id or slug.
:param anime_id: The Anime ID or Slug.
:type anime_id: int or str
:param str title_language: The PREFERED title language can be any of
`'canonical'`, `'english'`, ... | def function[get_anime, parameter[self, anime_id, title_language]]:
constant[Fetches the Anime Object of the given id or slug.
:param anime_id: The Anime ID or Slug.
:type anime_id: int or str
:param str title_language: The PREFERED title language can be any of
`'canonical'`... | keyword[def] identifier[get_anime] ( identifier[self] , identifier[anime_id] , identifier[title_language] = literal[string] ):
literal[string]
identifier[r] = identifier[self] . identifier[_query_] ( literal[string] % identifier[anime_id] , literal[string] ,
identifier[params] ={ literal[... | def get_anime(self, anime_id, title_language='canonical'):
"""Fetches the Anime Object of the given id or slug.
:param anime_id: The Anime ID or Slug.
:type anime_id: int or str
:param str title_language: The PREFERED title language can be any of
`'canonical'`, `'english'`, `'ro... |
def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(out... | def function[apply, parameter[self, incoming]]:
constant[
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
]
assert[compare[call[name[len], parameter[name[incoming]]] equal[==] name[self].size]]
name[self].incoming assi... | keyword[def] identifier[apply] ( identifier[self] , identifier[incoming] ):
literal[string]
keyword[assert] identifier[len] ( identifier[incoming] )== identifier[self] . identifier[size]
identifier[self] . identifier[incoming] = identifier[incoming]
identifier[outgoing] = ident... | def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(outgoing) == self.size
... |
def remove_isolated_clusters(labels, inlets):
r"""
Finds cluster labels not attached to the inlets, and sets them to
unoccupied (-1)
Parameters
----------
labels : tuple of site and bond labels
This information is provided by the ``site_percolation`` or
``bond_percolation`` func... | def function[remove_isolated_clusters, parameter[labels, inlets]]:
constant[
Finds cluster labels not attached to the inlets, and sets them to
unoccupied (-1)
Parameters
----------
labels : tuple of site and bond labels
This information is provided by the ``site_percolation`` or
... | keyword[def] identifier[remove_isolated_clusters] ( identifier[labels] , identifier[inlets] ):
literal[string]
identifier[inv_clusters] = identifier[sp] . identifier[unique] ( identifier[labels] . identifier[sites] [ identifier[inlets] ])
identifier[inv_clusters] = identifier[inv_clusters] [... | def remove_isolated_clusters(labels, inlets):
"""
Finds cluster labels not attached to the inlets, and sets them to
unoccupied (-1)
Parameters
----------
labels : tuple of site and bond labels
This information is provided by the ``site_percolation`` or
``bond_percolation`` funct... |
def divisors(n):
"""
From a given natural integer, returns the list of divisors in ascending order
:param n: Natural integer
:return: List of divisors of n in ascending order
"""
factors = _factor_generator(n)
_divisors = []
listexponents = [[k**x for x in range(0, factors[k]+1)] for k i... | def function[divisors, parameter[n]]:
constant[
From a given natural integer, returns the list of divisors in ascending order
:param n: Natural integer
:return: List of divisors of n in ascending order
]
variable[factors] assign[=] call[name[_factor_generator], parameter[name[n]]]
... | keyword[def] identifier[divisors] ( identifier[n] ):
literal[string]
identifier[factors] = identifier[_factor_generator] ( identifier[n] )
identifier[_divisors] =[]
identifier[listexponents] =[[ identifier[k] ** identifier[x] keyword[for] identifier[x] keyword[in] identifier[range] ( literal[... | def divisors(n):
"""
From a given natural integer, returns the list of divisors in ascending order
:param n: Natural integer
:return: List of divisors of n in ascending order
"""
factors = _factor_generator(n)
_divisors = []
listexponents = [[k ** x for x in range(0, factors[k] + 1)] for... |
def setitem_without_overwrite(d, key, value):
"""
@param d: An instance of dict, that is: isinstance(d, dict)
@param key: a key
@param value: a value to associate with the key
@return: None
@raise: OverwriteError if the key is already present in d.
"""
if key in d:
raise Overwr... | def function[setitem_without_overwrite, parameter[d, key, value]]:
constant[
@param d: An instance of dict, that is: isinstance(d, dict)
@param key: a key
@param value: a value to associate with the key
@return: None
@raise: OverwriteError if the key is already present in d.
]
... | keyword[def] identifier[setitem_without_overwrite] ( identifier[d] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[d] :
keyword[raise] identifier[OverwriteError] ( identifier[key] , identifier[value] , identifier[d] [ identifier[key] ... | def setitem_without_overwrite(d, key, value):
"""
@param d: An instance of dict, that is: isinstance(d, dict)
@param key: a key
@param value: a value to associate with the key
@return: None
@raise: OverwriteError if the key is already present in d.
"""
if key in d:
raise Overwr... |
def save(self, sender):
"""
Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:return: The saved :class:`Messa... | def function[save, parameter[self, sender]]:
constant[
Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:retu... | keyword[def] identifier[save] ( identifier[self] , identifier[sender] ):
literal[string]
identifier[um_to_user_list] = identifier[self] . identifier[cleaned_data] [ literal[string] ]
identifier[body] = identifier[self] . identifier[cleaned_data] [ literal[string] ]
identifier[msg... | def save(self, sender):
"""
Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:return: The saved :class:`Message`.... |
def sort(self, key_or_list, direction=None):
"""
Sorts a cursor object based on the input
:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
:param direction: sorting direction, 1 or -1, needed if key_or_list
... | def function[sort, parameter[self, key_or_list, direction]]:
constant[
Sorts a cursor object based on the input
:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
:param direction: sorting direction, 1 or -1, needed if k... | keyword[def] identifier[sort] ( identifier[self] , identifier[key_or_list] , identifier[direction] = keyword[None] ):
literal[string]
identifier[sort_specifier] = identifier[list] ()
keyword[if] identifier[isinstance] ( identifier[key_or_list] , identifier[list] ):
... | def sort(self, key_or_list, direction=None):
"""
Sorts a cursor object based on the input
:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
:param direction: sorting direction, 1 or -1, needed if key_or_list
... |
def get_template_dir():
"""Find and return the ntc-templates/templates dir."""
try:
template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"])
index = os.path.join(template_dir, "index")
if not os.path.isfile(index):
# Assume only base ./ntc-templates specified
... | def function[get_template_dir, parameter[]]:
constant[Find and return the ntc-templates/templates dir.]
<ast.Try object at 0x7da2054a6ce0>
variable[index] assign[=] call[name[os].path.join, parameter[name[template_dir], constant[index]]]
if <ast.BoolOp object at 0x7da2054a7880> begin[:]
... | keyword[def] identifier[get_template_dir] ():
literal[string]
keyword[try] :
identifier[template_dir] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[os] . identifier[environ] [ literal[string] ])
identifier[index] = identifier[os] . identifier[path] . identifier... | def get_template_dir():
"""Find and return the ntc-templates/templates dir."""
try:
template_dir = os.path.expanduser(os.environ['NET_TEXTFSM'])
index = os.path.join(template_dir, 'index')
if not os.path.isfile(index):
# Assume only base ./ntc-templates specified
... |
def sample(self, size=1):
""" Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transformations
"""
... | def function[sample, parameter[self, size]]:
constant[ Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transform... | keyword[def] identifier[sample] ( identifier[self] , identifier[size] = literal[int] ):
literal[string]
identifier[samples] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[size] ):
identifier[xi] = identifier[self] . identifier[_r_xi_rv] .... | def sample(self, size=1):
""" Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transformations
"""
sample... |
def _parse_playlist(self, playlist):
'''
Parse search json-data and create a :class:`Playlist` object.
'''
if playlist['Picture']:
cover_url = '%s70_%s' % (grooveshark.const.PLAYLIST_COVER_URL,
playlist['Picture'])
else:
... | def function[_parse_playlist, parameter[self, playlist]]:
constant[
Parse search json-data and create a :class:`Playlist` object.
]
if call[name[playlist]][constant[Picture]] begin[:]
variable[cover_url] assign[=] binary_operation[constant[%s70_%s] <ast.Mod object at 0x7d... | keyword[def] identifier[_parse_playlist] ( identifier[self] , identifier[playlist] ):
literal[string]
keyword[if] identifier[playlist] [ literal[string] ]:
identifier[cover_url] = literal[string] %( identifier[grooveshark] . identifier[const] . identifier[PLAYLIST_COVER_URL] ,
... | def _parse_playlist(self, playlist):
"""
Parse search json-data and create a :class:`Playlist` object.
"""
if playlist['Picture']:
cover_url = '%s70_%s' % (grooveshark.const.PLAYLIST_COVER_URL, playlist['Picture']) # depends on [control=['if'], data=[]]
else:
cover_url = Non... |
def boundary_cell_fractions(self):
"""Return a tuple of contained fractions of boundary cells.
Since the outermost grid points can have any distance to the
boundary of the partitioned set, the "natural" outermost cell
around these points can either be cropped or extended. This
p... | def function[boundary_cell_fractions, parameter[self]]:
constant[Return a tuple of contained fractions of boundary cells.
Since the outermost grid points can have any distance to the
boundary of the partitioned set, the "natural" outermost cell
around these points can either be cropped ... | keyword[def] identifier[boundary_cell_fractions] ( identifier[self] ):
literal[string]
identifier[frac_list] =[]
keyword[for] identifier[ax] ,( identifier[cvec] , identifier[bmin] , identifier[bmax] ) keyword[in] identifier[enumerate] ( identifier[zip] (
identifier[self] . ident... | def boundary_cell_fractions(self):
"""Return a tuple of contained fractions of boundary cells.
Since the outermost grid points can have any distance to the
boundary of the partitioned set, the "natural" outermost cell
around these points can either be cropped or extended. This
prope... |
def get_middleware_resolvers(middlewares: Tuple[Any, ...]) -> Iterator[Callable]:
"""Get a list of resolver functions from a list of classes or functions."""
for middleware in middlewares:
if isfunction(middleware):
yield middleware
else: # middleware provided as object with 'resolv... | def function[get_middleware_resolvers, parameter[middlewares]]:
constant[Get a list of resolver functions from a list of classes or functions.]
for taget[name[middleware]] in starred[name[middlewares]] begin[:]
if call[name[isfunction], parameter[name[middleware]]] begin[:]
... | keyword[def] identifier[get_middleware_resolvers] ( identifier[middlewares] : identifier[Tuple] [ identifier[Any] ,...])-> identifier[Iterator] [ identifier[Callable] ]:
literal[string]
keyword[for] identifier[middleware] keyword[in] identifier[middlewares] :
keyword[if] identifier[isfunction]... | def get_middleware_resolvers(middlewares: Tuple[Any, ...]) -> Iterator[Callable]:
"""Get a list of resolver functions from a list of classes or functions."""
for middleware in middlewares:
if isfunction(middleware):
yield middleware # depends on [control=['if'], data=[]]
else: # mi... |
def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613
'''
Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file
'''
return _gitfs().find_file(path, tgt_env=tgt_env, **kwargs) | def function[find_file, parameter[path, tgt_env]]:
constant[
Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file
]
return[call[call[name[_gitfs], parameter[]].find_file, parameter[name[path]]]] | keyword[def] identifier[find_file] ( identifier[path] , identifier[tgt_env] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[_gitfs] (). identifier[find_file] ( identifier[path] , identifier[tgt_env] = identifier[tgt_env] ,** identifier[kwargs] ) | def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613
'\n Find the first file to match the path and ref, read the file out of git\n and send the path to the newly cached file\n '
return _gitfs().find_file(path, tgt_env=tgt_env, **kwargs) |
def create_q(token):
"""
Creates the Q() object.
"""
meta = getattr(token, 'meta', None)
query = getattr(token, 'query', '')
wildcards = None
if isinstance(query, six.string_types): # Unicode -> Quoted string
search = query
else: # List -> No quoted string (possible wildcards)... | def function[create_q, parameter[token]]:
constant[
Creates the Q() object.
]
variable[meta] assign[=] call[name[getattr], parameter[name[token], constant[meta], constant[None]]]
variable[query] assign[=] call[name[getattr], parameter[name[token], constant[query], constant[]]]
va... | keyword[def] identifier[create_q] ( identifier[token] ):
literal[string]
identifier[meta] = identifier[getattr] ( identifier[token] , literal[string] , keyword[None] )
identifier[query] = identifier[getattr] ( identifier[token] , literal[string] , literal[string] )
identifier[wildcards] = keyword... | def create_q(token):
"""
Creates the Q() object.
"""
meta = getattr(token, 'meta', None)
query = getattr(token, 'query', '')
wildcards = None
if isinstance(query, six.string_types): # Unicode -> Quoted string
search = query # depends on [control=['if'], data=[]] # List -> No quote... |
def filter(self, record):
"""Change the severity of selected log records."""
if isinstance(record.msg, basestring):
message = record.msg.lower()
if all(kw in message for kw in self.KEYWORDS):
record.levelname = 'DEBUG'
record.levelno = logging.DEBU... | def function[filter, parameter[self, record]]:
constant[Change the severity of selected log records.]
if call[name[isinstance], parameter[name[record].msg, name[basestring]]] begin[:]
variable[message] assign[=] call[name[record].msg.lower, parameter[]]
if call[name[all],... | keyword[def] identifier[filter] ( identifier[self] , identifier[record] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[record] . identifier[msg] , identifier[basestring] ):
identifier[message] = identifier[record] . identifier[msg] . identifier[lower] ()
... | def filter(self, record):
"""Change the severity of selected log records."""
if isinstance(record.msg, basestring):
message = record.msg.lower()
if all((kw in message for kw in self.KEYWORDS)):
record.levelname = 'DEBUG'
record.levelno = logging.DEBUG # depends on [contr... |
def plotcommand(cosmology='WMAP5', plotname=None):
""" Example ways to interrogate the dataset and plot the commah output """
# Plot the c-M relation as a functon of redshift
xarray = 10**(np.arange(1, 15, 0.2))
yval = 'c'
# Specify the redshift range
zarray = np.arange(0, 5, 0.5)
xtitle ... | def function[plotcommand, parameter[cosmology, plotname]]:
constant[ Example ways to interrogate the dataset and plot the commah output ]
variable[xarray] assign[=] binary_operation[constant[10] ** call[name[np].arange, parameter[constant[1], constant[15], constant[0.2]]]]
variable[yval] assign[... | keyword[def] identifier[plotcommand] ( identifier[cosmology] = literal[string] , identifier[plotname] = keyword[None] ):
literal[string]
identifier[xarray] = literal[int] **( identifier[np] . identifier[arange] ( literal[int] , literal[int] , literal[int] ))
identifier[yval] = literal[string]
... | def plotcommand(cosmology='WMAP5', plotname=None):
""" Example ways to interrogate the dataset and plot the commah output """
# Plot the c-M relation as a functon of redshift
xarray = 10 ** np.arange(1, 15, 0.2)
yval = 'c'
# Specify the redshift range
zarray = np.arange(0, 5, 0.5)
xtitle = '... |
def pa_naxis(self, viewer, event, msg=True):
"""Interactively change the slice of the image in a data cube
by pan gesture.
"""
event = self._pa_synth_scroll_event(event)
if event.state != 'move':
return False
# TODO: be able to pick axis
axis = 2
... | def function[pa_naxis, parameter[self, viewer, event, msg]]:
constant[Interactively change the slice of the image in a data cube
by pan gesture.
]
variable[event] assign[=] call[name[self]._pa_synth_scroll_event, parameter[name[event]]]
if compare[name[event].state not_equal[!=] ... | keyword[def] identifier[pa_naxis] ( identifier[self] , identifier[viewer] , identifier[event] , identifier[msg] = keyword[True] ):
literal[string]
identifier[event] = identifier[self] . identifier[_pa_synth_scroll_event] ( identifier[event] )
keyword[if] identifier[event] . identifier[sta... | def pa_naxis(self, viewer, event, msg=True):
"""Interactively change the slice of the image in a data cube
by pan gesture.
"""
event = self._pa_synth_scroll_event(event)
if event.state != 'move':
return False # depends on [control=['if'], data=[]]
# TODO: be able to pick axis
... |
def get_vector(self):
"""Return the vector for this survey."""
vec = {}
for dim in ['forbidden', 'required', 'permitted']:
if self.survey[dim] is None:
continue
dim_vec = map(lambda x: (x['tag'], x['answer']),
self.survey[dim])
... | def function[get_vector, parameter[self]]:
constant[Return the vector for this survey.]
variable[vec] assign[=] dictionary[[], []]
for taget[name[dim]] in starred[list[[<ast.Constant object at 0x7da1b26aec50>, <ast.Constant object at 0x7da1b26ac460>, <ast.Constant object at 0x7da1b26aea10>]]] be... | keyword[def] identifier[get_vector] ( identifier[self] ):
literal[string]
identifier[vec] ={}
keyword[for] identifier[dim] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
keyword[if] identifier[self] . identifier[survey] [ identifier[dim] ] keyword[is] ... | def get_vector(self):
"""Return the vector for this survey."""
vec = {}
for dim in ['forbidden', 'required', 'permitted']:
if self.survey[dim] is None:
continue # depends on [control=['if'], data=[]]
dim_vec = map(lambda x: (x['tag'], x['answer']), self.survey[dim])
vec[... |
def create_logger(level=logging.NOTSET):
"""Create a logger for python-gnupg at a specific message level.
:type level: :obj:`int` or :obj:`str`
:param level: A string or an integer for the lowest level to include in
logs.
**Available levels:**
==== ======== =====================... | def function[create_logger, parameter[level]]:
constant[Create a logger for python-gnupg at a specific message level.
:type level: :obj:`int` or :obj:`str`
:param level: A string or an integer for the lowest level to include in
logs.
**Available levels:**
==== ======== =====... | keyword[def] identifier[create_logger] ( identifier[level] = identifier[logging] . identifier[NOTSET] ):
literal[string]
identifier[_test] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[getcwd] (), literal[string] ... | def create_logger(level=logging.NOTSET):
"""Create a logger for python-gnupg at a specific message level.
:type level: :obj:`int` or :obj:`str`
:param level: A string or an integer for the lowest level to include in
logs.
**Available levels:**
==== ======== =====================... |
def dict_from_qs(qs):
''' Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
'''
entries = qs.split(',') if qs.strip() else []
entries = [entry.strip() for entry in entries]
def _dict_from_qs(line, d):
... | def function[dict_from_qs, parameter[qs]]:
constant[ Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
]
variable[entries] assign[=] <ast.IfExp object at 0x7da2043466e0>
variable[entries] assign[=] <as... | keyword[def] identifier[dict_from_qs] ( identifier[qs] ):
literal[string]
identifier[entries] = identifier[qs] . identifier[split] ( literal[string] ) keyword[if] identifier[qs] . identifier[strip] () keyword[else] []
identifier[entries] =[ identifier[entry] . identifier[strip] () keyword[for] ident... | def dict_from_qs(qs):
""" Slightly introverted parser for lists of dot-notation nested fields
i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}}
"""
entries = qs.split(',') if qs.strip() else []
entries = [entry.strip() for entry in entries]
def _dict_from_qs(line, d):
... |
def disk_vmag(hemi, retinotopy='any', to=None, **kw):
'''
disk_vmag(mesh) yields the visual magnification based on the projection of disks on the cortical
surface into the visual field.
All options accepted by mag_data() are accepted by disk_vmag().
'''
mdat = mag_data(hemi, retinotopy=retino... | def function[disk_vmag, parameter[hemi, retinotopy, to]]:
constant[
disk_vmag(mesh) yields the visual magnification based on the projection of disks on the cortical
surface into the visual field.
All options accepted by mag_data() are accepted by disk_vmag().
]
variable[mdat] assign[=... | keyword[def] identifier[disk_vmag] ( identifier[hemi] , identifier[retinotopy] = literal[string] , identifier[to] = keyword[None] ,** identifier[kw] ):
literal[string]
identifier[mdat] = identifier[mag_data] ( identifier[hemi] , identifier[retinotopy] = identifier[retinotopy] ,** identifier[kw] )
keyw... | def disk_vmag(hemi, retinotopy='any', to=None, **kw):
"""
disk_vmag(mesh) yields the visual magnification based on the projection of disks on the cortical
surface into the visual field.
All options accepted by mag_data() are accepted by disk_vmag().
"""
mdat = mag_data(hemi, retinotopy=retino... |
def sign_direct(self, request, authheaders, secret):
"""Signs a request directly with an appropriate signature. The request's Authorization header will change.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object whic... | def function[sign_direct, parameter[self, request, authheaders, secret]]:
constant[Signs a request directly with an appropriate signature. The request's Authorization header will change.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A s... | keyword[def] identifier[sign_direct] ( identifier[self] , identifier[request] , identifier[authheaders] , identifier[secret] ):
literal[string]
identifier[sig] = identifier[self] . identifier[sign] ( identifier[request] , identifier[authheaders] , identifier[secret] )
keyword[return] iden... | def sign_direct(self, request, authheaders, secret):
"""Signs a request directly with an appropriate signature. The request's Authorization header will change.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which co... |
def shell(ctx, package, working_dir, sudo):
"""Runs a Canari interactive python shell"""
ctx.mode = CanariMode.LocalShellDebug
from canari.commands.shell import shell
shell(package, working_dir, sudo) | def function[shell, parameter[ctx, package, working_dir, sudo]]:
constant[Runs a Canari interactive python shell]
name[ctx].mode assign[=] name[CanariMode].LocalShellDebug
from relative_module[canari.commands.shell] import module[shell]
call[name[shell], parameter[name[package], name[working... | keyword[def] identifier[shell] ( identifier[ctx] , identifier[package] , identifier[working_dir] , identifier[sudo] ):
literal[string]
identifier[ctx] . identifier[mode] = identifier[CanariMode] . identifier[LocalShellDebug]
keyword[from] identifier[canari] . identifier[commands] . identifier[shell]... | def shell(ctx, package, working_dir, sudo):
"""Runs a Canari interactive python shell"""
ctx.mode = CanariMode.LocalShellDebug
from canari.commands.shell import shell
shell(package, working_dir, sudo) |
def connect_bulk(self, si, logger, vcenter_data_model, request):
"""
:param si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param request:
:return:
"""
self.logger = logger
self.logger.info('Apply connectivity changes has... | def function[connect_bulk, parameter[self, si, logger, vcenter_data_model, request]]:
constant[
:param si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param request:
:return:
]
name[self].logger assign[=] name[logger]
call... | keyword[def] identifier[connect_bulk] ( identifier[self] , identifier[si] , identifier[logger] , identifier[vcenter_data_model] , identifier[request] ):
literal[string]
identifier[self] . identifier[logger] = identifier[logger]
identifier[self] . identifier[logger] . identifier[info] ( l... | def connect_bulk(self, si, logger, vcenter_data_model, request):
"""
:param si:
:param logger:
:param VMwarevCenterResourceModel vcenter_data_model:
:param request:
:return:
"""
self.logger = logger
self.logger.info('Apply connectivity changes has started')
... |
def generate_statistics_pdf(activities=None, start_date=None, all_years=False, year=None):
''' Accepts EighthActivity objects and outputs a PDF file. '''
if activities is None:
activities = EighthActivity.objects.all().order_by("name")
if year is None:
year = current_school_year()
if no... | def function[generate_statistics_pdf, parameter[activities, start_date, all_years, year]]:
constant[ Accepts EighthActivity objects and outputs a PDF file. ]
if compare[name[activities] is constant[None]] begin[:]
variable[activities] assign[=] call[call[name[EighthActivity].objects.all,... | keyword[def] identifier[generate_statistics_pdf] ( identifier[activities] = keyword[None] , identifier[start_date] = keyword[None] , identifier[all_years] = keyword[False] , identifier[year] = keyword[None] ):
literal[string]
keyword[if] identifier[activities] keyword[is] keyword[None] :
identi... | def generate_statistics_pdf(activities=None, start_date=None, all_years=False, year=None):
""" Accepts EighthActivity objects and outputs a PDF file. """
if activities is None:
activities = EighthActivity.objects.all().order_by('name') # depends on [control=['if'], data=['activities']]
if year is N... |
def idx(self):
"""
Return partname index as integer for tuple partname or None for
singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
|None| for ``'/ppt/presentation.xml'``.
"""
filename = self.filename
if not filename:
return None
... | def function[idx, parameter[self]]:
constant[
Return partname index as integer for tuple partname or None for
singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
|None| for ``'/ppt/presentation.xml'``.
]
variable[filename] assign[=] name[self].filename
... | keyword[def] identifier[idx] ( identifier[self] ):
literal[string]
identifier[filename] = identifier[self] . identifier[filename]
keyword[if] keyword[not] identifier[filename] :
keyword[return] keyword[None]
identifier[name_part] = identifier[posixpath] . identif... | def idx(self):
"""
Return partname index as integer for tuple partname or None for
singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
|None| for ``'/ppt/presentation.xml'``.
"""
filename = self.filename
if not filename:
return None # depends on [co... |
def unflatten(obj):
'''
TODO: add docs
'''
if not isdict(obj):
raise ValueError(
'only dict-like objects can be unflattened, not %r' % (obj,))
ret = dict()
sub = dict()
for key, value in obj.items():
if '.' not in key and '[' not in key:
ret[key] = value
continue
if '.' in ke... | def function[unflatten, parameter[obj]]:
constant[
TODO: add docs
]
if <ast.UnaryOp object at 0x7da1b0aa2d70> begin[:]
<ast.Raise object at 0x7da1b0aa05e0>
variable[ret] assign[=] call[name[dict], parameter[]]
variable[sub] assign[=] call[name[dict], parameter[]]
for ... | keyword[def] identifier[unflatten] ( identifier[obj] ):
literal[string]
keyword[if] keyword[not] identifier[isdict] ( identifier[obj] ):
keyword[raise] identifier[ValueError] (
literal[string] %( identifier[obj] ,))
identifier[ret] = identifier[dict] ()
identifier[sub] = identifier[dict] ()
... | def unflatten(obj):
"""
TODO: add docs
"""
if not isdict(obj):
raise ValueError('only dict-like objects can be unflattened, not %r' % (obj,)) # depends on [control=['if'], data=[]]
ret = dict()
sub = dict()
for (key, value) in obj.items():
if '.' not in key and '[' not in key:
... |
def create_page(page_object_class_or_interface,
webdriver=None, **kwargs):
"""
Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to atte... | def function[create_page, parameter[page_object_class_or_interface, webdriver]]:
constant[
Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to attempt to c... | keyword[def] identifier[create_page] ( identifier[page_object_class_or_interface] ,
identifier[webdriver] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[webdriver] :
identifier[webdriver] = identifier[WTF_WEBDRIVER_MANAGER] . identifier... | def create_page(page_object_class_or_interface, webdriver=None, **kwargs):
"""
Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to attempt to consturct.
... |
def ratio(self, col: str, ratio_col: str="Ratio"):
"""
Add a column whith the percentages ratio from a column
:param col: column to calculate ratio from
:type col: str
:param ratio_col: new ratio column name, defaults to "Ratio"
:param ratio_col: str, optional
:... | def function[ratio, parameter[self, col, ratio_col]]:
constant[
Add a column whith the percentages ratio from a column
:param col: column to calculate ratio from
:type col: str
:param ratio_col: new ratio column name, defaults to "Ratio"
:param ratio_col: str, optional
... | keyword[def] identifier[ratio] ( identifier[self] , identifier[col] : identifier[str] , identifier[ratio_col] : identifier[str] = literal[string] ):
literal[string]
keyword[try] :
identifier[df] = identifier[self] . identifier[df] . identifier[copy] ()
identifier[df] [ ide... | def ratio(self, col: str, ratio_col: str='Ratio'):
"""
Add a column whith the percentages ratio from a column
:param col: column to calculate ratio from
:type col: str
:param ratio_col: new ratio column name, defaults to "Ratio"
:param ratio_col: str, optional
:exam... |
def switch(self, idx, control):
"""Switch a single control of <idx>"""
old = None
new = None
if control == 'Q':
if self.PQ[idx] == 1:
old = 'PQ'
new = 'PV'
elif self.vQ[idx] == 1:
old = 'vQ'
new = 'vV... | def function[switch, parameter[self, idx, control]]:
constant[Switch a single control of <idx>]
variable[old] assign[=] constant[None]
variable[new] assign[=] constant[None]
if compare[name[control] equal[==] constant[Q]] begin[:]
if compare[call[name[self].PQ][name[idx]]... | keyword[def] identifier[switch] ( identifier[self] , identifier[idx] , identifier[control] ):
literal[string]
identifier[old] = keyword[None]
identifier[new] = keyword[None]
keyword[if] identifier[control] == literal[string] :
keyword[if] identifier[self] . identi... | def switch(self, idx, control):
"""Switch a single control of <idx>"""
old = None
new = None
if control == 'Q':
if self.PQ[idx] == 1:
old = 'PQ'
new = 'PV' # depends on [control=['if'], data=[]]
elif self.vQ[idx] == 1:
old = 'vQ'
new = 'vV... |
def commit(self):
"""Remove temporary save dir: rollback will no longer be possible."""
if self.save_dir is not None:
rmtree(self.save_dir)
self.save_dir = None
self._moved_paths = [] | def function[commit, parameter[self]]:
constant[Remove temporary save dir: rollback will no longer be possible.]
if compare[name[self].save_dir is_not constant[None]] begin[:]
call[name[rmtree], parameter[name[self].save_dir]]
name[self].save_dir assign[=] constant[None]
... | keyword[def] identifier[commit] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[save_dir] keyword[is] keyword[not] keyword[None] :
identifier[rmtree] ( identifier[self] . identifier[save_dir] )
identifier[self] . identifier[save_dir] = k... | def commit(self):
"""Remove temporary save dir: rollback will no longer be possible."""
if self.save_dir is not None:
rmtree(self.save_dir)
self.save_dir = None
self._moved_paths = [] # depends on [control=['if'], data=[]] |
def create_operator(operator, auth, url):
"""
Function takes input of dictionary operator with the following keys
operator = { "fullName" : "" ,
"sessionTimeout" : "",
"password" : "",
"operatorGroupId" : "",
"name" : "",
"desc" : "",
... | def function[create_operator, parameter[operator, auth, url]]:
constant[
Function takes input of dictionary operator with the following keys
operator = { "fullName" : "" ,
"sessionTimeout" : "",
"password" : "",
"operatorGroupId" : "",
"name" : "",
... | keyword[def] identifier[create_operator] ( identifier[operator] , identifier[auth] , identifier[url] ):
literal[string]
identifier[f_url] = identifier[url] + literal[string]
identifier[payload] = identifier[json] . identifier[dumps] ( identifier[operator] , identifier[indent] = literal[int] )
id... | def create_operator(operator, auth, url):
"""
Function takes input of dictionary operator with the following keys
operator = { "fullName" : "" ,
"sessionTimeout" : "",
"password" : "",
"operatorGroupId" : "",
"name" : "",
"desc" : "",
... |
def diagram_layout(graph, height='freeenergy', sources=None, targets=None,
pos=None, scale=None, center=None, dim=2):
"""
Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will ... | def function[diagram_layout, parameter[graph, height, sources, targets, pos, scale, center, dim]]:
constant[
Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in... | keyword[def] identifier[diagram_layout] ( identifier[graph] , identifier[height] = literal[string] , identifier[sources] = keyword[None] , identifier[targets] = keyword[None] ,
identifier[pos] = keyword[None] , identifier[scale] = keyword[None] , identifier[center] = keyword[None] , identifier[dim] = literal[int] ):... | def diagram_layout(graph, height='freeenergy', sources=None, targets=None, pos=None, scale=None, center=None, dim=2):
"""
Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to ever... |
def delete_thumbnails(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
"""
Delete all thumbnails for a source image.
"""
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir,
prefix)
return _delete_us... | def function[delete_thumbnails, parameter[relative_source_path, root, basedir, subdir, prefix]]:
constant[
Delete all thumbnails for a source image.
]
variable[thumbs] assign[=] call[name[thumbnails_for_file], parameter[name[relative_source_path], name[root], name[basedir], name[subdir], name[pr... | keyword[def] identifier[delete_thumbnails] ( identifier[relative_source_path] , identifier[root] = keyword[None] , identifier[basedir] = keyword[None] ,
identifier[subdir] = keyword[None] , identifier[prefix] = keyword[None] ):
literal[string]
identifier[thumbs] = identifier[thumbnails_for_file] ( identif... | def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None):
"""
Delete all thumbnails for a source image.
"""
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix)
return _delete_using_thumbs_list(thumbs) |
def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
"""Decode a single field from a pax record.
"""
try:
return value.decode(encoding, "strict")
except UnicodeDecodeError:
return value.decode(fallback_encoding, fallback_errors) | def function[_decode_pax_field, parameter[self, value, encoding, fallback_encoding, fallback_errors]]:
constant[Decode a single field from a pax record.
]
<ast.Try object at 0x7da1b20885b0> | keyword[def] identifier[_decode_pax_field] ( identifier[self] , identifier[value] , identifier[encoding] , identifier[fallback_encoding] , identifier[fallback_errors] ):
literal[string]
keyword[try] :
keyword[return] identifier[value] . identifier[decode] ( identifier[encoding] , lite... | def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
"""Decode a single field from a pax record.
"""
try:
return value.decode(encoding, 'strict') # depends on [control=['try'], data=[]]
except UnicodeDecodeError:
return value.decode(fallback_encoding, fa... |
def show_vcs_output_vcs_nodes_vcs_node_info_co_ordinator(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "vcs... | def function[show_vcs_output_vcs_nodes_vcs_node_info_co_ordinator, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_vcs] assign[=] call[name[ET].Element, parameter[constant[show_vcs]]]
va... | keyword[def] identifier[show_vcs_output_vcs_nodes_vcs_node_info_co_ordinator] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_vcs] = identifier[ET] . identifier[Element] ( literal[str... | def show_vcs_output_vcs_nodes_vcs_node_info_co_ordinator(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_vcs = ET.Element('show_vcs')
config = show_vcs
output = ET.SubElement(show_vcs, 'output')
vcs_nodes = ET.SubElement(output, 'vcs-nodes')
vcs_node_in... |
def get_by_id(self, id):
"""
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.or... | def function[get_by_id, parameter[self, id]]:
constant[
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbo... | keyword[def] identifier[get_by_id] ( identifier[self] , identifier[id] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[self] . identifier[children] :
keyword[if] identifier[child] [ identifier[self] . identifier[child_id_attribute] ]== identifier[id] :
... | def get_by_id(self, id):
"""
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.org/
... |
def interval_timer(interval, func, *args, **kwargs):
'''Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
'''
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is after interval
... | def function[interval_timer, parameter[interval, func]]:
constant[Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
]
variable[stopped] assign[=] call[name[Event], parameter[]]
def function[loop, parameter[]]:
... | keyword[def] identifier[interval_timer] ( identifier[interval] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[stopped] = identifier[Event] ()
keyword[def] identifier[loop] ():
keyword[while] keyword[not] identifier[stopped] . identifier[wait] (... | def interval_timer(interval, func, *args, **kwargs):
"""Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
"""
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is after interval
... |
def _get_manifest_data(self):
"""
Return the list of items in the manifest
:return: list
"""
with tempfile.NamedTemporaryFile(delete=True) as tmp:
try:
self.s3.download_fileobj(self.sitename, self.manifest_file, tmp)
tmp.seek(0)
... | def function[_get_manifest_data, parameter[self]]:
constant[
Return the list of items in the manifest
:return: list
]
with call[name[tempfile].NamedTemporaryFile, parameter[]] begin[:]
<ast.Try object at 0x7da18f812f80>
return[list[[]]] | keyword[def] identifier[_get_manifest_data] ( identifier[self] ):
literal[string]
keyword[with] identifier[tempfile] . identifier[NamedTemporaryFile] ( identifier[delete] = keyword[True] ) keyword[as] identifier[tmp] :
keyword[try] :
identifier[self] . identifier[s3]... | def _get_manifest_data(self):
"""
Return the list of items in the manifest
:return: list
"""
with tempfile.NamedTemporaryFile(delete=True) as tmp:
try:
self.s3.download_fileobj(self.sitename, self.manifest_file, tmp)
tmp.seek(0)
data = tmp.read... |
def _parse_cli_args():
"""Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-g',
help='The photoset id to be downloaded',
metavar='<photoset_id>'... | def function[_parse_cli_args, parameter[]]:
constant[Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, param... | keyword[def] identifier[_parse_cli_args] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[parser] . identifier[add_argument] (
literal[string] ,
identifier[help] = literal[string] ,
identifier[metavar] = literal[string]
)
... | def _parse_cli_args():
"""Parse the arguments from CLI using ArgumentParser
:return: The arguments parsed by ArgumentParser
:rtype: Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument('-g', help='The photoset id to be downloaded', metavar='<photoset_id>')
parser.add_argument... |
def parse_args(args=None):
"""Parse command line arguments and return a dictionary of options
for ttfautohint.ttfautohint function.
`args` can be either None, a list of strings, or a single string,
that is split into individual options with `shlex.split`.
When `args` is None, the console's default... | def function[parse_args, parameter[args]]:
constant[Parse command line arguments and return a dictionary of options
for ttfautohint.ttfautohint function.
`args` can be either None, a list of strings, or a single string,
that is split into individual options with `shlex.split`.
When `args` is N... | keyword[def] identifier[parse_args] ( identifier[args] = keyword[None] ):
literal[string]
keyword[import] identifier[argparse]
keyword[from] identifier[ttfautohint] keyword[import] identifier[__version__] , identifier[libttfautohint]
keyword[from] identifier[ttfautohint] . identifier[cli] ... | def parse_args(args=None):
"""Parse command line arguments and return a dictionary of options
for ttfautohint.ttfautohint function.
`args` can be either None, a list of strings, or a single string,
that is split into individual options with `shlex.split`.
When `args` is None, the console's default... |
def set_max_priority(self, infohash_list):
"""
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/topPrio', data=data) | def function[set_max_priority, parameter[self, infohash_list]]:
constant[
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
]
variable[data] assign[=] call[name[self]._process_infohash_list, parameter[name[infohash_list]]]
return[c... | keyword[def] identifier[set_max_priority] ( identifier[self] , identifier[infohash_list] ):
literal[string]
identifier[data] = identifier[self] . identifier[_process_infohash_list] ( identifier[infohash_list] )
keyword[return] identifier[self] . identifier[_post] ( literal[string] , ident... | def set_max_priority(self, infohash_list):
"""
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/topPrio', data=data) |
def parse_200_row(row: list) -> NmiDetails:
""" Parse NMI data details record (200) """
return NmiDetails(row[1], row[2], row[3], row[4], row[5], row[6],
row[7], int(row[8]), parse_datetime(row[9])) | def function[parse_200_row, parameter[row]]:
constant[ Parse NMI data details record (200) ]
return[call[name[NmiDetails], parameter[call[name[row]][constant[1]], call[name[row]][constant[2]], call[name[row]][constant[3]], call[name[row]][constant[4]], call[name[row]][constant[5]], call[name[row]][constant[... | keyword[def] identifier[parse_200_row] ( identifier[row] : identifier[list] )-> identifier[NmiDetails] :
literal[string]
keyword[return] identifier[NmiDetails] ( identifier[row] [ literal[int] ], identifier[row] [ literal[int] ], identifier[row] [ literal[int] ], identifier[row] [ literal[int] ], identifi... | def parse_200_row(row: list) -> NmiDetails:
""" Parse NMI data details record (200) """
return NmiDetails(row[1], row[2], row[3], row[4], row[5], row[6], row[7], int(row[8]), parse_datetime(row[9])) |
def get_interpolation_function(self, times, data):
""" Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param data: One dimensional array of time series
:type data: numpy.array
:ret... | def function[get_interpolation_function, parameter[self, times, data]]:
constant[ Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param data: One dimensional array of time series
:type dat... | keyword[def] identifier[get_interpolation_function] ( identifier[self] , identifier[times] , identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[interpolation_object] ( identifier[times] , identifier[data] , identifier[axis] = literal[int] ,** identifier[self] . ident... | def get_interpolation_function(self, times, data):
""" Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param data: One dimensional array of time series
:type data: numpy.array
:return:... |
def get_context_menu(self):
"""
Gets the editor context menu.
:return: QMenu
"""
mnu = QtWidgets.QMenu()
mnu.addActions(self._actions)
mnu.addSeparator()
for menu in self._menus:
mnu.addMenu(menu)
return mnu | def function[get_context_menu, parameter[self]]:
constant[
Gets the editor context menu.
:return: QMenu
]
variable[mnu] assign[=] call[name[QtWidgets].QMenu, parameter[]]
call[name[mnu].addActions, parameter[name[self]._actions]]
call[name[mnu].addSeparator, para... | keyword[def] identifier[get_context_menu] ( identifier[self] ):
literal[string]
identifier[mnu] = identifier[QtWidgets] . identifier[QMenu] ()
identifier[mnu] . identifier[addActions] ( identifier[self] . identifier[_actions] )
identifier[mnu] . identifier[addSeparator] ()
... | def get_context_menu(self):
"""
Gets the editor context menu.
:return: QMenu
"""
mnu = QtWidgets.QMenu()
mnu.addActions(self._actions)
mnu.addSeparator()
for menu in self._menus:
mnu.addMenu(menu) # depends on [control=['for'], data=['menu']]
return mnu |
def get_options_menu(self):
"""Return options menu"""
env_action = create_action(
self,
_("Show environment variables"),
icon=ima.icon('environ'),
triggered=self.shellwidget.get_env
... | def function[get_options_menu, parameter[self]]:
constant[Return options menu]
variable[env_action] assign[=] call[name[create_action], parameter[name[self], call[name[_], parameter[constant[Show environment variables]]]]]
variable[syspath_action] assign[=] call[name[create_action], parameter[na... | keyword[def] identifier[get_options_menu] ( identifier[self] ):
literal[string]
identifier[env_action] = identifier[create_action] (
identifier[self] ,
identifier[_] ( literal[string] ),
identifier[icon] = identifier[ima] . identifier[icon] ( literal[string] ),
... | def get_options_menu(self):
"""Return options menu"""
env_action = create_action(self, _('Show environment variables'), icon=ima.icon('environ'), triggered=self.shellwidget.get_env)
syspath_action = create_action(self, _('Show sys.path contents'), icon=ima.icon('syspath'), triggered=self.shellwidget.get_sys... |
def download_sparse_points():
"""Used with ``download_saddle_surface``"""
saved_file, _ = _download_file('sparsePoints.txt')
points_reader = vtk.vtkDelimitedTextReader()
points_reader.SetFileName(saved_file)
points_reader.DetectNumericColumnsOn()
points_reader.SetFieldDelimiterCharacters('\t')
... | def function[download_sparse_points, parameter[]]:
constant[Used with ``download_saddle_surface``]
<ast.Tuple object at 0x7da18f58f1f0> assign[=] call[name[_download_file], parameter[constant[sparsePoints.txt]]]
variable[points_reader] assign[=] call[name[vtk].vtkDelimitedTextReader, parameter[]... | keyword[def] identifier[download_sparse_points] ():
literal[string]
identifier[saved_file] , identifier[_] = identifier[_download_file] ( literal[string] )
identifier[points_reader] = identifier[vtk] . identifier[vtkDelimitedTextReader] ()
identifier[points_reader] . identifier[SetFileName] ( ide... | def download_sparse_points():
"""Used with ``download_saddle_surface``"""
(saved_file, _) = _download_file('sparsePoints.txt')
points_reader = vtk.vtkDelimitedTextReader()
points_reader.SetFileName(saved_file)
points_reader.DetectNumericColumnsOn()
points_reader.SetFieldDelimiterCharacters('\t')... |
def ParseOptions(self, options):
"""Parses the options and initializes the front-end.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The data location is required to list signatures.
helpers_manager.ArgumentHel... | def function[ParseOptions, parameter[self, options]]:
constant[Parses the options and initializes the front-end.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
]
call[name[helpers_manager].ArgumentHelperManager.P... | keyword[def] identifier[ParseOptions] ( identifier[self] , identifier[options] ):
literal[string]
identifier[helpers_manager] . identifier[ArgumentHelperManager] . identifier[ParseOptions] (
identifier[options] , identifier[self] , identifier[names] =[ literal[string] ])
identifier[sig... | def ParseOptions(self, options):
"""Parses the options and initializes the front-end.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The data location is required to list signatures.
helpers_manager.ArgumentHel... |
def BC_0Displacement0Slope(self):
"""
0Displacement0Slope boundary condition for 0 deflection.
This requires that nothing be done to the edges of the solution array,
because the lack of the off-grid terms implies that they go to 0
Here we just turn the cells outside the array into nan, to ensu... | def function[BC_0Displacement0Slope, parameter[self]]:
constant[
0Displacement0Slope boundary condition for 0 deflection.
This requires that nothing be done to the edges of the solution array,
because the lack of the off-grid terms implies that they go to 0
Here we just turn the cells outside t... | keyword[def] identifier[BC_0Displacement0Slope] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[BC_W] == literal[string] :
identifier[i] = literal[int]
identifier[self] . identifier[l2] [ identifier[i] ]= identifier[np] . identifier[nan]
identifi... | def BC_0Displacement0Slope(self):
"""
0Displacement0Slope boundary condition for 0 deflection.
This requires that nothing be done to the edges of the solution array,
because the lack of the off-grid terms implies that they go to 0
Here we just turn the cells outside the array into nan, to ensure th... |
def _find_existing_instance(self):
"""
I find existing VMs that are already running that might be orphaned instances of this worker.
"""
if not self.connection:
return None
domains = yield self.connection.all()
for d in domains:
name = yield d.nam... | def function[_find_existing_instance, parameter[self]]:
constant[
I find existing VMs that are already running that might be orphaned instances of this worker.
]
if <ast.UnaryOp object at 0x7da18c4cdd50> begin[:]
return[constant[None]]
variable[domains] assign[=] <ast.Yie... | keyword[def] identifier[_find_existing_instance] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[connection] :
keyword[return] keyword[None]
identifier[domains] = keyword[yield] identifier[self] . identifier[connection] . iden... | def _find_existing_instance(self):
"""
I find existing VMs that are already running that might be orphaned instances of this worker.
"""
if not self.connection:
return None # depends on [control=['if'], data=[]]
domains = (yield self.connection.all())
for d in domains:
n... |
def _validate_oneof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'oneof'} """
valids, _errors = \
self.__validate_logical('oneof', definitions, field, value)
if valids != 1:
self._error(field, errors.ONEOF, _errors,
valids, len... | def function[_validate_oneof, parameter[self, definitions, field, value]]:
constant[ {'type': 'list', 'logical': 'oneof'} ]
<ast.Tuple object at 0x7da1b1de2cb0> assign[=] call[name[self].__validate_logical, parameter[constant[oneof], name[definitions], name[field], name[value]]]
if compare[name[... | keyword[def] identifier[_validate_oneof] ( identifier[self] , identifier[definitions] , identifier[field] , identifier[value] ):
literal[string]
identifier[valids] , identifier[_errors] = identifier[self] . identifier[__validate_logical] ( literal[string] , identifier[definitions] , identifier[fiel... | def _validate_oneof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'oneof'} """
(valids, _errors) = self.__validate_logical('oneof', definitions, field, value)
if valids != 1:
self._error(field, errors.ONEOF, _errors, valids, len(definitions)) # depends on [control=['if'], data=[... |
def p_else_part_label(p):
""" else_part : LABEL ELSE program_co endif
| LABEL ELSE statements_co endif
| LABEL ELSE co_statements_co endif
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = [make_block(lbl, p[3]), p[4]] | def function[p_else_part_label, parameter[p]]:
constant[ else_part : LABEL ELSE program_co endif
| LABEL ELSE statements_co endif
| LABEL ELSE co_statements_co endif
]
variable[lbl] assign[=] call[name[make_label], parameter[call[name[p]][constant[1]], call[name[p... | keyword[def] identifier[p_else_part_label] ( identifier[p] ):
literal[string]
identifier[lbl] = identifier[make_label] ( identifier[p] [ literal[int] ], identifier[p] . identifier[lineno] ( literal[int] ))
identifier[p] [ literal[int] ]=[ identifier[make_block] ( identifier[lbl] , identifier[p] [ lite... | def p_else_part_label(p):
""" else_part : LABEL ELSE program_co endif
| LABEL ELSE statements_co endif
| LABEL ELSE co_statements_co endif
"""
lbl = make_label(p[1], p.lineno(1))
p[0] = [make_block(lbl, p[3]), p[4]] |
def generate(self, tree):
'''
generates code based on templates and gen functions
defined in the <x> lang generator
'''
for middleware in DEFAULT_MIDDLEWARES + self.middlewares:
tree = middleware.process(tree) # changed in place!!
original = self._generate_nod... | def function[generate, parameter[self, tree]]:
constant[
generates code based on templates and gen functions
defined in the <x> lang generator
]
for taget[name[middleware]] in starred[binary_operation[name[DEFAULT_MIDDLEWARES] + name[self].middlewares]] begin[:]
v... | keyword[def] identifier[generate] ( identifier[self] , identifier[tree] ):
literal[string]
keyword[for] identifier[middleware] keyword[in] identifier[DEFAULT_MIDDLEWARES] + identifier[self] . identifier[middlewares] :
identifier[tree] = identifier[middleware] . identifier[process] (... | def generate(self, tree):
"""
generates code based on templates and gen functions
defined in the <x> lang generator
"""
for middleware in DEFAULT_MIDDLEWARES + self.middlewares:
tree = middleware.process(tree) # changed in place!! # depends on [control=['for'], data=['middlewar... |
def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data',
vectors=None, **kwargs):
"""Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... | def function[iters, parameter[cls, batch_size, bptt_len, device, root, vectors]]:
constant[Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
Arguments:
... | keyword[def] identifier[iters] ( identifier[cls] , identifier[batch_size] = literal[int] , identifier[bptt_len] = literal[int] , identifier[device] = literal[int] , identifier[root] = literal[string] ,
identifier[vectors] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[TEXT] =... | def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data', vectors=None, **kwargs):
"""Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
Arguments:
... |
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
v... | def function[volume_show, parameter[self, name]]:
constant[
Show one volume
]
if compare[name[self].volume_conn is constant[None]] begin[:]
<ast.Raise object at 0x7da1b21ee620>
variable[nt_ks] assign[=] name[self].volume_conn
variable[volumes] assign[=] call[name[... | keyword[def] identifier[volume_show] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[self] . identifier[volume_conn] keyword[is] keyword[None] :
keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] )
identifier[nt_ks] = identifie... | def volume_show(self, name):
"""
Show one volume
"""
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available') # depends on [control=['if'], data=[]]
nt_ks = self.volume_conn
volumes = self.volume_list(search_opts={'display_name': name})
volume =... |
def __yahoo_request(query):
"""Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL.
"""
query = quote(query)
url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + \
'&format=json&env=store://datatables.org... | def function[__yahoo_request, parameter[query]]:
constant[Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL.
]
variable[query] assign[=] call[name[quote], parameter[name[query]]]
variable[url] assign[=] binar... | keyword[def] identifier[__yahoo_request] ( identifier[query] ):
literal[string]
identifier[query] = identifier[quote] ( identifier[query] )
identifier[url] = literal[string] + identifier[query] + literal[string]
identifier[response] = identifier[urlopen] ( identifier[url] ). identifier[read] ()... | def __yahoo_request(query):
"""Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL.
"""
query = quote(query)
url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + '&format=json&env=store://datatables.org/alltables... |
def mark_clean(self, entity):
"""
Marks the given entity as CLEAN.
This is done when an entity is loaded fresh from the repository or
after a commit.
"""
state = EntityState.get_state(entity)
state.status = ENTITY_STATUS.CLEAN
state.is_persisted = True | def function[mark_clean, parameter[self, entity]]:
constant[
Marks the given entity as CLEAN.
This is done when an entity is loaded fresh from the repository or
after a commit.
]
variable[state] assign[=] call[name[EntityState].get_state, parameter[name[entity]]]
... | keyword[def] identifier[mark_clean] ( identifier[self] , identifier[entity] ):
literal[string]
identifier[state] = identifier[EntityState] . identifier[get_state] ( identifier[entity] )
identifier[state] . identifier[status] = identifier[ENTITY_STATUS] . identifier[CLEAN]
identif... | def mark_clean(self, entity):
"""
Marks the given entity as CLEAN.
This is done when an entity is loaded fresh from the repository or
after a commit.
"""
state = EntityState.get_state(entity)
state.status = ENTITY_STATUS.CLEAN
state.is_persisted = True |
def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, prediction.shape[-1])... | def function[neg_log_perplexity, parameter[batch, model_predictions]]:
constant[Calculate negative log perplexity.]
<ast.Tuple object at 0x7da1b20e54b0> assign[=] name[batch]
<ast.Tuple object at 0x7da1b20e6d70> assign[=] call[name[_make_list], parameter[name[model_predictions], name[targets]]]
... | keyword[def] identifier[neg_log_perplexity] ( identifier[batch] , identifier[model_predictions] ):
literal[string]
identifier[_] , identifier[targets] = identifier[batch]
identifier[model_predictions] , identifier[targets] = identifier[_make_list] ( identifier[model_predictions] , identifier[targets] )
... | def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
(_, targets) = batch
(model_predictions, targets) = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, pre... |
def set_workflow_by_name(self, workflow_name):
"""Configure the workflow to run by the name of this one.
Allows the modification of the workflow that the engine will run
by looking in the registry the name passed in parameter.
:param workflow_name: name of the workflow.
:type w... | def function[set_workflow_by_name, parameter[self, workflow_name]]:
constant[Configure the workflow to run by the name of this one.
Allows the modification of the workflow that the engine will run
by looking in the registry the name passed in parameter.
:param workflow_name: name of th... | keyword[def] identifier[set_workflow_by_name] ( identifier[self] , identifier[workflow_name] ):
literal[string]
keyword[from] . identifier[proxies] keyword[import] identifier[workflows]
keyword[if] identifier[workflow_name] keyword[not] keyword[in] identifier[workflows] :
... | def set_workflow_by_name(self, workflow_name):
"""Configure the workflow to run by the name of this one.
Allows the modification of the workflow that the engine will run
by looking in the registry the name passed in parameter.
:param workflow_name: name of the workflow.
:type workf... |
def _recursive_update(d1, d2):
""" Little helper function that does what d1.update(d2) does,
but works nice and recursively with dicts of dicts of dicts.
It's not necessarily very efficient.
"""
for k in set(d1).intersection(d2):
if isinstance(d1[k], dict) and isinstance(d2[k], dict):
... | def function[_recursive_update, parameter[d1, d2]]:
constant[ Little helper function that does what d1.update(d2) does,
but works nice and recursively with dicts of dicts of dicts.
It's not necessarily very efficient.
]
for taget[name[k]] in starred[call[call[name[set], parameter[name[d1]]]... | keyword[def] identifier[_recursive_update] ( identifier[d1] , identifier[d2] ):
literal[string]
keyword[for] identifier[k] keyword[in] identifier[set] ( identifier[d1] ). identifier[intersection] ( identifier[d2] ):
keyword[if] identifier[isinstance] ( identifier[d1] [ identifier[k] ], identi... | def _recursive_update(d1, d2):
""" Little helper function that does what d1.update(d2) does,
but works nice and recursively with dicts of dicts of dicts.
It's not necessarily very efficient.
"""
for k in set(d1).intersection(d2):
if isinstance(d1[k], dict) and isinstance(d2[k], dict):
... |
def mine_patterns(self, threshold):
"""
Mine the constructed FP tree for frequent patterns.
"""
if self.tree_has_single_path(self.root):
return self.generate_pattern_list()
else:
return self.zip_patterns(self.mine_sub_trees(threshold)) | def function[mine_patterns, parameter[self, threshold]]:
constant[
Mine the constructed FP tree for frequent patterns.
]
if call[name[self].tree_has_single_path, parameter[name[self].root]] begin[:]
return[call[name[self].generate_pattern_list, parameter[]]] | keyword[def] identifier[mine_patterns] ( identifier[self] , identifier[threshold] ):
literal[string]
keyword[if] identifier[self] . identifier[tree_has_single_path] ( identifier[self] . identifier[root] ):
keyword[return] identifier[self] . identifier[generate_pattern_list] ()
... | def mine_patterns(self, threshold):
"""
Mine the constructed FP tree for frequent patterns.
"""
if self.tree_has_single_path(self.root):
return self.generate_pattern_list() # depends on [control=['if'], data=[]]
else:
return self.zip_patterns(self.mine_sub_trees(threshold)) |
def list(self, full_properties=True, filter_args=None):
"""
List the (one) :term:`Console` representing the HMC this client is
connected to.
Authorization requirements:
* None
Parameters:
full_properties (bool):
Controls whether the full set of r... | def function[list, parameter[self, full_properties, filter_args]]:
constant[
List the (one) :term:`Console` representing the HMC this client is
connected to.
Authorization requirements:
* None
Parameters:
full_properties (bool):
Controls whether ... | keyword[def] identifier[list] ( identifier[self] , identifier[full_properties] = keyword[True] , identifier[filter_args] = keyword[None] ):
literal[string]
identifier[uri] = identifier[self] . identifier[_base_uri]
keyword[if] identifier[full_properties] :
identifier[props] ... | def list(self, full_properties=True, filter_args=None):
"""
List the (one) :term:`Console` representing the HMC this client is
connected to.
Authorization requirements:
* None
Parameters:
full_properties (bool):
Controls whether the full set of resou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.