code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def nacm_rule_list_rule_rule_type_data_node_path(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
rule_list = ET.SubElement(nacm, "rule-list")
name_key = ET... | def function[nacm_rule_list_rule_rule_type_data_node_path, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[nacm] assign[=] call[name[ET].SubElement, parameter[name[config], constant[nacm]]]
v... | keyword[def] identifier[nacm_rule_list_rule_rule_type_data_node_path] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[nacm] = identifier[ET] . identifier[SubElement] ( identifier[config] ,... | def nacm_rule_list_rule_rule_type_data_node_path(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
nacm = ET.SubElement(config, 'nacm', xmlns='urn:ietf:params:xml:ns:yang:ietf-netconf-acm')
rule_list = ET.SubElement(nacm, 'rule-list')
name_key = ET.SubElement(rule_lis... |
def docs():
"""
Docs
"""
with safe_cd(SRC):
with safe_cd("docs"):
my_env = config_pythonpath()
command = "{0} make html".format(PIPENV).strip()
print(command)
execute_with_environment(command, env=my_env) | def function[docs, parameter[]]:
constant[
Docs
]
with call[name[safe_cd], parameter[name[SRC]]] begin[:]
with call[name[safe_cd], parameter[constant[docs]]] begin[:]
variable[my_env] assign[=] call[name[config_pythonpath], parameter[]]
... | keyword[def] identifier[docs] ():
literal[string]
keyword[with] identifier[safe_cd] ( identifier[SRC] ):
keyword[with] identifier[safe_cd] ( literal[string] ):
identifier[my_env] = identifier[config_pythonpath] ()
identifier[command] = literal[string] . identifier[forma... | def docs():
"""
Docs
"""
with safe_cd(SRC):
with safe_cd('docs'):
my_env = config_pythonpath()
command = '{0} make html'.format(PIPENV).strip()
print(command)
execute_with_environment(command, env=my_env) # depends on [control=['with'], data=[]] ... |
def upgrade(safe=True):
"""
Upgrade all packages.
"""
manager = MANAGER
if safe:
cmd = 'upgrade'
else:
cmd = 'dist-upgrade'
run_as_root("%(manager)s --assume-yes %(cmd)s" % locals(), pty=False) | def function[upgrade, parameter[safe]]:
constant[
Upgrade all packages.
]
variable[manager] assign[=] name[MANAGER]
if name[safe] begin[:]
variable[cmd] assign[=] constant[upgrade]
call[name[run_as_root], parameter[binary_operation[constant[%(manager)s --assume-ye... | keyword[def] identifier[upgrade] ( identifier[safe] = keyword[True] ):
literal[string]
identifier[manager] = identifier[MANAGER]
keyword[if] identifier[safe] :
identifier[cmd] = literal[string]
keyword[else] :
identifier[cmd] = literal[string]
identifier[run_as_root] ( ... | def upgrade(safe=True):
"""
Upgrade all packages.
"""
manager = MANAGER
if safe:
cmd = 'upgrade' # depends on [control=['if'], data=[]]
else:
cmd = 'dist-upgrade'
run_as_root('%(manager)s --assume-yes %(cmd)s' % locals(), pty=False) |
def remove_redundant_acquaintance_opportunities(
strategy: circuits.Circuit) -> int:
"""Removes redundant acquaintance opportunities."""
if not is_acquaintance_strategy(strategy):
raise TypeError('not is_acquaintance_strategy(circuit)')
qubits = sorted(strategy.all_qubits())
mapping = {... | def function[remove_redundant_acquaintance_opportunities, parameter[strategy]]:
constant[Removes redundant acquaintance opportunities.]
if <ast.UnaryOp object at 0x7da1b1cec3d0> begin[:]
<ast.Raise object at 0x7da1b1cef940>
variable[qubits] assign[=] call[name[sorted], parameter[call[nam... | keyword[def] identifier[remove_redundant_acquaintance_opportunities] (
identifier[strategy] : identifier[circuits] . identifier[Circuit] )-> identifier[int] :
literal[string]
keyword[if] keyword[not] identifier[is_acquaintance_strategy] ( identifier[strategy] ):
keyword[raise] identifier[TypeE... | def remove_redundant_acquaintance_opportunities(strategy: circuits.Circuit) -> int:
"""Removes redundant acquaintance opportunities."""
if not is_acquaintance_strategy(strategy):
raise TypeError('not is_acquaintance_strategy(circuit)') # depends on [control=['if'], data=[]]
qubits = sorted(strategy... |
def grid(self, b=None, which='major', axis='both', kind='arbitrary',
center=None, **kwargs):
"""
Usage is identical to a normal axes grid except for the ``kind`` and
``center`` kwargs. ``kind="polar"`` will add a polar overlay.
The ``center`` and ``kind`` arguments allow y... | def function[grid, parameter[self, b, which, axis, kind, center]]:
constant[
Usage is identical to a normal axes grid except for the ``kind`` and
``center`` kwargs. ``kind="polar"`` will add a polar overlay.
The ``center`` and ``kind`` arguments allow you to add a grid from a
d... | keyword[def] identifier[grid] ( identifier[self] , identifier[b] = keyword[None] , identifier[which] = literal[string] , identifier[axis] = literal[string] , identifier[kind] = literal[string] ,
identifier[center] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[grid_on] = iden... | def grid(self, b=None, which='major', axis='both', kind='arbitrary', center=None, **kwargs):
"""
Usage is identical to a normal axes grid except for the ``kind`` and
``center`` kwargs. ``kind="polar"`` will add a polar overlay.
The ``center`` and ``kind`` arguments allow you to add a grid ... |
def predict(self, y, t=None, return_cov=True, return_var=False):
"""
Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.co... | def function[predict, parameter[self, y, t, return_cov, return_var]]:
constant[
Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:... | keyword[def] identifier[predict] ( identifier[self] , identifier[y] , identifier[t] = keyword[None] , identifier[return_cov] = keyword[True] , identifier[return_var] = keyword[False] ):
literal[string]
identifier[y] = identifier[self] . identifier[_process_input] ( identifier[y] )
keyword[... | def predict(self, y, t=None, return_cov=True, return_var=False):
"""
Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.comput... |
def dumppickle(obj, fname, protocol=-1):
"""
Pickle object `obj` to file `fname`.
"""
with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows
pickle.dump(obj, fout, protocol=protocol) | def function[dumppickle, parameter[obj, fname, protocol]]:
constant[
Pickle object `obj` to file `fname`.
]
with call[name[open], parameter[name[fname], constant[wb]]] begin[:]
call[name[pickle].dump, parameter[name[obj], name[fout]]] | keyword[def] identifier[dumppickle] ( identifier[obj] , identifier[fname] , identifier[protocol] =- literal[int] ):
literal[string]
keyword[with] identifier[open] ( identifier[fname] , literal[string] ) keyword[as] identifier[fout] :
identifier[pickle] . identifier[dump] ( identifier[obj] , iden... | def dumppickle(obj, fname, protocol=-1):
"""
Pickle object `obj` to file `fname`.
"""
with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows
pickle.dump(obj, fout, protocol=protocol) # depends on [control=['with'], data=['fout']] |
def overwrite_fits(hdulist, filename):
"""
Saves a FITS file. Combined file rename, save new, delete renamed for FITS files
Why: HDUlist.writeto() does not overwrite existing files
Why(2): It is also a standardized way to save FITS files
"""
assert isinstance(hdulist, (fits.HDUList, fits.Primar... | def function[overwrite_fits, parameter[hdulist, filename]]:
constant[
Saves a FITS file. Combined file rename, save new, delete renamed for FITS files
Why: HDUlist.writeto() does not overwrite existing files
Why(2): It is also a standardized way to save FITS files
]
assert[call[name[isinstan... | keyword[def] identifier[overwrite_fits] ( identifier[hdulist] , identifier[filename] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[hdulist] ,( identifier[fits] . identifier[HDUList] , identifier[fits] . identifier[PrimaryHDU] ))
identifier[temp_name] = keyword[None]
id... | def overwrite_fits(hdulist, filename):
"""
Saves a FITS file. Combined file rename, save new, delete renamed for FITS files
Why: HDUlist.writeto() does not overwrite existing files
Why(2): It is also a standardized way to save FITS files
"""
assert isinstance(hdulist, (fits.HDUList, fits.Primary... |
def clean_download_cache(self, args):
""" Deletes a download cache for recipes passed as arguments. If no
argument is passed, it'll delete *all* downloaded caches. ::
p4a clean_download_cache kivy,pyjnius
This does *not* delete the build caches or final distributions.
"""
... | def function[clean_download_cache, parameter[self, args]]:
constant[ Deletes a download cache for recipes passed as arguments. If no
argument is passed, it'll delete *all* downloaded caches. ::
p4a clean_download_cache kivy,pyjnius
This does *not* delete the build caches or final d... | keyword[def] identifier[clean_download_cache] ( identifier[self] , identifier[args] ):
literal[string]
identifier[ctx] = identifier[self] . identifier[ctx]
keyword[if] identifier[hasattr] ( identifier[args] , literal[string] ) keyword[and] identifier[args] . identifier[recipes] :
... | def clean_download_cache(self, args):
""" Deletes a download cache for recipes passed as arguments. If no
argument is passed, it'll delete *all* downloaded caches. ::
p4a clean_download_cache kivy,pyjnius
This does *not* delete the build caches or final distributions.
"""
c... |
def splitext(filepath):
""" Like os.path.splitext except splits compound extensions as one long one
>>> splitext('~/.bashrc.asciidoc.ext.ps4.42')
('~/.bashrc', '.asciidoc.ext.ps4.42')
>>> splitext('~/.bash_profile')
('~/.bash_profile', '')
"""
exts = getattr(CRE_FILENAME_EXT.search(filepath... | def function[splitext, parameter[filepath]]:
constant[ Like os.path.splitext except splits compound extensions as one long one
>>> splitext('~/.bashrc.asciidoc.ext.ps4.42')
('~/.bashrc', '.asciidoc.ext.ps4.42')
>>> splitext('~/.bash_profile')
('~/.bash_profile', '')
]
variable[exts]... | keyword[def] identifier[splitext] ( identifier[filepath] ):
literal[string]
identifier[exts] = identifier[getattr] ( identifier[CRE_FILENAME_EXT] . identifier[search] ( identifier[filepath] ), literal[string] , identifier[str] )()
keyword[return] ( identifier[filepath] [:(- identifier[len] ( identifie... | def splitext(filepath):
""" Like os.path.splitext except splits compound extensions as one long one
>>> splitext('~/.bashrc.asciidoc.ext.ps4.42')
('~/.bashrc', '.asciidoc.ext.ps4.42')
>>> splitext('~/.bash_profile')
('~/.bash_profile', '')
"""
exts = getattr(CRE_FILENAME_EXT.search(filepath... |
def spell(word):
"""most likely correction for everything up to a double typo"""
w = Word(word)
candidates = (common([word]) or exact([word]) or known([word]) or
known(w.typos()) or common(w.double_typos()) or
[word])
correction = max(candidates, key=NLP_COUNTS.get)
... | def function[spell, parameter[word]]:
constant[most likely correction for everything up to a double typo]
variable[w] assign[=] call[name[Word], parameter[name[word]]]
variable[candidates] assign[=] <ast.BoolOp object at 0x7da20c6ab400>
variable[correction] assign[=] call[name[max], para... | keyword[def] identifier[spell] ( identifier[word] ):
literal[string]
identifier[w] = identifier[Word] ( identifier[word] )
identifier[candidates] =( identifier[common] ([ identifier[word] ]) keyword[or] identifier[exact] ([ identifier[word] ]) keyword[or] identifier[known] ([ identifier[word] ]) key... | def spell(word):
"""most likely correction for everything up to a double typo"""
w = Word(word)
candidates = common([word]) or exact([word]) or known([word]) or known(w.typos()) or common(w.double_typos()) or [word]
correction = max(candidates, key=NLP_COUNTS.get)
return get_case(word, correction) |
def hget(self, key, field, *, encoding=_NOTSET):
"""Get the value of a hash field."""
return self.execute(b'HGET', key, field, encoding=encoding) | def function[hget, parameter[self, key, field]]:
constant[Get the value of a hash field.]
return[call[name[self].execute, parameter[constant[b'HGET'], name[key], name[field]]]] | keyword[def] identifier[hget] ( identifier[self] , identifier[key] , identifier[field] ,*, identifier[encoding] = identifier[_NOTSET] ):
literal[string]
keyword[return] identifier[self] . identifier[execute] ( literal[string] , identifier[key] , identifier[field] , identifier[encoding] = identifie... | def hget(self, key, field, *, encoding=_NOTSET):
"""Get the value of a hash field."""
return self.execute(b'HGET', key, field, encoding=encoding) |
def ifftm(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the magnitude of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | def function[ifftm, parameter[wave, npoints, indep_min, indep_max]]:
constant[
Return the magnitude of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | keyword[def] identifier[ifftm] ( identifier[wave] , identifier[npoints] = keyword[None] , identifier[indep_min] = keyword[None] , identifier[indep_max] = keyword[None] ):
literal[string]
keyword[return] identifier[abs] ( identifier[ifft] ( identifier[wave] , identifier[npoints] , identifier[indep_min] , i... | def ifftm(wave, npoints=None, indep_min=None, indep_max=None):
"""
Return the magnitude of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... |
def _get_licences():
""" Lists all the licenses on command line """
licenses = _LICENSES
for license in licenses:
print("{license_name} [{license_code}]".format(
license_name=licenses[license], license_code=license)) | def function[_get_licences, parameter[]]:
constant[ Lists all the licenses on command line ]
variable[licenses] assign[=] name[_LICENSES]
for taget[name[license]] in starred[name[licenses]] begin[:]
call[name[print], parameter[call[constant[{license_name} [{license_code}]].format... | keyword[def] identifier[_get_licences] ():
literal[string]
identifier[licenses] = identifier[_LICENSES]
keyword[for] identifier[license] keyword[in] identifier[licenses] :
identifier[print] ( literal[string] . identifier[format] (
identifier[license_name] = identifier[licenses] [ identifier[l... | def _get_licences():
""" Lists all the licenses on command line """
licenses = _LICENSES
for license in licenses:
print('{license_name} [{license_code}]'.format(license_name=licenses[license], license_code=license)) # depends on [control=['for'], data=['license']] |
def validateAllServers(self):
"""
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
"""
url = self._url + "/servers/validate"
params = {"f" : "json... | def function[validateAllServers, parameter[self]]:
constant[
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
]
variable[url] assign[=] binary_operation[n... | keyword[def] identifier[validateAllServers] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[_url] + literal[string]
identifier[params] ={ literal[string] : literal[string] }
keyword[return] identifier[self] . identifier[_get] ( identifier[ur... | def validateAllServers(self):
"""
This operation provides status information about a specific ArcGIS
Server federated with Portal for ArcGIS.
Parameters:
serverId - unique id of the server
"""
url = self._url + '/servers/validate'
params = {'f': 'json'}
return... |
def unitary(self, obj, qubits, label=None):
"""Apply u2 to q."""
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
return self.append(UnitaryGate(obj, label=label), qubits, []) | def function[unitary, parameter[self, obj, qubits, label]]:
constant[Apply u2 to q.]
if call[name[isinstance], parameter[name[qubits], name[QuantumRegister]]] begin[:]
variable[qubits] assign[=] call[name[qubits]][<ast.Slice object at 0x7da1b0339c00>]
return[call[name[self].append, p... | keyword[def] identifier[unitary] ( identifier[self] , identifier[obj] , identifier[qubits] , identifier[label] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[qubits] , identifier[QuantumRegister] ):
identifier[qubits] = identifier[qubits] [:]
keyword[retur... | def unitary(self, obj, qubits, label=None):
"""Apply u2 to q."""
if isinstance(qubits, QuantumRegister):
qubits = qubits[:] # depends on [control=['if'], data=[]]
return self.append(UnitaryGate(obj, label=label), qubits, []) |
def divide_work(list_of_indexes, batch_size):
"""
Given a sequential list of indexes split them into num_parts.
:param list_of_indexes: [int] list of indexes to be divided up
:param batch_size: number of items to put in batch(not exact obviously)
:return: [(int,int)] list of (ind... | def function[divide_work, parameter[list_of_indexes, batch_size]]:
constant[
Given a sequential list of indexes split them into num_parts.
:param list_of_indexes: [int] list of indexes to be divided up
:param batch_size: number of items to put in batch(not exact obviously)
:retur... | keyword[def] identifier[divide_work] ( identifier[list_of_indexes] , identifier[batch_size] ):
literal[string]
identifier[grouped_indexes] =[ identifier[list_of_indexes] [ identifier[i] : identifier[i] + identifier[batch_size] ] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[... | def divide_work(list_of_indexes, batch_size):
"""
Given a sequential list of indexes split them into num_parts.
:param list_of_indexes: [int] list of indexes to be divided up
:param batch_size: number of items to put in batch(not exact obviously)
:return: [(int,int)] list of (index, ... |
def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... | def function[run, parameter[pcap]]:
constant[
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
]
variable[start] assign[=] call[name[datetime].now, parameter[]]
variable[e... | keyword[def] identifier[run] ( identifier[pcap] ):
literal[string]
identifier[start] = identifier[datetime] . identifier[now] ()
identifier[errors] =[]
identifier[status] = identifier[STATUS_FAILED]
identifier[analyses] =[]
identifier[pool] = identifier[ThreadPool] ( identifier[MAX_THR... | def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... |
async def trigger_act(self, addr):
"""Trigger agent in :attr:`addr` to act.
This method is quite inefficient if used repeatedly for a large number
of agents.
.. seealso::
:py:meth:`creamas.mp.MultiEnvironment.trigger_all`
"""
r_agent = await self.env.connec... | <ast.AsyncFunctionDef object at 0x7da18bcc9840> | keyword[async] keyword[def] identifier[trigger_act] ( identifier[self] , identifier[addr] ):
literal[string]
identifier[r_agent] = keyword[await] identifier[self] . identifier[env] . identifier[connect] ( identifier[addr] , identifier[timeout] = identifier[TIMEOUT] )
keyword[return] key... | async def trigger_act(self, addr):
"""Trigger agent in :attr:`addr` to act.
This method is quite inefficient if used repeatedly for a large number
of agents.
.. seealso::
:py:meth:`creamas.mp.MultiEnvironment.trigger_all`
"""
r_agent = await self.env.connect(addr, ... |
def delete_grade_entry(self, grade_entry_id):
"""Deletes the ``GradeEntry`` identified by the given ``Id``.
arg: grade_entry_id (osid.id.Id): the ``Id`` of the
``GradeEntry`` to delete
raise: NotFound - a ``GradeEntry`` was not found identified by
the given `... | def function[delete_grade_entry, parameter[self, grade_entry_id]]:
constant[Deletes the ``GradeEntry`` identified by the given ``Id``.
arg: grade_entry_id (osid.id.Id): the ``Id`` of the
``GradeEntry`` to delete
raise: NotFound - a ``GradeEntry`` was not found identified by
... | keyword[def] identifier[delete_grade_entry] ( identifier[self] , identifier[grade_entry_id] ):
literal[string]
identifier[collection] = identifier[JSONClientValidated] ( literal[string] ,
identifier[collection] = literal[string] ,
identifier[runtime] = identifier... | def delete_grade_entry(self, grade_entry_id):
"""Deletes the ``GradeEntry`` identified by the given ``Id``.
arg: grade_entry_id (osid.id.Id): the ``Id`` of the
``GradeEntry`` to delete
raise: NotFound - a ``GradeEntry`` was not found identified by
the given ``Id`... |
def decode_header(header, normalize=False):
"""
decode a header value to a unicode string
values are usually a mixture of different substrings
encoded in quoted printable using different encodings.
This turns it into a single unicode string
:param header: the header value
:type header: str... | def function[decode_header, parameter[header, normalize]]:
constant[
decode a header value to a unicode string
values are usually a mixture of different substrings
encoded in quoted printable using different encodings.
This turns it into a single unicode string
:param header: the header va... | keyword[def] identifier[decode_header] ( identifier[header] , identifier[normalize] = keyword[False] ):
literal[string]
identifier[regex] = literal[string]
identifier[value] = identifier[re] . identifier[sub] ( identifier[regex] , literal[string] , identifier[header] )
identifier[... | def decode_header(header, normalize=False):
"""
decode a header value to a unicode string
values are usually a mixture of different substrings
encoded in quoted printable using different encodings.
This turns it into a single unicode string
:param header: the header value
:type header: str... |
def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
... | def function[execute_lines, parameter[self, lines]]:
constant[
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
]
for taget[name[line]] in starred[call[name[lines].splitlines, parameter[]]] begin[:]
variabl... | keyword[def] identifier[execute_lines] ( identifier[self] , identifier[lines] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[lines] . identifier[splitlines] ():
identifier[stripped_line] = identifier[line] . identifier[strip] ()
keyword[if] ... | def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
continue # depend... |
def xsl_text(self, text, parent):
"""Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
"""
res = ET.SubElement(parent, "text")
res.text = text
return res | def function[xsl_text, parameter[self, text, parent]]:
constant[Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
]
variable[res] assign[=] call[name[ET].SubElement, parameter[name[parent], constant[text]]]
name[res].text assign[=] name[text]... | keyword[def] identifier[xsl_text] ( identifier[self] , identifier[text] , identifier[parent] ):
literal[string]
identifier[res] = identifier[ET] . identifier[SubElement] ( identifier[parent] , literal[string] )
identifier[res] . identifier[text] = identifier[text]
keyword[return]... | def xsl_text(self, text, parent):
"""Construct an XSLT 'text' element containing `text`.
`parent` is this element's parent.
"""
res = ET.SubElement(parent, 'text')
res.text = text
return res |
def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this node
"""
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) | def function[check_write_permission, parameter[self, user_id, do_raise]]:
constant[
Check whether this user can write this node
]
return[call[call[name[self].get_resource, parameter[]].check_write_permission, parameter[name[user_id]]]] | keyword[def] identifier[check_write_permission] ( identifier[self] , identifier[user_id] , identifier[do_raise] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[get_resource] (). identifier[check_write_permission] ( identifier[user_id] , identifier[do_raise] = ident... | def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this node
"""
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) |
def get_database_size(db_user, db_name, localhost=False):
"""
Returns the total size for the given database role and name.
:param db_user: String representing the database role.
:param db_name: String representing the database name.
"""
localhost_part = ''
if localhost:
localhost_p... | def function[get_database_size, parameter[db_user, db_name, localhost]]:
constant[
Returns the total size for the given database role and name.
:param db_user: String representing the database role.
:param db_name: String representing the database name.
]
variable[localhost_part] assig... | keyword[def] identifier[get_database_size] ( identifier[db_user] , identifier[db_name] , identifier[localhost] = keyword[False] ):
literal[string]
identifier[localhost_part] = literal[string]
keyword[if] identifier[localhost] :
identifier[localhost_part] = literal[string]
identifier[c... | def get_database_size(db_user, db_name, localhost=False):
"""
Returns the total size for the given database role and name.
:param db_user: String representing the database role.
:param db_name: String representing the database name.
"""
localhost_part = ''
if localhost:
localhost_p... |
def check_collision_state( cls, collision_state, history_id_key, history_id, block_id, checked_ops, affected_opcodes ):
"""
Given a history ID, see if it already exists
at the given block ID (i.e. it's not expired),
using the given collision state.
Return True if so; False if not... | def function[check_collision_state, parameter[cls, collision_state, history_id_key, history_id, block_id, checked_ops, affected_opcodes]]:
constant[
Given a history ID, see if it already exists
at the given block ID (i.e. it's not expired),
using the given collision state.
Return... | keyword[def] identifier[check_collision_state] ( identifier[cls] , identifier[collision_state] , identifier[history_id_key] , identifier[history_id] , identifier[block_id] , identifier[checked_ops] , identifier[affected_opcodes] ):
literal[string]
keyword[if] identifier[collision_state] ... | def check_collision_state(cls, collision_state, history_id_key, history_id, block_id, checked_ops, affected_opcodes):
"""
Given a history ID, see if it already exists
at the given block ID (i.e. it's not expired),
using the given collision state.
Return True if so; False if not.
... |
def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like objec... | def function[copy, parameter[src, dst]]:
constant[
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path... | keyword[def] identifier[copy] ( identifier[src] , identifier[dst] ):
literal[string]
identifier[src] , identifier[src_is_storage] = identifier[format_and_is_storage] ( identifier[src] )
identifier[dst] , identifier[dst_is_storage] = identifier[format_and_is_storage] ( identifier[dst] )
... | def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like objec... |
def has_metaclass(parent):
""" we have to check the cls_node without changing it.
There are two possiblities:
1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
"""
for node in parent.children:
if nod... | def function[has_metaclass, parameter[parent]]:
constant[ we have to check the cls_node without changing it.
There are two possiblities:
1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
]
for taget[... | keyword[def] identifier[has_metaclass] ( identifier[parent] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[parent] . identifier[children] :
keyword[if] identifier[node] . identifier[type] == identifier[syms] . identifier[suite] :
keyword[return] identifie... | def has_metaclass(parent):
""" we have to check the cls_node without changing it.
There are two possiblities:
1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
"""
for node in parent.children:
if nod... |
def _init_filled_edges(self, renderer, properties, edge_mapping):
"Replace edge renderer with filled renderer"
glyph_model = Patches if self.filled else Bezier
allowed_properties = glyph_model.properties()
for glyph_type in ('', 'selection_', 'nonselection_', 'hover_', 'muted_'):
... | def function[_init_filled_edges, parameter[self, renderer, properties, edge_mapping]]:
constant[Replace edge renderer with filled renderer]
variable[glyph_model] assign[=] <ast.IfExp object at 0x7da1b1c67df0>
variable[allowed_properties] assign[=] call[name[glyph_model].properties, parameter[]]
... | keyword[def] identifier[_init_filled_edges] ( identifier[self] , identifier[renderer] , identifier[properties] , identifier[edge_mapping] ):
literal[string]
identifier[glyph_model] = identifier[Patches] keyword[if] identifier[self] . identifier[filled] keyword[else] identifier[Bezier]
... | def _init_filled_edges(self, renderer, properties, edge_mapping):
"""Replace edge renderer with filled renderer"""
glyph_model = Patches if self.filled else Bezier
allowed_properties = glyph_model.properties()
for glyph_type in ('', 'selection_', 'nonselection_', 'hover_', 'muted_'):
glyph = get... |
def validate(self, ip, **kwargs):
"""Check to see if this is a valid ip address."""
if ip is None:
return False
ip = stringify(ip)
if self.IPV4_REGEX.match(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
return True
... | def function[validate, parameter[self, ip]]:
constant[Check to see if this is a valid ip address.]
if compare[name[ip] is constant[None]] begin[:]
return[constant[False]]
variable[ip] assign[=] call[name[stringify], parameter[name[ip]]]
if call[name[self].IPV4_REGEX.match, parame... | keyword[def] identifier[validate] ( identifier[self] , identifier[ip] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[ip] keyword[is] keyword[None] :
keyword[return] keyword[False]
identifier[ip] = identifier[stringify] ( identifier[ip] )
keyw... | def validate(self, ip, **kwargs):
"""Check to see if this is a valid ip address."""
if ip is None:
return False # depends on [control=['if'], data=[]]
ip = stringify(ip)
if self.IPV4_REGEX.match(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
return True # depend... |
def attach_kernel_driver(self, interface):
r"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
"""
self._ctx.managed_open()
self._c... | def function[attach_kernel_driver, parameter[self, interface]]:
constant[Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
]
call[name[self].... | keyword[def] identifier[attach_kernel_driver] ( identifier[self] , identifier[interface] ):
literal[string]
identifier[self] . identifier[_ctx] . identifier[managed_open] ()
identifier[self] . identifier[_ctx] . identifier[backend] . identifier[attach_kernel_driver] (
identifier[s... | def attach_kernel_driver(self, interface):
"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
"""
self._ctx.managed_open()
self._ctx.backend.at... |
def flatwrite(cls, table,
order=None,
header=None,
output="table",
sort_keys=True,
show_none="",
sep="."
):
"""
writes the information given in the table
:param table: th... | def function[flatwrite, parameter[cls, table, order, header, output, sort_keys, show_none, sep]]:
constant[
writes the information given in the table
:param table: the table of values
:param order: the order of the columns
:param header: the header for the columns
:param ... | keyword[def] identifier[flatwrite] ( identifier[cls] , identifier[table] ,
identifier[order] = keyword[None] ,
identifier[header] = keyword[None] ,
identifier[output] = literal[string] ,
identifier[sort_keys] = keyword[True] ,
identifier[show_none] = literal[string] ,
identifier[sep] = literal[string]
):
... | def flatwrite(cls, table, order=None, header=None, output='table', sort_keys=True, show_none='', sep='.'):
"""
writes the information given in the table
:param table: the table of values
:param order: the order of the columns
:param header: the header for the columns
:param o... |
def run_services(config, *services, **kwargs):
""" Serves a number of services for a contextual block.
The caller can specify a number of service classes then serve them either
stopping (default) or killing them on exiting the contextual block.
Example::
with run_services(config, Foobar, Spam... | def function[run_services, parameter[config]]:
constant[ Serves a number of services for a contextual block.
The caller can specify a number of service classes then serve them either
stopping (default) or killing them on exiting the contextual block.
Example::
with run_services(config, Fo... | keyword[def] identifier[run_services] ( identifier[config] ,* identifier[services] ,** identifier[kwargs] ):
literal[string]
identifier[kill_on_exit] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
identifier[runner] = identifier[ServiceRunner] ( identifier[config] )
... | def run_services(config, *services, **kwargs):
""" Serves a number of services for a contextual block.
The caller can specify a number of service classes then serve them either
stopping (default) or killing them on exiting the contextual block.
Example::
with run_services(config, Foobar, Spam... |
def _VmB (VmKey):
"""Parse /proc/<pid>/status file for given key.
@return: requested number value of status entry
@rtype: float
"""
if os.name != 'posix':
# not supported
return 0.0
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_p... | def function[_VmB, parameter[VmKey]]:
constant[Parse /proc/<pid>/status file for given key.
@return: requested number value of status entry
@rtype: float
]
if compare[name[os].name not_equal[!=] constant[posix]] begin[:]
return[constant[0.0]]
<ast.Global object at 0x7da1b0913d00... | keyword[def] identifier[_VmB] ( identifier[VmKey] ):
literal[string]
keyword[if] identifier[os] . identifier[name] != literal[string] :
keyword[return] literal[int]
keyword[global] identifier[_proc_status] , identifier[_scale]
keyword[try] :
identifier[t] = identi... | def _VmB(VmKey):
"""Parse /proc/<pid>/status file for given key.
@return: requested number value of status entry
@rtype: float
"""
if os.name != 'posix':
# not supported
return 0.0 # depends on [control=['if'], data=[]]
global _proc_status, _scale
# get pseudo file /proc/<p... |
def get_results():
"""Parse all search result pages."""
base = "http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d"
session = requests.Session()
# store info in a dictio... | def function[get_results, parameter[]]:
constant[Parse all search result pages.]
variable[base] assign[=] constant[http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d]
... | keyword[def] identifier[get_results] ():
literal[string]
identifier[base] = literal[string]
identifier[session] = identifier[requests] . identifier[Session] ()
identifier[res] ={}
identifier[result_pages] = literal[int]
identifier[print] ( literal[string] , identifier[result... | def get_results():
"""Parse all search result pages."""
base = 'http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d'
session = requests.Session()
# store info in a dictio... |
def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0):
"""
Calculate slope and aspect map.
Return a pair of arrays 2 pixels smaller than the input elevation array.
Slope is returned in radians, from 0 for sheer face to pi/2 for
flat ground. Aspect is returned in radians, counterclock... | def function[calculate_slope_aspect, parameter[elevation, xres, yres, z, scale]]:
constant[
Calculate slope and aspect map.
Return a pair of arrays 2 pixels smaller than the input elevation array.
Slope is returned in radians, from 0 for sheer face to pi/2 for
flat ground. Aspect is returned i... | keyword[def] identifier[calculate_slope_aspect] ( identifier[elevation] , identifier[xres] , identifier[yres] , identifier[z] = literal[int] , identifier[scale] = literal[int] ):
literal[string]
identifier[z] = identifier[float] ( identifier[z] )
identifier[scale] = identifier[float] ( identifier[scal... | def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0):
"""
Calculate slope and aspect map.
Return a pair of arrays 2 pixels smaller than the input elevation array.
Slope is returned in radians, from 0 for sheer face to pi/2 for
flat ground. Aspect is returned in radians, counterclock... |
def seed_instance(self, seed=None):
"""Calls random.seed"""
if self.__random == random:
# create per-instance random obj when first time seed_instance() is
# called
self.__random = random_module.Random()
self.__random.seed(seed)
return self | def function[seed_instance, parameter[self, seed]]:
constant[Calls random.seed]
if compare[name[self].__random equal[==] name[random]] begin[:]
name[self].__random assign[=] call[name[random_module].Random, parameter[]]
call[name[self].__random.seed, parameter[name[seed]]]
re... | keyword[def] identifier[seed_instance] ( identifier[self] , identifier[seed] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[__random] == identifier[random] :
identifier[self] . identifier[__random] = identifier[random_module] . identifie... | def seed_instance(self, seed=None):
"""Calls random.seed"""
if self.__random == random:
# create per-instance random obj when first time seed_instance() is
# called
self.__random = random_module.Random() # depends on [control=['if'], data=[]]
self.__random.seed(seed)
return self |
def search(query, data, replacements=None):
"""Yield objects from 'data' that match the 'query'."""
query = q.Query(query, params=replacements)
for entry in data:
if solve.solve(query, entry).value:
yield entry | def function[search, parameter[query, data, replacements]]:
constant[Yield objects from 'data' that match the 'query'.]
variable[query] assign[=] call[name[q].Query, parameter[name[query]]]
for taget[name[entry]] in starred[name[data]] begin[:]
if call[name[solve].solve, paramete... | keyword[def] identifier[search] ( identifier[query] , identifier[data] , identifier[replacements] = keyword[None] ):
literal[string]
identifier[query] = identifier[q] . identifier[Query] ( identifier[query] , identifier[params] = identifier[replacements] )
keyword[for] identifier[entry] keyword[in] ... | def search(query, data, replacements=None):
"""Yield objects from 'data' that match the 'query'."""
query = q.Query(query, params=replacements)
for entry in data:
if solve.solve(query, entry).value:
yield entry # depends on [control=['if'], data=[]] # depends on [control=['for'], data=... |
def get_last_commit(git_path='git'):
"""Returns the details of the last git commit
Returns a tuple (hash, date, author name, author e-mail,
committer name, committer e-mail).
"""
hash_, udate, aname, amail, cname, cmail = (
call((git_path, 'log', '-1',
'--pretty=format:%H,%ct,... | def function[get_last_commit, parameter[git_path]]:
constant[Returns the details of the last git commit
Returns a tuple (hash, date, author name, author e-mail,
committer name, committer e-mail).
]
<ast.Tuple object at 0x7da2046213f0> assign[=] call[call[name[call], parameter[tuple[[<ast.Na... | keyword[def] identifier[get_last_commit] ( identifier[git_path] = literal[string] ):
literal[string]
identifier[hash_] , identifier[udate] , identifier[aname] , identifier[amail] , identifier[cname] , identifier[cmail] =(
identifier[call] (( identifier[git_path] , literal[string] , literal[string] ,
... | def get_last_commit(git_path='git'):
"""Returns the details of the last git commit
Returns a tuple (hash, date, author name, author e-mail,
committer name, committer e-mail).
"""
(hash_, udate, aname, amail, cname, cmail) = call((git_path, 'log', '-1', '--pretty=format:%H,%ct,%an,%ae,%cn,%ce')).spl... |
def _get_conversion_type(self, convert_to=None):
'''a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
'''
acceptable = ['... | def function[_get_conversion_type, parameter[self, convert_to]]:
constant[a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
]
... | keyword[def] identifier[_get_conversion_type] ( identifier[self] , identifier[convert_to] = keyword[None] ):
literal[string]
identifier[acceptable] =[ literal[string] , literal[string] ]
identifier[conversion] = literal[string]
keyword[if] identifier[self] . identifier... | def _get_conversion_type(self, convert_to=None):
"""a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
"""
acceptable = ['singular... |
def process_string_tensor_event(event):
"""Convert a TensorEvent into a JSON-compatible response."""
string_arr = tensor_util.make_ndarray(event.tensor_proto)
html = text_array_to_html(string_arr)
return {
'wall_time': event.wall_time,
'step': event.step,
'text': html,
} | def function[process_string_tensor_event, parameter[event]]:
constant[Convert a TensorEvent into a JSON-compatible response.]
variable[string_arr] assign[=] call[name[tensor_util].make_ndarray, parameter[name[event].tensor_proto]]
variable[html] assign[=] call[name[text_array_to_html], parameter... | keyword[def] identifier[process_string_tensor_event] ( identifier[event] ):
literal[string]
identifier[string_arr] = identifier[tensor_util] . identifier[make_ndarray] ( identifier[event] . identifier[tensor_proto] )
identifier[html] = identifier[text_array_to_html] ( identifier[string_arr] )
keyword[ret... | def process_string_tensor_event(event):
"""Convert a TensorEvent into a JSON-compatible response."""
string_arr = tensor_util.make_ndarray(event.tensor_proto)
html = text_array_to_html(string_arr)
return {'wall_time': event.wall_time, 'step': event.step, 'text': html} |
def add_rdataset(self, section, name, rdataset, **kw):
"""Add the rdataset to the specified section, using the specified
name as the owner name.
Any keyword arguments are passed on to the rdataset's to_wire()
routine.
@param section: the section
@type section: int
... | def function[add_rdataset, parameter[self, section, name, rdataset]]:
constant[Add the rdataset to the specified section, using the specified
name as the owner name.
Any keyword arguments are passed on to the rdataset's to_wire()
routine.
@param section: the section
@ty... | keyword[def] identifier[add_rdataset] ( identifier[self] , identifier[section] , identifier[name] , identifier[rdataset] ,** identifier[kw] ):
literal[string]
identifier[self] . identifier[_set_section] ( identifier[section] )
identifier[before] = identifier[self] . identifier[output] . i... | def add_rdataset(self, section, name, rdataset, **kw):
"""Add the rdataset to the specified section, using the specified
name as the owner name.
Any keyword arguments are passed on to the rdataset's to_wire()
routine.
@param section: the section
@type section: int
@... |
def is_email_verified(self, request, email):
"""
Checks whether or not the email address is already verified
beyond allauth scope, for example, by having accepted an
invitation before signing up.
"""
ret = False
verified_email = request.session.get('account_verifi... | def function[is_email_verified, parameter[self, request, email]]:
constant[
Checks whether or not the email address is already verified
beyond allauth scope, for example, by having accepted an
invitation before signing up.
]
variable[ret] assign[=] constant[False]
... | keyword[def] identifier[is_email_verified] ( identifier[self] , identifier[request] , identifier[email] ):
literal[string]
identifier[ret] = keyword[False]
identifier[verified_email] = identifier[request] . identifier[session] . identifier[get] ( literal[string] )
keyword[if] id... | def is_email_verified(self, request, email):
"""
Checks whether or not the email address is already verified
beyond allauth scope, for example, by having accepted an
invitation before signing up.
"""
ret = False
verified_email = request.session.get('account_verified_email')
... |
def add_edge(self, from_node, to_node):
"""Add edge between two node
The edge is oriented
:param from_node: node where edge starts
:type from_node: object
:param to_node: node where edge ends
:type to_node: object
:return: None
"""
# Maybe to_node... | def function[add_edge, parameter[self, from_node, to_node]]:
constant[Add edge between two node
The edge is oriented
:param from_node: node where edge starts
:type from_node: object
:param to_node: node where edge ends
:type to_node: object
:return: None
... | keyword[def] identifier[add_edge] ( identifier[self] , identifier[from_node] , identifier[to_node] ):
literal[string]
keyword[if] identifier[to_node] keyword[not] keyword[in] identifier[self] . identifier[nodes] :
identifier[self] . identifier[add_node] ( identifier[to_nod... | def add_edge(self, from_node, to_node):
"""Add edge between two node
The edge is oriented
:param from_node: node where edge starts
:type from_node: object
:param to_node: node where edge ends
:type to_node: object
:return: None
"""
# Maybe to_node is unkn... |
def inference_minibatch(self, kern, X, Z, likelihood, Y):
"""
The second phase of inference: Computing the derivatives over a minibatch of Y
Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL
return a flag showing whether it reached the end of Y (isEnd)
"""
num_data, outp... | def function[inference_minibatch, parameter[self, kern, X, Z, likelihood, Y]]:
constant[
The second phase of inference: Computing the derivatives over a minibatch of Y
Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL
return a flag showing whether it reached the end of Y (isEnd)
... | keyword[def] identifier[inference_minibatch] ( identifier[self] , identifier[kern] , identifier[X] , identifier[Z] , identifier[likelihood] , identifier[Y] ):
literal[string]
identifier[num_data] , identifier[output_dim] = identifier[Y] . identifier[shape]
keyword[if] identifier[isinst... | def inference_minibatch(self, kern, X, Z, likelihood, Y):
"""
The second phase of inference: Computing the derivatives over a minibatch of Y
Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL
return a flag showing whether it reached the end of Y (isEnd)
"""
(num_data, output_dim) ... |
def list():
"""Use this function to display all of the stored URLs.
This command is used for displaying all of the URLs and their names from
the stored list.
"""
for name, url in get_all_data().items():
echo('{}: {}'.format(
style(name, fg='blue'),
style(url, fg='gre... | def function[list, parameter[]]:
constant[Use this function to display all of the stored URLs.
This command is used for displaying all of the URLs and their names from
the stored list.
]
for taget[tuple[[<ast.Name object at 0x7da1b26ae320>, <ast.Name object at 0x7da1b26ae530>]]] in starred[... | keyword[def] identifier[list] ():
literal[string]
keyword[for] identifier[name] , identifier[url] keyword[in] identifier[get_all_data] (). identifier[items] ():
identifier[echo] ( literal[string] . identifier[format] (
identifier[style] ( identifier[name] , identifier[fg] = literal[str... | def list():
"""Use this function to display all of the stored URLs.
This command is used for displaying all of the URLs and their names from
the stored list.
"""
for (name, url) in get_all_data().items():
echo('{}: {}'.format(style(name, fg='blue'), style(url, fg='green'))) # depends on [c... |
def applicationlinks(self, cached=True):
"""List of application links.
:return: json
"""
# if cached, return the last result
if cached and hasattr(self, '_applicationlinks'):
return self._applicationlinks
# url = self._options['server'] + '/rest/applinks/lat... | def function[applicationlinks, parameter[self, cached]]:
constant[List of application links.
:return: json
]
if <ast.BoolOp object at 0x7da1b216ee90> begin[:]
return[name[self]._applicationlinks]
variable[url] assign[=] binary_operation[call[name[self]._options][constant... | keyword[def] identifier[applicationlinks] ( identifier[self] , identifier[cached] = keyword[True] ):
literal[string]
keyword[if] identifier[cached] keyword[and] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[return] identifier[self] . identifier[_appli... | def applicationlinks(self, cached=True):
"""List of application links.
:return: json
"""
# if cached, return the last result
if cached and hasattr(self, '_applicationlinks'):
return self._applicationlinks # depends on [control=['if'], data=[]]
# url = self._options['server'] + ... |
def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `clien... | def function[verify_client, parameter[self, client_jid, domains]]:
constant[Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
... | keyword[def] identifier[verify_client] ( identifier[self] , identifier[client_jid] = keyword[None] , identifier[domains] = keyword[None] ):
literal[string]
identifier[jids] =[ identifier[jid] keyword[for] identifier[jid] keyword[in] identifier[self] . identifier[get_jids] () keyword[if] identi... | def verify_client(self, client_jid=None, domains=None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: ... |
def _unstructure_mapping(self, mapping):
"""Convert a mapping of attr classes to primitive equivalents."""
# We can reuse the mapping class, so dicts stay dicts and OrderedDicts
# stay OrderedDicts.
dispatch = self._unstructure_func.dispatch
return mapping.__class__(
... | def function[_unstructure_mapping, parameter[self, mapping]]:
constant[Convert a mapping of attr classes to primitive equivalents.]
variable[dispatch] assign[=] name[self]._unstructure_func.dispatch
return[call[name[mapping].__class__, parameter[<ast.GeneratorExp object at 0x7da20c993e80>]]] | keyword[def] identifier[_unstructure_mapping] ( identifier[self] , identifier[mapping] ):
literal[string]
identifier[dispatch] = identifier[self] . identifier[_unstructure_func] . identifier[dispatch]
keyword[return] identifier[mapping] . identifier[__class__] (
... | def _unstructure_mapping(self, mapping):
"""Convert a mapping of attr classes to primitive equivalents."""
# We can reuse the mapping class, so dicts stay dicts and OrderedDicts
# stay OrderedDicts.
dispatch = self._unstructure_func.dispatch
return mapping.__class__(((dispatch(k.__class__)(k), dispa... |
def translate_config(self, profile, merge=None, replace=None):
"""
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`... | def function[translate_config, parameter[self, profile, merge, replace]]:
constant[
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
v... | keyword[def] identifier[translate_config] ( identifier[self] , identifier[profile] , identifier[merge] = keyword[None] , identifier[replace] = keyword[None] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] :
i... | def translate_config(self, profile, merge=None, replace=None):
"""
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`` un... |
def _cleanup_ca_temp_file(self):
"""
Function to clean up ca temp file for requests.
**Returns:** Removes TEMP ca file, no return
"""
if os.name == 'nt':
if isinstance(self.ca_verify_filename, (binary_type, text_type)):
# windows requires file to be c... | def function[_cleanup_ca_temp_file, parameter[self]]:
constant[
Function to clean up ca temp file for requests.
**Returns:** Removes TEMP ca file, no return
]
if compare[name[os].name equal[==] constant[nt]] begin[:]
if call[name[isinstance], parameter[name[self]... | keyword[def] identifier[_cleanup_ca_temp_file] ( identifier[self] ):
literal[string]
keyword[if] identifier[os] . identifier[name] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[self] . identifier[ca_verify_filename] ,( identifier[binary_type] , identifier[text_... | def _cleanup_ca_temp_file(self):
"""
Function to clean up ca temp file for requests.
**Returns:** Removes TEMP ca file, no return
"""
if os.name == 'nt':
if isinstance(self.ca_verify_filename, (binary_type, text_type)):
# windows requires file to be closed for access... |
def measure(*qubits: raw_types.Qid,
key: Optional[str] = None,
invert_mask: Tuple[bool, ...] = ()
) -> gate_operation.GateOperation:
"""Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*q... | def function[measure, parameter[]]:
constant[Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*qubits: The qubits that the measurement gate should measure.
key: The string key of the measurement. If this is None... | keyword[def] identifier[measure] (* identifier[qubits] : identifier[raw_types] . identifier[Qid] ,
identifier[key] : identifier[Optional] [ identifier[str] ]= keyword[None] ,
identifier[invert_mask] : identifier[Tuple] [ identifier[bool] ,...]=()
)-> identifier[gate_operation] . identifier[GateOperation] :
lit... | def measure(*qubits: raw_types.Qid, key: Optional[str]=None, invert_mask: Tuple[bool, ...]=()) -> gate_operation.GateOperation:
"""Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*qubits: The qubits that the measurement ga... |
def publications(columns, n_results, queries):
"""Search for publications"""
if not isinstance(queries, dict):
query_dict = {}
for q in queries:
key, value = q.split('=')
if key == 'distinct':
if value in ['True', 'true']:
query_dict.up... | def function[publications, parameter[columns, n_results, queries]]:
constant[Search for publications]
if <ast.UnaryOp object at 0x7da20c6c6b60> begin[:]
variable[query_dict] assign[=] dictionary[[], []]
for taget[name[q]] in starred[name[queries]] begin[:]
... | keyword[def] identifier[publications] ( identifier[columns] , identifier[n_results] , identifier[queries] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[queries] , identifier[dict] ):
identifier[query_dict] ={}
keyword[for] identifier[q] keyword[in] i... | def publications(columns, n_results, queries):
"""Search for publications"""
if not isinstance(queries, dict):
query_dict = {}
for q in queries:
(key, value) = q.split('=')
if key == 'distinct':
if value in ['True', 'true']:
query_dict.... |
def run(self):
"""
Load handler and collector classes and then start collectors
"""
#######################################################################
# Config
#######################################################################
self.config = load_config(... | def function[run, parameter[self]]:
constant[
Load handler and collector classes and then start collectors
]
name[self].config assign[=] call[name[load_config], parameter[name[self].configfile]]
variable[collectors] assign[=] call[name[load_collectors], parameter[call[call[name[s... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[config] = identifier[load_config] ( identifier[self] . identifier[configfile] )
identifier[collectors] = identifier[load_collectors] ( identifier[self] . identifier... | def run(self):
"""
Load handler and collector classes and then start collectors
"""
#######################################################################
# Config
#######################################################################
self.config = load_config(self.configfile)
... |
def list(self, all_pages=False, **kwargs):
"""Return a list of notification templates.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
If one or more filters are provided through keyword arguments,
... | def function[list, parameter[self, all_pages]]:
constant[Return a list of notification templates.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
If one or more filters are provided through keyword argument... | keyword[def] identifier[list] ( identifier[self] , identifier[all_pages] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_separate] ( identifier[kwargs] )
keyword[return] identifier[super] ( identifier[Resource] , identifier[self] ). identifier[lis... | def list(self, all_pages=False, **kwargs):
"""Return a list of notification templates.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
If one or more filters are provided through keyword arguments,
filt... |
def _get_file_handlers(self, dsid):
"""Get the file handler to load this dataset."""
ds_info = self.ids[dsid]
fhs = [fh for fh in self.file_handlers['generic_file']
if set(fh.datasets) & set(ds_info['dataset_groups'])]
if not fhs:
LOG.warning("Required file ty... | def function[_get_file_handlers, parameter[self, dsid]]:
constant[Get the file handler to load this dataset.]
variable[ds_info] assign[=] call[name[self].ids][name[dsid]]
variable[fhs] assign[=] <ast.ListComp object at 0x7da1b22b9d20>
if <ast.UnaryOp object at 0x7da1b22b98a0> begin[:]
... | keyword[def] identifier[_get_file_handlers] ( identifier[self] , identifier[dsid] ):
literal[string]
identifier[ds_info] = identifier[self] . identifier[ids] [ identifier[dsid] ]
identifier[fhs] =[ identifier[fh] keyword[for] identifier[fh] keyword[in] identifier[self] . identifier[fi... | def _get_file_handlers(self, dsid):
"""Get the file handler to load this dataset."""
ds_info = self.ids[dsid]
fhs = [fh for fh in self.file_handlers['generic_file'] if set(fh.datasets) & set(ds_info['dataset_groups'])]
if not fhs:
LOG.warning("Required file type '%s' not found or loaded for '%s'... |
def open_audio(frequency=44100, format=AudioFormat.default, channels=2, chunksize=1024):
"""Open the mixer with a certain audio format.
Args:
frequency (int): Output sampling frequency in samples per second (Hz).
format (AudioFormat): Output sample format.
channels (int): Number of ... | def function[open_audio, parameter[frequency, format, channels, chunksize]]:
constant[Open the mixer with a certain audio format.
Args:
frequency (int): Output sampling frequency in samples per second (Hz).
format (AudioFormat): Output sample format.
channels (int): Number of so... | keyword[def] identifier[open_audio] ( identifier[frequency] = literal[int] , identifier[format] = identifier[AudioFormat] . identifier[default] , identifier[channels] = literal[int] , identifier[chunksize] = literal[int] ):
literal[string]
identifier[check_int_err] ( identifier[lib] . identifier[Mix_OpenAu... | def open_audio(frequency=44100, format=AudioFormat.default, channels=2, chunksize=1024):
"""Open the mixer with a certain audio format.
Args:
frequency (int): Output sampling frequency in samples per second (Hz).
format (AudioFormat): Output sample format.
channels (int): Number of ... |
def get_output_content(job_id, max_size=1024, conn=None):
"""
returns the content buffer for a job_id if that job output exists
:param job_id: <str> id for the job
:param max_size: <int> truncate after [max_size] bytes
:param conn: (optional)<connection> to run on
:return: <str> or <bytes>
... | def function[get_output_content, parameter[job_id, max_size, conn]]:
constant[
returns the content buffer for a job_id if that job output exists
:param job_id: <str> id for the job
:param max_size: <int> truncate after [max_size] bytes
:param conn: (optional)<connection> to run on
:return: ... | keyword[def] identifier[get_output_content] ( identifier[job_id] , identifier[max_size] = literal[int] , identifier[conn] = keyword[None] ):
literal[string]
identifier[content] = keyword[None]
keyword[if] identifier[RBO] . identifier[index_list] (). identifier[contains] ( identifier[IDX_OUTPUT_JOB_I... | def get_output_content(job_id, max_size=1024, conn=None):
"""
returns the content buffer for a job_id if that job output exists
:param job_id: <str> id for the job
:param max_size: <int> truncate after [max_size] bytes
:param conn: (optional)<connection> to run on
:return: <str> or <bytes>
... |
def get_ancestors(self, include_self=False, depth=None):
"""Return all the ancestors of this object."""
if self.is_root_node():
if not include_self:
return self._toplevel().objects.none()
else:
# Filter on pk for efficiency.
return ... | def function[get_ancestors, parameter[self, include_self, depth]]:
constant[Return all the ancestors of this object.]
if call[name[self].is_root_node, parameter[]] begin[:]
if <ast.UnaryOp object at 0x7da2044c2ef0> begin[:]
return[call[call[name[self]._toplevel, parameter[]].... | keyword[def] identifier[get_ancestors] ( identifier[self] , identifier[include_self] = keyword[False] , identifier[depth] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[is_root_node] ():
keyword[if] keyword[not] identifier[include_self] :
... | def get_ancestors(self, include_self=False, depth=None):
"""Return all the ancestors of this object."""
if self.is_root_node():
if not include_self:
return self._toplevel().objects.none() # depends on [control=['if'], data=[]]
else:
# Filter on pk for efficiency.
... |
def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a cloudwatch alarm
CLI example to delete a queue::
salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.de... | def function[delete_alarm, parameter[name, region, key, keyid, profile]]:
constant[
Delete a cloudwatch alarm
CLI example to delete a queue::
salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1
]
variable[conn] assign[=] call[name[_get_conn], parameter[]]
ca... | keyword[def] identifier[delete_alarm] ( identifier[name] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifier[region] = identifier[region] , i... | def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
"""
Delete a cloudwatch alarm
CLI example to delete a queue::
salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.del... |
def goto(self, rules, symbol):
"""Computes the next closure for rules based on the symbol we got.
Args:
rules - an iterable of DottedRules
symbol - a string denoting the symbol we've just seen
Returns: frozenset of DottedRules
"""
return self.closure(
... | def function[goto, parameter[self, rules, symbol]]:
constant[Computes the next closure for rules based on the symbol we got.
Args:
rules - an iterable of DottedRules
symbol - a string denoting the symbol we've just seen
Returns: frozenset of DottedRules
]
re... | keyword[def] identifier[goto] ( identifier[self] , identifier[rules] , identifier[symbol] ):
literal[string]
keyword[return] identifier[self] . identifier[closure] (
{ identifier[rule] . identifier[move_dot] () keyword[for] identifier[rule] keyword[in] identifier[rules]
keywor... | def goto(self, rules, symbol):
"""Computes the next closure for rules based on the symbol we got.
Args:
rules - an iterable of DottedRules
symbol - a string denoting the symbol we've just seen
Returns: frozenset of DottedRules
"""
return self.closure({rule.move_... |
def one(self, filetype, **kwargs):
''' Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the... | def function[one, parameter[self, filetype]]:
constant[ Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression str... | keyword[def] identifier[one] ( identifier[self] , identifier[filetype] ,** identifier[kwargs] ):
literal[string]
identifier[expanded_files] = identifier[self] . identifier[expand] ( identifier[filetype] ,** identifier[kwargs] )
identifier[isany] = identifier[self] . identifier[any] ( ident... | def one(self, filetype, **kwargs):
""" Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the lis... |
def echo(
message=None, file=None, nl=True, err=False, color=None, carriage_return=False
):
"""
Patched click echo function.
"""
message = message or ""
if carriage_return and nl:
click_echo(message + "\r\n", file, False, err, color)
elif carriage_return and not nl:
click_ech... | def function[echo, parameter[message, file, nl, err, color, carriage_return]]:
constant[
Patched click echo function.
]
variable[message] assign[=] <ast.BoolOp object at 0x7da1b127b310>
if <ast.BoolOp object at 0x7da1b127b220> begin[:]
call[name[click_echo], parameter[bin... | keyword[def] identifier[echo] (
identifier[message] = keyword[None] , identifier[file] = keyword[None] , identifier[nl] = keyword[True] , identifier[err] = keyword[False] , identifier[color] = keyword[None] , identifier[carriage_return] = keyword[False]
):
literal[string]
identifier[message] = identifier... | def echo(message=None, file=None, nl=True, err=False, color=None, carriage_return=False):
"""
Patched click echo function.
"""
message = message or ''
if carriage_return and nl:
click_echo(message + '\r\n', file, False, err, color) # depends on [control=['if'], data=[]]
elif carriage_re... |
def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... | def function[get_service_methods, parameter[iface]]:
constant[Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for t... | keyword[def] identifier[get_service_methods] ( identifier[iface] ):
literal[string]
identifier[methods] = identifier[inspect] . identifier[getmembers] ( identifier[iface] , identifier[predicate] = identifier[inspect] . identifier[ismethod] )
keyword[return] identifier[set] (
identifier[name] k... | def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... |
def _handle_result_line(self, sline):
"""
Parses the data line and adds to the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or
return the code error -1
"""
as_kw = sline[3]
a_result ... | def function[_handle_result_line, parameter[self, sline]]:
constant[
Parses the data line and adds to the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or
return the code error -1
]
variable[... | keyword[def] identifier[_handle_result_line] ( identifier[self] , identifier[sline] ):
literal[string]
identifier[as_kw] = identifier[sline] [ literal[int] ]
identifier[a_result] = identifier[str] ( identifier[sline] [ literal[int] ]. identifier[split] ( literal[string] )[ literal[int] ])
... | def _handle_result_line(self, sline):
"""
Parses the data line and adds to the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or
return the code error -1
"""
as_kw = sline[3]
a_result = str(sline[... |
def make_array_access(id_, lineno, arglist):
""" Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
"""
return symbols.ARRAYACCESS.make_node(id_, arglist, lineno) | def function[make_array_access, parameter[id_, lineno, arglist]]:
constant[ Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
]
return[call[name[symbols].ARRAYACCESS.make_node, parameter[name[id_], name[arglist], name[lineno]]]] | keyword[def] identifier[make_array_access] ( identifier[id_] , identifier[lineno] , identifier[arglist] ):
literal[string]
keyword[return] identifier[symbols] . identifier[ARRAYACCESS] . identifier[make_node] ( identifier[id_] , identifier[arglist] , identifier[lineno] ) | def make_array_access(id_, lineno, arglist):
""" Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element)
"""
return symbols.ARRAYACCESS.make_node(id_, arglist, lineno) |
def dAbr_dV(self, dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Based on dAbr_dV.m from MATPOWER by Ray Zimmerman, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information.
@rtype: tuple
@return: The partial derivatives of the squared flo... | def function[dAbr_dV, parameter[self, dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St]]:
constant[ Based on dAbr_dV.m from MATPOWER by Ray Zimmerman, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information.
@rtype: tuple
@return: The partial der... | keyword[def] identifier[dAbr_dV] ( identifier[self] , identifier[dSf_dVa] , identifier[dSf_dVm] , identifier[dSt_dVa] , identifier[dSt_dVm] , identifier[Sf] , identifier[St] ):
literal[string]
identifier[il] = identifier[range] ( identifier[len] ( identifier[Sf] ))
identifier[dAf_dPf] = i... | def dAbr_dV(self, dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Based on dAbr_dV.m from MATPOWER by Ray Zimmerman, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information.
@rtype: tuple
@return: The partial derivatives of the squared flow ma... |
def get_all_projects(self, scope):
"""
Returns all projects in the domain
"""
url = "{0}/{1}/{2}".format(self.keystone_server_url, DEFAULT_KEYSTONE_API_VERSION, "projects")
headers = {'X-Auth-Token': scope.auth_token}
try:
r = self._make_request_with_auth_fall... | def function[get_all_projects, parameter[self, scope]]:
constant[
Returns all projects in the domain
]
variable[url] assign[=] call[constant[{0}/{1}/{2}].format, parameter[name[self].keystone_server_url, name[DEFAULT_KEYSTONE_API_VERSION], constant[projects]]]
variable[headers] a... | keyword[def] identifier[get_all_projects] ( identifier[self] , identifier[scope] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[self] . identifier[keystone_server_url] , identifier[DEFAULT_KEYSTONE_API_VERSION] , literal[string] )
identifier[headers]... | def get_all_projects(self, scope):
"""
Returns all projects in the domain
"""
url = '{0}/{1}/{2}'.format(self.keystone_server_url, DEFAULT_KEYSTONE_API_VERSION, 'projects')
headers = {'X-Auth-Token': scope.auth_token}
try:
r = self._make_request_with_auth_fallback(url, headers)
... |
def pythonize(self, val):
"""Convert value into a boolean
:param val: value to convert
:type val: bool, int, str
:return: boolean corresponding to value ::
{'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
... | def function[pythonize, parameter[self, val]]:
constant[Convert value into a boolean
:param val: value to convert
:type val: bool, int, str
:return: boolean corresponding to value ::
{'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': F... | keyword[def] identifier[pythonize] ( identifier[self] , identifier[val] ):
literal[string]
identifier[__boolean_states__] ={ literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[True] ,
literal[string] : keyword[Fal... | def pythonize(self, val):
"""Convert value into a boolean
:param val: value to convert
:type val: bool, int, str
:return: boolean corresponding to value ::
{'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
:r... |
def unlock(self):
"""Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server.
"""
url = self.reddit_session.config['unlock']
... | def function[unlock, parameter[self]]:
constant[Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server.
]
variable[url] assign[=... | keyword[def] identifier[unlock] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[reddit_session] . identifier[config] [ literal[string] ]
identifier[data] ={ literal[string] : identifier[self] . identifier[fullname] }
keyword[return] identifie... | def unlock(self):
"""Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server.
"""
url = self.reddit_session.config['unlock']
data = {... |
def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
# Route to master... | def function[_minion_event, parameter[self, load]]:
constant[
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
]
variable[load] assign[=] call[name[self].__verify_load, parameter[name[load], tuple[[<ast.Const... | keyword[def] identifier[_minion_event] ( identifier[self] , identifier[load] ):
literal[string]
identifier[load] = identifier[self] . identifier[__verify_load] ( identifier[load] ,( literal[string] , literal[string] ))
keyword[if] identifier[load] keyword[is] keyword[False] :
... | def _minion_event(self, load):
"""
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
"""
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {} # depends on [control=['if'], data=[]]
... |
def format_installed_dap(name, full=False):
'''Formats information about an installed DAP in a human readable form to list of lines'''
dap_data = get_installed_daps_detailed().get(name)
if not dap_data:
raise DapiLocalError('DAP "{dap}" is not installed, can not query for info.'.format(dap=name))
... | def function[format_installed_dap, parameter[name, full]]:
constant[Formats information about an installed DAP in a human readable form to list of lines]
variable[dap_data] assign[=] call[call[name[get_installed_daps_detailed], parameter[]].get, parameter[name[name]]]
if <ast.UnaryOp object at 0... | keyword[def] identifier[format_installed_dap] ( identifier[name] , identifier[full] = keyword[False] ):
literal[string]
identifier[dap_data] = identifier[get_installed_daps_detailed] (). identifier[get] ( identifier[name] )
keyword[if] keyword[not] identifier[dap_data] :
keyword[raise] ide... | def format_installed_dap(name, full=False):
"""Formats information about an installed DAP in a human readable form to list of lines"""
dap_data = get_installed_daps_detailed().get(name)
if not dap_data:
raise DapiLocalError('DAP "{dap}" is not installed, can not query for info.'.format(dap=name)) #... |
def move_cursor_one_word(self, word=LEFT):
"""Move the cursor of one word to the right (1) or the the left (-1)."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self)
... | def function[move_cursor_one_word, parameter[self, word]]:
constant[Move the cursor of one word to the right (1) or the the left (-1).]
assert[compare[name[word] in tuple[[<ast.Attribute object at 0x7da18f723c40>, <ast.Attribute object at 0x7da18f720730>]]]]
if compare[name[word] equal[==] name[self... | keyword[def] identifier[move_cursor_one_word] ( identifier[self] , identifier[word] = identifier[LEFT] ):
literal[string]
keyword[assert] identifier[word] keyword[in] ( identifier[self] . identifier[RIGHT] , identifier[self] . identifier[LEFT] )
keyword[if] identifier[word] == identif... | def move_cursor_one_word(self, word=LEFT):
"""Move the cursor of one word to the right (1) or the the left (-1)."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self) # depends on [control=['if'... |
def countByValue(self):
"""Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
... | def function[countByValue, parameter[self]]:
constant[Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming... | keyword[def] identifier[countByValue] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[transform] (
keyword[lambda] identifier[rdd] : identifier[self] . identifier[_context] . identifier[_context] . identifier[parallelize] (
identifier[rdd] . i... | def countByValue(self):
"""Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
... |
def CreateGallery():
"""Creates a Gallery on the server. Returns a Gallery object with the
editor_id and reader_id.
"""
url = 'http://min.us/api/CreateGallery'
response = _dopost(url)
_editor_id = response["editor_id"]
_reader_id = response["reader_id"]
return Gallery(_reader_id, edi... | def function[CreateGallery, parameter[]]:
constant[Creates a Gallery on the server. Returns a Gallery object with the
editor_id and reader_id.
]
variable[url] assign[=] constant[http://min.us/api/CreateGallery]
variable[response] assign[=] call[name[_dopost], parameter[name[url]]]
... | keyword[def] identifier[CreateGallery] ():
literal[string]
identifier[url] = literal[string]
identifier[response] = identifier[_dopost] ( identifier[url] )
identifier[_editor_id] = identifier[response] [ literal[string] ]
identifier[_reader_id] = identifier[response] [ literal[string] ]
... | def CreateGallery():
"""Creates a Gallery on the server. Returns a Gallery object with the
editor_id and reader_id.
"""
url = 'http://min.us/api/CreateGallery'
response = _dopost(url)
_editor_id = response['editor_id']
_reader_id = response['reader_id']
return Gallery(_reader_id, editor... |
def subontology(self, nodes=None, minimal=False, relations=None):
"""
Return a new ontology that is an extract of this one
Arguments
---------
- nodes: list
list of node IDs to include in subontology. If None, all are used
- relations: list
list o... | def function[subontology, parameter[self, nodes, minimal, relations]]:
constant[
Return a new ontology that is an extract of this one
Arguments
---------
- nodes: list
list of node IDs to include in subontology. If None, all are used
- relations: list
... | keyword[def] identifier[subontology] ( identifier[self] , identifier[nodes] = keyword[None] , identifier[minimal] = keyword[False] , identifier[relations] = keyword[None] ):
literal[string]
identifier[g] = keyword[None]
keyword[if] identifier[nodes] keyword[is] keyword[not] keyword[No... | def subontology(self, nodes=None, minimal=False, relations=None):
"""
Return a new ontology that is an extract of this one
Arguments
---------
- nodes: list
list of node IDs to include in subontology. If None, all are used
- relations: list
list of re... |
def uninstall_tracer(pattern=r".*", flags=0):
"""
Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool
... | def function[uninstall_tracer, parameter[pattern, flags]]:
constant[
Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition succes... | keyword[def] identifier[uninstall_tracer] ( identifier[pattern] = literal[string] , identifier[flags] = literal[int] ):
literal[string]
keyword[for] identifier[module] keyword[in] identifier[REGISTERED_MODULES] :
keyword[if] keyword[not] identifier[is_traced] ( identifier[module] ):
... | def uninstall_tracer(pattern='.*', flags=0):
"""
Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool
... |
def db_ws004c(self, value=None):
""" Corresponds to IDD Field `db_ws004c`
Mean coincident dry-bulb temperature to wind speed corresponding to 0.40% cumulative frequency for coldest month
Args:
value (float): value for IDD Field `db_ws004c`
Unit: C
if... | def function[db_ws004c, parameter[self, value]]:
constant[ Corresponds to IDD Field `db_ws004c`
Mean coincident dry-bulb temperature to wind speed corresponding to 0.40% cumulative frequency for coldest month
Args:
value (float): value for IDD Field `db_ws004c`
Unit... | keyword[def] identifier[db_ws004c] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[float] ( identifier[value] )
... | def db_ws004c(self, value=None):
""" Corresponds to IDD Field `db_ws004c`
Mean coincident dry-bulb temperature to wind speed corresponding to 0.40% cumulative frequency for coldest month
Args:
value (float): value for IDD Field `db_ws004c`
Unit: C
if `va... |
def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
'''
oprot.write_struct_begin('DatabaseConfi... | def function[write, parameter[self, oprot]]:
constant[
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
]
call[name[oprot... | keyword[def] identifier[write] ( identifier[self] , identifier[oprot] ):
literal[string]
identifier[oprot] . identifier[write_struct_begin] ( literal[string] )
keyword[if] identifier[self] . identifier[dbf] keyword[is] keyword[not] keyword[None] :
identifier[oprot] . ide... | def write(self, oprot):
"""
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
"""
oprot.write_struct_begin('DatabaseConfiguration'... |
def _call(self, dx):
"""Return ``self(x)``."""
x = self.point
dx_norm = dx.norm()
if dx_norm == 0:
return 0
scaled_dx = dx * (self.step / dx_norm)
if self.method == 'backward':
dAdx = self.operator(x) - self.operator(x - scaled_dx)
elif ... | def function[_call, parameter[self, dx]]:
constant[Return ``self(x)``.]
variable[x] assign[=] name[self].point
variable[dx_norm] assign[=] call[name[dx].norm, parameter[]]
if compare[name[dx_norm] equal[==] constant[0]] begin[:]
return[constant[0]]
variable[scaled_dx] ass... | keyword[def] identifier[_call] ( identifier[self] , identifier[dx] ):
literal[string]
identifier[x] = identifier[self] . identifier[point]
identifier[dx_norm] = identifier[dx] . identifier[norm] ()
keyword[if] identifier[dx_norm] == literal[int] :
keyword[return] ... | def _call(self, dx):
"""Return ``self(x)``."""
x = self.point
dx_norm = dx.norm()
if dx_norm == 0:
return 0 # depends on [control=['if'], data=[]]
scaled_dx = dx * (self.step / dx_norm)
if self.method == 'backward':
dAdx = self.operator(x) - self.operator(x - scaled_dx) # depen... |
def handle(self, *args, **options): # NoQA
"""
Execute the command.
"""
# Load the settings
self.require_settings(args, options)
# Load your AWS credentials from ~/.aws/credentials
self.load_credentials()
#Get the Django settings file
self.get... | def function[handle, parameter[self]]:
constant[
Execute the command.
]
call[name[self].require_settings, parameter[name[args], name[options]]]
call[name[self].load_credentials, parameter[]]
call[name[self].get_django_settings_file, parameter[]]
if <ast.UnaryOp o... | keyword[def] identifier[handle] ( identifier[self] ,* identifier[args] ,** identifier[options] ):
literal[string]
identifier[self] . identifier[require_settings] ( identifier[args] , identifier[options] )
identifier[self] . identifier[load_credentials] ()
... | def handle(self, *args, **options): # NoQA
'\n Execute the command.\n\n '
# Load the settings
self.require_settings(args, options)
# Load your AWS credentials from ~/.aws/credentials
self.load_credentials()
#Get the Django settings file
self.get_django_settings_file()
# Cr... |
def specialInterpretValue(value,index,*args,**kwargs):
"""Interprets a passed value. In this order:
- If it's callable, call it with the parameters provided
- If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict
- Else, just return it
"""
if callable(valu... | def function[specialInterpretValue, parameter[value, index]]:
constant[Interprets a passed value. In this order:
- If it's callable, call it with the parameters provided
- If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict
- Else, just return it
]
... | keyword[def] identifier[specialInterpretValue] ( identifier[value] , identifier[index] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[callable] ( identifier[value] ): keyword[return] identifier[value] (* identifier[args] ,** identifier[kwargs] )
keyword[if] ide... | def specialInterpretValue(value, index, *args, **kwargs):
"""Interprets a passed value. In this order:
- If it's callable, call it with the parameters provided
- If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict
- Else, just return it
"""
if callable(v... |
def refresh_leader_status(self, instance):
"""
calls kubeutil.refresh_leader and compares the resulting
leader status with the previous one.
If it changed, update the event collection logic
"""
if not self.leader_candidate:
return
leader_status = self... | def function[refresh_leader_status, parameter[self, instance]]:
constant[
calls kubeutil.refresh_leader and compares the resulting
leader status with the previous one.
If it changed, update the event collection logic
]
if <ast.UnaryOp object at 0x7da20c6c7f70> begin[:]
... | keyword[def] identifier[refresh_leader_status] ( identifier[self] , identifier[instance] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[leader_candidate] :
keyword[return]
identifier[leader_status] = identifier[self] . identifier[kubeutil] . iden... | def refresh_leader_status(self, instance):
"""
calls kubeutil.refresh_leader and compares the resulting
leader status with the previous one.
If it changed, update the event collection logic
"""
if not self.leader_candidate:
return # depends on [control=['if'], data=[]]
... |
def purge_results(self, jobs=[], targets=[]):
"""Tell the Hub to forget results.
Individual results can be purged by msg_id, or the entire
history of specific targets can be purged.
Use `purge_results('all')` to scrub everything from the Hub's db.
Parameters
----------... | def function[purge_results, parameter[self, jobs, targets]]:
constant[Tell the Hub to forget results.
Individual results can be purged by msg_id, or the entire
history of specific targets can be purged.
Use `purge_results('all')` to scrub everything from the Hub's db.
Paramete... | keyword[def] identifier[purge_results] ( identifier[self] , identifier[jobs] =[], identifier[targets] =[]):
literal[string]
keyword[if] keyword[not] identifier[targets] keyword[and] keyword[not] identifier[jobs] :
keyword[raise] identifier[ValueError] ( literal[string] )
... | def purge_results(self, jobs=[], targets=[]):
"""Tell the Hub to forget results.
Individual results can be purged by msg_id, or the entire
history of specific targets can be purged.
Use `purge_results('all')` to scrub everything from the Hub's db.
Parameters
----------
... |
def get_parameter(self, var):
"""
This method supports the functional tags by providing the actual
values in the function as list of dict in case of table type parameter or as
nested dict in case of decision diagram
"""
parameter = []
for parameter_tag in var.fin... | def function[get_parameter, parameter[self, var]]:
constant[
This method supports the functional tags by providing the actual
values in the function as list of dict in case of table type parameter or as
nested dict in case of decision diagram
]
variable[parameter] assign[... | keyword[def] identifier[get_parameter] ( identifier[self] , identifier[var] ):
literal[string]
identifier[parameter] =[]
keyword[for] identifier[parameter_tag] keyword[in] identifier[var] . identifier[findall] ( literal[string] ):
identifier[parameter_type] = literal[strin... | def get_parameter(self, var):
"""
This method supports the functional tags by providing the actual
values in the function as list of dict in case of table type parameter or as
nested dict in case of decision diagram
"""
parameter = []
for parameter_tag in var.findall('Paramet... |
def get_uniq_list_dutmodels(self):
"""
Gets a list of dut models in this TC
:return: List of dut models in this TC. Empty list if information is not available.
"""
models = []
if self.dutinformations:
for info in self.dutinformations:
models.ap... | def function[get_uniq_list_dutmodels, parameter[self]]:
constant[
Gets a list of dut models in this TC
:return: List of dut models in this TC. Empty list if information is not available.
]
variable[models] assign[=] list[[]]
if name[self].dutinformations begin[:]
... | keyword[def] identifier[get_uniq_list_dutmodels] ( identifier[self] ):
literal[string]
identifier[models] =[]
keyword[if] identifier[self] . identifier[dutinformations] :
keyword[for] identifier[info] keyword[in] identifier[self] . identifier[dutinformations] :
... | def get_uniq_list_dutmodels(self):
"""
Gets a list of dut models in this TC
:return: List of dut models in this TC. Empty list if information is not available.
"""
models = []
if self.dutinformations:
for info in self.dutinformations:
models.append(info.platform) ... |
def execute_command(self, command):
"""
This method will execute the commands on the device without as if you were just connected to it (it will not
enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing.
Args:
* **command** (str... | def function[execute_command, parameter[self, command]]:
constant[
This method will execute the commands on the device without as if you were just connected to it (it will not
enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing.
Args:
... | keyword[def] identifier[execute_command] ( identifier[self] , identifier[command] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] % identifier[command] )
identifier[err_msg] = literal[string]
identifier[chan] = identifier[self] . identifier[ssh] . id... | def execute_command(self, command):
"""
This method will execute the commands on the device without as if you were just connected to it (it will not
enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing.
Args:
* **command** (str) --... |
def _set_isis_spf_log_reason(self, v, load=False):
"""
Setter method for isis_spf_log_reason, mapped from YANG variable /spf_log_state/spf_log_levels/spf_log_events/isis_spf_log_reason (isis-spf-log-reason-code)
If this variable is read-only (config: false) in the
source YANG file, then _set_isis_spf_lo... | def function[_set_isis_spf_log_reason, parameter[self, v, load]]:
constant[
Setter method for isis_spf_log_reason, mapped from YANG variable /spf_log_state/spf_log_levels/spf_log_events/isis_spf_log_reason (isis-spf-log-reason-code)
If this variable is read-only (config: false) in the
source YANG fi... | keyword[def] identifier[_set_isis_spf_log_reason] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_isis_spf_log_reason(self, v, load=False):
"""
Setter method for isis_spf_log_reason, mapped from YANG variable /spf_log_state/spf_log_levels/spf_log_events/isis_spf_log_reason (isis-spf-log-reason-code)
If this variable is read-only (config: false) in the
source YANG file, then _set_isis_spf_lo... |
def _add_not_exposed(
analysis_row,
enable_rounding,
is_population,
exposure_unit,
coefficient):
"""Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need t... | def function[_add_not_exposed, parameter[analysis_row, enable_rounding, is_population, exposure_unit, coefficient]]:
constant[Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need to do a rou... | keyword[def] identifier[_add_not_exposed] (
identifier[analysis_row] ,
identifier[enable_rounding] ,
identifier[is_population] ,
identifier[exposure_unit] ,
identifier[coefficient] ):
literal[string]
identifier[not_exposed_field] =(
identifier[hazard_count_field] [ literal[string] ]% identif... | def _add_not_exposed(analysis_row, enable_rounding, is_population, exposure_unit, coefficient):
"""Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need to do a rounding.
:type enable_roundin... |
def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data(... | def function[move, parameter[self, path, dest, raise_if_exists]]:
constant[
Moves a single file from path to dest
]
if <ast.BoolOp object at 0x7da2041d87c0> begin[:]
<ast.Raise object at 0x7da2041da8c0>
variable[contents] assign[=] call[call[name[self].get_all_data, param... | keyword[def] identifier[move] ( identifier[self] , identifier[path] , identifier[dest] , identifier[raise_if_exists] = keyword[False] ):
literal[string]
keyword[if] identifier[raise_if_exists] keyword[and] identifier[dest] keyword[in] identifier[self] . identifier[get_all_data] ():
... | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path) # depends on [control=['if'], data=[]]
contents = self.get_all_data().pop(path)
... |
def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
... | def function[_wait_for_consistency, parameter[checker]]:
constant[Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
]
for taget[name[_]] in starred[call[name[xrange], p... | keyword[def] identifier[_wait_for_consistency] ( identifier[checker] ):
literal[string]
keyword[for] identifier[_] keyword[in] identifier[xrange] ( identifier[EVENTUAL_CONSISTENCY_MAX_SLEEPS] ):
keyword[if] identifier[checker] ():
keyword[return]
identifier[time] . iden... | def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
... |
def create_transition(self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id):
""" Creates a new transition.
Lookout: Check the parameters first before creating a new transition
:param from_state_id: The source state of the transition
:param from_outcome: The outcome... | def function[create_transition, parameter[self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id]]:
constant[ Creates a new transition.
Lookout: Check the parameters first before creating a new transition
:param from_state_id: The source state of the transition
:para... | keyword[def] identifier[create_transition] ( identifier[self] , identifier[from_state_id] , identifier[from_outcome] , identifier[to_state_id] , identifier[to_outcome] , identifier[transition_id] ):
literal[string]
keyword[if] identifier[from_state_id] keyword[is] keyword[not] keyword... | def create_transition(self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id):
""" Creates a new transition.
Lookout: Check the parameters first before creating a new transition
:param from_state_id: The source state of the transition
:param from_outcome: The outcome of ... |
def quil_to_program(quil: str) -> Program:
"""Parse a quil program and return a Program object"""
pyquil_instructions = pyquil.parser.parse(quil)
return pyquil_to_program(pyquil_instructions) | def function[quil_to_program, parameter[quil]]:
constant[Parse a quil program and return a Program object]
variable[pyquil_instructions] assign[=] call[name[pyquil].parser.parse, parameter[name[quil]]]
return[call[name[pyquil_to_program], parameter[name[pyquil_instructions]]]] | keyword[def] identifier[quil_to_program] ( identifier[quil] : identifier[str] )-> identifier[Program] :
literal[string]
identifier[pyquil_instructions] = identifier[pyquil] . identifier[parser] . identifier[parse] ( identifier[quil] )
keyword[return] identifier[pyquil_to_program] ( identifier[pyquil_... | def quil_to_program(quil: str) -> Program:
"""Parse a quil program and return a Program object"""
pyquil_instructions = pyquil.parser.parse(quil)
return pyquil_to_program(pyquil_instructions) |
def literal_to_dict(value):
""" Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list
"""
if isinstance(value, Literal):
if value.language is not None:
return {"@... | def function[literal_to_dict, parameter[value]]:
constant[ Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list
]
if call[name[isinstance], parameter[name[value], name[Liter... | keyword[def] identifier[literal_to_dict] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Literal] ):
keyword[if] identifier[value] . identifier[language] keyword[is] keyword[not] keyword[None] :
keyword[return] { literal[... | def literal_to_dict(value):
""" Transform an object value into a dict readable value
:param value: Object of a triple which is not a BNode
:type value: Literal or URIRef
:return: dict or str or list
"""
if isinstance(value, Literal):
if value.language is not None:
return {'@... |
def numpy_psd(x, f_sample=1.0):
""" calculate power spectral density of input signal x
x = signal
f_sample = sampling frequency in Hz. i.e. 1/fs is the time-interval
in seconds between datapoints
scale fft so that output corresponds to 1-sided PSD
output has units of [X^... | def function[numpy_psd, parameter[x, f_sample]]:
constant[ calculate power spectral density of input signal x
x = signal
f_sample = sampling frequency in Hz. i.e. 1/fs is the time-interval
in seconds between datapoints
scale fft so that output corresponds to 1-sided PSD
... | keyword[def] identifier[numpy_psd] ( identifier[x] , identifier[f_sample] = literal[int] ):
literal[string]
identifier[psd_of_x] =( literal[int] /( identifier[float] ( identifier[len] ( identifier[x] ))* identifier[f_sample] ))* identifier[numpy] . identifier[abs] ( identifier[numpy] . identifier[fft] . id... | def numpy_psd(x, f_sample=1.0):
""" calculate power spectral density of input signal x
x = signal
f_sample = sampling frequency in Hz. i.e. 1/fs is the time-interval
in seconds between datapoints
scale fft so that output corresponds to 1-sided PSD
output has units of [X^... |
def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` ... | def function[bind, parameter[self, attribute, cls, buffer, fmt]]:
constant[
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer... | keyword[def] identifier[bind] ( identifier[self] , identifier[attribute] , identifier[cls] , identifier[buffer] , identifier[fmt] ,*, identifier[offset] = literal[int] , identifier[stride] = literal[int] , identifier[divisor] = literal[int] , identifier[normalize] = keyword[False] )-> keyword[None] :
literal... | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
"""
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or `... |
def get_roles(username, **kwargs):
'''
Get roles assigned to a username.
.. code-block: bash
salt '*' nxos.cmd get_roles username=admin
'''
user = get_user(username)
if not user:
return []
command = 'show user-account {0}'.format(username)
info = ''
info = show(comm... | def function[get_roles, parameter[username]]:
constant[
Get roles assigned to a username.
.. code-block: bash
salt '*' nxos.cmd get_roles username=admin
]
variable[user] assign[=] call[name[get_user], parameter[name[username]]]
if <ast.UnaryOp object at 0x7da1b20345e0> begi... | keyword[def] identifier[get_roles] ( identifier[username] ,** identifier[kwargs] ):
literal[string]
identifier[user] = identifier[get_user] ( identifier[username] )
keyword[if] keyword[not] identifier[user] :
keyword[return] []
identifier[command] = literal[string] . identifier[format]... | def get_roles(username, **kwargs):
"""
Get roles assigned to a username.
.. code-block: bash
salt '*' nxos.cmd get_roles username=admin
"""
user = get_user(username)
if not user:
return [] # depends on [control=['if'], data=[]]
command = 'show user-account {0}'.format(user... |
def write_file(
path: str,
contents,
mode: str = 'w',
retry_count: int = 3,
offset: int = 0
) -> typing.Tuple[bool, typing.Union[None, Exception]]:
"""
Writes the specified contents to a file, with retry attempts if the write
operation fails. This is useful to prevent... | def function[write_file, parameter[path, contents, mode, retry_count, offset]]:
constant[
Writes the specified contents to a file, with retry attempts if the write
operation fails. This is useful to prevent OS related write collisions with
files that are regularly written to and read from quickly.
... | keyword[def] identifier[write_file] (
identifier[path] : identifier[str] ,
identifier[contents] ,
identifier[mode] : identifier[str] = literal[string] ,
identifier[retry_count] : identifier[int] = literal[int] ,
identifier[offset] : identifier[int] = literal[int]
)-> identifier[typing] . identifier[Tuple] [ ide... | def write_file(path: str, contents, mode: str='w', retry_count: int=3, offset: int=0) -> typing.Tuple[bool, typing.Union[None, Exception]]:
"""
Writes the specified contents to a file, with retry attempts if the write
operation fails. This is useful to prevent OS related write collisions with
files that... |
def slicify(slc, dim):
"""
Force a slice to have defined start, stop, and step from a known dim.
Start and stop will always be positive. Step may be negative.
There is an exception where a negative step overflows the stop needs to have
the default value set to -1. This is the only case of a negativ... | def function[slicify, parameter[slc, dim]]:
constant[
Force a slice to have defined start, stop, and step from a known dim.
Start and stop will always be positive. Step may be negative.
There is an exception where a negative step overflows the stop needs to have
the default value set to -1. Thi... | keyword[def] identifier[slicify] ( identifier[slc] , identifier[dim] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[slc] , identifier[slice] ):
identifier[start] = literal[int] keyword[if] identifier[slc] . identifier[start] keyword[is] keyword[None] keyword[else] ... | def slicify(slc, dim):
"""
Force a slice to have defined start, stop, and step from a known dim.
Start and stop will always be positive. Step may be negative.
There is an exception where a negative step overflows the stop needs to have
the default value set to -1. This is the only case of a negativ... |
def check_membership_existence(self, subject_descriptor, container_descriptor):
"""CheckMembershipExistence.
[Preview API] Check to see if a membership relationship between a container and subject exists.
:param str subject_descriptor: The group or user that is a child subject of the relationshi... | def function[check_membership_existence, parameter[self, subject_descriptor, container_descriptor]]:
constant[CheckMembershipExistence.
[Preview API] Check to see if a membership relationship between a container and subject exists.
:param str subject_descriptor: The group or user that is a child... | keyword[def] identifier[check_membership_existence] ( identifier[self] , identifier[subject_descriptor] , identifier[container_descriptor] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[subject_descriptor] keyword[is] keyword[not] keyword[None] :
id... | def check_membership_existence(self, subject_descriptor, container_descriptor):
"""CheckMembershipExistence.
[Preview API] Check to see if a membership relationship between a container and subject exists.
:param str subject_descriptor: The group or user that is a child subject of the relationship.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.