code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def smoothstep(edge0, edge1, x):
""" performs smooth Hermite interpolation
between 0 and 1 when edge0 < x < edge1. """
# Scale, bias and saturate x to 0..1 range
x = np.clip((x - edge0)/(edge1 - edge0), 0.0, 1.0)
# Evaluate polynomial
return x*x*(3 - 2*x) | def function[smoothstep, parameter[edge0, edge1, x]]:
constant[ performs smooth Hermite interpolation
between 0 and 1 when edge0 < x < edge1. ]
variable[x] assign[=] call[name[np].clip, parameter[binary_operation[binary_operation[name[x] - name[edge0]] / binary_operation[name[edge1] - name[edge... | keyword[def] identifier[smoothstep] ( identifier[edge0] , identifier[edge1] , identifier[x] ):
literal[string]
identifier[x] = identifier[np] . identifier[clip] (( identifier[x] - identifier[edge0] )/( identifier[edge1] - identifier[edge0] ), literal[int] , literal[int] )
keyword[return] id... | def smoothstep(edge0, edge1, x):
""" performs smooth Hermite interpolation
between 0 and 1 when edge0 < x < edge1. """
# Scale, bias and saturate x to 0..1 range
x = np.clip((x - edge0) / (edge1 - edge0), 0.0, 1.0)
# Evaluate polynomial
return x * x * (3 - 2 * x) |
def experiment_list(args):
'''get the information of all experiments'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1)
update_experiment()
experiment_id_list = ... | def function[experiment_list, parameter[args]]:
constant[get the information of all experiments]
variable[experiment_config] assign[=] call[name[Experiments], parameter[]]
variable[experiment_dict] assign[=] call[name[experiment_config].get_all_experiments, parameter[]]
if <ast.UnaryOp o... | keyword[def] identifier[experiment_list] ( identifier[args] ):
literal[string]
identifier[experiment_config] = identifier[Experiments] ()
identifier[experiment_dict] = identifier[experiment_config] . identifier[get_all_experiments] ()
keyword[if] keyword[not] identifier[experiment_dict] :
... | def experiment_list(args):
"""get the information of all experiments"""
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1) # depends on [control=['if'], data=[]]
updat... |
def oauth_get_user(client_id, account_info=None, access_token=None):
"""Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary with the account info.... | def function[oauth_get_user, parameter[client_id, account_info, access_token]]:
constant[Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary w... | keyword[def] identifier[oauth_get_user] ( identifier[client_id] , identifier[account_info] = keyword[None] , identifier[access_token] = keyword[None] ):
literal[string]
keyword[if] identifier[access_token] :
identifier[token] = identifier[RemoteToken] . identifier[get_by_token] ( identifier[clien... | def oauth_get_user(client_id, account_info=None, access_token=None):
"""Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary with the account info.... |
def yn2Kn2Der(nu, y, n=0, tol=5e-4, nterms=1, nu_step=0.001):
r"""Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives.
Care has been taken to handle the conditions at :math:`y=0`.
For `n=0`, uses a direct evaluation of the expression, replacing points
where `y=0` with ... | def function[yn2Kn2Der, parameter[nu, y, n, tol, nterms, nu_step]]:
constant[Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives.
Care has been taken to handle the conditions at :math:`y=0`.
For `n=0`, uses a direct evaluation of the expression, replacing points
wh... | keyword[def] identifier[yn2Kn2Der] ( identifier[nu] , identifier[y] , identifier[n] = literal[int] , identifier[tol] = literal[int] , identifier[nterms] = literal[int] , identifier[nu_step] = literal[int] ):
literal[string]
identifier[n] = identifier[int] ( identifier[n] )
identifier[y] = identifier[s... | def yn2Kn2Der(nu, y, n=0, tol=0.0005, nterms=1, nu_step=0.001):
"""Computes the function :math:`y^{\\nu/2} K_{\\nu}(y^{1/2})` and its derivatives.
Care has been taken to handle the conditions at :math:`y=0`.
For `n=0`, uses a direct evaluation of the expression, replacing points
where `y=0` wi... |
def attachment_probability(G):
"""
Calculates the observed attachment probability for each node at each
time-step.
Attachment probability is calculated based on the observed new edges in the
next time-step. So if a node acquires new edges at time t, this will accrue
to the node's attac... | def function[attachment_probability, parameter[G]]:
constant[
Calculates the observed attachment probability for each node at each
time-step.
Attachment probability is calculated based on the observed new edges in the
next time-step. So if a node acquires new edges at time t, this will... | keyword[def] identifier[attachment_probability] ( identifier[G] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[string] )
identifier[probs] ={}
identifier[G_] = keyword[None]
identifier[k_] = keyword[None]
keyword[for] identifier[k] , identifier[g] keyword[in] ... | def attachment_probability(G):
"""
Calculates the observed attachment probability for each node at each
time-step.
Attachment probability is calculated based on the observed new edges in the
next time-step. So if a node acquires new edges at time t, this will accrue
to the node's attac... |
def create_port(self, name, network, device_id=None, admin_state_up=True):
'''
Creates a new port
'''
net_id = self._find_network_id(network)
body = {'admin_state_up': admin_state_up,
'name': name,
'network_id': net_id}
if device_id:
... | def function[create_port, parameter[self, name, network, device_id, admin_state_up]]:
constant[
Creates a new port
]
variable[net_id] assign[=] call[name[self]._find_network_id, parameter[name[network]]]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b1c464a0>... | keyword[def] identifier[create_port] ( identifier[self] , identifier[name] , identifier[network] , identifier[device_id] = keyword[None] , identifier[admin_state_up] = keyword[True] ):
literal[string]
identifier[net_id] = identifier[self] . identifier[_find_network_id] ( identifier[network] )
... | def create_port(self, name, network, device_id=None, admin_state_up=True):
"""
Creates a new port
"""
net_id = self._find_network_id(network)
body = {'admin_state_up': admin_state_up, 'name': name, 'network_id': net_id}
if device_id:
body['device_id'] = device_id # depends on [c... |
def seqfy(strs):
''' 序列化 字符串--->实际效果是,为字符串,添加行号,返回字符串
Sampe usage:
strs = ["", None, u"First-line\nSecond-line\nThird-line", u"没有换行符"]
for s in strs:
print "---"
result = seqfy(s)
print result
print unseqfy(result)
'''
if no... | def function[seqfy, parameter[strs]]:
constant[ 序列化 字符串--->实际效果是,为字符串,添加行号,返回字符串
Sampe usage:
strs = ["", None, u"First-line
Second-line
Third-line", u"没有换行符"]
for s in strs:
print "---"
result = seqfy(s)
print result
print unseqfy(result)
... | keyword[def] identifier[seqfy] ( identifier[strs] ):
literal[string]
keyword[if] keyword[not] identifier[strs] :
keyword[return]
identifier[result] = literal[string]
identifier[seq] = literal[int]
identifier[ss] = identifier[strs] . identifier[split] ( literal[string]... | def seqfy(strs):
""" 序列化 字符串--->实际效果是,为字符串,添加行号,返回字符串
Sampe usage:
strs = ["", None, u"First-line
Second-line
Third-line", u"没有换行符"]
for s in strs:
print "---"
result = seqfy(s)
print result
print unseqfy(result)
"""
if not strs:
re... |
def check_num_tasks(chain, task_count):
"""Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
Raises:
CoTErr... | def function[check_num_tasks, parameter[chain, task_count]]:
constant[Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of lin... | keyword[def] identifier[check_num_tasks] ( identifier[chain] , identifier[task_count] ):
literal[string]
identifier[errors] =[]
identifier[min_decision_tasks] = literal[int]
keyword[if] identifier[task_count] [ literal[string] ]< identifier[min_decision_tasks] :
identifier[er... | def check_num_tasks(chain, task_count):
"""Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
Raises:
CoTErr... |
def set_children(self, child_ids):
"""Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
... | def function[set_children, parameter[self, child_ids]]:
constant[Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This me... | keyword[def] identifier[set_children] ( identifier[self] , identifier[child_ids] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[child_ids] , identifier[list] ):
keyword[raise] identifier[errors] . identifier[InvalidArgument] ()
keyword[if] ... | def set_children(self, child_ids):
"""Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
... |
def write_tabular_otu_table(self, sample_names, read_taxonomies, combined_output_otu_table_io):
'''A function that takes a hash of trusted placements, and compiles them
into an OTU-esque table.'''
delim = u'\t'
combined_output_otu_table_io.write(delim.join(['#ID',
... | def function[write_tabular_otu_table, parameter[self, sample_names, read_taxonomies, combined_output_otu_table_io]]:
constant[A function that takes a hash of trusted placements, and compiles them
into an OTU-esque table.]
variable[delim] assign[=] constant[ ]
call[name[combined_output_ot... | keyword[def] identifier[write_tabular_otu_table] ( identifier[self] , identifier[sample_names] , identifier[read_taxonomies] , identifier[combined_output_otu_table_io] ):
literal[string]
identifier[delim] = literal[string]
identifier[combined_output_otu_table_io] . identifier[write] ( ide... | def write_tabular_otu_table(self, sample_names, read_taxonomies, combined_output_otu_table_io):
"""A function that takes a hash of trusted placements, and compiles them
into an OTU-esque table."""
delim = u'\t'
combined_output_otu_table_io.write(delim.join(['#ID', delim.join(sample_names), 'Consensu... |
def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
... | def function[url_for_hit, parameter[hit, default]]:
constant[Helper for building URLs from results.]
<ast.Try object at 0x7da20c6c4d90> | keyword[def] identifier[url_for_hit] ( identifier[hit] , identifier[default] = literal[string] ):
literal[string]
keyword[try] :
identifier[object_type] = identifier[hit] [ literal[string] ]
identifier[object_id] = identifier[int] ( identifier[hit] [ literal[string] ])
keyword[re... | def url_for_hit(hit, default='#'):
"""Helper for building URLs from results."""
try:
object_type = hit['object_type']
object_id = int(hit['id'])
return current_app.default_view.url_for(hit, object_type, object_id) # depends on [control=['try'], data=[]]
except KeyError:
retu... |
def _setup_google_spreadsheets(settings, path, prompt=True):
"""
Set up a Google spreadsheet.
"""
ret = {}
if prompt:
use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ")
if use.lower() != "y" and use != "":
return settings
dirname = os.path.dirname... | def function[_setup_google_spreadsheets, parameter[settings, path, prompt]]:
constant[
Set up a Google spreadsheet.
]
variable[ret] assign[=] dictionary[[], []]
if name[prompt] begin[:]
variable[use] assign[=] call[name[raw_input], parameter[constant[
Would you like to us... | keyword[def] identifier[_setup_google_spreadsheets] ( identifier[settings] , identifier[path] , identifier[prompt] = keyword[True] ):
literal[string]
identifier[ret] ={}
keyword[if] identifier[prompt] :
identifier[use] = identifier[raw_input] ( literal[string] )
keyword[if] identif... | def _setup_google_spreadsheets(settings, path, prompt=True):
"""
Set up a Google spreadsheet.
"""
ret = {}
if prompt:
use = raw_input('\nWould you like to use Google spreadsheets [Y/n]? ')
if use.lower() != 'y' and use != '':
return settings # depends on [control=['if'],... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'voices') and self.voices is not None:
_dict['voices'] = [x._to_dict() for x in self.voices]
return _dict | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da204623400> begin[:]
call[name[_dict]][constant[voices]] assign[=] <ast.ListComp object at 0x7da204621300... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[voices] keyword[is] keyword[not] keyword[None] :
identifier[_dic... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'voices') and self.voices is not None:
_dict['voices'] = [x._to_dict() for x in self.voices] # depends on [control=['if'], data=[]]
return _dict |
def _create_delegate_handler(delegate):
"""Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A :class:`callable` handler that ... | def function[_create_delegate_handler, parameter[delegate]]:
constant[Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A ... | keyword[def] identifier[_create_delegate_handler] ( identifier[delegate] ):
literal[string]
@ identifier[coroutine]
keyword[def] identifier[handler] (* identifier[args] ):
keyword[yield]
keyword[yield] identifier[delegate] . identifier[send] ( identifier[Transition] ( identifier[a... | def _create_delegate_handler(delegate):
"""Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A :class:`callable` handler that ... |
def add_favicon_path(self, path: str) -> None:
"""Add path to serve favicon file.
``path`` should be a directory, which contains favicon file
(``favicon.ico``) for your app.
"""
spec = web.URLSpec(
'/(favicon.ico)',
StaticFileHandler,
dict(pat... | def function[add_favicon_path, parameter[self, path]]:
constant[Add path to serve favicon file.
``path`` should be a directory, which contains favicon file
(``favicon.ico``) for your app.
]
variable[spec] assign[=] call[name[web].URLSpec, parameter[constant[/(favicon.ico)], name... | keyword[def] identifier[add_favicon_path] ( identifier[self] , identifier[path] : identifier[str] )-> keyword[None] :
literal[string]
identifier[spec] = identifier[web] . identifier[URLSpec] (
literal[string] ,
identifier[StaticFileHandler] ,
identifier[dict] ( identifier... | def add_favicon_path(self, path: str) -> None:
"""Add path to serve favicon file.
``path`` should be a directory, which contains favicon file
(``favicon.ico``) for your app.
"""
spec = web.URLSpec('/(favicon.ico)', StaticFileHandler, dict(path=path))
# Need some check
handlers =... |
def get_pixels(self):
"""
Returns a list containing 64 smaller lists of [R,G,B] pixels
representing what is currently displayed on the LED matrix
"""
pixel_list = []
with open(self._fb_device, 'rb') as f:
map = self._pix_map[self._rotation]
for ro... | def function[get_pixels, parameter[self]]:
constant[
Returns a list containing 64 smaller lists of [R,G,B] pixels
representing what is currently displayed on the LED matrix
]
variable[pixel_list] assign[=] list[[]]
with call[name[open], parameter[name[self]._fb_device, co... | keyword[def] identifier[get_pixels] ( identifier[self] ):
literal[string]
identifier[pixel_list] =[]
keyword[with] identifier[open] ( identifier[self] . identifier[_fb_device] , literal[string] ) keyword[as] identifier[f] :
identifier[map] = identifier[self] . identifier[_p... | def get_pixels(self):
"""
Returns a list containing 64 smaller lists of [R,G,B] pixels
representing what is currently displayed on the LED matrix
"""
pixel_list = []
with open(self._fb_device, 'rb') as f:
map = self._pix_map[self._rotation]
for row in range(8):
... |
def serve_forever(self, banner=None):
"""Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``.
"""
if hasattr(readline, "read_history_file"):
try:
readline.read_history... | def function[serve_forever, parameter[self, banner]]:
constant[Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``.
]
if call[name[hasattr], parameter[name[readline], constant[read_history_file]]... | keyword[def] identifier[serve_forever] ( identifier[self] , identifier[banner] = keyword[None] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[readline] , literal[string] ):
keyword[try] :
identifier[readline] . identifier[read_history_file] ( identifi... | def serve_forever(self, banner=None):
"""Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``.
"""
if hasattr(readline, 'read_history_file'):
try:
readline.read_history_file(self.histf... |
def can_edit_post(self, post, user):
""" Given a forum post, checks whether the user can edit the latter. """
checker = self._get_checker(user)
# A user can edit a post if...
# they are a superuser
# they are the original poster of the forum post
# they belon... | def function[can_edit_post, parameter[self, post, user]]:
constant[ Given a forum post, checks whether the user can edit the latter. ]
variable[checker] assign[=] call[name[self]._get_checker, parameter[name[user]]]
variable[is_author] assign[=] call[name[self]._is_post_author, parameter[name[po... | keyword[def] identifier[can_edit_post] ( identifier[self] , identifier[post] , identifier[user] ):
literal[string]
identifier[checker] = identifier[self] . identifier[_get_checker] ( identifier[user] )
identifier[is_author] = identifier[self] . identifi... | def can_edit_post(self, post, user):
""" Given a forum post, checks whether the user can edit the latter. """
checker = self._get_checker(user)
# A user can edit a post if...
# they are a superuser
# they are the original poster of the forum post
# they belong to the forum moderators... |
def run_simulation(projectname: str, xmlfile: str):
"""Perform a HydPy workflow in agreement with the given XML configuration
file available in the directory of the given project. ToDo
Function |run_simulation| is a "script function" and is normally used as
explained in the main documentation on module... | def function[run_simulation, parameter[projectname, xmlfile]]:
constant[Perform a HydPy workflow in agreement with the given XML configuration
file available in the directory of the given project. ToDo
Function |run_simulation| is a "script function" and is normally used as
explained in the main do... | keyword[def] identifier[run_simulation] ( identifier[projectname] : identifier[str] , identifier[xmlfile] : identifier[str] ):
literal[string]
identifier[write] = identifier[commandtools] . identifier[print_textandtime]
identifier[hydpy] . identifier[pub] . identifier[options] . identifier[printprogr... | def run_simulation(projectname: str, xmlfile: str):
"""Perform a HydPy workflow in agreement with the given XML configuration
file available in the directory of the given project. ToDo
Function |run_simulation| is a "script function" and is normally used as
explained in the main documentation on module... |
def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0
except ConfigParser.Error as error:
print('Error: %s' % error)
return 1
except:
print('Unexpected Error')
... | def function[lint, parameter[filename]]:
constant[Lints an INI file, returning 0 in case of success.]
variable[config] assign[=] call[name[ConfigParser].ConfigParser, parameter[]]
<ast.Try object at 0x7da1b0b64580> | keyword[def] identifier[lint] ( identifier[filename] ):
literal[string]
identifier[config] = identifier[ConfigParser] . identifier[ConfigParser] ()
keyword[try] :
identifier[config] . identifier[read] ( identifier[filename] )
keyword[return] literal[int]
keyword[except] ident... | def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0 # depends on [control=['try'], data=[]]
except ConfigParser.Error as error:
print('Error: %s' % error)
return 1 # depend... |
def SYSCALL(cpu):
"""
Calls to interrupt procedure.
The INT n instruction generates a call to the interrupt or exception handler specified
with the destination operand. The INT n instruction is the general mnemonic for executing
a software-generated call to an interrupt handler.... | def function[SYSCALL, parameter[cpu]]:
constant[
Calls to interrupt procedure.
The INT n instruction generates a call to the interrupt or exception handler specified
with the destination operand. The INT n instruction is the general mnemonic for executing
a software-generated ca... | keyword[def] identifier[SYSCALL] ( identifier[cpu] ):
literal[string]
identifier[cpu] . identifier[RCX] = identifier[cpu] . identifier[RIP]
identifier[cpu] . identifier[R11] = identifier[cpu] . identifier[RFLAGS]
keyword[raise] identifier[Syscall] () | def SYSCALL(cpu):
"""
Calls to interrupt procedure.
The INT n instruction generates a call to the interrupt or exception handler specified
with the destination operand. The INT n instruction is the general mnemonic for executing
a software-generated call to an interrupt handler. The... |
def _update(self, resource, update_dict=None, params=None, **kwargs):
"""Update the object."""
url = self._client._build_url(resource, **kwargs)
response = self._client._request('PUT', url, json=update_dict, params=params)
if response.status_code != requests.codes.ok: # pragma: no cove... | def function[_update, parameter[self, resource, update_dict, params]]:
constant[Update the object.]
variable[url] assign[=] call[name[self]._client._build_url, parameter[name[resource]]]
variable[response] assign[=] call[name[self]._client._request, parameter[constant[PUT], name[url]]]
i... | keyword[def] identifier[_update] ( identifier[self] , identifier[resource] , identifier[update_dict] = keyword[None] , identifier[params] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[url] = identifier[self] . identifier[_client] . identifier[_build_url] ( identifier[resource... | def _update(self, resource, update_dict=None, params=None, **kwargs):
"""Update the object."""
url = self._client._build_url(resource, **kwargs)
response = self._client._request('PUT', url, json=update_dict, params=params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise A... |
def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs):
"""
To send email
:param to: the recipients, list or string
:param subject: the subject
:param body: the body
:param reply_to: reply_to
:param template: template, will use the tem... | def function[send, parameter[self, to, subject, body, reply_to, template]]:
constant[
To send email
:param to: the recipients, list or string
:param subject: the subject
:param body: the body
:param reply_to: reply_to
:param template: template, will use the templa... | keyword[def] identifier[send] ( identifier[self] , identifier[to] , identifier[subject] = keyword[None] , identifier[body] = keyword[None] , identifier[reply_to] = keyword[None] , identifier[template] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[sender] = identifier[self] . ... | def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs):
"""
To send email
:param to: the recipients, list or string
:param subject: the subject
:param body: the body
:param reply_to: reply_to
:param template: template, will use the templat... |
def right_click_high_equalarea(self, event):
"""
toggles between zoom and pan effects for the high equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
high_EA_setting, t... | def function[right_click_high_equalarea, parameter[self, event]]:
constant[
toggles between zoom and pan effects for the high equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------... | keyword[def] identifier[right_click_high_equalarea] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[event] . identifier[LeftIsDown] ():
keyword[return]
keyword[elif] identifier[self] . identifier[high_EA_setting] == literal[string] :
... | def right_click_high_equalarea(self, event):
"""
toggles between zoom and pan effects for the high equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
high_EA_setting, toolb... |
def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim']
self.projection_count = config['projection_count']
self.normals = config['normals']
self.tree_root = config['tree_root']
self.minim... | def function[apply_config, parameter[self, config]]:
constant[
Applies config
]
name[self].hash_name assign[=] call[name[config]][constant[hash_name]]
name[self].dim assign[=] call[name[config]][constant[dim]]
name[self].projection_count assign[=] call[name[config]][const... | keyword[def] identifier[apply_config] ( identifier[self] , identifier[config] ):
literal[string]
identifier[self] . identifier[hash_name] = identifier[config] [ literal[string] ]
identifier[self] . identifier[dim] = identifier[config] [ literal[string] ]
identifier[self] . identif... | def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim']
self.projection_count = config['projection_count']
self.normals = config['normals']
self.tree_root = config['tree_root']
self.minimum_result_size = config['min... |
def _reproject(wcs1, wcs2):
"""
Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Returns
-------
... | def function[_reproject, parameter[wcs1, wcs2]]:
constant[
Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Re... | keyword[def] identifier[_reproject] ( identifier[wcs1] , identifier[wcs2] ):
literal[string]
keyword[import] identifier[gwcs]
identifier[forward_origin] =[]
keyword[if] identifier[isinstance] ( identifier[wcs1] , identifier[fitswcs] . identifier[WCS] ):
identifie... | def _reproject(wcs1, wcs2):
"""
Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Returns
-------
r... |
def _save(self, stateName, path):
"""save into 'stateName' to pyz-path"""
print('saving...')
state = {'session': dict(self.opts),
'dialogs': self.dialogs.saveState()}
self.sigSave.emit(state)
self.saveThread.prepare(stateName, path, self.tmp_dir_session... | def function[_save, parameter[self, stateName, path]]:
constant[save into 'stateName' to pyz-path]
call[name[print], parameter[constant[saving...]]]
variable[state] assign[=] dictionary[[<ast.Constant object at 0x7da1b158a3e0>, <ast.Constant object at 0x7da1b158ad70>], [<ast.Call object at 0x7da... | keyword[def] identifier[_save] ( identifier[self] , identifier[stateName] , identifier[path] ):
literal[string]
identifier[print] ( literal[string] )
identifier[state] ={ literal[string] : identifier[dict] ( identifier[self] . identifier[opts] ),
literal[string] : identifier... | def _save(self, stateName, path):
"""save into 'stateName' to pyz-path"""
print('saving...')
state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()}
self.sigSave.emit(state)
self.saveThread.prepare(stateName, path, self.tmp_dir_session, state)
self.saveThread.start()
self.c... |
def _set_aspect(self, axes, aspect):
"""
Set the aspect on the axes based on the aspect setting.
"""
if ((isinstance(aspect, util.basestring) and aspect != 'square') or
self.data_aspect):
data_ratio = self.data_aspect or aspect
else:
(x0, x1), ... | def function[_set_aspect, parameter[self, axes, aspect]]:
constant[
Set the aspect on the axes based on the aspect setting.
]
if <ast.BoolOp object at 0x7da18dc05c00> begin[:]
variable[data_ratio] assign[=] <ast.BoolOp object at 0x7da18dc04e20>
call[name[axes].set... | keyword[def] identifier[_set_aspect] ( identifier[self] , identifier[axes] , identifier[aspect] ):
literal[string]
keyword[if] (( identifier[isinstance] ( identifier[aspect] , identifier[util] . identifier[basestring] ) keyword[and] identifier[aspect] != literal[string] ) keyword[or]
ide... | def _set_aspect(self, axes, aspect):
"""
Set the aspect on the axes based on the aspect setting.
"""
if isinstance(aspect, util.basestring) and aspect != 'square' or self.data_aspect:
data_ratio = self.data_aspect or aspect # depends on [control=['if'], data=[]]
else:
((x0, ... |
def pipeRecvConsole(self):
'''watch for piped data from save dialog'''
try:
while True:
console_msg = self.parent_pipe_recv_console.recv()
if console_msg is not None:
self.console.writeln(console_msg)
time.sleep(0.1)
... | def function[pipeRecvConsole, parameter[self]]:
constant[watch for piped data from save dialog]
<ast.Try object at 0x7da18f09f010> | keyword[def] identifier[pipeRecvConsole] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[while] keyword[True] :
identifier[console_msg] = identifier[self] . identifier[parent_pipe_recv_console] . identifier[recv] ()
keyword[if] identifie... | def pipeRecvConsole(self):
"""watch for piped data from save dialog"""
try:
while True:
console_msg = self.parent_pipe_recv_console.recv()
if console_msg is not None:
self.console.writeln(console_msg) # depends on [control=['if'], data=['console_msg']]
... |
def a_over_Rs(P,R2,M2,M1=1,R1=1,planet=True):
"""
Returns a/Rs for given parameters.
"""
if planet:
M2 *= REARTH/RSUN
R2 *= MEARTH/MSUN
return semimajor(P,M1+M2)*AU/(R1*RSUN) | def function[a_over_Rs, parameter[P, R2, M2, M1, R1, planet]]:
constant[
Returns a/Rs for given parameters.
]
if name[planet] begin[:]
<ast.AugAssign object at 0x7da1b285b640>
<ast.AugAssign object at 0x7da1b285ab90>
return[binary_operation[binary_operation[call[name[semimajo... | keyword[def] identifier[a_over_Rs] ( identifier[P] , identifier[R2] , identifier[M2] , identifier[M1] = literal[int] , identifier[R1] = literal[int] , identifier[planet] = keyword[True] ):
literal[string]
keyword[if] identifier[planet] :
identifier[M2] *= identifier[REARTH] / identifier[RSUN]
... | def a_over_Rs(P, R2, M2, M1=1, R1=1, planet=True):
"""
Returns a/Rs for given parameters.
"""
if planet:
M2 *= REARTH / RSUN
R2 *= MEARTH / MSUN # depends on [control=['if'], data=[]]
return semimajor(P, M1 + M2) * AU / (R1 * RSUN) |
def upload_receipt(self, url, data):
"""Upload a receipt to the give url
:param url:
:param data:
:return:
"""
return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json') | def function[upload_receipt, parameter[self, url, data]]:
constant[Upload a receipt to the give url
:param url:
:param data:
:return:
]
return[call[name[self].upload_attachment, parameter[]]] | keyword[def] identifier[upload_receipt] ( identifier[self] , identifier[url] , identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[upload_attachment] ( identifier[url] = identifier[url] , identifier[data] = identifier[data] , identifier[mime_type] = literal[string] ) | def upload_receipt(self, url, data):
"""Upload a receipt to the give url
:param url:
:param data:
:return:
"""
return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json') |
def nelect(self):
"""
Gets the default number of electrons for a given structure.
"""
# if structure is not sorted this can cause problems, so must take
# care to remove redundant symbols when counting electrons
site_symbols = list(set(self.poscar.site_symbols))
n... | def function[nelect, parameter[self]]:
constant[
Gets the default number of electrons for a given structure.
]
variable[site_symbols] assign[=] call[name[list], parameter[call[name[set], parameter[name[self].poscar.site_symbols]]]]
variable[nelect] assign[=] constant[0.0]
... | keyword[def] identifier[nelect] ( identifier[self] ):
literal[string]
identifier[site_symbols] = identifier[list] ( identifier[set] ( identifier[self] . identifier[poscar] . identifier[site_symbols] ))
identifier[nelect] = literal[int]
keyword[for] identifier[p... | def nelect(self):
"""
Gets the default number of electrons for a given structure.
"""
# if structure is not sorted this can cause problems, so must take
# care to remove redundant symbols when counting electrons
site_symbols = list(set(self.poscar.site_symbols))
nelect = 0.0
for ... |
def prep_files(paths, extensions):
"""Parses `paths` (which may consist of files and/or directories).
Removes duplicates, sorts, and returns verified srt files."""
from batchpath import GeneratePaths
filenames = GeneratePaths().files(paths, os.W_OK, extensions, 0, True)
if filenames:
retu... | def function[prep_files, parameter[paths, extensions]]:
constant[Parses `paths` (which may consist of files and/or directories).
Removes duplicates, sorts, and returns verified srt files.]
from relative_module[batchpath] import module[GeneratePaths]
variable[filenames] assign[=] call[call[name[G... | keyword[def] identifier[prep_files] ( identifier[paths] , identifier[extensions] ):
literal[string]
keyword[from] identifier[batchpath] keyword[import] identifier[GeneratePaths]
identifier[filenames] = identifier[GeneratePaths] (). identifier[files] ( identifier[paths] , identifier[os] . identif... | def prep_files(paths, extensions):
"""Parses `paths` (which may consist of files and/or directories).
Removes duplicates, sorts, and returns verified srt files."""
from batchpath import GeneratePaths
filenames = GeneratePaths().files(paths, os.W_OK, extensions, 0, True)
if filenames:
return ... |
def pages(self):
"""Get pages, reloading the site if needed."""
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._pages | def function[pages, parameter[self]]:
constant[Get pages, reloading the site if needed.]
variable[rev] assign[=] call[name[self].db.get, parameter[constant[site:rev]]]
if compare[call[name[int], parameter[name[rev]]] not_equal[!=] name[self].revision] begin[:]
call[name[self].rel... | keyword[def] identifier[pages] ( identifier[self] ):
literal[string]
identifier[rev] = identifier[self] . identifier[db] . identifier[get] ( literal[string] )
keyword[if] identifier[int] ( identifier[rev] )!= identifier[self] . identifier[revision] :
identifier[self] . identi... | def pages(self):
"""Get pages, reloading the site if needed."""
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site() # depends on [control=['if'], data=[]]
return self._pages |
def group(*args, **kwargs):
"""Decorator to define a command group.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
object constructor.
"""
def decorator(f):
f.required = kwargs.pop('required',... | def function[group, parameter[]]:
constant[Decorator to define a command group.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html#argumentparser-objects>`_
object constructor.
]
def function[decorator, parameter[f]]:
... | keyword[def] identifier[group] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
identifier[f] . identifier[required] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[True] )
keyword[if] literal[string] ... | def group(*args, **kwargs):
"""Decorator to define a command group.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html#argumentparser-objects>`_
object constructor.
"""
def decorator(f):
f.required = kwargs.pop('required', ... |
def run_fba(model, rxn_id, direction="max", single_value=True):
"""
Return the solution of an FBA to a set objective function.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
rxn_id : string
A string containing the reaction ID of the desired FB... | def function[run_fba, parameter[model, rxn_id, direction, single_value]]:
constant[
Return the solution of an FBA to a set objective function.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
rxn_id : string
A string containing the reaction ... | keyword[def] identifier[run_fba] ( identifier[model] , identifier[rxn_id] , identifier[direction] = literal[string] , identifier[single_value] = keyword[True] ):
literal[string]
identifier[model] . identifier[objective] = identifier[model] . identifier[reactions] . identifier[get_by_id] ( identifier[rxn_id... | def run_fba(model, rxn_id, direction='max', single_value=True):
"""
Return the solution of an FBA to a set objective function.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
rxn_id : string
A string containing the reaction ID of the desired FB... |
def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is Fals... | def function[print_model, parameter[self, include_unsigned_edges]]:
constant[Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most P... | keyword[def] identifier[print_model] ( identifier[self] , identifier[include_unsigned_edges] = keyword[False] ):
literal[string]
identifier[sif_str] = literal[string]
keyword[for] identifier[edge] keyword[in] identifier[self] . identifier[graph] . identifier[edges] ( identifier[data] =... | def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False.
... |
def pack_iterable(messages):
'''Pack an iterable of messages in the TCP protocol format'''
# [ 4-byte body size ]
# [ 4-byte num messages ]
# [ 4-byte message #1 size ][ N-byte binary data ]
# ... (repeated <num_messages> times)
return pack_string(
struct.pack('>l', len(messages)) +... | def function[pack_iterable, parameter[messages]]:
constant[Pack an iterable of messages in the TCP protocol format]
return[call[name[pack_string], parameter[binary_operation[call[name[struct].pack, parameter[constant[>l], call[name[len], parameter[name[messages]]]]] + call[constant[].join, parameter[call[na... | keyword[def] identifier[pack_iterable] ( identifier[messages] ):
literal[string]
keyword[return] identifier[pack_string] (
identifier[struct] . identifier[pack] ( literal[string] , identifier[len] ( identifier[messages] ))+
literal[string] . identifier[join] ( identifier[map]... | def pack_iterable(messages):
"""Pack an iterable of messages in the TCP protocol format"""
# [ 4-byte body size ]
# [ 4-byte num messages ]
# [ 4-byte message #1 size ][ N-byte binary data ]
# ... (repeated <num_messages> times)
return pack_string(struct.pack('>l', len(messages)) + ''.join(... |
def __setup_dfs_data(graph, adj):
"""Sets up the dfs_data object, for consistency."""
dfs_data = __get_dfs_data(graph, adj)
dfs_data['graph'] = graph
dfs_data['adj'] = adj
L1, L2 = __low_point_dfs(dfs_data)
dfs_data['lowpoint_1_lookup'] = L1
dfs_data['lowpoint_2_lookup'] = L2
edge_wei... | def function[__setup_dfs_data, parameter[graph, adj]]:
constant[Sets up the dfs_data object, for consistency.]
variable[dfs_data] assign[=] call[name[__get_dfs_data], parameter[name[graph], name[adj]]]
call[name[dfs_data]][constant[graph]] assign[=] name[graph]
call[name[dfs_data]][const... | keyword[def] identifier[__setup_dfs_data] ( identifier[graph] , identifier[adj] ):
literal[string]
identifier[dfs_data] = identifier[__get_dfs_data] ( identifier[graph] , identifier[adj] )
identifier[dfs_data] [ literal[string] ]= identifier[graph]
identifier[dfs_data] [ literal[string] ]= iden... | def __setup_dfs_data(graph, adj):
"""Sets up the dfs_data object, for consistency."""
dfs_data = __get_dfs_data(graph, adj)
dfs_data['graph'] = graph
dfs_data['adj'] = adj
(L1, L2) = __low_point_dfs(dfs_data)
dfs_data['lowpoint_1_lookup'] = L1
dfs_data['lowpoint_2_lookup'] = L2
edge_weig... |
def DOM_setOuterHTML(self, nodeId, outerHTML):
"""
Function path: DOM.setOuterHTML
Domain: DOM
Method name: setOuterHTML
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to set markup for.
'outerHTML' (type: string) -> Outer HTML markup to set.
No return value.
... | def function[DOM_setOuterHTML, parameter[self, nodeId, outerHTML]]:
constant[
Function path: DOM.setOuterHTML
Domain: DOM
Method name: setOuterHTML
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to set markup for.
'outerHTML' (type: string) -> Outer HTML ma... | keyword[def] identifier[DOM_setOuterHTML] ( identifier[self] , identifier[nodeId] , identifier[outerHTML] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[outerHTML] ,( identifier[str] ,)
), literal[string] % identifier[type] (
identifier[outerHTML] )
identifier[subdom_funcs] = i... | def DOM_setOuterHTML(self, nodeId, outerHTML):
"""
Function path: DOM.setOuterHTML
Domain: DOM
Method name: setOuterHTML
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to set markup for.
'outerHTML' (type: string) -> Outer HTML markup to set.
No return value... |
def server_random(self):
"""
Retrieve the random value used with the server hello message.
:return: A string representing the state
"""
session = _lib.SSL_get_session(self._ssl)
if session == _ffi.NULL:
return None
length = _lib.SSL_get_server_random(... | def function[server_random, parameter[self]]:
constant[
Retrieve the random value used with the server hello message.
:return: A string representing the state
]
variable[session] assign[=] call[name[_lib].SSL_get_session, parameter[name[self]._ssl]]
if compare[name[sessi... | keyword[def] identifier[server_random] ( identifier[self] ):
literal[string]
identifier[session] = identifier[_lib] . identifier[SSL_get_session] ( identifier[self] . identifier[_ssl] )
keyword[if] identifier[session] == identifier[_ffi] . identifier[NULL] :
keyword[return] ... | def server_random(self):
"""
Retrieve the random value used with the server hello message.
:return: A string representing the state
"""
session = _lib.SSL_get_session(self._ssl)
if session == _ffi.NULL:
return None # depends on [control=['if'], data=[]]
length = _lib.SS... |
def get_configurations(self, id, **kwargs):
"""
Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... | def function[get_configurations, parameter[self, id]]:
constant[
Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving ... | keyword[def] identifier[get_configurations] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[s... | def get_configurations(self, id, **kwargs):
"""
Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... |
def google_app_engine_ndb_delete_expired_sessions(dormant_for=86400, limit=500):
"""
Deletes expired sessions
A session is expired if it expires date is set and has passed or
if it has not been accessed for a given period of time.
:param dormant_for: seconds since last access to delete sessions, de... | def function[google_app_engine_ndb_delete_expired_sessions, parameter[dormant_for, limit]]:
constant[
Deletes expired sessions
A session is expired if it expires date is set and has passed or
if it has not been accessed for a given period of time.
:param dormant_for: seconds since last access t... | keyword[def] identifier[google_app_engine_ndb_delete_expired_sessions] ( identifier[dormant_for] = literal[int] , identifier[limit] = literal[int] ):
literal[string]
keyword[from] identifier[vishnu] . identifier[backend] . identifier[client] . identifier[google_app_engine_ndb] keyword[import] identifier... | def google_app_engine_ndb_delete_expired_sessions(dormant_for=86400, limit=500):
"""
Deletes expired sessions
A session is expired if it expires date is set and has passed or
if it has not been accessed for a given period of time.
:param dormant_for: seconds since last access to delete sessions, de... |
def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None):
"""Creates a set of new records or updates the existing
ones with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
rows:... | def function[bulk_upsert, parameter[self, conflict_target, rows, index_predicate]]:
constant[Creates a set of new records or updates the existing
ones with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
rows:
... | keyword[def] identifier[bulk_upsert] ( identifier[self] , identifier[conflict_target] : identifier[List] , identifier[rows] : identifier[List] [ identifier[Dict] ], identifier[index_predicate] : identifier[str] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[rows] keyword... | def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None):
"""Creates a set of new records or updates the existing
ones with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
rows:
... |
def set_default_reference(self, method, reference):
"""
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference}
"""
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.... | def function[set_default_reference, parameter[self, method, reference]]:
constant[
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference}
]
if compare[name[method] <ast.NotIn object at 0x7da2590d7190> name[se... | keyword[def] identifier[set_default_reference] ( identifier[self] , identifier[method] , identifier[reference] ):
literal[string]
keyword[if] identifier[method] keyword[not] keyword[in] identifier[self] . identifier[_available_methods] :
keyword[raise] identifier[ValueError] ( lit... | def set_default_reference(self, method, reference):
"""
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference}
"""
if method not in self._available_methods:
raise ValueError('Unknown method: {0}'.format(metho... |
def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return v... | def function[extract_constant, parameter[code, symbol, default]]:
constant[Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, ... | keyword[def] identifier[extract_constant] ( identifier[code] , identifier[symbol] , identifier[default] =- literal[int] ):
literal[string]
keyword[if] identifier[symbol] keyword[not] keyword[in] identifier[code] . identifier[co_names] :
keyword[return] keyword[None]
identifier[na... | def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return v... |
def attached(name, force=False):
'''
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](instal... | def function[attached, parameter[name, force]]:
constant[
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da1b1c610f0>, <ast.Constant object at 0x7da1b1c60820>,... | keyword[def] identifier[attached] ( identifier[name] , identifier[force] = keyword[False] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[None] ,
literal[string] : literal[string] }
identifier[zones] = identifier... | def attached(name, force=False):
"""
Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone
"""
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if ... |
def parse_delta(filename):
"""Returns (alignment length, similarity errors) tuple from passed .delta.
- filename - path to the input .delta file
Extracts the aligned length and number of similarity errors for each
aligned uniquely-matched region, and returns the cumulative total for
each as a tupl... | def function[parse_delta, parameter[filename]]:
constant[Returns (alignment length, similarity errors) tuple from passed .delta.
- filename - path to the input .delta file
Extracts the aligned length and number of similarity errors for each
aligned uniquely-matched region, and returns the cumulati... | keyword[def] identifier[parse_delta] ( identifier[filename] ):
literal[string]
identifier[aln_length] , identifier[sim_errors] = literal[int] , literal[int]
keyword[for] identifier[line] keyword[in] [ identifier[l] . identifier[strip] (). identifier[split] () keyword[for] identifier[l] keyword[in... | def parse_delta(filename):
"""Returns (alignment length, similarity errors) tuple from passed .delta.
- filename - path to the input .delta file
Extracts the aligned length and number of similarity errors for each
aligned uniquely-matched region, and returns the cumulative total for
each as a tupl... |
def is_admin(self, roles):
"""determine from a list of roles if is ldapcherry administrator"""
for r in roles:
if r in self.admin_roles:
return True
return False | def function[is_admin, parameter[self, roles]]:
constant[determine from a list of roles if is ldapcherry administrator]
for taget[name[r]] in starred[name[roles]] begin[:]
if compare[name[r] in name[self].admin_roles] begin[:]
return[constant[True]]
return[constant[False]... | keyword[def] identifier[is_admin] ( identifier[self] , identifier[roles] ):
literal[string]
keyword[for] identifier[r] keyword[in] identifier[roles] :
keyword[if] identifier[r] keyword[in] identifier[self] . identifier[admin_roles] :
keyword[return] keyword[True... | def is_admin(self, roles):
"""determine from a list of roles if is ldapcherry administrator"""
for r in roles:
if r in self.admin_roles:
return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['r']]
return False |
def alpha_balance_loss(labels, loss, alpha_weights):
"""
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label c... | def function[alpha_balance_loss, parameter[labels, loss, alpha_weights]]:
constant[
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
:param labels: A float tensor of shape [batch_size, ..., num_cl... | keyword[def] identifier[alpha_balance_loss] ( identifier[labels] , identifier[loss] , identifier[alpha_weights] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( literal[string] ):
identifier[weights] = identifier[tf] . identifier[reduce_sum] ( identifier[labels]... | def alpha_balance_loss(labels, loss, alpha_weights):
"""
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label c... |
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
conti... | def function[register_function_hooks, parameter[self, func]]:
constant[Looks at an object method and registers it for relevent transitions.]
for taget[tuple[[<ast.Name object at 0x7da18f58d930>, <ast.Name object at 0x7da18f58f970>]]] in starred[call[name[func].xworkflows_hook.items, parameter[]]] begin[... | keyword[def] identifier[register_function_hooks] ( identifier[self] , identifier[func] ):
literal[string]
keyword[for] identifier[hook_kind] , identifier[hooks] keyword[in] identifier[func] . identifier[xworkflows_hook] . identifier[items] ():
keyword[for] identifier[field_name] , ... | def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for (hook_kind, hooks) in func.xworkflows_hook.items():
for (field_name, hook) in hooks:
if field_name and field_name != self.state_field:
continue # depends o... |
def verify_images(path:PathOrStr, delete:bool=True, max_workers:int=4, max_size:Union[int]=None, recurse:bool=False,
dest:PathOrStr='.', n_channels:int=3, interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None,
resume:bool=None, **kwargs):
"Check if the images in `path` are... | def function[verify_images, parameter[path, delete, max_workers, max_size, recurse, dest, n_channels, interp, ext, img_format, resume]]:
constant[Check if the images in `path` aren't broken, maybe resize them and copy it in `dest`.]
variable[path] assign[=] call[name[Path], parameter[name[path]]]
... | keyword[def] identifier[verify_images] ( identifier[path] : identifier[PathOrStr] , identifier[delete] : identifier[bool] = keyword[True] , identifier[max_workers] : identifier[int] = literal[int] , identifier[max_size] : identifier[Union] [ identifier[int] ]= keyword[None] , identifier[recurse] : identifier[bool] = ... | def verify_images(path: PathOrStr, delete: bool=True, max_workers: int=4, max_size: Union[int]=None, recurse: bool=False, dest: PathOrStr='.', n_channels: int=3, interp=PIL.Image.BILINEAR, ext: str=None, img_format: str=None, resume: bool=None, **kwargs):
"""Check if the images in `path` aren't broken, maybe resize... |
def walk(self, basedir):
"""Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk
"""
system_d = SitePackagesDir()
filter_system_d = system_d and os.path.commonprefix([system_d, ba... | def function[walk, parameter[self, basedir]]:
constant[Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk
]
variable[system_d] assign[=] call[name[SitePackagesDir], parameter[]]
... | keyword[def] identifier[walk] ( identifier[self] , identifier[basedir] ):
literal[string]
identifier[system_d] = identifier[SitePackagesDir] ()
identifier[filter_system_d] = identifier[system_d] keyword[and] identifier[os] . identifier[path] . identifier[commonprefix] ([ identifier[syste... | def walk(self, basedir):
"""Walk all the directories of basedir except hidden directories
:param basedir: string, the directory to walk
:returns: generator, same as os.walk
"""
system_d = SitePackagesDir()
filter_system_d = system_d and os.path.commonprefix([system_d, basedir]) != s... |
def notebook_to_md(notebook):
"""Convert a notebook to its Markdown representation, using Pandoc"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(ipynb_writes(notebook).encode('utf-8'))
tmp_file.close()
pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre... | def function[notebook_to_md, parameter[notebook]]:
constant[Convert a notebook to its Markdown representation, using Pandoc]
variable[tmp_file] assign[=] call[name[tempfile].NamedTemporaryFile, parameter[]]
call[name[tmp_file].write, parameter[call[call[name[ipynb_writes], parameter[name[noteboo... | keyword[def] identifier[notebook_to_md] ( identifier[notebook] ):
literal[string]
identifier[tmp_file] = identifier[tempfile] . identifier[NamedTemporaryFile] ( identifier[delete] = keyword[False] )
identifier[tmp_file] . identifier[write] ( identifier[ipynb_writes] ( identifier[notebook] ). identifie... | def notebook_to_md(notebook):
"""Convert a notebook to its Markdown representation, using Pandoc"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(ipynb_writes(notebook).encode('utf-8'))
tmp_file.close()
pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pres... |
def allocate_ids(self, project_id, keys):
"""Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb2.Key]
:param keys:... | def function[allocate_ids, parameter[self, project_id, keys]]:
constant[Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb... | keyword[def] identifier[allocate_ids] ( identifier[self] , identifier[project_id] , identifier[keys] ):
literal[string]
identifier[request_pb] = identifier[_datastore_pb2] . identifier[AllocateIdsRequest] ( identifier[keys] = identifier[keys] )
keyword[return] identifier[_rpc] (
... | def allocate_ids(self, project_id, keys):
"""Perform an ``allocateIds`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type keys: List[.entity_pb2.Key]
:param keys: The... |
def publish(self, body, routing_key, exchange='amq.default',
virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange ... | def function[publish, parameter[self, body, routing_key, exchange, virtual_host, properties, payload_encoding]]:
constant[Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the messag... | keyword[def] identifier[publish] ( identifier[self] , identifier[body] , identifier[routing_key] , identifier[exchange] = literal[string] ,
identifier[virtual_host] = literal[string] , identifier[properties] = keyword[None] , identifier[payload_encoding] = literal[string] ):
literal[string]
identi... | def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the messa... |
def get_cnts_levels_depths_recs(recs):
"""Collect counts of levels and depths in a Group of GO Terms."""
cnts = cx.defaultdict(lambda: cx.defaultdict(cx.Counter))
for rec in recs:
if rec is not None and not rec.is_obsolete:
cnts['level'][rec.level][rec.namespace] += 1... | def function[get_cnts_levels_depths_recs, parameter[recs]]:
constant[Collect counts of levels and depths in a Group of GO Terms.]
variable[cnts] assign[=] call[name[cx].defaultdict, parameter[<ast.Lambda object at 0x7da2044c38b0>]]
for taget[name[rec]] in starred[name[recs]] begin[:]
... | keyword[def] identifier[get_cnts_levels_depths_recs] ( identifier[recs] ):
literal[string]
identifier[cnts] = identifier[cx] . identifier[defaultdict] ( keyword[lambda] : identifier[cx] . identifier[defaultdict] ( identifier[cx] . identifier[Counter] ))
keyword[for] identifier[rec] keywo... | def get_cnts_levels_depths_recs(recs):
"""Collect counts of levels and depths in a Group of GO Terms."""
cnts = cx.defaultdict(lambda : cx.defaultdict(cx.Counter))
for rec in recs:
if rec is not None and (not rec.is_obsolete):
cnts['level'][rec.level][rec.namespace] += 1
cnts... |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the sysctl output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
# The KeyValueParser generates an ordered d... | def function[Parse, parameter[self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base]]:
constant[Parse the sysctl output.]
variable[_] assign[=] tuple[[<ast.Name object at 0x7da1b1b465c0>, <ast.Name object at 0x7da1b1b463e0>, <ast.Name object at 0x7da1b1b452a0>, <ast.Name object at 0x7d... | keyword[def] identifier[Parse] ( identifier[self] , identifier[cmd] , identifier[args] , identifier[stdout] , identifier[stderr] , identifier[return_val] , identifier[time_taken] ,
identifier[knowledge_base] ):
literal[string]
identifier[_] = identifier[stderr] , identifier[time_taken] , identifier[args] ... | def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base):
"""Parse the sysctl output."""
_ = (stderr, time_taken, args, knowledge_base) # Unused.
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
# The KeyValueParser generates an ordered dict by def... |
def guess_payload_class(self, payload):
"""
ISOTP encodes the frame type in the first nibble of a frame.
"""
t = (orb(payload[0]) & 0xf0) >> 4
if t == 0:
return ISOTP_SF
elif t == 1:
return ISOTP_FF
elif t == 2:
return ISOTP_CF
... | def function[guess_payload_class, parameter[self, payload]]:
constant[
ISOTP encodes the frame type in the first nibble of a frame.
]
variable[t] assign[=] binary_operation[binary_operation[call[name[orb], parameter[call[name[payload]][constant[0]]]] <ast.BitAnd object at 0x7da2590d6b60>... | keyword[def] identifier[guess_payload_class] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[t] =( identifier[orb] ( identifier[payload] [ literal[int] ])& literal[int] )>> literal[int]
keyword[if] identifier[t] == literal[int] :
keyword[return] ident... | def guess_payload_class(self, payload):
"""
ISOTP encodes the frame type in the first nibble of a frame.
"""
t = (orb(payload[0]) & 240) >> 4
if t == 0:
return ISOTP_SF # depends on [control=['if'], data=[]]
elif t == 1:
return ISOTP_FF # depends on [control=['if'], dat... |
def gaus_pdf(x, mean, std):
'''Gaussian distribution's probability density function.
See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float mean: mean or expectation
:param float str: standard deviation... | def function[gaus_pdf, parameter[x, mean, std]]:
constant[Gaussian distribution's probability density function.
See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float mean: mean or expectation
:para... | keyword[def] identifier[gaus_pdf] ( identifier[x] , identifier[mean] , identifier[std] ):
literal[string]
keyword[return] identifier[exp] (-(( identifier[x] - identifier[mean] )/ identifier[std] )** literal[int] / literal[int] )/ identifier[sqrt] ( literal[int] * identifier[pi] )/ identifier[std] | def gaus_pdf(x, mean, std):
"""Gaussian distribution's probability density function.
See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float mean: mean or expectation
:param float str: standard deviation... |
def build_recursive_localize_env(destination, inputs):
"""Return a multi-line string with export statements for the variables.
Arguments:
destination: Folder where the data will be put.
For example /mnt/data
inputs: a list of InputFileParam
Returns:
a multi-line string with a shell ... | def function[build_recursive_localize_env, parameter[destination, inputs]]:
constant[Return a multi-line string with export statements for the variables.
Arguments:
destination: Folder where the data will be put.
For example /mnt/data
inputs: a list of InputFileParam
Returns:
... | keyword[def] identifier[build_recursive_localize_env] ( identifier[destination] , identifier[inputs] ):
literal[string]
identifier[export_input_dirs] = literal[string] . identifier[join] ([
literal[string] . identifier[format] ( identifier[var] . identifier[name] , identifier[destination] . identifier[rstri... | def build_recursive_localize_env(destination, inputs):
"""Return a multi-line string with export statements for the variables.
Arguments:
destination: Folder where the data will be put.
For example /mnt/data
inputs: a list of InputFileParam
Returns:
a multi-line string with a shel... |
def parse_tree_from_dict(node, locs):
"""Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the l... | def function[parse_tree_from_dict, parameter[node, locs]]:
constant[Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. ... | keyword[def] identifier[parse_tree_from_dict] ( identifier[node] , identifier[locs] ):
literal[string]
identifier[d] = identifier[dict] ()
keyword[for] identifier[n] , identifier[l] keyword[in] identifier[locs] . identifier[items] ():
keyword[try] :
keyword[if] identifier[l] ... | def parse_tree_from_dict(node, locs):
"""Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the l... |
def enable_performance_data(self):
"""Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None
"""
if not self.my_conf.process_performance_data:
self.my_conf.modified_attributes |= \... | def function[enable_performance_data, parameter[self]]:
constant[Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None
]
if <ast.UnaryOp object at 0x7da18f58e020> begin[:]
<ast.AugAss... | keyword[def] identifier[enable_performance_data] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[my_conf] . identifier[process_performance_data] :
identifier[self] . identifier[my_conf] . identifier[modified_attributes] |= identifier[DICT_... | def enable_performance_data(self):
"""Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None
"""
if not self.my_conf.process_performance_data:
self.my_conf.modified_attributes |= DICT_MODATTR[... |
def cmd(send, msg, _):
"""Gets a slogan.
Syntax: {command} [text]
"""
if not msg:
msg = textutils.gen_word()
send(textutils.gen_slogan(msg)) | def function[cmd, parameter[send, msg, _]]:
constant[Gets a slogan.
Syntax: {command} [text]
]
if <ast.UnaryOp object at 0x7da1b20f89a0> begin[:]
variable[msg] assign[=] call[name[textutils].gen_word, parameter[]]
call[name[send], parameter[call[name[textutils].gen_slog... | keyword[def] identifier[cmd] ( identifier[send] , identifier[msg] , identifier[_] ):
literal[string]
keyword[if] keyword[not] identifier[msg] :
identifier[msg] = identifier[textutils] . identifier[gen_word] ()
identifier[send] ( identifier[textutils] . identifier[gen_slogan] ( identifier[ms... | def cmd(send, msg, _):
"""Gets a slogan.
Syntax: {command} [text]
"""
if not msg:
msg = textutils.gen_word() # depends on [control=['if'], data=[]]
send(textutils.gen_slogan(msg)) |
def _AddReprMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __repr__(self):
return text_format.MessageToString(self)
cls.__repr__ = __repr__ | def function[_AddReprMethod, parameter[message_descriptor, cls]]:
constant[Helper for _AddMessageMethods().]
def function[__repr__, parameter[self]]:
return[call[name[text_format].MessageToString, parameter[name[self]]]]
name[cls].__repr__ assign[=] name[__repr__] | keyword[def] identifier[_AddReprMethod] ( identifier[message_descriptor] , identifier[cls] ):
literal[string]
keyword[def] identifier[__repr__] ( identifier[self] ):
keyword[return] identifier[text_format] . identifier[MessageToString] ( identifier[self] )
identifier[cls] . identifier[__repr__] = ide... | def _AddReprMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __repr__(self):
return text_format.MessageToString(self)
cls.__repr__ = __repr__ |
def print_violations(self, violations):
""" Print a given set of violations to the standard error output """
for v in violations:
line_nr = v.line_nr if v.line_nr else "-"
self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True)
self.display.ee(u"{0}: {1} {2... | def function[print_violations, parameter[self, violations]]:
constant[ Print a given set of violations to the standard error output ]
for taget[name[v]] in starred[name[violations]] begin[:]
variable[line_nr] assign[=] <ast.IfExp object at 0x7da20c7cb160>
call[name[self].... | keyword[def] identifier[print_violations] ( identifier[self] , identifier[violations] ):
literal[string]
keyword[for] identifier[v] keyword[in] identifier[violations] :
identifier[line_nr] = identifier[v] . identifier[line_nr] keyword[if] identifier[v] . identifier[line_nr] keywo... | def print_violations(self, violations):
""" Print a given set of violations to the standard error output """
for v in violations:
line_nr = v.line_nr if v.line_nr else '-'
self.display.e(u'{0}: {1}'.format(line_nr, v.rule_id), exact=True)
self.display.ee(u'{0}: {1} {2}'.format(line_nr, v... |
def remove_prefix(self, auth, spec, recursive = False):
""" Remove prefix matching `spec`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies prefixe to remove.
* `recursive` [bool]
When set to True, also remove ... | def function[remove_prefix, parameter[self, auth, spec, recursive]]:
constant[ Remove prefix matching `spec`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies prefixe to remove.
* `recursive` [bool]
When set to... | keyword[def] identifier[remove_prefix] ( identifier[self] , identifier[auth] , identifier[spec] , identifier[recursive] = keyword[False] ):
literal[string]
identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] % identifier[unicode] ( identifier[spec] ))
ke... | def remove_prefix(self, auth, spec, recursive=False):
""" Remove prefix matching `spec`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies prefixe to remove.
* `recursive` [bool]
When set to True, also remove child ... |
def commit(self):
"""
.. seealso:: :py:meth:`sqlite3.Connection.commit`
"""
try:
self.check_connection()
except NullDatabaseConnectionError:
return
logger.debug("commit: path='{}'".format(self.database_path))
try:
self.connec... | def function[commit, parameter[self]]:
constant[
.. seealso:: :py:meth:`sqlite3.Connection.commit`
]
<ast.Try object at 0x7da1b04eff40>
call[name[logger].debug, parameter[call[constant[commit: path='{}'].format, parameter[name[self].database_path]]]]
<ast.Try object at 0x7da1b04e... | keyword[def] identifier[commit] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[check_connection] ()
keyword[except] identifier[NullDatabaseConnectionError] :
keyword[return]
identifier[logger] . identifier[debug] ( ... | def commit(self):
"""
.. seealso:: :py:meth:`sqlite3.Connection.commit`
"""
try:
self.check_connection() # depends on [control=['try'], data=[]]
except NullDatabaseConnectionError:
return # depends on [control=['except'], data=[]]
logger.debug("commit: path='{}'".format... |
def main():
"""A simple command-line interface for :py:func:`run_simple`."""
# in contrast to argparse, this works at least under Python < 2.7
import optparse
from .utils import import_string
parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
parser.add_option... | def function[main, parameter[]]:
constant[A simple command-line interface for :py:func:`run_simple`.]
import module[optparse]
from relative_module[utils] import module[import_string]
variable[parser] assign[=] call[name[optparse].OptionParser, parameter[]]
call[name[parser].add_option, p... | keyword[def] identifier[main] ():
literal[string]
keyword[import] identifier[optparse]
keyword[from] . identifier[utils] keyword[import] identifier[import_string]
identifier[parser] = identifier[optparse] . identifier[OptionParser] ( identifier[usage] = literal[string] )
identifi... | def main():
"""A simple command-line interface for :py:func:`run_simple`."""
# in contrast to argparse, this works at least under Python < 2.7
import optparse
from .utils import import_string
parser = optparse.OptionParser(usage='Usage: %prog [options] app_module:app_object')
parser.add_option('... |
def quote_single_identifier(self, string):
"""
Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str
"""
c = self.get_identifier_quote_c... | def function[quote_single_identifier, parameter[self, string]]:
constant[
Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str
]
variab... | keyword[def] identifier[quote_single_identifier] ( identifier[self] , identifier[string] ):
literal[string]
identifier[c] = identifier[self] . identifier[get_identifier_quote_character] ()
keyword[return] literal[string] %( identifier[c] , identifier[string] . identifier[replace] ( ident... | def quote_single_identifier(self, string):
"""
Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str
"""
c = self.get_identifier_quote_character... |
def gx_coords(node):
"""
Given a KML DOM node, grab its <gx:coord> and <gx:timestamp><when>subnodes, and convert them into a dictionary with the keys and values
- ``'coordinates'``: list of lists of float coordinates
- ``'times'``: list of timestamps corresponding to the coordinates
"""
els = ... | def function[gx_coords, parameter[node]]:
constant[
Given a KML DOM node, grab its <gx:coord> and <gx:timestamp><when>subnodes, and convert them into a dictionary with the keys and values
- ``'coordinates'``: list of lists of float coordinates
- ``'times'``: list of timestamps corresponding to the ... | keyword[def] identifier[gx_coords] ( identifier[node] ):
literal[string]
identifier[els] = identifier[get] ( identifier[node] , literal[string] )
identifier[coordinates] =[]
identifier[times] =[]
identifier[coordinates] =[ identifier[gx_coords1] ( identifier[val] ( identifier[el] )) keyword[... | def gx_coords(node):
"""
Given a KML DOM node, grab its <gx:coord> and <gx:timestamp><when>subnodes, and convert them into a dictionary with the keys and values
- ``'coordinates'``: list of lists of float coordinates
- ``'times'``: list of timestamps corresponding to the coordinates
"""
els = ... |
def get_overlay_gateway(self):
"""
Get overlay-gateway name on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Dictionary containing details of VXLAN Overlay G... | def function[get_overlay_gateway, parameter[self]]:
constant[
Get overlay-gateway name on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Dictionary containing... | keyword[def] identifier[get_overlay_gateway] ( identifier[self] ):
literal[string]
identifier[urn] = literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , iden... | def get_overlay_gateway(self):
"""
Get overlay-gateway name on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Dictionary containing details of VXLAN Overlay Gatew... |
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg) | def function[__ipv4_netmask, parameter[value]]:
constant[validate an IPv4 dotted quad or integer CIDR netmask]
<ast.Tuple object at 0x7da1b1f9ab00> assign[=] tuple[[<ast.Constant object at 0x7da1b1f9bd60>, <ast.Constant object at 0x7da1b1f9b9d0>]]
<ast.Tuple object at 0x7da1b1f9b6a0> assign[=] c... | keyword[def] identifier[__ipv4_netmask] ( identifier[value] ):
literal[string]
identifier[valid] , identifier[errmsg] = keyword[False] , literal[string]
identifier[valid] , identifier[value] , identifier[_] = identifier[__int] ( identifier[value] )
keyword[if] keyword[not] ( identifier[valid] ... | def __ipv4_netmask(value):
"""validate an IPv4 dotted quad or integer CIDR netmask"""
(valid, errmsg) = (False, 'dotted quad or integer CIDR (0->32)')
(valid, value, _) = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value) # depends on [control=['if'... |
def receive(self, ikpdb):
"""Waits for a message from the debugger and returns it as a dict.
"""
# with self._connection_lock:
while self._network_loop:
_logger.n_debug("Enter socket.recv(%s) with self._received_data = %s",
self.SOCKET_BUFFER_SIZE... | def function[receive, parameter[self, ikpdb]]:
constant[Waits for a message from the debugger and returns it as a dict.
]
while name[self]._network_loop begin[:]
call[name[_logger].n_debug, parameter[constant[Enter socket.recv(%s) with self._received_data = %s], name[self].SOCKET... | keyword[def] identifier[receive] ( identifier[self] , identifier[ikpdb] ):
literal[string]
keyword[while] identifier[self] . identifier[_network_loop] :
identifier[_logger] . identifier[n_debug] ( literal[string] ,
identifier[self] . identifier[SOCKET_BUFFER_SIZE... | def receive(self, ikpdb):
"""Waits for a message from the debugger and returns it as a dict.
"""
# with self._connection_lock:
while self._network_loop:
_logger.n_debug('Enter socket.recv(%s) with self._received_data = %s', self.SOCKET_BUFFER_SIZE, self._received_data)
try:
... |
def authenticate(self):
"""
Indicate to the client that it needs to authenticate via a 401.
"""
if request.headers.get('Authorization') or request.args.get('access_token'):
realm = 'Bearer realm="%s", error="invalid_token"' % __package__
else:
realm = 'Bea... | def function[authenticate, parameter[self]]:
constant[
Indicate to the client that it needs to authenticate via a 401.
]
if <ast.BoolOp object at 0x7da1b27edfc0> begin[:]
variable[realm] assign[=] binary_operation[constant[Bearer realm="%s", error="invalid_token"] <ast.Mo... | keyword[def] identifier[authenticate] ( identifier[self] ):
literal[string]
keyword[if] identifier[request] . identifier[headers] . identifier[get] ( literal[string] ) keyword[or] identifier[request] . identifier[args] . identifier[get] ( literal[string] ):
identifier[realm] = litera... | def authenticate(self):
"""
Indicate to the client that it needs to authenticate via a 401.
"""
if request.headers.get('Authorization') or request.args.get('access_token'):
realm = 'Bearer realm="%s", error="invalid_token"' % __package__ # depends on [control=['if'], data=[]]
else:
... |
def _get_branch_opts(branch, local_branch, all_local_branches,
desired_upstream, git_ver=None):
'''
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
'''
if branch is not None and branch not in all_local_branches:
# We ... | def function[_get_branch_opts, parameter[branch, local_branch, all_local_branches, desired_upstream, git_ver]]:
constant[
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
]
if <ast.BoolOp object at 0x7da1b1fa27a0> begin[:]
return[c... | keyword[def] identifier[_get_branch_opts] ( identifier[branch] , identifier[local_branch] , identifier[all_local_branches] ,
identifier[desired_upstream] , identifier[git_ver] = keyword[None] ):
literal[string]
keyword[if] identifier[branch] keyword[is] keyword[not] keyword[None] keyword[and] identi... | def _get_branch_opts(branch, local_branch, all_local_branches, desired_upstream, git_ver=None):
"""
DRY helper to build list of opts for git.branch, for the purposes of
setting upstream tracking branch
"""
if branch is not None and branch not in all_local_branches:
# We won't be setting upst... |
def fcoe_fcoe_map_fcoe_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_map = ET.SubElement(fcoe, "fcoe-map")
fcoe_map_name = ET.SubElement(fcoe_map, "fc... | def function[fcoe_fcoe_map_fcoe_map_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[fcoe] assign[=] call[name[ET].SubElement, parameter[name[config], constant[fcoe]]]
variable[fcoe_map]... | keyword[def] identifier[fcoe_fcoe_map_fcoe_map_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[fcoe] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] ... | def fcoe_fcoe_map_fcoe_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
fcoe = ET.SubElement(config, 'fcoe', xmlns='urn:brocade.com:mgmt:brocade-fcoe')
fcoe_map = ET.SubElement(fcoe, 'fcoe-map')
fcoe_map_name = ET.SubElement(fcoe_map, 'fcoe-map-name')
fc... |
def url(self):
"""
The URL to access this preview.
"""
return reverse('%s:detail' % URL_NAMESPACE, kwargs={
'module': self.module,
'preview': type(self).__name__,
}) | def function[url, parameter[self]]:
constant[
The URL to access this preview.
]
return[call[name[reverse], parameter[binary_operation[constant[%s:detail] <ast.Mod object at 0x7da2590d6920> name[URL_NAMESPACE]]]]] | keyword[def] identifier[url] ( identifier[self] ):
literal[string]
keyword[return] identifier[reverse] ( literal[string] % identifier[URL_NAMESPACE] , identifier[kwargs] ={
literal[string] : identifier[self] . identifier[module] ,
literal[string] : identifier[type] ( identifier[s... | def url(self):
"""
The URL to access this preview.
"""
return reverse('%s:detail' % URL_NAMESPACE, kwargs={'module': self.module, 'preview': type(self).__name__}) |
def pause_transfer_operation(self, operation_name):
"""
Pauses an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
"""
self.get_conn().transferOperation... | def function[pause_transfer_operation, parameter[self, operation_name]]:
constant[
Pauses an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
]
call[cal... | keyword[def] identifier[pause_transfer_operation] ( identifier[self] , identifier[operation_name] ):
literal[string]
identifier[self] . identifier[get_conn] (). identifier[transferOperations] (). identifier[pause] ( identifier[name] = identifier[operation_name] ). identifier[execute] ( identifier[n... | def pause_transfer_operation(self, operation_name):
"""
Pauses an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
"""
self.get_conn().transferOperations().paus... |
def post(self, request, format=None):
""" authenticate """
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
login(request, serializer.instance)
if request.data.get('remember'):
# TODO: remember configurable
... | def function[post, parameter[self, request, format]]:
constant[ authenticate ]
variable[serializer] assign[=] call[name[self].serializer_class, parameter[]]
if call[name[serializer].is_valid, parameter[]] begin[:]
call[name[login], parameter[name[request], name[serializer].instan... | keyword[def] identifier[post] ( identifier[self] , identifier[request] , identifier[format] = keyword[None] ):
literal[string]
identifier[serializer] = identifier[self] . identifier[serializer_class] ( identifier[data] = identifier[request] . identifier[data] )
keyword[if] identifier[ser... | def post(self, request, format=None):
""" authenticate """
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
login(request, serializer.instance)
if request.data.get('remember'):
# TODO: remember configurable
request.session.set_expiry(60 ... |
def create_app_factory(app_name, config_loader=None,
extension_entry_points=None, extensions=None,
blueprint_entry_points=None, blueprints=None,
converter_entry_points=None, converters=None,
wsgi_factory=None, **app_kwargs):
... | def function[create_app_factory, parameter[app_name, config_loader, extension_entry_points, extensions, blueprint_entry_points, blueprints, converter_entry_points, converters, wsgi_factory]]:
constant[Create a Flask application factory.
The application factory will load Flask extensions and blueprints spec... | keyword[def] identifier[create_app_factory] ( identifier[app_name] , identifier[config_loader] = keyword[None] ,
identifier[extension_entry_points] = keyword[None] , identifier[extensions] = keyword[None] ,
identifier[blueprint_entry_points] = keyword[None] , identifier[blueprints] = keyword[None] ,
identifier[con... | def create_app_factory(app_name, config_loader=None, extension_entry_points=None, extensions=None, blueprint_entry_points=None, blueprints=None, converter_entry_points=None, converters=None, wsgi_factory=None, **app_kwargs):
"""Create a Flask application factory.
The application factory will load Flask extensi... |
def finalize(self, block):
"""
The final step of CBC-MAC encrypts before xor.
"""
t1 = self.mac_aes.encrypt(block)
t2 = _xor_block(self.mac, t1)
self.mac = t2 | def function[finalize, parameter[self, block]]:
constant[
The final step of CBC-MAC encrypts before xor.
]
variable[t1] assign[=] call[name[self].mac_aes.encrypt, parameter[name[block]]]
variable[t2] assign[=] call[name[_xor_block], parameter[name[self].mac, name[t1]]]
na... | keyword[def] identifier[finalize] ( identifier[self] , identifier[block] ):
literal[string]
identifier[t1] = identifier[self] . identifier[mac_aes] . identifier[encrypt] ( identifier[block] )
identifier[t2] = identifier[_xor_block] ( identifier[self] . identifier[mac] , identifier[t1] )
... | def finalize(self, block):
"""
The final step of CBC-MAC encrypts before xor.
"""
t1 = self.mac_aes.encrypt(block)
t2 = _xor_block(self.mac, t1)
self.mac = t2 |
def _apply_search_backrefs(pattern, flags=0):
"""Apply the search backrefs to the search pattern."""
if isinstance(pattern, (str, bytes)):
re_verbose = VERBOSE & flags
if flags & V0:
re_version = V0
elif flags & V1:
re_version = V1
else:
re_ve... | def function[_apply_search_backrefs, parameter[pattern, flags]]:
constant[Apply the search backrefs to the search pattern.]
if call[name[isinstance], parameter[name[pattern], tuple[[<ast.Name object at 0x7da1b04b11b0>, <ast.Name object at 0x7da1b04b2380>]]]] begin[:]
variable[re_verbose]... | keyword[def] identifier[_apply_search_backrefs] ( identifier[pattern] , identifier[flags] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[pattern] ,( identifier[str] , identifier[bytes] )):
identifier[re_verbose] = identifier[VERBOSE] & identifier[flags]
... | def _apply_search_backrefs(pattern, flags=0):
"""Apply the search backrefs to the search pattern."""
if isinstance(pattern, (str, bytes)):
re_verbose = VERBOSE & flags
if flags & V0:
re_version = V0 # depends on [control=['if'], data=[]]
elif flags & V1:
re_versi... |
def nodes(xmrs):
"""Return the list of Nodes for *xmrs*."""
nodes = []
_props = xmrs.properties
varsplit = sort_vid_split
for p in xmrs.eps():
sortinfo = None
iv = p.intrinsic_variable
if iv is not None:
sort, _ = varsplit(iv)
sortinfo = _props(iv)
... | def function[nodes, parameter[xmrs]]:
constant[Return the list of Nodes for *xmrs*.]
variable[nodes] assign[=] list[[]]
variable[_props] assign[=] name[xmrs].properties
variable[varsplit] assign[=] name[sort_vid_split]
for taget[name[p]] in starred[call[name[xmrs].eps, parameter[... | keyword[def] identifier[nodes] ( identifier[xmrs] ):
literal[string]
identifier[nodes] =[]
identifier[_props] = identifier[xmrs] . identifier[properties]
identifier[varsplit] = identifier[sort_vid_split]
keyword[for] identifier[p] keyword[in] identifier[xmrs] . identifier[eps] ():
... | def nodes(xmrs):
"""Return the list of Nodes for *xmrs*."""
nodes = []
_props = xmrs.properties
varsplit = sort_vid_split
for p in xmrs.eps():
sortinfo = None
iv = p.intrinsic_variable
if iv is not None:
(sort, _) = varsplit(iv)
sortinfo = _props(iv)
... |
def countries(instance):
"""Ensure that the `country` property of `location` objects is a valid
ISO 3166-1 ALPHA-2 Code.
"""
if (instance['type'] == 'location' and 'country' in instance and not
instance['country'].upper() in enums.COUNTRY_CODES):
return JSONError("Location `country`... | def function[countries, parameter[instance]]:
constant[Ensure that the `country` property of `location` objects is a valid
ISO 3166-1 ALPHA-2 Code.
]
if <ast.BoolOp object at 0x7da1b0fd4730> begin[:]
return[call[name[JSONError], parameter[constant[Location `country` should be a valid ISO... | keyword[def] identifier[countries] ( identifier[instance] ):
literal[string]
keyword[if] ( identifier[instance] [ literal[string] ]== literal[string] keyword[and] literal[string] keyword[in] identifier[instance] keyword[and] keyword[not]
identifier[instance] [ literal[string] ]. identifier[uppe... | def countries(instance):
"""Ensure that the `country` property of `location` objects is a valid
ISO 3166-1 ALPHA-2 Code.
"""
if instance['type'] == 'location' and 'country' in instance and (not instance['country'].upper() in enums.COUNTRY_CODES):
return JSONError('Location `country` should be a ... |
def scan_download(self, scan_id, format='v2'):
"""scan_download scan_id [format]
Will download an individual scan and return a string with the results.
"""
payload = {
'downloadType': format,
'scanResultID': scan_id,
}
data = self.raw_query('scanRe... | def function[scan_download, parameter[self, scan_id, format]]:
constant[scan_download scan_id [format]
Will download an individual scan and return a string with the results.
]
variable[payload] assign[=] dictionary[[<ast.Constant object at 0x7da1b28d6bc0>, <ast.Constant object at 0x7da1b... | keyword[def] identifier[scan_download] ( identifier[self] , identifier[scan_id] , identifier[format] = literal[string] ):
literal[string]
identifier[payload] ={
literal[string] : identifier[format] ,
literal[string] : identifier[scan_id] ,
}
identifier[data] = ide... | def scan_download(self, scan_id, format='v2'):
"""scan_download scan_id [format]
Will download an individual scan and return a string with the results.
"""
payload = {'downloadType': format, 'scanResultID': scan_id}
data = self.raw_query('scanResult', 'download', data=payload, dejson=False)
... |
def get_stp_mst_detail_output_msti_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti... | def function[get_stp_mst_detail_output_msti_port_edge_delay, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_stp_mst_detail] assign[=] call[name[ET].Element, parameter[constant[get_stp_mst_detail... | keyword[def] identifier[get_stp_mst_detail_output_msti_port_edge_delay] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_stp_mst_detail] = identifier[ET] . identifier[Element] ( literal... | def get_stp_mst_detail_output_msti_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_stp_mst_detail = ET.Element('get_stp_mst_detail')
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, 'output')
msti = ET.SubElement(output,... |
def connect_to_images(region=None, public=True):
"""Creates a client for working with Images."""
return _create_client(ep_name="image", region=region, public=public) | def function[connect_to_images, parameter[region, public]]:
constant[Creates a client for working with Images.]
return[call[name[_create_client], parameter[]]] | keyword[def] identifier[connect_to_images] ( identifier[region] = keyword[None] , identifier[public] = keyword[True] ):
literal[string]
keyword[return] identifier[_create_client] ( identifier[ep_name] = literal[string] , identifier[region] = identifier[region] , identifier[public] = identifier[public] ) | def connect_to_images(region=None, public=True):
"""Creates a client for working with Images."""
return _create_client(ep_name='image', region=region, public=public) |
def _encrypt_xor(a, b, aes):
""" Returns encrypt(a ^ b). """
a = unhexlify("%0.32x" % (int((a), 16) ^ int(hexlify(b), 16)))
return aes.encrypt(a) | def function[_encrypt_xor, parameter[a, b, aes]]:
constant[ Returns encrypt(a ^ b). ]
variable[a] assign[=] call[name[unhexlify], parameter[binary_operation[constant[%0.32x] <ast.Mod object at 0x7da2590d6920> binary_operation[call[name[int], parameter[name[a], constant[16]]] <ast.BitXor object at 0x7da2... | keyword[def] identifier[_encrypt_xor] ( identifier[a] , identifier[b] , identifier[aes] ):
literal[string]
identifier[a] = identifier[unhexlify] ( literal[string] %( identifier[int] (( identifier[a] ), literal[int] )^ identifier[int] ( identifier[hexlify] ( identifier[b] ), literal[int] )))
keyword[re... | def _encrypt_xor(a, b, aes):
""" Returns encrypt(a ^ b). """
a = unhexlify('%0.32x' % (int(a, 16) ^ int(hexlify(b), 16)))
return aes.encrypt(a) |
def sign_metadata(metadata, key, cert, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Signs the metadata with the key/cert provided
:param metadata: SAML Metadata XML
:type metadata: string
:param key: x509 key
:ty... | def function[sign_metadata, parameter[metadata, key, cert, sign_algorithm, digest_algorithm]]:
constant[
Signs the metadata with the key/cert provided
:param metadata: SAML Metadata XML
:type metadata: string
:param key: x509 key
:type key: string
:param cert: ... | keyword[def] identifier[sign_metadata] ( identifier[metadata] , identifier[key] , identifier[cert] , identifier[sign_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[RSA_SHA1] , identifier[digest_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[SHA1] ):
literal[string]
k... | def sign_metadata(metadata, key, cert, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Signs the metadata with the key/cert provided
:param metadata: SAML Metadata XML
:type metadata: string
:param key: x509 key
:type k... |
def create_dep(self, projects):
"""Create and return a new dep
:param projects: the projects for the dep
:type projects: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created dep or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Dep`
:raises: None... | def function[create_dep, parameter[self, projects]]:
constant[Create and return a new dep
:param projects: the projects for the dep
:type projects: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created dep or None
:rtype: None | :class:`jukeboxcore.djadapter.models... | keyword[def] identifier[create_dep] ( identifier[self] , identifier[projects] ):
literal[string]
identifier[dialog] = identifier[DepCreatorDialog] ( identifier[projects] = identifier[projects] , identifier[parent] = identifier[self] )
identifier[dialog] . identifier[exec_] ()
iden... | def create_dep(self, projects):
"""Create and return a new dep
:param projects: the projects for the dep
:type projects: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created dep or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Dep`
:raises: None
... |
def render(obj, backend=None, **kwargs):
"""
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the spec... | def function[render, parameter[obj, backend]]:
constant[
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects... | keyword[def] identifier[render] ( identifier[obj] , identifier[backend] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[backend] = identifier[backend] keyword[or] identifier[Store] . identifier[current_backend]
identifier[renderer_obj] = identifier[renderer] ( identifier[backen... | def render(obj, backend=None, **kwargs):
"""
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the spec... |
def openioc_embedding_pred(self,parent, child, ns_mapping):
"""
Predicate for recognizing inlined content in an XML; to
be used for DINGO's xml-import hook 'embedded_predicate'.
The question this predicate must answer is whether
the child should be extracted into a separate objec... | def function[openioc_embedding_pred, parameter[self, parent, child, ns_mapping]]:
constant[
Predicate for recognizing inlined content in an XML; to
be used for DINGO's xml-import hook 'embedded_predicate'.
The question this predicate must answer is whether
the child should be ext... | keyword[def] identifier[openioc_embedding_pred] ( identifier[self] , identifier[parent] , identifier[child] , identifier[ns_mapping] ):
literal[string]
identifier[child_attributes] = identifier[extract_attributes] ( identifier[child] , identifier[prefix_key_char] = literal[strin... | def openioc_embedding_pred(self, parent, child, ns_mapping):
"""
Predicate for recognizing inlined content in an XML; to
be used for DINGO's xml-import hook 'embedded_predicate'.
The question this predicate must answer is whether
the child should be extracted into a separate object.
... |
def __respond_with_dict(self, data):
"""
Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary
"""
response = {}
if isinstance(data, list):
temp_data, data = data, {}
for key, value in enu... | def function[__respond_with_dict, parameter[self, data]]:
constant[
Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary
]
variable[response] assign[=] dictionary[[], []]
if call[name[isinstance], parameter[name... | keyword[def] identifier[__respond_with_dict] ( identifier[self] , identifier[data] ):
literal[string]
identifier[response] ={}
keyword[if] identifier[isinstance] ( identifier[data] , identifier[list] ):
identifier[temp_data] , identifier[data] = identifier[data] ,{}
... | def __respond_with_dict(self, data):
"""
Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary
"""
response = {}
if isinstance(data, list):
(temp_data, data) = (data, {})
for (key, value) in enumerate(temp_da... |
def show_zoning_enabled_configuration_input_request_type_get_request_zone_name_pattern(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration")
config = show_zoning_enabled_config... | def function[show_zoning_enabled_configuration_input_request_type_get_request_zone_name_pattern, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_zoning_enabled_configuration] assign[=] call[name... | keyword[def] identifier[show_zoning_enabled_configuration_input_request_type_get_request_zone_name_pattern] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_zoning_enabled_configuratio... | def show_zoning_enabled_configuration_input_request_type_get_request_zone_name_pattern(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_zoning_enabled_configuration = ET.Element('show_zoning_enabled_configuration')
config = show_zoning_enabled_configuration
inpu... |
def merge(self, other, successor=None):
"""
Merge two abstract states.
For any node A whose dominance frontier that the current node (at the current program location) belongs to, we
create a phi variable V' for each variable V that is defined in A, and then replace all existence of V wi... | def function[merge, parameter[self, other, successor]]:
constant[
Merge two abstract states.
For any node A whose dominance frontier that the current node (at the current program location) belongs to, we
create a phi variable V' for each variable V that is defined in A, and then replace... | keyword[def] identifier[merge] ( identifier[self] , identifier[other] , identifier[successor] = keyword[None] ):
literal[string]
identifier[replacements] ={}
keyword[if] identifier[successor] keyword[in] identifier[self] . identifier[dominance_frontiers] :
identifier[repla... | def merge(self, other, successor=None):
"""
Merge two abstract states.
For any node A whose dominance frontier that the current node (at the current program location) belongs to, we
create a phi variable V' for each variable V that is defined in A, and then replace all existence of V with V... |
def make_article_info_dates(self):
"""
Makes the section containing important dates for the article: typically
Received, Accepted, and Published.
"""
dates_div = etree.Element('div', {'id': 'article-dates'})
d = './front/article-meta/history/date'
received = self... | def function[make_article_info_dates, parameter[self]]:
constant[
Makes the section containing important dates for the article: typically
Received, Accepted, and Published.
]
variable[dates_div] assign[=] call[name[etree].Element, parameter[constant[div], dictionary[[<ast.Constan... | keyword[def] identifier[make_article_info_dates] ( identifier[self] ):
literal[string]
identifier[dates_div] = identifier[etree] . identifier[Element] ( literal[string] ,{ literal[string] : literal[string] })
identifier[d] = literal[string]
identifier[received] = identifier[self... | def make_article_info_dates(self):
"""
Makes the section containing important dates for the article: typically
Received, Accepted, and Published.
"""
dates_div = etree.Element('div', {'id': 'article-dates'})
d = './front/article-meta/history/date'
received = self.article.root.xpa... |
def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param interna... | def function[process, parameter[self, context, internal_response]]:
constant[
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response con... | keyword[def] identifier[process] ( identifier[self] , identifier[context] , identifier[internal_response] ):
literal[string]
identifier[consent_state] = identifier[context] . identifier[state] [ identifier[STATE_KEY] ]
identifier[internal_response] . identifier[attributes] = identifier[se... | def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_re... |
def intr_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of ... | def function[intr_write, parameter[self, dev_handle, ep, intf, data, timeout]]:
constant[Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfa... | keyword[def] identifier[intr_write] ( identifier[self] , identifier[dev_handle] , identifier[ep] , identifier[intf] , identifier[data] , identifier[timeout] ):
literal[string]
identifier[_not_implemented] ( identifier[self] . identifier[intr_write] ) | def intr_write(self, dev_handle, ep, intf, data, timeout):
"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the i... |
def schema(self):
"""List[google.cloud.bigquery.schema.SchemaField]: Schema of the
destination table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
"""
schema = _helpers._get_sub_prop(self._properties, ["load", "schema", "fie... | def function[schema, parameter[self]]:
constant[List[google.cloud.bigquery.schema.SchemaField]: Schema of the
destination table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
]
variable[schema] assign[=] call[name[_helpers]._... | keyword[def] identifier[schema] ( identifier[self] ):
literal[string]
identifier[schema] = identifier[_helpers] . identifier[_get_sub_prop] ( identifier[self] . identifier[_properties] ,[ literal[string] , literal[string] , literal[string] ])
keyword[if] identifier[schema] keyword[is] k... | def schema(self):
"""List[google.cloud.bigquery.schema.SchemaField]: Schema of the
destination table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
"""
schema = _helpers._get_sub_prop(self._properties, ['load', 'schema', 'fields'])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.