code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _as_graph_element(self):
"""Returns the underlying graph element if possible."""
if self.is_sequence():
raise TypeError('A Pretty Tensor that holds a sequence cannot be '
'represented as a graph element.')
else:
# Self might be holding something else that isn't a true t... | def function[_as_graph_element, parameter[self]]:
constant[Returns the underlying graph element if possible.]
if call[name[self].is_sequence, parameter[]] begin[:]
<ast.Raise object at 0x7da20c7c9c00> | keyword[def] identifier[_as_graph_element] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_sequence] ():
keyword[raise] identifier[TypeError] ( literal[string]
literal[string] )
keyword[else] :
identifier[obj] = identifier[... | def _as_graph_element(self):
"""Returns the underlying graph element if possible."""
if self.is_sequence():
raise TypeError('A Pretty Tensor that holds a sequence cannot be represented as a graph element.') # depends on [control=['if'], data=[]]
else:
# Self might be holding something else ... |
def get_name(obj, setting_name='LONG_NAME_FORMAT'):
"""
Returns the correct order of the name according to the current language.
"""
nickname = obj.get_nickname()
romanized_first_name = obj.get_romanized_first_name()
romanized_last_name = obj.get_romanized_last_name()
non_romanized_first_na... | def function[get_name, parameter[obj, setting_name]]:
constant[
Returns the correct order of the name according to the current language.
]
variable[nickname] assign[=] call[name[obj].get_nickname, parameter[]]
variable[romanized_first_name] assign[=] call[name[obj].get_romanized_first_n... | keyword[def] identifier[get_name] ( identifier[obj] , identifier[setting_name] = literal[string] ):
literal[string]
identifier[nickname] = identifier[obj] . identifier[get_nickname] ()
identifier[romanized_first_name] = identifier[obj] . identifier[get_romanized_first_name] ()
identifier[romanize... | def get_name(obj, setting_name='LONG_NAME_FORMAT'):
"""
Returns the correct order of the name according to the current language.
"""
nickname = obj.get_nickname()
romanized_first_name = obj.get_romanized_first_name()
romanized_last_name = obj.get_romanized_last_name()
non_romanized_first_na... |
def add(self, name, session, pict_url=None, parent_cid=None, sort_order=None):
'''taobao.sellercats.list.add 添加卖家自定义类目
此API添加卖家店铺内自定义类目 父类目parent_cid值等于0:表示此类目为店铺下的一级类目,值不等于0:表示此类目有父类目 注:因为缓存的关系,添加的新类目需8个小时后才可以在淘宝页面上正常显示,但是不影响在该类目下商品发布'''
request = TOPRequest('taobao.sellercats.list.add... | def function[add, parameter[self, name, session, pict_url, parent_cid, sort_order]]:
constant[taobao.sellercats.list.add 添加卖家自定义类目
此API添加卖家店铺内自定义类目 父类目parent_cid值等于0:表示此类目为店铺下的一级类目,值不等于0:表示此类目有父类目 注:因为缓存的关系,添加的新类目需8个小时后才可以在淘宝页面上正常显示,但是不影响在该类目下商品发布]
variable[request] assign[=] call[name[... | keyword[def] identifier[add] ( identifier[self] , identifier[name] , identifier[session] , identifier[pict_url] = keyword[None] , identifier[parent_cid] = keyword[None] , identifier[sort_order] = keyword[None] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
... | def add(self, name, session, pict_url=None, parent_cid=None, sort_order=None):
"""taobao.sellercats.list.add 添加卖家自定义类目
此API添加卖家店铺内自定义类目 父类目parent_cid值等于0:表示此类目为店铺下的一级类目,值不等于0:表示此类目有父类目 注:因为缓存的关系,添加的新类目需8个小时后才可以在淘宝页面上正常显示,但是不影响在该类目下商品发布"""
request = TOPRequest('taobao.sellercats.list.add')
r... |
def uninitialize(cls) -> None:
"""Removes the ``SIGCHLD`` handler."""
if not cls._initialized:
return
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False | def function[uninitialize, parameter[cls]]:
constant[Removes the ``SIGCHLD`` handler.]
if <ast.UnaryOp object at 0x7da1b20ca7a0> begin[:]
return[None]
call[name[signal].signal, parameter[name[signal].SIGCHLD, name[cls]._old_sigchld]]
name[cls]._initialized assign[=] constant[Fals... | keyword[def] identifier[uninitialize] ( identifier[cls] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[cls] . identifier[_initialized] :
keyword[return]
identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGCHLD] , identifier[... | def uninitialize(cls) -> None:
"""Removes the ``SIGCHLD`` handler."""
if not cls._initialized:
return # depends on [control=['if'], data=[]]
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False |
def auth_traps_enabled(name, status=True):
'''
Manage the sending of authentication traps.
:param bool status: The enabled status.
Example of usage:
.. code-block:: yaml
snmp-auth-traps:
win_snmp.auth_traps_enabled:
- status: True
'''
ret = {'name': na... | def function[auth_traps_enabled, parameter[name, status]]:
constant[
Manage the sending of authentication traps.
:param bool status: The enabled status.
Example of usage:
.. code-block:: yaml
snmp-auth-traps:
win_snmp.auth_traps_enabled:
- status: True
... | keyword[def] identifier[auth_traps_enabled] ( identifier[name] , identifier[status] = keyword[True] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : identifier[six] . identifier[text_type] (),
literal[string] : keyword[None] }
... | def auth_traps_enabled(name, status=True):
"""
Manage the sending of authentication traps.
:param bool status: The enabled status.
Example of usage:
.. code-block:: yaml
snmp-auth-traps:
win_snmp.auth_traps_enabled:
- status: True
"""
ret = {'name': na... |
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
r"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of ... | def function[site_data_dir, parameter[appname, appauthor, version, multipath]]:
constant[Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the... | keyword[def] identifier[site_data_dir] ( identifier[appname] = keyword[None] , identifier[appauthor] = keyword[None] , identifier[version] = keyword[None] , identifier[multipath] = keyword[False] ):
literal[string]
keyword[if] identifier[system] == literal[string] :
keyword[if] identifier[appaut... | def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of t... |
def _set_access_log(self, config, level):
""" Configure access logs
"""
access_handler = self._get_param(
'global',
'log.access_handler',
config,
'syslog',
)
# log format for syslog
syslog_formatter = logging.Formatter(... | def function[_set_access_log, parameter[self, config, level]]:
constant[ Configure access logs
]
variable[access_handler] assign[=] call[name[self]._get_param, parameter[constant[global], constant[log.access_handler], name[config], constant[syslog]]]
variable[syslog_formatter] assign[=] ... | keyword[def] identifier[_set_access_log] ( identifier[self] , identifier[config] , identifier[level] ):
literal[string]
identifier[access_handler] = identifier[self] . identifier[_get_param] (
literal[string] ,
literal[string] ,
identifier[config] ,
literal[strin... | def _set_access_log(self, config, level):
""" Configure access logs
"""
access_handler = self._get_param('global', 'log.access_handler', config, 'syslog')
# log format for syslog
syslog_formatter = logging.Formatter('ldapcherry[%(process)d]: %(message)s')
# replace access log handler by a sy... |
def create_xml_file_from_string(self, content, destination=None):
"""
Creates XML file from text.
:param content: C++ source code
:type content: str
:param destination: file name for xml file
:type destination: str
:rtype: returns file name of xml file
... | def function[create_xml_file_from_string, parameter[self, content, destination]]:
constant[
Creates XML file from text.
:param content: C++ source code
:type content: str
:param destination: file name for xml file
:type destination: str
:rtype: returns file nam... | keyword[def] identifier[create_xml_file_from_string] ( identifier[self] , identifier[content] , identifier[destination] = keyword[None] ):
literal[string]
identifier[header_file] = identifier[utils] . identifier[create_temp_file_name] ( identifier[suffix] = literal[string] )
keyword[try] ... | def create_xml_file_from_string(self, content, destination=None):
"""
Creates XML file from text.
:param content: C++ source code
:type content: str
:param destination: file name for xml file
:type destination: str
:rtype: returns file name of xml file
"""
... |
def update_from_dict(self, d):
"""
Apply options from a serialized body to the current instance. Modifies
the object in-place. Used mostly by ``from_dict``.
"""
d = d.copy()
if 'query' in d:
self.query._proxied = Q(d.pop('query'))
if 'post_filter' in d... | def function[update_from_dict, parameter[self, d]]:
constant[
Apply options from a serialized body to the current instance. Modifies
the object in-place. Used mostly by ``from_dict``.
]
variable[d] assign[=] call[name[d].copy, parameter[]]
if compare[constant[query] in na... | keyword[def] identifier[update_from_dict] ( identifier[self] , identifier[d] ):
literal[string]
identifier[d] = identifier[d] . identifier[copy] ()
keyword[if] literal[string] keyword[in] identifier[d] :
identifier[self] . identifier[query] . identifier[_proxied] = identifi... | def update_from_dict(self, d):
"""
Apply options from a serialized body to the current instance. Modifies
the object in-place. Used mostly by ``from_dict``.
"""
d = d.copy()
if 'query' in d:
self.query._proxied = Q(d.pop('query')) # depends on [control=['if'], data=['d']]
... |
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method')
if not cls._pool:
cls._pool = yield from create_pool(**c... | def function[get_pool, parameter[cls]]:
constant[
Yields:
existing db connection pool
]
if compare[call[name[len], parameter[name[cls]._connection_params]] less[<] constant[5]] begin[:]
<ast.Raise object at 0x7da1b00364d0>
if <ast.UnaryOp object at 0x7da1b0035... | keyword[def] identifier[get_pool] ( identifier[cls] )-> identifier[Pool] :
literal[string]
keyword[if] identifier[len] ( identifier[cls] . identifier[_connection_params] )< literal[int] :
keyword[raise] identifier[ConnectionError] ( literal[string] )
keyword[if] keyword[not... | def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method') # depends on [control=['if'], data=[]]
if not cls._pool:
cls._pool = (yield... |
def add_evaluation_step(result_tensor, ground_truth_tensor):
"""Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation step,... | def function[add_evaluation_step, parameter[result_tensor, ground_truth_tensor]]:
constant[Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Return... | keyword[def] identifier[add_evaluation_step] ( identifier[result_tensor] , identifier[ground_truth_tensor] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[prediction... | def add_evaluation_step(result_tensor, ground_truth_tensor):
"""Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation ste... |
def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False):
"""Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format.""... | def function[get_full_page_box_list_assigning_media_and_crop, parameter[input_doc, quiet]]:
constant[Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not ... | keyword[def] identifier[get_full_page_box_list_assigning_media_and_crop] ( identifier[input_doc] , identifier[quiet] = keyword[False] ):
literal[string]
identifier[full_page_box_list] =[]
identifier[rotation_list] =[]
keyword[if] identifier[args] . identifier[verbose] keyword[and] keyword[no... | def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False):
"""Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format.""... |
def token(function):
"""Attach a CSRF token for POST requests."""
def wrapped(session, *args):
"""Wrap function."""
resp = session.get(TOKEN_URL).json()
session.headers.update({'mopar-csrf-salt': resp['token']})
return function(session, *args)
return wrapped | def function[token, parameter[function]]:
constant[Attach a CSRF token for POST requests.]
def function[wrapped, parameter[session]]:
constant[Wrap function.]
variable[resp] assign[=] call[call[name[session].get, parameter[name[TOKEN_URL]]].json, parameter[]]
... | keyword[def] identifier[token] ( identifier[function] ):
literal[string]
keyword[def] identifier[wrapped] ( identifier[session] ,* identifier[args] ):
literal[string]
identifier[resp] = identifier[session] . identifier[get] ( identifier[TOKEN_URL] ). identifier[json] ()
identif... | def token(function):
"""Attach a CSRF token for POST requests."""
def wrapped(session, *args):
"""Wrap function."""
resp = session.get(TOKEN_URL).json()
session.headers.update({'mopar-csrf-salt': resp['token']})
return function(session, *args)
return wrapped |
def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None,
auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON,
line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep... | def function[PopupNonBlocking, parameter[]]:
constant[
Show Popup box and immediately return (does not block)
:param args:
:param button_type:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
... | keyword[def] identifier[PopupNonBlocking] (* identifier[args] , identifier[button_type] = identifier[POPUP_BUTTONS_OK] , identifier[button_color] = keyword[None] , identifier[background_color] = keyword[None] , identifier[text_color] = keyword[None] ,
identifier[auto_close] = keyword[False] , identifier[auto_close_d... | def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None)):
... |
def get_embeddings(self, rand=None, dtype='float32', corpus='common_crawl_48', n_dim=300):
"""
Retrieves the embeddings for the vocabulary.
:param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`.
:param dtype: Type... | def function[get_embeddings, parameter[self, rand, dtype, corpus, n_dim]]:
constant[
Retrieves the embeddings for the vocabulary.
:param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`.
:param dtype: Type of the ma... | keyword[def] identifier[get_embeddings] ( identifier[self] , identifier[rand] = keyword[None] , identifier[dtype] = literal[string] , identifier[corpus] = literal[string] , identifier[n_dim] = literal[int] ):
literal[string]
keyword[assert] identifier[corpus] keyword[in] identifier[self] . ident... | def get_embeddings(self, rand=None, dtype='float32', corpus='common_crawl_48', n_dim=300):
"""
Retrieves the embeddings for the vocabulary.
:param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`.
:param dtype: Type of ... |
def gen_radio_edit(sig_dic):
'''
editing for HTML radio control.
'''
edit_zuoxiang = '''7
<label for="{0}"><span>
<a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;">
</a>{1}</span>
'''.format(sig_dic['en'], sig_dic['zh'])
dic_tmp = sig_dic['dic']
for ke... | def function[gen_radio_edit, parameter[sig_dic]]:
constant[
editing for HTML radio control.
]
variable[edit_zuoxiang] assign[=] call[constant[7
<label for="{0}"><span>
<a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;">
</a>{1}</span>
].format, parameter... | keyword[def] identifier[gen_radio_edit] ( identifier[sig_dic] ):
literal[string]
identifier[edit_zuoxiang] = literal[string] . identifier[format] ( identifier[sig_dic] [ literal[string] ], identifier[sig_dic] [ literal[string] ])
identifier[dic_tmp] = identifier[sig_dic] [ literal[string] ]
keyw... | def gen_radio_edit(sig_dic):
"""
editing for HTML radio control.
"""
edit_zuoxiang = '7\n <label for="{0}"><span>\n <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;">\n </a>{1}</span>\n '.format(sig_dic['en'], sig_dic['zh'])
dic_tmp = sig_dic['dic']
for key... |
def needs_low_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.LOW_PRIORITY:
self.parser_error("needs low priority set") | def function[needs_low_priority, parameter[self, priority]]:
constant[
:return: None
]
assert[call[name[isinstance], parameter[name[priority], name[int]]]]
if compare[name[priority] not_equal[!=] name[velbus].LOW_PRIORITY] begin[:]
call[name[self].parser_error, parame... | keyword[def] identifier[needs_low_priority] ( identifier[self] , identifier[priority] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[priority] , identifier[int] )
keyword[if] identifier[priority] != identifier[velbus] . identifier[LOW_PRIORITY] :
... | def needs_low_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.LOW_PRIORITY:
self.parser_error('needs low priority set') # depends on [control=['if'], data=[]] |
def get_variable_and_source(x: str):
""" Process the variable name to make it more human-readable. """
xs = x.replace("\/", "|").split("/")
xs = [x.replace("|", "/") for x in xs]
if xs[0] == "FAO":
return " ".join(xs[2:]), xs[0]
else:
return xs[-1], xs[0] | def function[get_variable_and_source, parameter[x]]:
constant[ Process the variable name to make it more human-readable. ]
variable[xs] assign[=] call[call[name[x].replace, parameter[constant[\/], constant[|]]].split, parameter[constant[/]]]
variable[xs] assign[=] <ast.ListComp object at 0x7da1b... | keyword[def] identifier[get_variable_and_source] ( identifier[x] : identifier[str] ):
literal[string]
identifier[xs] = identifier[x] . identifier[replace] ( literal[string] , literal[string] ). identifier[split] ( literal[string] )
identifier[xs] =[ identifier[x] . identifier[replace] ( literal[string... | def get_variable_and_source(x: str):
""" Process the variable name to make it more human-readable. """
xs = x.replace('\\/', '|').split('/')
xs = [x.replace('|', '/') for x in xs]
if xs[0] == 'FAO':
return (' '.join(xs[2:]), xs[0]) # depends on [control=['if'], data=[]]
else:
return... |
def import_txt(filename, **kwargs):
"""Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as... | def function[import_txt, parameter[filename]]:
constant[Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-po... | keyword[def] identifier[import_txt] ( identifier[filename] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[fid] :
identifier[text] = identifier[fid] . identifier[read] ()
identifier[strings_to_re... | def import_txt(filename, **kwargs):
"""Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as... |
def nla_len(self, value):
"""Length setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_uint16(value or 0)) | def function[nla_len, parameter[self, value]]:
constant[Length setter.]
call[name[self].bytearray][call[name[self]._get_slicers, parameter[constant[0]]]] assign[=] call[name[bytearray], parameter[call[name[c_uint16], parameter[<ast.BoolOp object at 0x7da1b28f0160>]]]] | keyword[def] identifier[nla_len] ( identifier[self] , identifier[value] ):
literal[string]
identifier[self] . identifier[bytearray] [ identifier[self] . identifier[_get_slicers] ( literal[int] )]= identifier[bytearray] ( identifier[c_uint16] ( identifier[value] keyword[or] literal[int] )) | def nla_len(self, value):
"""Length setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_uint16(value or 0)) |
def date_to_datetime_tz(
cr, table_name, user_field_name, date_field_name, datetime_field_name):
""" Take the related user's timezone into account when converting
date field to datetime in a given table.
This function must be call in post migration script.
:param table_name : Name of the table ... | def function[date_to_datetime_tz, parameter[cr, table_name, user_field_name, date_field_name, datetime_field_name]]:
constant[ Take the related user's timezone into account when converting
date field to datetime in a given table.
This function must be call in post migration script.
:param table_nam... | keyword[def] identifier[date_to_datetime_tz] (
identifier[cr] , identifier[table_name] , identifier[user_field_name] , identifier[date_field_name] , identifier[datetime_field_name] ):
literal[string]
identifier[cr] . identifier[execute] (
literal[string] %( identifier[table_name] , identifier[user_fi... | def date_to_datetime_tz(cr, table_name, user_field_name, date_field_name, datetime_field_name):
""" Take the related user's timezone into account when converting
date field to datetime in a given table.
This function must be call in post migration script.
:param table_name : Name of the table where the... |
def _parse_single(self, text, tagname):
"""
A hack to get the content of the XML responses from the CAS server.
## Arguments
* `text` (str): The XML string to parse.
* `tagname` (str): The tag that contains the info that we want.
## Returns
* `content` (str): ... | def function[_parse_single, parameter[self, text, tagname]]:
constant[
A hack to get the content of the XML responses from the CAS server.
## Arguments
* `text` (str): The XML string to parse.
* `tagname` (str): The tag that contains the info that we want.
## Returns
... | keyword[def] identifier[_parse_single] ( identifier[self] , identifier[text] , identifier[tagname] ):
literal[string]
keyword[return] identifier[minidom] . identifier[parseString] ( identifier[text] ). identifier[getElementsByTagName] ( identifier[tagname] )[ literal[int] ]. identifier[firstChild]... | def _parse_single(self, text, tagname):
"""
A hack to get the content of the XML responses from the CAS server.
## Arguments
* `text` (str): The XML string to parse.
* `tagname` (str): The tag that contains the info that we want.
## Returns
* `content` (str): The ... |
def create(self, subscription_id, name, parameters, type='analysis', service='facebook'):
""" Create a PYLON task
:param subscription_id: The ID of the recording to create the task for
:type subscription_id: str
:param name: The name of the new task
:type name: s... | def function[create, parameter[self, subscription_id, name, parameters, type, service]]:
constant[ Create a PYLON task
:param subscription_id: The ID of the recording to create the task for
:type subscription_id: str
:param name: The name of the new task
:type na... | keyword[def] identifier[create] ( identifier[self] , identifier[subscription_id] , identifier[name] , identifier[parameters] , identifier[type] = literal[string] , identifier[service] = literal[string] ):
literal[string]
identifier[params] ={
literal[string] : identifier[subscription_id] ... | def create(self, subscription_id, name, parameters, type='analysis', service='facebook'):
""" Create a PYLON task
:param subscription_id: The ID of the recording to create the task for
:type subscription_id: str
:param name: The name of the new task
:type name: str
... |
def _validate(self):
"""
Ensure that our expression string has variables of the form x_0, x_1,
... x_(N - 1), where N is the length of our inputs.
"""
variable_names, _unused = getExprNames(self._expr, {})
expr_indices = []
for name in variable_names:
... | def function[_validate, parameter[self]]:
constant[
Ensure that our expression string has variables of the form x_0, x_1,
... x_(N - 1), where N is the length of our inputs.
]
<ast.Tuple object at 0x7da18bc72fe0> assign[=] call[name[getExprNames], parameter[name[self]._expr, dict... | keyword[def] identifier[_validate] ( identifier[self] ):
literal[string]
identifier[variable_names] , identifier[_unused] = identifier[getExprNames] ( identifier[self] . identifier[_expr] ,{})
identifier[expr_indices] =[]
keyword[for] identifier[name] keyword[in] identifier[var... | def _validate(self):
"""
Ensure that our expression string has variables of the form x_0, x_1,
... x_(N - 1), where N is the length of our inputs.
"""
(variable_names, _unused) = getExprNames(self._expr, {})
expr_indices = []
for name in variable_names:
if name == 'inf':
... |
def kill_conditional_comments(self, doc):
"""
IE conditional comments basically embed HTML that the parser
doesn't normally see. We can't allow anything like that, so
we'll kill any comments that could be conditional.
"""
bad = []
self._kill_elements(
... | def function[kill_conditional_comments, parameter[self, doc]]:
constant[
IE conditional comments basically embed HTML that the parser
doesn't normally see. We can't allow anything like that, so
we'll kill any comments that could be conditional.
]
variable[bad] assign[=] ... | keyword[def] identifier[kill_conditional_comments] ( identifier[self] , identifier[doc] ):
literal[string]
identifier[bad] =[]
identifier[self] . identifier[_kill_elements] (
identifier[doc] , keyword[lambda] identifier[el] : identifier[_conditional_comment_re] . identifier[searc... | def kill_conditional_comments(self, doc):
"""
IE conditional comments basically embed HTML that the parser
doesn't normally see. We can't allow anything like that, so
we'll kill any comments that could be conditional.
"""
bad = []
self._kill_elements(doc, lambda el: _conditi... |
def _init_solc_binary(version):
"""Figure out solc binary and version.
Only proper versions are supported. No nightlies, commits etc (such as available in remix).
"""
if not version:
return os.environ.get("SOLC") or "solc"
# tried converting input to semver, seemed... | def function[_init_solc_binary, parameter[version]]:
constant[Figure out solc binary and version.
Only proper versions are supported. No nightlies, commits etc (such as available in remix).
]
if <ast.UnaryOp object at 0x7da1b1dde530> begin[:]
return[<ast.BoolOp object at 0x7da1b... | keyword[def] identifier[_init_solc_binary] ( identifier[version] ):
literal[string]
keyword[if] keyword[not] identifier[version] :
keyword[return] identifier[os] . identifier[environ] . identifier[get] ( literal[string] ) keyword[or] literal[string]
identif... | def _init_solc_binary(version):
"""Figure out solc binary and version.
Only proper versions are supported. No nightlies, commits etc (such as available in remix).
"""
if not version:
return os.environ.get('SOLC') or 'solc' # depends on [control=['if'], data=[]]
# tried converting i... |
def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first ... | def function[evaluate_model, parameter[filepath, train_start, train_end, test_start, test_end, batch_size, testing, num_threads]]:
constant[
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first training set example
:param train_end: index of last ... | keyword[def] identifier[evaluate_model] ( identifier[filepath] ,
identifier[train_start] = literal[int] , identifier[train_end] = literal[int] , identifier[test_start] = literal[int] ,
identifier[test_end] = literal[int] , identifier[batch_size] = literal[int] ,
identifier[testing] = keyword[False] , identifier[nu... | def evaluate_model(filepath, train_start=0, train_end=60000, test_start=0, test_end=10000, batch_size=128, testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first training set example
:param train_end: index of last ... |
def create(cls, account_id, resource_id, action, timestamp, metrics):
""" Set properties for an enforcement action"""
enforcement = Enforcements()
enforcement.account_id = account_id
enforcement.resource_id = resource_id
enforcement.action = action
enforcement.timestamp ... | def function[create, parameter[cls, account_id, resource_id, action, timestamp, metrics]]:
constant[ Set properties for an enforcement action]
variable[enforcement] assign[=] call[name[Enforcements], parameter[]]
name[enforcement].account_id assign[=] name[account_id]
name[enforcement].r... | keyword[def] identifier[create] ( identifier[cls] , identifier[account_id] , identifier[resource_id] , identifier[action] , identifier[timestamp] , identifier[metrics] ):
literal[string]
identifier[enforcement] = identifier[Enforcements] ()
identifier[enforcement] . identifier[account_id]... | def create(cls, account_id, resource_id, action, timestamp, metrics):
""" Set properties for an enforcement action"""
enforcement = Enforcements()
enforcement.account_id = account_id
enforcement.resource_id = resource_id
enforcement.action = action
enforcement.timestamp = timestamp
enforceme... |
def _update_from_database(self):
"""Updates map to latest state in database.
Should be called prior to major object events to assure that an
assessment being taken on multiple devices are reasonably synchronized.
"""
collection = JSONClientValidated('assessment',
... | def function[_update_from_database, parameter[self]]:
constant[Updates map to latest state in database.
Should be called prior to major object events to assure that an
assessment being taken on multiple devices are reasonably synchronized.
]
variable[collection] assign[=] call[... | keyword[def] identifier[_update_from_database] ( identifier[self] ):
literal[string]
identifier[collection] = identifier[JSONClientValidated] ( literal[string] ,
identifier[collection] = literal[string] ,
identifier[runtime] = identifier[self] . identifier[_runtime] )
ide... | def _update_from_database(self):
"""Updates map to latest state in database.
Should be called prior to major object events to assure that an
assessment being taken on multiple devices are reasonably synchronized.
"""
collection = JSONClientValidated('assessment', collection='Assessment... |
def layout(args):
"""
%prog layout query.subject.simple query.seqids subject.seqids
Compute optimal seqids order in a second genome, based on seqids on one
genome, given the pairwise blocks in .simple format.
"""
from jcvi.algorithms.ec import GA_setup, GA_run
p = OptionParser(layout.__doc... | def function[layout, parameter[args]]:
constant[
%prog layout query.subject.simple query.seqids subject.seqids
Compute optimal seqids order in a second genome, based on seqids on one
genome, given the pairwise blocks in .simple format.
]
from relative_module[jcvi.algorithms.ec] import modul... | keyword[def] identifier[layout] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[algorithms] . identifier[ec] keyword[import] identifier[GA_setup] , identifier[GA_run]
identifier[p] = identifier[OptionParser] ( identifier[layout] . identifier[__doc__] )
ident... | def layout(args):
"""
%prog layout query.subject.simple query.seqids subject.seqids
Compute optimal seqids order in a second genome, based on seqids on one
genome, given the pairwise blocks in .simple format.
"""
from jcvi.algorithms.ec import GA_setup, GA_run
p = OptionParser(layout.__doc_... |
def prepare(self, strict=True):
""" preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
"""
self.__root = self.prepare_obj(self.raw, self.__url)
self.validate(strict=strict)
if hasattr(self.__root, 'schemes') and... | def function[prepare, parameter[self, strict]]:
constant[ preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
]
name[self].__root assign[=] call[name[self].prepare_obj, parameter[name[self].raw, name[self].__url]]
call[nam... | keyword[def] identifier[prepare] ( identifier[self] , identifier[strict] = keyword[True] ):
literal[string]
identifier[self] . identifier[__root] = identifier[self] . identifier[prepare_obj] ( identifier[self] . identifier[raw] , identifier[self] . identifier[__url] )
identifier[self] . i... | def prepare(self, strict=True):
""" preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
"""
self.__root = self.prepare_obj(self.raw, self.__url)
self.validate(strict=strict)
if hasattr(self.__root, 'schemes') and self.__root.schem... |
def muteThreadMentions(self, mute=True, thread_id=None):
"""
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
... | def function[muteThreadMentions, parameter[self, mute, thread_id]]:
constant[
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
]
<ast.Tuple object at 0x7da1b188d4b0> assign[=] call... | keyword[def] identifier[muteThreadMentions] ( identifier[self] , identifier[mute] = keyword[True] , identifier[thread_id] = keyword[None] ):
literal[string]
identifier[thread_id] , identifier[thread_type] = identifier[self] . identifier[_getThread] ( identifier[thread_id] , keyword[None] )
... | def muteThreadMentions(self, mute=True, thread_id=None):
"""
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
(thread_id, thread_type) = self._getThread(thread_id, None)
data = {'m... |
def add_node(self, node_id, name, labels):
"""Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported.
"""
... | def function[add_node, parameter[self, node_id, name, labels]]:
constant[Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is no... | keyword[def] identifier[add_node] ( identifier[self] , identifier[node_id] , identifier[name] , identifier[labels] ):
literal[string]
identifier[node] = identifier[self] . identifier[graph_db] . identifier[get_or_create_indexed_node] ( literal[string] , literal[string] , identifier[node_id] ,{ lite... | def add_node(self, node_id, name, labels):
"""Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported.
"""
no... |
def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.do... | def function[_get_lattice_parameters, parameter[lattice]]:
constant[Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
]
r... | keyword[def] identifier[_get_lattice_parameters] ( identifier[lattice] ):
literal[string]
keyword[return] identifier[np] . identifier[array] ( identifier[np] . identifier[sqrt] ( identifier[np] . identifier[dot] ( identifier[lattice] . identifier[T] , identifier[lattice] ). identifier[diagonal] ()),
... | def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.dot... |
def scale_pixels(color, layer):
"""Scales the pixel to the virtual pixelmap."""
pixelmap = []
# Scaling the pixel offsets.
for pix_x in range(MAX_X + 1):
for pix_y in range(MAX_Y + 1):
# Horizontal pixels
y1 = pix_y * dotsize[0]
x1 = pix_x * dotsize[1]
... | def function[scale_pixels, parameter[color, layer]]:
constant[Scales the pixel to the virtual pixelmap.]
variable[pixelmap] assign[=] list[[]]
for taget[name[pix_x]] in starred[call[name[range], parameter[binary_operation[name[MAX_X] + constant[1]]]]] begin[:]
for taget[name[pix_... | keyword[def] identifier[scale_pixels] ( identifier[color] , identifier[layer] ):
literal[string]
identifier[pixelmap] =[]
keyword[for] identifier[pix_x] keyword[in] identifier[range] ( identifier[MAX_X] + literal[int] ):
keyword[for] identifier[pix_y] keyword[in] identifier[range]... | def scale_pixels(color, layer):
"""Scales the pixel to the virtual pixelmap."""
pixelmap = []
# Scaling the pixel offsets.
for pix_x in range(MAX_X + 1):
for pix_y in range(MAX_Y + 1):
# Horizontal pixels
y1 = pix_y * dotsize[0]
x1 = pix_x * dotsize[1]
... |
def _get_nodal_planes_from_ndk_string(self, ndk_string):
"""
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
"""
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {... | def function[_get_nodal_planes_from_ndk_string, parameter[self, ndk_string]]:
constant[
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
]
variable[planes] assign[=] call[na... | keyword[def] identifier[_get_nodal_planes_from_ndk_string] ( identifier[self] , identifier[ndk_string] ):
literal[string]
identifier[planes] = identifier[GCMTNodalPlanes] ()
identifier[planes] . identifier[nodal_plane_1] ={ literal[string] : identifier[float] ( identifier[ndk_string] [ lit... | def _get_nodal_planes_from_ndk_string(self, ndk_string):
"""
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
"""
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {'strike': fl... |
def install(args, console, env, ciprcfg, opts):
"""
Install a package from github and make it available for use.
"""
if len(args) == 0:
# Is this a cipr project?
if ciprcfg.exists:
# Install all the packages for this project
console.quiet('Installing current proje... | def function[install, parameter[args, console, env, ciprcfg, opts]]:
constant[
Install a package from github and make it available for use.
]
if compare[call[name[len], parameter[name[args]]] equal[==] constant[0]] begin[:]
if name[ciprcfg].exists begin[:]
... | keyword[def] identifier[install] ( identifier[args] , identifier[console] , identifier[env] , identifier[ciprcfg] , identifier[opts] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyword[if] identifier[ciprcfg] . identifier[exists] :
... | def install(args, console, env, ciprcfg, opts):
"""
Install a package from github and make it available for use.
"""
if len(args) == 0:
# Is this a cipr project?
if ciprcfg.exists:
# Install all the packages for this project
console.quiet('Installing current proje... |
def check_consistent_parameter_grouping(self):
"""
Ensures this object does not have conflicting groups of parameters.
:raises ValueError: For conflicting or absent parameters.
"""
parameter_groups = {}
if self.indices_per_axis is not None:
parameter_groups["... | def function[check_consistent_parameter_grouping, parameter[self]]:
constant[
Ensures this object does not have conflicting groups of parameters.
:raises ValueError: For conflicting or absent parameters.
]
variable[parameter_groups] assign[=] dictionary[[], []]
if compar... | keyword[def] identifier[check_consistent_parameter_grouping] ( identifier[self] ):
literal[string]
identifier[parameter_groups] ={}
keyword[if] identifier[self] . identifier[indices_per_axis] keyword[is] keyword[not] keyword[None] :
identifier[parameter_groups] [ literal[s... | def check_consistent_parameter_grouping(self):
"""
Ensures this object does not have conflicting groups of parameters.
:raises ValueError: For conflicting or absent parameters.
"""
parameter_groups = {}
if self.indices_per_axis is not None:
parameter_groups['indices_per_axis... |
def _twos_comp_conditional(orig_wire, sign_bit, bw=None):
"""Returns two's complement of wire (using bitwidth bw) if sign_bit == 1"""
if bw is None:
bw = len(orig_wire)
new_wire = pyrtl.WireVector(bw)
with pyrtl.conditional_assignment:
with sign_bit:
new_wire |= ~orig_wire + ... | def function[_twos_comp_conditional, parameter[orig_wire, sign_bit, bw]]:
constant[Returns two's complement of wire (using bitwidth bw) if sign_bit == 1]
if compare[name[bw] is constant[None]] begin[:]
variable[bw] assign[=] call[name[len], parameter[name[orig_wire]]]
variable[ne... | keyword[def] identifier[_twos_comp_conditional] ( identifier[orig_wire] , identifier[sign_bit] , identifier[bw] = keyword[None] ):
literal[string]
keyword[if] identifier[bw] keyword[is] keyword[None] :
identifier[bw] = identifier[len] ( identifier[orig_wire] )
identifier[new_wire] = identi... | def _twos_comp_conditional(orig_wire, sign_bit, bw=None):
"""Returns two's complement of wire (using bitwidth bw) if sign_bit == 1"""
if bw is None:
bw = len(orig_wire) # depends on [control=['if'], data=['bw']]
new_wire = pyrtl.WireVector(bw)
with pyrtl.conditional_assignment:
with sig... |
def schema_list(dbname, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
D... | def function[schema_list, parameter[dbname, user, db_user, db_password, db_host, db_port]]:
constant[
Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
Database name we query on
... | keyword[def] identifier[schema_list] ( identifier[dbname] , identifier[user] = keyword[None] ,
identifier[db_user] = keyword[None] , identifier[db_password] = keyword[None] ,
identifier[db_host] = keyword[None] , identifier[db_port] = keyword[None] ):
literal[string]
identifier[ret] ={}
identifier... | def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None):
"""
Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
Database name we query on
us... |
def complete_get(self, text, line, begidx, endidx):
"""completion for find command"""
options = self.GET_OPTS
if not text:
completions = options
else:
completions = [f
for f in options
if f.startswith(text)
... | def function[complete_get, parameter[self, text, line, begidx, endidx]]:
constant[completion for find command]
variable[options] assign[=] name[self].GET_OPTS
if <ast.UnaryOp object at 0x7da1b10109d0> begin[:]
variable[completions] assign[=] name[options]
return[name[completi... | keyword[def] identifier[complete_get] ( identifier[self] , identifier[text] , identifier[line] , identifier[begidx] , identifier[endidx] ):
literal[string]
identifier[options] = identifier[self] . identifier[GET_OPTS]
keyword[if] keyword[not] identifier[text] :
identifier... | def complete_get(self, text, line, begidx, endidx):
"""completion for find command"""
options = self.GET_OPTS
if not text:
completions = options # depends on [control=['if'], data=[]]
else:
completions = [f for f in options if f.startswith(text)]
return completions |
def init_registered(self, request):
""" Create default price list items for each registered resource. """
created_items = models.DefaultPriceListItem.init_from_registered_resources()
if created_items:
message = ungettext(
_('Price item was created: %s.') % created_it... | def function[init_registered, parameter[self, request]]:
constant[ Create default price list items for each registered resource. ]
variable[created_items] assign[=] call[name[models].DefaultPriceListItem.init_from_registered_resources, parameter[]]
if name[created_items] begin[:]
... | keyword[def] identifier[init_registered] ( identifier[self] , identifier[request] ):
literal[string]
identifier[created_items] = identifier[models] . identifier[DefaultPriceListItem] . identifier[init_from_registered_resources] ()
keyword[if] identifier[created_items] :
iden... | def init_registered(self, request):
""" Create default price list items for each registered resource. """
created_items = models.DefaultPriceListItem.init_from_registered_resources()
if created_items:
message = ungettext(_('Price item was created: %s.') % created_items[0].name, _('Price items were c... |
def stop_image_acquisition(self):
"""
Stops image acquisition.
:return: None.
"""
if self.is_acquiring_images:
#
self._is_acquiring_images = False
#
if self.thread_image_acquisition.is_running: # TODO
self.thread_... | def function[stop_image_acquisition, parameter[self]]:
constant[
Stops image acquisition.
:return: None.
]
if name[self].is_acquiring_images begin[:]
name[self]._is_acquiring_images assign[=] constant[False]
if name[self].thread_image_acquisition.... | keyword[def] identifier[stop_image_acquisition] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_acquiring_images] :
identifier[self] . identifier[_is_acquiring_images] = keyword[False]
keyword[if] identifier[self... | def stop_image_acquisition(self):
"""
Stops image acquisition.
:return: None.
"""
if self.is_acquiring_images:
#
self._is_acquiring_images = False
#
if self.thread_image_acquisition.is_running: # TODO
self.thread_image_acquisition.stop() # d... |
def _build(self, inputs):
"""Assembles the module network and adds it to the graph.
The internal computation graph is assembled according to the set of
constraints provided at construction time.
Args:
inputs: Tensor containing a batch of transformation parameters.
Returns:
A batch of ... | def function[_build, parameter[self, inputs]]:
constant[Assembles the module network and adds it to the graph.
The internal computation graph is assembled according to the set of
constraints provided at construction time.
Args:
inputs: Tensor containing a batch of transformation parameters.
... | keyword[def] identifier[_build] ( identifier[self] , identifier[inputs] ):
literal[string]
identifier[input_shape] = identifier[tf] . identifier[shape] ( identifier[inputs] )
identifier[input_dtype] = identifier[inputs] . identifier[dtype] . identifier[as_numpy_dtype]
identifier[batch_size] = id... | def _build(self, inputs):
"""Assembles the module network and adds it to the graph.
The internal computation graph is assembled according to the set of
constraints provided at construction time.
Args:
inputs: Tensor containing a batch of transformation parameters.
Returns:
A batch of ... |
def _validate_calibration_params(strategy='accuracy', min_rate=None,
beta=1.):
"""Ensure that calibration parameters have allowed values"""
if strategy not in ('accuracy', 'f_beta', 'max_tpr',
'max_tnr'):
raise ValueError('Strategy can either be "... | def function[_validate_calibration_params, parameter[strategy, min_rate, beta]]:
constant[Ensure that calibration parameters have allowed values]
if compare[name[strategy] <ast.NotIn object at 0x7da2590d7190> tuple[[<ast.Constant object at 0x7da1b1da1f60>, <ast.Constant object at 0x7da1b1da1870>, <ast.C... | keyword[def] identifier[_validate_calibration_params] ( identifier[strategy] = literal[string] , identifier[min_rate] = keyword[None] ,
identifier[beta] = literal[int] ):
literal[string]
keyword[if] identifier[strategy] keyword[not] keyword[in] ( literal[string] , literal[string] , literal[string] ,
... | def _validate_calibration_params(strategy='accuracy', min_rate=None, beta=1.0):
"""Ensure that calibration parameters have allowed values"""
if strategy not in ('accuracy', 'f_beta', 'max_tpr', 'max_tnr'):
raise ValueError('Strategy can either be "accuracy", "f_beta" or "max_tpr" or "max_tnr". Got "{}" ... |
def _get_function_wrapper(
self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
) -> typing.Callable[..., "typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]"]:
"""Here should be constructed and returned real decorator.
:p... | def function[_get_function_wrapper, parameter[self, func]]:
constant[Here should be constructed and returned real decorator.
:param func: Wrapped function
:type func: typing.Callable
:return: wrapped coroutine or function
:rtype: typing.Callable[..., typing.Union[typing.Awaitabl... | keyword[def] identifier[_get_function_wrapper] (
identifier[self] , identifier[func] : identifier[typing] . identifier[Callable] [..., identifier[typing] . identifier[Union] [ literal[string] , identifier[typing] . identifier[Any] ]]
)-> identifier[typing] . identifier[Callable] [..., literal[string] ]:
lit... | def _get_function_wrapper(self, func: typing.Callable[..., typing.Union['typing.Awaitable[typing.Any]', typing.Any]]) -> typing.Callable[..., 'typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]']:
"""Here should be constructed and returned real decorator.
:param func: Wrapped... |
def read(self, size):
"""
Read wrapper.
Parameters
----------
size : int
Number of bytes to read
"""
data = None
while True:
try:
data = self.handle.recv(size)
except socket.timeout as socket_error:
... | def function[read, parameter[self, size]]:
constant[
Read wrapper.
Parameters
----------
size : int
Number of bytes to read
]
variable[data] assign[=] constant[None]
while constant[True] begin[:]
<ast.Try object at 0x7da2054a5120>
... | keyword[def] identifier[read] ( identifier[self] , identifier[size] ):
literal[string]
identifier[data] = keyword[None]
keyword[while] keyword[True] :
keyword[try] :
identifier[data] = identifier[self] . identifier[handle] . identifier[recv] ( identifier[siz... | def read(self, size):
"""
Read wrapper.
Parameters
----------
size : int
Number of bytes to read
"""
data = None
while True:
try:
data = self.handle.recv(size) # depends on [control=['try'], data=[]]
except socket.timeout as soc... |
def record_to_fs(self):
"""Create a filesystem file from a File"""
fr = self.record
if fr.contents:
with self._fs.open(self.file_name, 'w', encoding='utf-8') as f:
self.record_to_fh(f) | def function[record_to_fs, parameter[self]]:
constant[Create a filesystem file from a File]
variable[fr] assign[=] name[self].record
if name[fr].contents begin[:]
with call[name[self]._fs.open, parameter[name[self].file_name, constant[w]]] begin[:]
call[na... | keyword[def] identifier[record_to_fs] ( identifier[self] ):
literal[string]
identifier[fr] = identifier[self] . identifier[record]
keyword[if] identifier[fr] . identifier[contents] :
keyword[with] identifier[self] . identifier[_fs] . identifier[open] ( identifier[self] . ... | def record_to_fs(self):
"""Create a filesystem file from a File"""
fr = self.record
if fr.contents:
with self._fs.open(self.file_name, 'w', encoding='utf-8') as f:
self.record_to_fh(f) # depends on [control=['with'], data=['f']] # depends on [control=['if'], data=[]] |
def update(old, new, collection, sneaky_update_filter=None):
"""
update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed o... | def function[update, parameter[old, new, collection, sneaky_update_filter]]:
constant[
update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
co... | keyword[def] identifier[update] ( identifier[old] , identifier[new] , identifier[collection] , identifier[sneaky_update_filter] = keyword[None] ):
literal[string]
identifier[need_save] = keyword[False]
identifier[locked_fields] = identifier[old] . identifier[get] ( literal[string] ,[])
ke... | def update(old, new, collection, sneaky_update_filter=None):
"""
update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed o... |
def create_from_file(self, file=None, fmt='gaf', skim=True, **args):
"""
Creates from a file. If fmt is set to None then the file suffixes will
be used to choose a parser.
Arguments
---------
file : str or file
input file or filename
fmt : str
... | def function[create_from_file, parameter[self, file, fmt, skim]]:
constant[
Creates from a file. If fmt is set to None then the file suffixes will
be used to choose a parser.
Arguments
---------
file : str or file
input file or filename
fmt : str
... | keyword[def] identifier[create_from_file] ( identifier[self] , identifier[file] = keyword[None] , identifier[fmt] = literal[string] , identifier[skim] = keyword[True] ,** identifier[args] ):
literal[string]
keyword[if] identifier[fmt] keyword[is] keyword[not] keyword[None] keyword[and] keywor... | def create_from_file(self, file=None, fmt='gaf', skim=True, **args):
"""
Creates from a file. If fmt is set to None then the file suffixes will
be used to choose a parser.
Arguments
---------
file : str or file
input file or filename
fmt : str
... |
def get_modules():
'''Returns a list of available modules.'''
modules = set()
cwd = os.getcwd()
for d in os.listdir(cwd):
if d == 'module.yml':
modules.add(Module(cwd))
path = unipath(cwd, d)
if utils.is_module(path):
modules.add(Module(cwd))
modu... | def function[get_modules, parameter[]]:
constant[Returns a list of available modules.]
variable[modules] assign[=] call[name[set], parameter[]]
variable[cwd] assign[=] call[name[os].getcwd, parameter[]]
for taget[name[d]] in starred[call[name[os].listdir, parameter[name[cwd]]]] begin[:]
... | keyword[def] identifier[get_modules] ():
literal[string]
identifier[modules] = identifier[set] ()
identifier[cwd] = identifier[os] . identifier[getcwd] ()
keyword[for] identifier[d] keyword[in] identifier[os] . identifier[listdir] ( identifier[cwd] ):
keyword[if] identifier[d] == ... | def get_modules():
"""Returns a list of available modules."""
modules = set()
cwd = os.getcwd()
for d in os.listdir(cwd):
if d == 'module.yml':
modules.add(Module(cwd)) # depends on [control=['if'], data=[]]
path = unipath(cwd, d)
if utils.is_module(path):
... |
def type(self, col):
"""
The type for the given column.
:param col: either a name, or an index of the column to look up
:returns: type of the column, one of: ``str``, ``int``, ``real``, ``enum``, ``time``, ``bool``.
:raises H2OValueError: if such column does not exist in the fra... | def function[type, parameter[self, col]]:
constant[
The type for the given column.
:param col: either a name, or an index of the column to look up
:returns: type of the column, one of: ``str``, ``int``, ``real``, ``enum``, ``time``, ``bool``.
:raises H2OValueError: if such colum... | keyword[def] identifier[type] ( identifier[self] , identifier[col] ):
literal[string]
identifier[assert_is_type] ( identifier[col] , identifier[int] , identifier[str] )
keyword[if] keyword[not] identifier[self] . identifier[_ex] . identifier[_cache] . identifier[types_valid] () keyword[o... | def type(self, col):
"""
The type for the given column.
:param col: either a name, or an index of the column to look up
:returns: type of the column, one of: ``str``, ``int``, ``real``, ``enum``, ``time``, ``bool``.
:raises H2OValueError: if such column does not exist in the frame.
... |
def determine_rotation(rotation, mark):
"""
Determines the number of degrees to rotate the watermark image.
"""
if isinstance(rotation, six.string_types) and rotation.lower() == 'r':
rotation = random.randint(0, 359)
else:
rotation = _int(rotation)
return rotation | def function[determine_rotation, parameter[rotation, mark]]:
constant[
Determines the number of degrees to rotate the watermark image.
]
if <ast.BoolOp object at 0x7da1b2865630> begin[:]
variable[rotation] assign[=] call[name[random].randint, parameter[constant[0], constant[359]]... | keyword[def] identifier[determine_rotation] ( identifier[rotation] , identifier[mark] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[rotation] , identifier[six] . identifier[string_types] ) keyword[and] identifier[rotation] . identifier[lower] ()== literal[string] :
identifie... | def determine_rotation(rotation, mark):
"""
Determines the number of degrees to rotate the watermark image.
"""
if isinstance(rotation, six.string_types) and rotation.lower() == 'r':
rotation = random.randint(0, 359) # depends on [control=['if'], data=[]]
else:
rotation = _int(rotat... |
def scale(self, n):
""" Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
Kub... | def function[scale, parameter[self, n]]:
constant[ Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeC... | keyword[def] identifier[scale] ( identifier[self] , identifier[n] ):
literal[string]
identifier[pods] = identifier[self] . identifier[_cleanup_terminated_pods] ( identifier[self] . identifier[pods] ())
keyword[if] identifier[n] >= identifier[len] ( identifier[pods] ):
keyword... | def scale(self, n):
""" Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
KubeClu... |
def update_mock_repo():
"""
Clone and gzip the memote-mock-repo used for CLI and integration tests.
The repo is hosted at
'https://github.com/ChristianLieven/memote-mock-repo.git' and maintained
separately from
"""
target_file = os.path.abspath(
join("tests", "data", "memote-mock-r... | def function[update_mock_repo, parameter[]]:
constant[
Clone and gzip the memote-mock-repo used for CLI and integration tests.
The repo is hosted at
'https://github.com/ChristianLieven/memote-mock-repo.git' and maintained
separately from
]
variable[target_file] assign[=] call[name[... | keyword[def] identifier[update_mock_repo] ():
literal[string]
identifier[target_file] = identifier[os] . identifier[path] . identifier[abspath] (
identifier[join] ( literal[string] , literal[string] , literal[string] )
)
identifier[temp_dir] = identifier[mkdtemp] ( identifier[prefix] = litera... | def update_mock_repo():
"""
Clone and gzip the memote-mock-repo used for CLI and integration tests.
The repo is hosted at
'https://github.com/ChristianLieven/memote-mock-repo.git' and maintained
separately from
"""
target_file = os.path.abspath(join('tests', 'data', 'memote-mock-repo.tar.g... |
def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesyste... | def function[fsencode, parameter[path, os_name, fs_encoding, errors]]:
constant[
Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current fil... | keyword[def] identifier[fsencode] ( identifier[path] , identifier[os_name] = identifier[os] . identifier[name] , identifier[fs_encoding] = identifier[FS_ENCODING] , identifier[errors] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[path] , identifier[bytes] ):
k... | def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
"""
Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesyste... |
def load_cloudformation_template(path=None):
"""Load cloudformation template from path.
:param path: Absolute or relative path of cloudformation template. Defaults to cwd.
:return: module, success
"""
if not path:
path = os.path.abspath('cloudformation.py')
else:
path = os.path.... | def function[load_cloudformation_template, parameter[path]]:
constant[Load cloudformation template from path.
:param path: Absolute or relative path of cloudformation template. Defaults to cwd.
:return: module, success
]
if <ast.UnaryOp object at 0x7da204346ce0> begin[:]
var... | keyword[def] identifier[load_cloudformation_template] ( identifier[path] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[path] :
identifier[path] = identifier[os] . identifier[path] . identifier[abspath] ( literal[string] )
keyword[else] :
identifier[path] = ... | def load_cloudformation_template(path=None):
"""Load cloudformation template from path.
:param path: Absolute or relative path of cloudformation template. Defaults to cwd.
:return: module, success
"""
if not path:
path = os.path.abspath('cloudformation.py') # depends on [control=['if'], da... |
def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, "%s" % str(key)
return utils.weighted_choice(transitions[key].items()) | def function[_generate_next_token_helper, parameter[self, past_states, transitions]]:
constant[ generates next token based previous states ]
variable[key] assign[=] call[name[tuple], parameter[name[past_states]]]
assert[compare[name[key] in name[transitions]]]
return[call[name[utils].weighted_ch... | keyword[def] identifier[_generate_next_token_helper] ( identifier[self] , identifier[past_states] , identifier[transitions] ):
literal[string]
identifier[key] = identifier[tuple] ( identifier[past_states] )
keyword[assert] identifier[key] keyword[in] identifier[transitions] , literal[st... | def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, '%s' % str(key)
return utils.weighted_choice(transitions[key].items()) |
def _get_exponential_spaced_values(mmin, mmax, number_samples):
'''
Function to return a set of exponentially spaced values between mmin and
mmax
:param float mmin:
Minimum value
:param float mmax:
Maximum value
:param float number_samples:
Number of exponentially spaced... | def function[_get_exponential_spaced_values, parameter[mmin, mmax, number_samples]]:
constant[
Function to return a set of exponentially spaced values between mmin and
mmax
:param float mmin:
Minimum value
:param float mmax:
Maximum value
:param float number_samples:
... | keyword[def] identifier[_get_exponential_spaced_values] ( identifier[mmin] , identifier[mmax] , identifier[number_samples] ):
literal[string]
identifier[lhs] = identifier[np] . identifier[exp] ( identifier[mmin] )+ identifier[np] . identifier[arange] ( literal[int] , identifier[number_samples] - literal[in... | def _get_exponential_spaced_values(mmin, mmax, number_samples):
"""
Function to return a set of exponentially spaced values between mmin and
mmax
:param float mmin:
Minimum value
:param float mmax:
Maximum value
:param float number_samples:
Number of exponentially spaced... |
def get_hdrs(self, **kws):
"""Initialize column headers."""
hdrs = get_hdrs(self.prt_flds, **kws)
# Values in a "format_txt" "column" are used for formatting, not printing
return [h for h in hdrs if h != "format_txt"] | def function[get_hdrs, parameter[self]]:
constant[Initialize column headers.]
variable[hdrs] assign[=] call[name[get_hdrs], parameter[name[self].prt_flds]]
return[<ast.ListComp object at 0x7da18bcc9060>] | keyword[def] identifier[get_hdrs] ( identifier[self] ,** identifier[kws] ):
literal[string]
identifier[hdrs] = identifier[get_hdrs] ( identifier[self] . identifier[prt_flds] ,** identifier[kws] )
keyword[return] [ identifier[h] keyword[for] identifier[h] keyword[in] identifier... | def get_hdrs(self, **kws):
"""Initialize column headers."""
hdrs = get_hdrs(self.prt_flds, **kws)
# Values in a "format_txt" "column" are used for formatting, not printing
return [h for h in hdrs if h != 'format_txt'] |
def cmd():
'''Return a command to launch a subshell'''
if platform == 'win':
return ['cmd.exe', '/K']
elif platform == 'linux':
ppid = os.getppid()
ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)
try:
with open(ppid_cmdline_file) as f:
cmd =... | def function[cmd, parameter[]]:
constant[Return a command to launch a subshell]
if compare[name[platform] equal[==] constant[win]] begin[:]
return[list[[<ast.Constant object at 0x7da1b004b550>, <ast.Constant object at 0x7da1b004be20>]]]
return[list[[<ast.Name object at 0x7da1afe89b10>, <ast.... | keyword[def] identifier[cmd] ():
literal[string]
keyword[if] identifier[platform] == literal[string] :
keyword[return] [ literal[string] , literal[string] ]
keyword[elif] identifier[platform] == literal[string] :
identifier[ppid] = identifier[os] . identifier[getppid] ()
... | def cmd():
"""Return a command to launch a subshell"""
if platform == 'win':
return ['cmd.exe', '/K'] # depends on [control=['if'], data=[]]
elif platform == 'linux':
ppid = os.getppid()
ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)
try:
with open(ppid_cmd... |
def iso_date(d) -> str:
"""
Return iso format of a date
Args:
d:
Returns: str
"""
if isinstance(d, datetime):
return d.isoformat()
elif isinstance(d, date):
return datetime.combine(d, datetime.min.time()).isoformat()
e... | def function[iso_date, parameter[d]]:
constant[
Return iso format of a date
Args:
d:
Returns: str
]
if call[name[isinstance], parameter[name[d], name[datetime]]] begin[:]
return[call[name[d].isoformat, parameter[]]]
<ast.Raise object at 0x7da1b0b... | keyword[def] identifier[iso_date] ( identifier[d] )-> identifier[str] :
literal[string]
keyword[if] identifier[isinstance] ( identifier[d] , identifier[datetime] ):
keyword[return] identifier[d] . identifier[isoformat] ()
keyword[elif] identifier[isinstance] ( identifier[d]... | def iso_date(d) -> str:
"""
Return iso format of a date
Args:
d:
Returns: str
"""
if isinstance(d, datetime):
return d.isoformat() # depends on [control=['if'], data=[]]
elif isinstance(d, date):
return datetime.combine(d, datetime.min.time()).i... |
def _main_loop(self):
"""
Run jobs until must_stop returns True
"""
fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)
while not self.must_stop():
self.set_status('waiting'... | def function[_main_loop, parameter[self]]:
constant[
Run jobs until must_stop returns True
]
variable[fetch_priorities_delay] assign[=] call[name[timedelta], parameter[]]
variable[fetch_delayed_delay] assign[=] call[name[timedelta], parameter[]]
while <ast.UnaryOp object ... | keyword[def] identifier[_main_loop] ( identifier[self] ):
literal[string]
identifier[fetch_priorities_delay] = identifier[timedelta] ( identifier[seconds] = identifier[self] . identifier[fetch_priorities_delay] )
identifier[fetch_delayed_delay] = identifier[timedelta] ( identifier[seconds]... | def _main_loop(self):
"""
Run jobs until must_stop returns True
"""
fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)
while not self.must_stop():
self.set_status('waiting')
if self.las... |
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ... | def function[get_id, parameter[opts, cache_minion_id]]:
constant[
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns ... | keyword[def] identifier[get_id] ( identifier[opts] , identifier[cache_minion_id] = keyword[False] ):
literal[string]
keyword[if] identifier[opts] [ literal[string] ] keyword[is] keyword[None] :
identifier[root_dir] = identifier[salt] . identifier[syspaths] . identifier[ROOT_DIR]
keyword[el... | def get_id(opts, cache_minion_id=False):
"""
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ... |
def compile_kernel(self, instance, verbose):
"""compile the kernel for this specific instance"""
logging.debug('compile_kernel ' + instance.name)
#compile kernel_string into device func
func = None
try:
func = self.dev.compile(instance.name, instance.kernel_string)
... | def function[compile_kernel, parameter[self, instance, verbose]]:
constant[compile the kernel for this specific instance]
call[name[logging].debug, parameter[binary_operation[constant[compile_kernel ] + name[instance].name]]]
variable[func] assign[=] constant[None]
<ast.Try object at 0x7da1b... | keyword[def] identifier[compile_kernel] ( identifier[self] , identifier[instance] , identifier[verbose] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] + identifier[instance] . identifier[name] )
identifier[func] = keyword[None]
keyword[try]... | def compile_kernel(self, instance, verbose):
"""compile the kernel for this specific instance"""
logging.debug('compile_kernel ' + instance.name)
#compile kernel_string into device func
func = None
try:
func = self.dev.compile(instance.name, instance.kernel_string) # depends on [control=['t... |
def cv_compute(self, b, A, B, C, mK, f, m1, m2):
'''
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
'''
A = np.sum([l * a for l, a in zip(self.lam[b], A)
if l is not None], axis=0)
B = np.sum([l * b for l, b in zip(self.lam[b], B)
... | def function[cv_compute, parameter[self, b, A, B, C, mK, f, m1, m2]]:
constant[
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
]
variable[A] assign[=] call[name[np].sum, parameter[<ast.ListComp object at 0x7da1b0e32680>]]
variable[B] assign[=] call[name[np... | keyword[def] identifier[cv_compute] ( identifier[self] , identifier[b] , identifier[A] , identifier[B] , identifier[C] , identifier[mK] , identifier[f] , identifier[m1] , identifier[m2] ):
literal[string]
identifier[A] = identifier[np] . identifier[sum] ([ identifier[l] * identifier[a] keyword[fo... | def cv_compute(self, b, A, B, C, mK, f, m1, m2):
"""
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
"""
A = np.sum([l * a for (l, a) in zip(self.lam[b], A) if l is not None], axis=0)
B = np.sum([l * b for (l, b) in zip(self.lam[b], B) if l is not None], axis=0)
W ... |
def flip_axis_multi(x, axis, is_random=False):
"""Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others ... | def function[flip_axis_multi, parameter[x, axis, is_random]]:
constant[Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channe... | keyword[def] identifier[flip_axis_multi] ( identifier[x] , identifier[axis] , identifier[is_random] = keyword[False] ):
literal[string]
keyword[if] identifier[is_random] :
identifier[factor] = identifier[np] . identifier[random] . identifier[uniform] (- literal[int] , literal[int] )
keyw... | def flip_axis_multi(x, axis, is_random=False):
"""Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others ... |
def _delete_reverses(self):
"""
Delete all objects that would have been cloned
on a clone command. This is done separately because
there may be m2m and other relationships that
would have not been deleted otherwise.
"""
for reverse in self.clone_related:
... | def function[_delete_reverses, parameter[self]]:
constant[
Delete all objects that would have been cloned
on a clone command. This is done separately because
there may be m2m and other relationships that
would have not been deleted otherwise.
]
for taget[name[reve... | keyword[def] identifier[_delete_reverses] ( identifier[self] ):
literal[string]
keyword[for] identifier[reverse] keyword[in] identifier[self] . identifier[clone_related] :
identifier[self] . identifier[_delete_reverse] ( identifier[reverse] )
keyword[for] identifier[fiel... | def _delete_reverses(self):
"""
Delete all objects that would have been cloned
on a clone command. This is done separately because
there may be m2m and other relationships that
would have not been deleted otherwise.
"""
for reverse in self.clone_related:
self._del... |
def unmap_volume_from_sdc(self, volObj, sdcObj=None, **kwargs):
"""
Unmap a Volume from SDC or all SDCs
:param volObj: ScaleIO Volume object
:param sdcObj: ScaleIO SDC object
:param \**kwargs:
:Keyword Arguments:
*disableMapAllSdcs* (``bool``) -- True to disable a... | def function[unmap_volume_from_sdc, parameter[self, volObj, sdcObj]]:
constant[
Unmap a Volume from SDC or all SDCs
:param volObj: ScaleIO Volume object
:param sdcObj: ScaleIO SDC object
:param \**kwargs:
:Keyword Arguments:
*disableMapAllSdcs* (``bool``) -- True ... | keyword[def] identifier[unmap_volume_from_sdc] ( identifier[self] , identifier[volObj] , identifier[sdcObj] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[conn] . identifier[connection] . identifier[_check_login] ()
... | def unmap_volume_from_sdc(self, volObj, sdcObj=None, **kwargs):
"""
Unmap a Volume from SDC or all SDCs
:param volObj: ScaleIO Volume object
:param sdcObj: ScaleIO SDC object
:param \\**kwargs:
:Keyword Arguments:
*disableMapAllSdcs* (``bool``) -- True to disable all ... |
def issymmetric(am):
r"""
A method to check if a square matrix is symmetric
Returns ``True`` if the sparse adjacency matrix is symmetric
"""
if am.shape[0] != am.shape[1]:
logger.warning('Matrix is not square, symmetrical is irrelevant')
return False
if am.format != 'coo':
... | def function[issymmetric, parameter[am]]:
constant[
A method to check if a square matrix is symmetric
Returns ``True`` if the sparse adjacency matrix is symmetric
]
if compare[call[name[am].shape][constant[0]] not_equal[!=] call[name[am].shape][constant[1]]] begin[:]
call[nam... | keyword[def] identifier[issymmetric] ( identifier[am] ):
literal[string]
keyword[if] identifier[am] . identifier[shape] [ literal[int] ]!= identifier[am] . identifier[shape] [ literal[int] ]:
identifier[logger] . identifier[warning] ( literal[string] )
keyword[return] keyword[False]
... | def issymmetric(am):
"""
A method to check if a square matrix is symmetric
Returns ``True`` if the sparse adjacency matrix is symmetric
"""
if am.shape[0] != am.shape[1]:
logger.warning('Matrix is not square, symmetrical is irrelevant')
return False # depends on [control=['if'], dat... |
def get_out_segmentlistdict(self, process_ids = None):
"""
Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
con... | def function[get_out_segmentlistdict, parameter[self, process_ids]]:
constant[
Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesc... | keyword[def] identifier[get_out_segmentlistdict] ( identifier[self] , identifier[process_ids] = keyword[None] ):
literal[string]
identifier[seglists] = identifier[segments] . identifier[segmentlistdict] ()
keyword[for] identifier[row] keyword[in] identifier[self] :
identifier[ifos] = identifier[row] ... | def get_out_segmentlistdict(self, process_ids=None):
"""
Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
con... |
def _eval(self, text):
"""
Evaluate text and return (obj, valid)
where *obj* is the object represented by *text*
and *valid* is True if object evaluation did not raise any exception
"""
from spyder_kernels.py3compat import is_text_string
assert is_text_string(tex... | def function[_eval, parameter[self, text]]:
constant[
Evaluate text and return (obj, valid)
where *obj* is the object represented by *text*
and *valid* is True if object evaluation did not raise any exception
]
from relative_module[spyder_kernels.py3compat] import module[is_t... | keyword[def] identifier[_eval] ( identifier[self] , identifier[text] ):
literal[string]
keyword[from] identifier[spyder_kernels] . identifier[py3compat] keyword[import] identifier[is_text_string]
keyword[assert] identifier[is_text_string] ( identifier[text] )
identifier[ns] ... | def _eval(self, text):
"""
Evaluate text and return (obj, valid)
where *obj* is the object represented by *text*
and *valid* is True if object evaluation did not raise any exception
"""
from spyder_kernels.py3compat import is_text_string
assert is_text_string(text)
ns = s... |
def main_func(args=None):
"""Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
"""
# we have to initialize a gui even if we dont need one right now.
# as soon as you call maya.standalone.in... | def function[main_func, parameter[args]]:
constant[Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
]
call[name[guimain].init_gui, parameter[]]
call[name[main].init, parameter[... | keyword[def] identifier[main_func] ( identifier[args] = keyword[None] ):
literal[string]
identifier[guimain] . identifier[init_gui] ()
identifier[main] . identifier[init] ()
identifier[launcher] = identifier[Launcher] ()
identifier[parsed] , identifier[unknown] = identif... | def main_func(args=None):
"""Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
"""
# we have to initialize a gui even if we dont need one right now.
# as soon as you call maya.standalone.in... |
def drop_invalid_columns(feed: "Feed") -> "Feed":
"""
Drop all DataFrame columns of the given "Feed" that are not
listed in the GTFS.
Return the resulting new "Feed".
"""
feed = feed.copy()
for table, group in cs.GTFS_REF.groupby("table"):
f = getattr(feed, table)
if f is Non... | def function[drop_invalid_columns, parameter[feed]]:
constant[
Drop all DataFrame columns of the given "Feed" that are not
listed in the GTFS.
Return the resulting new "Feed".
]
variable[feed] assign[=] call[name[feed].copy, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da... | keyword[def] identifier[drop_invalid_columns] ( identifier[feed] : literal[string] )-> literal[string] :
literal[string]
identifier[feed] = identifier[feed] . identifier[copy] ()
keyword[for] identifier[table] , identifier[group] keyword[in] identifier[cs] . identifier[GTFS_REF] . identifier[groupb... | def drop_invalid_columns(feed: 'Feed') -> 'Feed':
"""
Drop all DataFrame columns of the given "Feed" that are not
listed in the GTFS.
Return the resulting new "Feed".
"""
feed = feed.copy()
for (table, group) in cs.GTFS_REF.groupby('table'):
f = getattr(feed, table)
if f is N... |
def addDependency(self, item):
"""
Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem>
"""
if item in self._dependencies:
return
... | def function[addDependency, parameter[self, item]]:
constant[
Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem>
]
if compare[name[item] in name[self]._depe... | keyword[def] identifier[addDependency] ( identifier[self] , identifier[item] ):
literal[string]
keyword[if] identifier[item] keyword[in] identifier[self] . identifier[_dependencies] :
keyword[return]
identifier[viewItem] = identifier[XGanttDepItem] ( identifier[self]... | def addDependency(self, item):
"""
Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem>
"""
if item in self._dependencies:
return # depends on [control=['if'... |
def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... | def function[parse_filename, parameter[fname]]:
constant[Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* noteb... | keyword[def] identifier[parse_filename] ( identifier[fname] ):
literal[string]
keyword[if] identifier[fname] . identifier[endswith] ( literal[string] ):
identifier[format] = literal[string]
keyword[elif] identifier[fname] . identifier[endswith] ( literal[string] ):
identifier[form... | def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... |
def run(configobj=None):
"""
TEAL interface for the `acscteforwardmodel` function.
"""
acscteforwardmodel(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
... | def function[run, parameter[configobj]]:
constant[
TEAL interface for the `acscteforwardmodel` function.
]
call[name[acscteforwardmodel], parameter[call[name[configobj]][constant[input]]]] | keyword[def] identifier[run] ( identifier[configobj] = keyword[None] ):
literal[string]
identifier[acscteforwardmodel] ( identifier[configobj] [ literal[string] ],
identifier[exec_path] = identifier[configobj] [ literal[string] ],
identifier[time_stamps] = identifier[configobj] [ literal[string] ... | def run(configobj=None):
"""
TEAL interface for the `acscteforwardmodel` function.
"""
acscteforwardmodel(configobj['input'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], quiet=configobj['quiet'], single_core=configobj['single_core']) |
def block(seed):
""" Return block of normal random numbers
Parameters
----------
seed : {None, int}
The seed to generate the noise.sd
Returns
--------
noise : numpy.ndarray
Array of random numbers
"""
num = SAMPLE_RATE * BLOCK_SIZE
rng = RandomState(seed % 2**32... | def function[block, parameter[seed]]:
constant[ Return block of normal random numbers
Parameters
----------
seed : {None, int}
The seed to generate the noise.sd
Returns
--------
noise : numpy.ndarray
Array of random numbers
]
variable[num] assign[=] binary_o... | keyword[def] identifier[block] ( identifier[seed] ):
literal[string]
identifier[num] = identifier[SAMPLE_RATE] * identifier[BLOCK_SIZE]
identifier[rng] = identifier[RandomState] ( identifier[seed] % literal[int] ** literal[int] )
identifier[variance] = identifier[SAMPLE_RATE] / literal[int]
... | def block(seed):
""" Return block of normal random numbers
Parameters
----------
seed : {None, int}
The seed to generate the noise.sd
Returns
--------
noise : numpy.ndarray
Array of random numbers
"""
num = SAMPLE_RATE * BLOCK_SIZE
rng = RandomState(seed % 2 ** ... |
def add_weekdays2df(time_df, holidays=None, holiday_is_sunday=False):
r"""Giving back a DataFrame containing weekdays and optionally holidays for
the given year.
Parameters
----------
time_df : pandas DataFrame
DataFrame to which the weekdays should be added
Optional Parameters
--... | def function[add_weekdays2df, parameter[time_df, holidays, holiday_is_sunday]]:
constant[Giving back a DataFrame containing weekdays and optionally holidays for
the given year.
Parameters
----------
time_df : pandas DataFrame
DataFrame to which the weekdays should be added
Optiona... | keyword[def] identifier[add_weekdays2df] ( identifier[time_df] , identifier[holidays] = keyword[None] , identifier[holiday_is_sunday] = keyword[False] ):
literal[string]
identifier[time_df] [ literal[string] ]= identifier[time_df] . identifier[index] . identifier[weekday] + literal[int]
identifier[ti... | def add_weekdays2df(time_df, holidays=None, holiday_is_sunday=False):
"""Giving back a DataFrame containing weekdays and optionally holidays for
the given year.
Parameters
----------
time_df : pandas DataFrame
DataFrame to which the weekdays should be added
Optional Parameters
---... |
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path,
out_filepaths):
"""Produce examples from shard_ids to out_filepaths."""
# * Join the Wikipedia articles with their references
# * Run Tf-idf to sort reference paragraphs
# * Encode the Wikipedia and reference text wi... | def function[produce_examples, parameter[shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths]]:
constant[Produce examples from shard_ids to out_filepaths.]
call[name[tf].logging.info, parameter[constant[Processing %d input shards into %d output files.], call[name[len], parameter[name[sha... | keyword[def] identifier[produce_examples] ( identifier[shard_ids] , identifier[wikis_dir] , identifier[refs_dir] , identifier[urls_dir] , identifier[vocab_path] ,
identifier[out_filepaths] ):
literal[string]
identifier[tf] . identifier[logging] . identifier[info] ( literal[string] ,
identifier[... | def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths):
"""Produce examples from shard_ids to out_filepaths."""
# * Join the Wikipedia articles with their references
# * Run Tf-idf to sort reference paragraphs
# * Encode the Wikipedia and reference text with the vocabu... |
def kl_divergence(V_a, V_b):
"""
Calculate Kullback-Leibler distance.
Uses the smoothing method described in `Bigi 2003
<http://lvk.cs.msu.su/~bruzz/articles/classification/Using%20Kullback-Leibler%20Distance%20for%20Text%20Categorization.pdf>`_
to facilitate better comparisons between vectors desc... | def function[kl_divergence, parameter[V_a, V_b]]:
constant[
Calculate Kullback-Leibler distance.
Uses the smoothing method described in `Bigi 2003
<http://lvk.cs.msu.su/~bruzz/articles/classification/Using%20Kullback-Leibler%20Distance%20for%20Text%20Categorization.pdf>`_
to facilitate better c... | keyword[def] identifier[kl_divergence] ( identifier[V_a] , identifier[V_b] ):
literal[string]
identifier[Ndiff] = identifier[_shared_features] ( identifier[V_a] , identifier[V_b] )
identifier[aprob] = identifier[map] ( keyword[lambda] identifier[v] : identifier[float] ( identifier[v] )/ i... | def kl_divergence(V_a, V_b):
"""
Calculate Kullback-Leibler distance.
Uses the smoothing method described in `Bigi 2003
<http://lvk.cs.msu.su/~bruzz/articles/classification/Using%20Kullback-Leibler%20Distance%20for%20Text%20Categorization.pdf>`_
to facilitate better comparisons between vectors desc... |
def enum(self):
"""
Enumeration of allowed object values.
The enumeration must not contain duplicates.
"""
value = self._schema.get("enum", None)
if value is None:
return
if not isinstance(value, list):
raise SchemaError(
"... | def function[enum, parameter[self]]:
constant[
Enumeration of allowed object values.
The enumeration must not contain duplicates.
]
variable[value] assign[=] call[name[self]._schema.get, parameter[constant[enum], constant[None]]]
if compare[name[value] is constant[None]]... | keyword[def] identifier[enum] ( identifier[self] ):
literal[string]
identifier[value] = identifier[self] . identifier[_schema] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return]
keyword[i... | def enum(self):
"""
Enumeration of allowed object values.
The enumeration must not contain duplicates.
"""
value = self._schema.get('enum', None)
if value is None:
return # depends on [control=['if'], data=[]]
if not isinstance(value, list):
raise SchemaError('e... |
def initialize_arg_parser():
"""
Initializes the option parser with the options -
-q --image-query {[str]} -- [Image Search Query]
-n --image-count {[int]} -- [Count of images that need to be downloaded]
-f --destination-folder {[str]} -- [Download Destination Folder]... | def function[initialize_arg_parser, parameter[]]:
constant[
Initializes the option parser with the options -
-q --image-query {[str]} -- [Image Search Query]
-n --image-count {[int]} -- [Count of images that need to be downloaded]
-f --destination-folder {[str]} -- [D... | keyword[def] identifier[initialize_arg_parser] ():
literal[string]
identifier[GoogleImageExtractor] . identifier[__argParser] = identifier[ArgumentParser] (
identifier[description] = literal[string] )
identifier[requiredArguments] = identifier[GoogleImageExtractor] . id... | def initialize_arg_parser():
"""
Initializes the option parser with the options -
-q --image-query {[str]} -- [Image Search Query]
-n --image-count {[int]} -- [Count of images that need to be downloaded]
-f --destination-folder {[str]} -- [Download Destination Folder]
... |
def _load_from_environ(metadata, value_func=None):
"""
Load configuration from environment variables.
Any environment variable prefixed with the metadata's name will be
used to recursively set dictionary keys, splitting on '__'.
:param value_func: a mutator for the envvar's value (if any)
"""... | def function[_load_from_environ, parameter[metadata, value_func]]:
constant[
Load configuration from environment variables.
Any environment variable prefixed with the metadata's name will be
used to recursively set dictionary keys, splitting on '__'.
:param value_func: a mutator for the envvar... | keyword[def] identifier[_load_from_environ] ( identifier[metadata] , identifier[value_func] = keyword[None] ):
literal[string]
identifier[prefix] = identifier[metadata] . identifier[name] . identifier[upper] (). identifier[replace] ( literal[string] ,... | def _load_from_environ(metadata, value_func=None):
"""
Load configuration from environment variables.
Any environment variable prefixed with the metadata's name will be
used to recursively set dictionary keys, splitting on '__'.
:param value_func: a mutator for the envvar's value (if any)
"""... |
def fix_report(self, report, errors="drop", prefer="before"):
"""Perform utc assignment on all readings in a report.
The returned report will have all reading timestamps in UTC. This only
works on SignedListReport objects. Note that the report should
typically have previously been adde... | def function[fix_report, parameter[self, report, errors, prefer]]:
constant[Perform utc assignment on all readings in a report.
The returned report will have all reading timestamps in UTC. This only
works on SignedListReport objects. Note that the report should
typically have previousl... | keyword[def] identifier[fix_report] ( identifier[self] , identifier[report] , identifier[errors] = literal[string] , identifier[prefer] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[report] , identifier[SignedListReport] ):
keyword... | def fix_report(self, report, errors='drop', prefer='before'):
"""Perform utc assignment on all readings in a report.
The returned report will have all reading timestamps in UTC. This only
works on SignedListReport objects. Note that the report should
typically have previously been added to... |
def _is_writable(self, obj):
"""Check if the argument is a writable file-like object."""
try:
write = getattr(obj, 'write')
except AttributeError:
return False
else:
return is_method(write, min_arity=1, max_arity=1) | def function[_is_writable, parameter[self, obj]]:
constant[Check if the argument is a writable file-like object.]
<ast.Try object at 0x7da1b0e63670> | keyword[def] identifier[_is_writable] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[try] :
identifier[write] = identifier[getattr] ( identifier[obj] , literal[string] )
keyword[except] identifier[AttributeError] :
keyword[return] keyword[False]... | def _is_writable(self, obj):
"""Check if the argument is a writable file-like object."""
try:
write = getattr(obj, 'write') # depends on [control=['try'], data=[]]
except AttributeError:
return False # depends on [control=['except'], data=[]]
else:
return is_method(write, min_a... |
def _find_sections(md_ast, sections, last, last_class, total_lines=None):
"""
Walks through a CommonMark AST to find section headers that delineate
content that should be updated by this script
:param md_ast:
The AST of the markdown document
:param sections:
A dict to store the sta... | def function[_find_sections, parameter[md_ast, sections, last, last_class, total_lines]]:
constant[
Walks through a CommonMark AST to find section headers that delineate
content that should be updated by this script
:param md_ast:
The AST of the markdown document
:param sections:
... | keyword[def] identifier[_find_sections] ( identifier[md_ast] , identifier[sections] , identifier[last] , identifier[last_class] , identifier[total_lines] = keyword[None] ):
literal[string]
keyword[def] identifier[child_walker] ( identifier[node] ):
keyword[for] identifier[child] , identifier[en... | def _find_sections(md_ast, sections, last, last_class, total_lines=None):
"""
Walks through a CommonMark AST to find section headers that delineate
content that should be updated by this script
:param md_ast:
The AST of the markdown document
:param sections:
A dict to store the sta... |
def cbrt (x):
"""Returns the cube root of x."""
if x >= 0:
return math.pow(x , 1.0 / 3.0)
else:
return - math.pow(abs(x), 1.0 / 3.0) | def function[cbrt, parameter[x]]:
constant[Returns the cube root of x.]
if compare[name[x] greater_or_equal[>=] constant[0]] begin[:]
return[call[name[math].pow, parameter[name[x], binary_operation[constant[1.0] / constant[3.0]]]]] | keyword[def] identifier[cbrt] ( identifier[x] ):
literal[string]
keyword[if] identifier[x] >= literal[int] :
keyword[return] identifier[math] . identifier[pow] ( identifier[x] , literal[int] / literal[int] )
keyword[else] :
keyword[return] - identifier[math] . identifier[pow] ( identifier[abs] (... | def cbrt(x):
"""Returns the cube root of x."""
if x >= 0:
return math.pow(x, 1.0 / 3.0) # depends on [control=['if'], data=['x']]
else:
return -math.pow(abs(x), 1.0 / 3.0) |
def get_date_range_this_year(now=None):
"""Return the starting and ending date of the current school year."""
if now is None:
now = datetime.datetime.now().date()
if now.month <= settings.YEAR_TURNOVER_MONTH:
date_start = datetime.datetime(now.year - 1, 8, 1) # TODO; don't hardcode these va... | def function[get_date_range_this_year, parameter[now]]:
constant[Return the starting and ending date of the current school year.]
if compare[name[now] is constant[None]] begin[:]
variable[now] assign[=] call[call[name[datetime].datetime.now, parameter[]].date, parameter[]]
if com... | keyword[def] identifier[get_date_range_this_year] ( identifier[now] = keyword[None] ):
literal[string]
keyword[if] identifier[now] keyword[is] keyword[None] :
identifier[now] = identifier[datetime] . identifier[datetime] . identifier[now] (). identifier[date] ()
keyword[if] identifier[now... | def get_date_range_this_year(now=None):
"""Return the starting and ending date of the current school year."""
if now is None:
now = datetime.datetime.now().date() # depends on [control=['if'], data=['now']]
if now.month <= settings.YEAR_TURNOVER_MONTH:
date_start = datetime.datetime(now.yea... |
def load_config(self, namespace=None, rcfile=None):
""" Load file given in "rcfile".
"""
if namespace is None:
namespace = config
if namespace.scgi_url:
return # already have the connection to rTorrent
# Get and check config file name
if not rcfi... | def function[load_config, parameter[self, namespace, rcfile]]:
constant[ Load file given in "rcfile".
]
if compare[name[namespace] is constant[None]] begin[:]
variable[namespace] assign[=] name[config]
if name[namespace].scgi_url begin[:]
return[None]
if <... | keyword[def] identifier[load_config] ( identifier[self] , identifier[namespace] = keyword[None] , identifier[rcfile] = keyword[None] ):
literal[string]
keyword[if] identifier[namespace] keyword[is] keyword[None] :
identifier[namespace] = identifier[config]
keyword[if] ide... | def load_config(self, namespace=None, rcfile=None):
""" Load file given in "rcfile".
"""
if namespace is None:
namespace = config # depends on [control=['if'], data=['namespace']]
if namespace.scgi_url:
return # already have the connection to rTorrent # depends on [control=['if'],... |
def rename(
df,
values: Dict[str, Dict[str, str]] = None,
columns: Dict[str, Dict[str, str]] = None,
locale: str = None
):
"""
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be re... | def function[rename, parameter[df, values, columns, locale]]:
constant[
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be replaced
- value:
- key: the locale e.g. 'en' or 'fr'
... | keyword[def] identifier[rename] (
identifier[df] ,
identifier[values] : identifier[Dict] [ identifier[str] , identifier[Dict] [ identifier[str] , identifier[str] ]]= keyword[None] ,
identifier[columns] : identifier[Dict] [ identifier[str] , identifier[Dict] [ identifier[str] , identifier[str] ]]= keyword[None] ,
... | def rename(df, values: Dict[str, Dict[str, str]]=None, columns: Dict[str, Dict[str, str]]=None, locale: str=None):
"""
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be replaced
- value:
- ke... |
def _write_hex_long(self, data, pos, value):
"""
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type... | def function[_write_hex_long, parameter[self, data, pos, value]]:
constant[
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the v... | keyword[def] identifier[_write_hex_long] ( identifier[self] , identifier[data] , identifier[pos] , identifier[value] ):
literal[string]
identifier[self] . identifier[_write_hex_byte] ( identifier[data] , identifier[pos] + literal[int] ,( identifier[value] >> literal[int] )& literal[int] )
... | def _write_hex_long(self, data, pos, value):
"""
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type val... |
async def _pb_request(self, endpoint, request_pb, response_pb):
"""Send a Protocol Buffer formatted chat API request.
Args:
endpoint (str): The chat API endpoint to use.
request_pb: The request body as a Protocol Buffer message.
response_pb: The response body as a Pr... | <ast.AsyncFunctionDef object at 0x7da207f99600> | keyword[async] keyword[def] identifier[_pb_request] ( identifier[self] , identifier[endpoint] , identifier[request_pb] , identifier[response_pb] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[endpoint] ,
identifier[request_pb] )
identifie... | async def _pb_request(self, endpoint, request_pb, response_pb):
"""Send a Protocol Buffer formatted chat API request.
Args:
endpoint (str): The chat API endpoint to use.
request_pb: The request body as a Protocol Buffer message.
response_pb: The response body as a Protoc... |
def close_drivers(cls, scope, test_name, test_passed=True, context=None):
"""Stop all drivers, capture screenshots, copy webdriver and GGR logs and download saved videos
:param scope: execution scope (function, module, class or session)
:param test_name: executed test name
:param test_p... | def function[close_drivers, parameter[cls, scope, test_name, test_passed, context]]:
constant[Stop all drivers, capture screenshots, copy webdriver and GGR logs and download saved videos
:param scope: execution scope (function, module, class or session)
:param test_name: executed test name
... | keyword[def] identifier[close_drivers] ( identifier[cls] , identifier[scope] , identifier[test_name] , identifier[test_passed] = keyword[True] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[scope] == literal[string] :
keyword[if] keyword[not]... | def close_drivers(cls, scope, test_name, test_passed=True, context=None):
"""Stop all drivers, capture screenshots, copy webdriver and GGR logs and download saved videos
:param scope: execution scope (function, module, class or session)
:param test_name: executed test name
:param test_passe... |
def get_login_password(site_name="github.com",
netrc_file="~/.netrc",
git_credential_file="~/.git-credentials"):
"""Read a .netrc file and return login/password for LWN."""
try:
n = netrc.netrc(os.path.expanduser(netrc_file))
except OSError:
pass... | def function[get_login_password, parameter[site_name, netrc_file, git_credential_file]]:
constant[Read a .netrc file and return login/password for LWN.]
<ast.Try object at 0x7da18c4cd720>
<ast.Try object at 0x7da1b152ad10>
return[tuple[[<ast.Constant object at 0x7da1b1529900>, <ast.Constant object a... | keyword[def] identifier[get_login_password] ( identifier[site_name] = literal[string] ,
identifier[netrc_file] = literal[string] ,
identifier[git_credential_file] = literal[string] ):
literal[string]
keyword[try] :
identifier[n] = identifier[netrc] . identifier[netrc] ( identifier[os] . identifi... | def get_login_password(site_name='github.com', netrc_file='~/.netrc', git_credential_file='~/.git-credentials'):
"""Read a .netrc file and return login/password for LWN."""
try:
n = netrc.netrc(os.path.expanduser(netrc_file)) # depends on [control=['try'], data=[]]
except OSError:
pass # d... |
def readline(self, size=-1):
'''This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\... | def function[readline, parameter[self, size]]:
constant[This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newlin... | keyword[def] identifier[readline] ( identifier[self] , identifier[size] =- literal[int] ):
literal[string]
keyword[if] identifier[size] == literal[int] :
keyword[return] identifier[self] . identifier[string_type] ()
identifier[index] = identifier[self] . identi... | def readline(self, size=-1):
"""This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) e... |
def get_tails(chains):
"""
Args:
An ordered collection of block generators.
Returns
A dictionary of lists of blocks for all chains where:
1. The first block in all the lists has the same block number
2. Each list has all blocks from the common block to the current
... | def function[get_tails, parameter[chains]]:
constant[
Args:
An ordered collection of block generators.
Returns
A dictionary of lists of blocks for all chains where:
1. The first block in all the lists has the same block number
2. Each list has all blocks from the... | keyword[def] identifier[get_tails] ( identifier[chains] ):
literal[string]
keyword[def] identifier[get_num_of_oldest] ( identifier[blocks] ):
keyword[return] identifier[blocks] [ literal[int] ]. identifier[num]
identifier[tails] ={}
identifier[bad_chains] =[]
keyword[f... | def get_tails(chains):
"""
Args:
An ordered collection of block generators.
Returns
A dictionary of lists of blocks for all chains where:
1. The first block in all the lists has the same block number
2. Each list has all blocks from the common block to the current
... |
def tag(version, params):
"""Build and return full command to use with subprocess.Popen for 'git tag' command
:param version:
:param params:
:return: list
"""
cmd = ['git', 'tag', '-a', '-m', 'v%s' % version, str(version)]
if params:
cmd.extend(params... | def function[tag, parameter[version, params]]:
constant[Build and return full command to use with subprocess.Popen for 'git tag' command
:param version:
:param params:
:return: list
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b087a0b0>, <ast.Constant ob... | keyword[def] identifier[tag] ( identifier[version] , identifier[params] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] % identifier[version] , identifier[str] ( identifier[version] )]
keyword[if] identifier[par... | def tag(version, params):
"""Build and return full command to use with subprocess.Popen for 'git tag' command
:param version:
:param params:
:return: list
"""
cmd = ['git', 'tag', '-a', '-m', 'v%s' % version, str(version)]
if params:
cmd.extend(params) # depends on ... |
def get_abs_template_path(template_name, directory, extension):
""" Given a template name, a directory, and an extension, return the
absolute path to the template. """
# Get the relative path
relative_path = join(directory, template_name)
file_with_ext = template_name
if extension:
# If... | def function[get_abs_template_path, parameter[template_name, directory, extension]]:
constant[ Given a template name, a directory, and an extension, return the
absolute path to the template. ]
variable[relative_path] assign[=] call[name[join], parameter[name[directory], name[template_name]]]
... | keyword[def] identifier[get_abs_template_path] ( identifier[template_name] , identifier[directory] , identifier[extension] ):
literal[string]
identifier[relative_path] = identifier[join] ( identifier[directory] , identifier[template_name] )
identifier[file_with_ext] = identifier[template_name]
... | def get_abs_template_path(template_name, directory, extension):
""" Given a template name, a directory, and an extension, return the
absolute path to the template. """
# Get the relative path
relative_path = join(directory, template_name)
file_with_ext = template_name
if extension:
# If ... |
def ctypes2buffer(cptr, length):
"""Convert ctypes pointer to buffer type."""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise RuntimeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
if not ctypes.memmove(rptr, cptr, length)... | def function[ctypes2buffer, parameter[cptr, length]]:
constant[Convert ctypes pointer to buffer type.]
if <ast.UnaryOp object at 0x7da1b209b430> begin[:]
<ast.Raise object at 0x7da1b209a080>
variable[res] assign[=] call[name[bytearray], parameter[name[length]]]
variable[rptr] ass... | keyword[def] identifier[ctypes2buffer] ( identifier[cptr] , identifier[length] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[cptr] , identifier[ctypes] . identifier[POINTER] ( identifier[ctypes] . identifier[c_char] )):
keyword[raise] identifier[RuntimeError] (... | def ctypes2buffer(cptr, length):
"""Convert ctypes pointer to buffer type."""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise RuntimeError('expected char pointer') # depends on [control=['if'], data=[]]
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.