code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def setdict(self, D=None, B=None):
"""Set dictionary array."""
if D is not None:
self.D = np.asarray(D, dtype=self.dtype)
if B is not None:
self.B = np.asarray(B, dtype=self.dtype)
if B is not None or not hasattr(self, 'Gamma'):
self.Gamma, self.Q = ... | def function[setdict, parameter[self, D, B]]:
constant[Set dictionary array.]
if compare[name[D] is_not constant[None]] begin[:]
name[self].D assign[=] call[name[np].asarray, parameter[name[D]]]
if compare[name[B] is_not constant[None]] begin[:]
name[self].B assig... | keyword[def] identifier[setdict] ( identifier[self] , identifier[D] = keyword[None] , identifier[B] = keyword[None] ):
literal[string]
keyword[if] identifier[D] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[D] = identifier[np] . identifier[asarray] ( ident... | def setdict(self, D=None, B=None):
"""Set dictionary array."""
if D is not None:
self.D = np.asarray(D, dtype=self.dtype) # depends on [control=['if'], data=['D']]
if B is not None:
self.B = np.asarray(B, dtype=self.dtype) # depends on [control=['if'], data=['B']]
if B is not None or n... |
def get_slac_default_args(job_time=1500):
""" Create a batch job interface object.
Parameters
----------
job_time : int
Expected max length of the job, in seconds.
This is used to select the batch queue and set the
job_check_sleep parameter that sets how often
we check ... | def function[get_slac_default_args, parameter[job_time]]:
constant[ Create a batch job interface object.
Parameters
----------
job_time : int
Expected max length of the job, in seconds.
This is used to select the batch queue and set the
job_check_sleep parameter that sets h... | keyword[def] identifier[get_slac_default_args] ( identifier[job_time] = literal[int] ):
literal[string]
identifier[slac_default_args] = identifier[dict] ( identifier[lsf_args] ={ literal[string] : identifier[job_time] ,
literal[string] : literal[string] },
identifier[max_jobs] = literal[int] ,
... | def get_slac_default_args(job_time=1500):
""" Create a batch job interface object.
Parameters
----------
job_time : int
Expected max length of the job, in seconds.
This is used to select the batch queue and set the
job_check_sleep parameter that sets how often
we check ... |
def export(self):
"""
Exports a network as a networkx MultiDiGraph intermediate representation
suitable for visualization.
:return: networkx MultiDiGraph
"""
graph = nx.MultiDiGraph()
# Add regions to graph as nodes, annotated by name
regions = self.network.getRegions()
for idx in... | def function[export, parameter[self]]:
constant[
Exports a network as a networkx MultiDiGraph intermediate representation
suitable for visualization.
:return: networkx MultiDiGraph
]
variable[graph] assign[=] call[name[nx].MultiDiGraph, parameter[]]
variable[regions] assign[=] c... | keyword[def] identifier[export] ( identifier[self] ):
literal[string]
identifier[graph] = identifier[nx] . identifier[MultiDiGraph] ()
identifier[regions] = identifier[self] . identifier[network] . identifier[getRegions] ()
keyword[for] identifier[idx] keyword[in] identifier[xrange] ( i... | def export(self):
"""
Exports a network as a networkx MultiDiGraph intermediate representation
suitable for visualization.
:return: networkx MultiDiGraph
"""
graph = nx.MultiDiGraph()
# Add regions to graph as nodes, annotated by name
regions = self.network.getRegions()
for idx in x... |
def allocate(self):
"""Builds the context and the Hooks."""
self.logger.debug("Allocating environment.")
self._allocate()
self.logger.debug("Environment successfully allocated.") | def function[allocate, parameter[self]]:
constant[Builds the context and the Hooks.]
call[name[self].logger.debug, parameter[constant[Allocating environment.]]]
call[name[self]._allocate, parameter[]]
call[name[self].logger.debug, parameter[constant[Environment successfully allocated.]]] | keyword[def] identifier[allocate] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[_allocate] ()
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] ) | def allocate(self):
"""Builds the context and the Hooks."""
self.logger.debug('Allocating environment.')
self._allocate()
self.logger.debug('Environment successfully allocated.') |
def plot_aligned(pca, sparse=True, **kwargs):
""" Plots the residuals of a principal component
analysis of attiude data.
"""
colormap = kwargs.pop('colormap',None)
A = pca.rotated()
# Flip the result if upside down
if pca.normal[2] < 0:
A[:,-1] *= -1
minmax = [(A[:,i].min(),... | def function[plot_aligned, parameter[pca, sparse]]:
constant[ Plots the residuals of a principal component
analysis of attiude data.
]
variable[colormap] assign[=] call[name[kwargs].pop, parameter[constant[colormap], constant[None]]]
variable[A] assign[=] call[name[pca].rotated, para... | keyword[def] identifier[plot_aligned] ( identifier[pca] , identifier[sparse] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[colormap] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[A] = identifier[pca] . identifier[rotated] ()
key... | def plot_aligned(pca, sparse=True, **kwargs):
""" Plots the residuals of a principal component
analysis of attiude data.
"""
colormap = kwargs.pop('colormap', None)
A = pca.rotated()
# Flip the result if upside down
if pca.normal[2] < 0:
A[:, -1] *= -1 # depends on [control=['if... |
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['enco... | def function[object2xml, parameter[self, data]]:
constant[Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
]
if ... | keyword[def] identifier[object2xml] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__options] [ literal[string] ]:
identifier[self] . identifier[set_options] ( identifier[encoding] = identifier[self] . identifier[__enco... | def object2xml(self, data):
"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
... |
def tool(_progname=sys.argv[0],
_argv=sys.argv[1:],
_syspath=sys.path,
_findMachines=findMachines,
_print=print):
"""
Entry point for command line utility.
"""
DESCRIPTION = """
Visualize automat.MethodicalMachines as graphviz graphs.
"""
EPILOG = """
... | def function[tool, parameter[_progname, _argv, _syspath, _findMachines, _print]]:
constant[
Entry point for command line utility.
]
variable[DESCRIPTION] assign[=] constant[
Visualize automat.MethodicalMachines as graphviz graphs.
]
variable[EPILOG] assign[=] constant[
You mu... | keyword[def] identifier[tool] ( identifier[_progname] = identifier[sys] . identifier[argv] [ literal[int] ],
identifier[_argv] = identifier[sys] . identifier[argv] [ literal[int] :],
identifier[_syspath] = identifier[sys] . identifier[path] ,
identifier[_findMachines] = identifier[findMachines] ,
identifier[_prin... | def tool(_progname=sys.argv[0], _argv=sys.argv[1:], _syspath=sys.path, _findMachines=findMachines, _print=print):
"""
Entry point for command line utility.
"""
DESCRIPTION = '\n Visualize automat.MethodicalMachines as graphviz graphs.\n '
EPILOG = '\n You must have the graphviz tool suite i... |
def client_new():
"""Create new client."""
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', ... | def function[client_new, parameter[]]:
constant[Create new client.]
variable[form] assign[=] call[name[ClientForm], parameter[name[request].form]]
if call[name[form].validate_on_submit, parameter[]] begin[:]
variable[c] assign[=] call[name[Client], parameter[]]
ca... | keyword[def] identifier[client_new] ():
literal[string]
identifier[form] = identifier[ClientForm] ( identifier[request] . identifier[form] )
keyword[if] identifier[form] . identifier[validate_on_submit] ():
identifier[c] = identifier[Client] ( identifier[user_id] = identifier[current_user] ... | def client_new():
"""Create new client."""
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', c... |
def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]:
"""
Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (r... | def function[walk_train_dirs, parameter[root_dir]]:
constant[
Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (root_dir, trai... | keyword[def] identifier[walk_train_dirs] ( identifier[root_dir] : identifier[str] )-> identifier[Iterable] [ identifier[Tuple] [ identifier[str] , identifier[Iterable] [ identifier[str] ]]]:
literal[string]
keyword[if] identifier[is_train_dir] ( identifier[root_dir] ):
keyword[yield] literal[str... | def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]:
"""
Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (r... |
def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | def function[getlist, parameter[self, name]]:
constant[
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
]
variable[value] assign[=] call[name[... | keyword[def] identifier[getlist] ( identifier[self] , identifier[name] ):
literal[string]
identifier[value] = identifier[self] . identifier[getvalue] ( identifier[name] )
identifier[complex] ={}
keyword[def] identifier[str_value] ( identifier[val] ):
keywor... | def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def str_value(val):... |
def _send(self, command):
"""
Sends a raw line to the server.
:param command: line to send.
:type command: unicode
"""
command = command.encode('utf-8')
log.debug('>> ' + command)
self.conn.oqueue.put(command) | def function[_send, parameter[self, command]]:
constant[
Sends a raw line to the server.
:param command: line to send.
:type command: unicode
]
variable[command] assign[=] call[name[command].encode, parameter[constant[utf-8]]]
call[name[log].debug, parameter[bina... | keyword[def] identifier[_send] ( identifier[self] , identifier[command] ):
literal[string]
identifier[command] = identifier[command] . identifier[encode] ( literal[string] )
identifier[log] . identifier[debug] ( literal[string] + identifier[command] )
identifier[self] . identifier... | def _send(self, command):
"""
Sends a raw line to the server.
:param command: line to send.
:type command: unicode
"""
command = command.encode('utf-8')
log.debug('>> ' + command)
self.conn.oqueue.put(command) |
def getPrimeFactors(n):
"""
Get all the prime factor of given integer
@param n integer
@return list [1, ..., n]
"""
lo = [1]
n2 = n // 2
k = 2
for k in range(2, n2 + 1):
if (n // k)*k == n:
lo.append(k)
return lo + [n, ] | def function[getPrimeFactors, parameter[n]]:
constant[
Get all the prime factor of given integer
@param n integer
@return list [1, ..., n]
]
variable[lo] assign[=] list[[<ast.Constant object at 0x7da2049627d0>]]
variable[n2] assign[=] binary_operation[name[n] <ast.FloorDiv object... | keyword[def] identifier[getPrimeFactors] ( identifier[n] ):
literal[string]
identifier[lo] =[ literal[int] ]
identifier[n2] = identifier[n] // literal[int]
identifier[k] = literal[int]
keyword[for] identifier[k] keyword[in] identifier[range] ( literal[int] , identifier[n2] + literal[int... | def getPrimeFactors(n):
"""
Get all the prime factor of given integer
@param n integer
@return list [1, ..., n]
"""
lo = [1]
n2 = n // 2
k = 2
for k in range(2, n2 + 1):
if n // k * k == n:
lo.append(k) # depends on [control=['if'], data=[]] # depends on [contro... |
def resolve_id(resolver, identifier, name='object'):
"""Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the object type, to be used in ... | def function[resolve_id, parameter[resolver, identifier, name]]:
constant[Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the objec... | keyword[def] identifier[resolve_id] ( identifier[resolver] , identifier[identifier] , identifier[name] = literal[string] ):
literal[string]
keyword[try] :
keyword[return] identifier[int] ( identifier[identifier] )
keyword[except] identifier[ValueError] :
keyword[pass]
identi... | def resolve_id(resolver, identifier, name='object'):
"""Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the object type, to be used in ... |
def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info("Running file: %s"%filename)
logger.debug(" Reading columns: %s"%columns)
data = fitsio.read(filename,columns=colum... | def function[add_column, parameter[filename, column, formula, force]]:
constant[ Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
]
variable[columns] assign[=] call[name[parse_formula], parameter[name[formula]]]
call[name[logger].info, parameter[binary_operation[cons... | keyword[def] identifier[add_column] ( identifier[filename] , identifier[column] , identifier[formula] , identifier[force] = keyword[False] ):
literal[string]
identifier[columns] = identifier[parse_formula] ( identifier[formula] )
identifier[logger] . identifier[info] ( literal[string] % identifier[fil... | def add_column(filename, column, formula, force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info('Running file: %s' % filename)
logger.debug(' Reading columns: %s' % columns)
data = fitsio.read(filename, colum... |
def to_file(self, path, precision='%.2g'):
"""
Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter
"""
table_info = self.get_table_info()
def dump_rows(rows):
if len(rows) > 1:
for... | def function[to_file, parameter[self, path, precision]]:
constant[
Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter
]
variable[table_info] assign[=] call[name[self].get_table_info, parameter[]]
def function... | keyword[def] identifier[to_file] ( identifier[self] , identifier[path] , identifier[precision] = literal[string] ):
literal[string]
identifier[table_info] = identifier[self] . identifier[get_table_info] ()
keyword[def] identifier[dump_rows] ( identifier[rows] ):
keyword[if] ... | def to_file(self, path, precision='%.2g'):
"""
Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter
"""
table_info = self.get_table_info()
def dump_rows(rows):
if len(rows) > 1:
for row in rows:
... |
def replace(self, **kwargs):
""" Return a :class:`.Date` with one or more components replaced
with new values.
"""
return Date(kwargs.get("year", self.__year),
kwargs.get("month", self.__month),
kwargs.get("day", self.__day)) | def function[replace, parameter[self]]:
constant[ Return a :class:`.Date` with one or more components replaced
with new values.
]
return[call[name[Date], parameter[call[name[kwargs].get, parameter[constant[year], name[self].__year]], call[name[kwargs].get, parameter[constant[month], name[sel... | keyword[def] identifier[replace] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[Date] ( identifier[kwargs] . identifier[get] ( literal[string] , identifier[self] . identifier[__year] ),
identifier[kwargs] . identifier[get] ( literal[string] , ident... | def replace(self, **kwargs):
""" Return a :class:`.Date` with one or more components replaced
with new values.
"""
return Date(kwargs.get('year', self.__year), kwargs.get('month', self.__month), kwargs.get('day', self.__day)) |
def ReadHuntClientResourcesStats(self, hunt_id):
"""Read/calculate hunt client resources stats."""
result = rdf_stats.ClientResourcesStats()
for f in self._GetHuntFlows(hunt_id):
cr = rdf_client_stats.ClientResources(
session_id="%s/%s" % (f.client_id, f.flow_id),
client_id=f.clie... | def function[ReadHuntClientResourcesStats, parameter[self, hunt_id]]:
constant[Read/calculate hunt client resources stats.]
variable[result] assign[=] call[name[rdf_stats].ClientResourcesStats, parameter[]]
for taget[name[f]] in starred[call[name[self]._GetHuntFlows, parameter[name[hunt_id]]]] b... | keyword[def] identifier[ReadHuntClientResourcesStats] ( identifier[self] , identifier[hunt_id] ):
literal[string]
identifier[result] = identifier[rdf_stats] . identifier[ClientResourcesStats] ()
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[_GetHuntFlows] ( identifier[hunt_i... | def ReadHuntClientResourcesStats(self, hunt_id):
"""Read/calculate hunt client resources stats."""
result = rdf_stats.ClientResourcesStats()
for f in self._GetHuntFlows(hunt_id):
cr = rdf_client_stats.ClientResources(session_id='%s/%s' % (f.client_id, f.flow_id), client_id=f.client_id, cpu_usage=f.c... |
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if (self.current_retry_attempt_count < self._max_retry_attempt_count) and self.needsRetry(excepti... | def function[ShouldRetry, parameter[self, exception]]:
constant[Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
]
if <ast.BoolOp object at 0x7da1b18e79d0> begin[:]
<ast.AugAssign... | keyword[def] identifier[ShouldRetry] ( identifier[self] , identifier[exception] ):
literal[string]
keyword[if] ( identifier[self] . identifier[current_retry_attempt_count] < identifier[self] . identifier[_max_retry_attempt_count] ) keyword[and] identifier[self] . identifier[needsRetry] ( identifie... | def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if self.current_retry_attempt_count < self._max_retry_attempt_count and self.needsRetry(exception.status_... |
def event_lookup_query(self, id, **kwargs):
"""
Query the Yelp Event Lookup API.
documentation: https://www.yelp.com/developers/documentation/v3/event
required parameters:
* id - event ID
"""
if not id:
raise ValueErro... | def function[event_lookup_query, parameter[self, id]]:
constant[
Query the Yelp Event Lookup API.
documentation: https://www.yelp.com/developers/documentation/v3/event
required parameters:
* id - event ID
]
if <ast.UnaryOp object ... | keyword[def] identifier[event_lookup_query] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[id] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[self] . identifier[_que... | def event_lookup_query(self, id, **kwargs):
"""
Query the Yelp Event Lookup API.
documentation: https://www.yelp.com/developers/documentation/v3/event
required parameters:
* id - event ID
"""
if not id:
raise ValueError('A valid e... |
def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
... | def function[query_other_gene_name, parameter[]]:
constant[
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short... | keyword[def] identifier[query_other_gene_name] ():
literal[string]
identifier[args] = identifier[get_args] (
identifier[request_args] = identifier[request] . identifier[args] ,
identifier[allowed_str_args] =[ literal[string] , literal[string] ],
identifier[allowed_int_args] =[ literal[strin... | def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
... |
def isdir(self, relpath, rsc=None):
"""
Returns whether or not the resource is a directory.
:return <bool>
"""
filepath = self.find(relpath, rsc)
if filepath.startswith(':'):
resource = QtCore.QResource(filepath)
return not re... | def function[isdir, parameter[self, relpath, rsc]]:
constant[
Returns whether or not the resource is a directory.
:return <bool>
]
variable[filepath] assign[=] call[name[self].find, parameter[name[relpath], name[rsc]]]
if call[name[filepath].startswith, param... | keyword[def] identifier[isdir] ( identifier[self] , identifier[relpath] , identifier[rsc] = keyword[None] ):
literal[string]
identifier[filepath] = identifier[self] . identifier[find] ( identifier[relpath] , identifier[rsc] )
keyword[if] identifier[filepath] . identifier[startswith] ( ... | def isdir(self, relpath, rsc=None):
"""
Returns whether or not the resource is a directory.
:return <bool>
"""
filepath = self.find(relpath, rsc)
if filepath.startswith(':'):
resource = QtCore.QResource(filepath)
return not resource.isFile() # depends on... |
def any_validator(obj, validators, **kwargs):
"""
Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors.
"""
if not len(validators) > 1:
raise ValueError(
"any_validator requires at least 2 validator. Only ... | def function[any_validator, parameter[obj, validators]]:
constant[
Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors.
]
if <ast.UnaryOp object at 0x7da1b0fcca90> begin[:]
<ast.Raise object at 0x7da1b0fcd8d0>... | keyword[def] identifier[any_validator] ( identifier[obj] , identifier[validators] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[validators] )> literal[int] :
keyword[raise] identifier[ValueError] (
literal[string]
literal[stri... | def any_validator(obj, validators, **kwargs):
"""
Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors.
"""
if not len(validators) > 1:
raise ValueError('any_validator requires at least 2 validator. Only got {0}'.form... |
def rename_acquisition(self, plate_name, name, new_name):
'''Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
name that should... | def function[rename_acquisition, parameter[self, plate_name, name, new_name]]:
constant[Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
... | keyword[def] identifier[rename_acquisition] ( identifier[self] , identifier[plate_name] , identifier[name] , identifier[new_name] ):
literal[string]
identifier[logger] . identifier[info] (
literal[string] ,
identifier[name] , identifier[self] . identifier[experiment_name] , identi... | def rename_acquisition(self, plate_name, name, new_name):
"""Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
name that should be ... |
def Click(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.... | def function[Click, parameter[self, x, y, ratioX, ratioY, simulateMove, waitTime]]:
constant[
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ra... | keyword[def] identifier[Click] ( identifier[self] , identifier[x] : identifier[int] = keyword[None] , identifier[y] : identifier[int] = keyword[None] , identifier[ratioX] : identifier[float] = literal[int] , identifier[ratioY] : identifier[float] = literal[int] , identifier[simulateMove] : identifier[bool] = keyword[... | def Click(self, x: int=None, y: int=None, ratioX: float=0.5, ratioY: float=0.5, simulateMove: bool=True, waitTime: float=OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if n... |
def solve_limited(self, assumptions=[]):
"""
Solve internal formula using given budgets for conflicts and
propagations.
"""
if self.minicard:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
... | def function[solve_limited, parameter[self, assumptions]]:
constant[
Solve internal formula using given budgets for conflicts and
propagations.
]
if name[self].minicard begin[:]
if name[self].use_timer begin[:]
variable[start_time] ... | keyword[def] identifier[solve_limited] ( identifier[self] , identifier[assumptions] =[]):
literal[string]
keyword[if] identifier[self] . identifier[minicard] :
keyword[if] identifier[self] . identifier[use_timer] :
identifier[start_time] = identifier[time] . identi... | def solve_limited(self, assumptions=[]):
"""
Solve internal formula using given budgets for conflicts and
propagations.
"""
if self.minicard:
if self.use_timer:
start_time = time.clock() # depends on [control=['if'], data=[]]
# saving default SIGINT h... |
def BE_vs_clean_SE(self, delu_dict, delu_default=0, plot_eads=False,
annotate_monolayer=True, JPERM2=False):
"""
For each facet, plot the clean surface energy against the most
stable binding energy.
Args:
delu_dict (Dict): Dictionary of the chemical... | def function[BE_vs_clean_SE, parameter[self, delu_dict, delu_default, plot_eads, annotate_monolayer, JPERM2]]:
constant[
For each facet, plot the clean surface energy against the most
stable binding energy.
Args:
delu_dict (Dict): Dictionary of the chemical potentials to ... | keyword[def] identifier[BE_vs_clean_SE] ( identifier[self] , identifier[delu_dict] , identifier[delu_default] = literal[int] , identifier[plot_eads] = keyword[False] ,
identifier[annotate_monolayer] = keyword[True] , identifier[JPERM2] = keyword[False] ):
literal[string]
identifier[plt] = identif... | def BE_vs_clean_SE(self, delu_dict, delu_default=0, plot_eads=False, annotate_monolayer=True, JPERM2=False):
"""
For each facet, plot the clean surface energy against the most
stable binding energy.
Args:
delu_dict (Dict): Dictionary of the chemical potentials to be set as
... |
def _comprise(dict1,dict2):
'''
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2)
'''
len_1 = dict1.__len__()
len_2 = dict2.__len__()
if(len_2>len_1):
return(False)
else:
for k2 in dict2:
v2 = dict2[k2]
... | def function[_comprise, parameter[dict1, dict2]]:
constant[
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2)
]
variable[len_1] assign[=] call[name[dict1].__len__, parameter[]]
variable[len_2] assign[=] call[name[dict2].__len__, parameter[... | keyword[def] identifier[_comprise] ( identifier[dict1] , identifier[dict2] ):
literal[string]
identifier[len_1] = identifier[dict1] . identifier[__len__] ()
identifier[len_2] = identifier[dict2] . identifier[__len__] ()
keyword[if] ( identifier[len_2] > identifier[len_1] ):
keyword[retur... | def _comprise(dict1, dict2):
"""
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2)
"""
len_1 = dict1.__len__()
len_2 = dict2.__len__()
if len_2 > len_1:
return False # depends on [control=['if'], data=[]]
else:
for k2 in dict2... |
def changebasis(uu, vv, nn, pps):
"""
For a list of points given in standard coordinates (in terms of e1, e2 and e3), returns the same list
expressed in the basis (uu, vv, nn), which is supposed to be orthonormal.
:param uu: First vector of the basis
:param vv: Second vector of the basis
:param ... | def function[changebasis, parameter[uu, vv, nn, pps]]:
constant[
For a list of points given in standard coordinates (in terms of e1, e2 and e3), returns the same list
expressed in the basis (uu, vv, nn), which is supposed to be orthonormal.
:param uu: First vector of the basis
:param vv: Second ... | keyword[def] identifier[changebasis] ( identifier[uu] , identifier[vv] , identifier[nn] , identifier[pps] ):
literal[string]
identifier[MM] = identifier[np] . identifier[zeros] ([ literal[int] , literal[int] ], identifier[np] . identifier[float] )
keyword[for] identifier[ii] keyword[in] identifier[... | def changebasis(uu, vv, nn, pps):
"""
For a list of points given in standard coordinates (in terms of e1, e2 and e3), returns the same list
expressed in the basis (uu, vv, nn), which is supposed to be orthonormal.
:param uu: First vector of the basis
:param vv: Second vector of the basis
:param ... |
def spin_up_instance(self, command, job_name):
"""Start an instance in the VPC in the first available subnet.
N instances will be started if nodes_per_block > 1.
Not supported. We only do 1 node per block.
Parameters
----------
command : str
Command string t... | def function[spin_up_instance, parameter[self, command, job_name]]:
constant[Start an instance in the VPC in the first available subnet.
N instances will be started if nodes_per_block > 1.
Not supported. We only do 1 node per block.
Parameters
----------
command : str
... | keyword[def] identifier[spin_up_instance] ( identifier[self] , identifier[command] , identifier[job_name] ):
literal[string]
identifier[command] = identifier[Template] ( identifier[template_string] ). identifier[substitute] ( identifier[jobname] = identifier[job_name] ,
identifier[user_sc... | def spin_up_instance(self, command, job_name):
"""Start an instance in the VPC in the first available subnet.
N instances will be started if nodes_per_block > 1.
Not supported. We only do 1 node per block.
Parameters
----------
command : str
Command string to ex... |
def setup(app):
"""Allow this package to be used as Sphinx extension.
This is also called from the top-level ``__init__.py``.
:type app: sphinx.application.Sphinx
"""
from .patches import patch_django_for_autodoc
# When running, make sure Django doesn't execute querysets
patch_django_for_a... | def function[setup, parameter[app]]:
constant[Allow this package to be used as Sphinx extension.
This is also called from the top-level ``__init__.py``.
:type app: sphinx.application.Sphinx
]
from relative_module[patches] import module[patch_django_for_autodoc]
call[name[patch_django_fo... | keyword[def] identifier[setup] ( identifier[app] ):
literal[string]
keyword[from] . identifier[patches] keyword[import] identifier[patch_django_for_autodoc]
identifier[patch_django_for_autodoc] ()
identifier[app] . identifier[connect] ( literal[string] , identifier[improve_mod... | def setup(app):
"""Allow this package to be used as Sphinx extension.
This is also called from the top-level ``__init__.py``.
:type app: sphinx.application.Sphinx
"""
from .patches import patch_django_for_autodoc
# When running, make sure Django doesn't execute querysets
patch_django_for_au... |
def _compute_site_response_term(self, C, sites, pga1000):
"""
Compute and return site response model term
This GMPE adopts the same site response scaling model of
Walling et al (2008) as implemented in the Abrahamson & Silva (2008)
GMPE. The functional form is retained here.
... | def function[_compute_site_response_term, parameter[self, C, sites, pga1000]]:
constant[
Compute and return site response model term
This GMPE adopts the same site response scaling model of
Walling et al (2008) as implemented in the Abrahamson & Silva (2008)
GMPE. The functional ... | keyword[def] identifier[_compute_site_response_term] ( identifier[self] , identifier[C] , identifier[sites] , identifier[pga1000] ):
literal[string]
identifier[vs_star] = identifier[sites] . identifier[vs30] . identifier[copy] ()
identifier[vs_star] [ identifier[vs_star] > literal[int] ]= ... | def _compute_site_response_term(self, C, sites, pga1000):
"""
Compute and return site response model term
This GMPE adopts the same site response scaling model of
Walling et al (2008) as implemented in the Abrahamson & Silva (2008)
GMPE. The functional form is retained here.
... |
def by_cat(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the ... | def function[by_cat, parameter[self]]:
constant[
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tup... | keyword[def] identifier[by_cat] ( identifier[self] ):
literal[string]
keyword[for] identifier[value] keyword[in] identifier[np] . identifier[unique] ( identifier[self] . identifier[category] ):
identifier[cat_fm] = identifier[self] . identifier[filter] ( identifier[self] . identifie... | def by_cat(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the filt... |
def resolved_row(objs, geomatcher):
"""Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted."""
def get_locations(lst):
for elem in lst:
try:
... | def function[resolved_row, parameter[objs, geomatcher]]:
constant[Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted.]
def function[get_locations, param... | keyword[def] identifier[resolved_row] ( identifier[objs] , identifier[geomatcher] ):
literal[string]
keyword[def] identifier[get_locations] ( identifier[lst] ):
keyword[for] identifier[elem] keyword[in] identifier[lst] :
keyword[try] :
keyword[yield] identifier[e... | def resolved_row(objs, geomatcher):
"""Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted."""
def get_locations(lst):
for elem in lst:
try:... |
def get_secret(key, *args, **kwargs):
"""Retrieves a secret."""
env_value = os.environ.get(key.replace('.', '_').upper())
if not env_value:
# Backwards compatibility: the deprecated secrets vault
return _get_secret_from_vault(key, *args, **kwargs)
return env_value | def function[get_secret, parameter[key]]:
constant[Retrieves a secret.]
variable[env_value] assign[=] call[name[os].environ.get, parameter[call[call[name[key].replace, parameter[constant[.], constant[_]]].upper, parameter[]]]]
if <ast.UnaryOp object at 0x7da20e956a70> begin[:]
return[cal... | keyword[def] identifier[get_secret] ( identifier[key] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[env_value] = identifier[os] . identifier[environ] . identifier[get] ( identifier[key] . identifier[replace] ( literal[string] , literal[string] ). identifier[upper] ())
keywor... | def get_secret(key, *args, **kwargs):
"""Retrieves a secret."""
env_value = os.environ.get(key.replace('.', '_').upper())
if not env_value:
# Backwards compatibility: the deprecated secrets vault
return _get_secret_from_vault(key, *args, **kwargs) # depends on [control=['if'], data=[]]
... |
def _rem_id_from_index(self, indexedField, pk, val, conn=None):
'''
_rem_id_from_index - Removes an id from an index
internal
'''
if conn is None:
conn = self._get_connection()
conn.srem(self._get_key_for_index(indexedField, val), pk) | def function[_rem_id_from_index, parameter[self, indexedField, pk, val, conn]]:
constant[
_rem_id_from_index - Removes an id from an index
internal
]
if compare[name[conn] is constant[None]] begin[:]
variable[conn] assign[=] call[name[self]._get_connection, parameter[]]
c... | keyword[def] identifier[_rem_id_from_index] ( identifier[self] , identifier[indexedField] , identifier[pk] , identifier[val] , identifier[conn] = keyword[None] ):
literal[string]
keyword[if] identifier[conn] keyword[is] keyword[None] :
identifier[conn] = identifier[self] . identifier[_get_connection] ()... | def _rem_id_from_index(self, indexedField, pk, val, conn=None):
"""
_rem_id_from_index - Removes an id from an index
internal
"""
if conn is None:
conn = self._get_connection() # depends on [control=['if'], data=['conn']]
conn.srem(self._get_key_for_index(indexedField, val), pk) |
def __get_formulas(self):
"""
Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned.
"""
array = self._get_target().getFormulaArray()
return tuple(itertools.cha... | def function[__get_formulas, parameter[self]]:
constant[
Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned.
]
variable[array] assign[=] call[call[name[self]._get_ta... | keyword[def] identifier[__get_formulas] ( identifier[self] ):
literal[string]
identifier[array] = identifier[self] . identifier[_get_target] (). identifier[getFormulaArray] ()
keyword[return] identifier[tuple] ( identifier[itertools] . identifier[chain] . identifier[from_iterable] ( ident... | def __get_formulas(self):
"""
Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned.
"""
array = self._get_target().getFormulaArray()
return tuple(itertools.chain.from_iter... |
def is_connected(self, attempts=3):
"""Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int``
"""
if self.gce is None:
while attempts > 0:
self.logger.info("Attempting to connect .... | def function[is_connected, parameter[self, attempts]]:
constant[Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int``
]
if compare[name[self].gce is constant[None]] begin[:]
while compare[nam... | keyword[def] identifier[is_connected] ( identifier[self] , identifier[attempts] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[gce] keyword[is] keyword[None] :
keyword[while] identifier[attempts] > literal[int] :
identifier[self] . iden... | def is_connected(self, attempts=3):
"""Try to reconnect if neccessary.
:param attempts: The amount of tries to reconnect if neccessary.
:type attempts: ``int``
"""
if self.gce is None:
while attempts > 0:
self.logger.info('Attempting to connect ...')
... |
def from_html(html_style_colour_str: str):
"""
Parser for KDialog output, which outputs a HTML style hex code like #55aa00
@param html_style_colour_str: HTML style hex string encoded colour. (#rrggbb)
@return: ColourData instance
@rtype: ColourData
"""
html_style_... | def function[from_html, parameter[html_style_colour_str]]:
constant[
Parser for KDialog output, which outputs a HTML style hex code like #55aa00
@param html_style_colour_str: HTML style hex string encoded colour. (#rrggbb)
@return: ColourData instance
@rtype: ColourData
]... | keyword[def] identifier[from_html] ( identifier[html_style_colour_str] : identifier[str] ):
literal[string]
identifier[html_style_colour_str] = identifier[html_style_colour_str] . identifier[lstrip] ( literal[string] )
identifier[components] = identifier[list] ( identifier[map] ( literal[s... | def from_html(html_style_colour_str: str):
"""
Parser for KDialog output, which outputs a HTML style hex code like #55aa00
@param html_style_colour_str: HTML style hex string encoded colour. (#rrggbb)
@return: ColourData instance
@rtype: ColourData
"""
html_style_colour_s... |
def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_k... | def function[boot, parameter[self]]:
constant[
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
]
if <ast.UnaryOp object at 0x7da1b033e290> begin[:]
call[call[name[type], parameter[name[self]]]._ports][name[self].p... | keyword[def] identifier[boot] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[responsive] :
identifier[type] ( identifier[self] ). identifier[_ports] [ identifier[self] . identifier[port_key] ]= identifier[self] . identifier[port... | def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_key] = self.port
... |
def _imm_resolve_deps(cls):
'''
_imm_resolve_deps(imm_class) resolves the dependencies of the given immutable class imm_class
and edits the immutable metadata appropriately.
'''
dat = cls._pimms_immutable_data_
params = dat['params']
values = dat['values']
consts = dat['consts']
chec... | def function[_imm_resolve_deps, parameter[cls]]:
constant[
_imm_resolve_deps(imm_class) resolves the dependencies of the given immutable class imm_class
and edits the immutable metadata appropriately.
]
variable[dat] assign[=] name[cls]._pimms_immutable_data_
variable[params] assign[... | keyword[def] identifier[_imm_resolve_deps] ( identifier[cls] ):
literal[string]
identifier[dat] = identifier[cls] . identifier[_pimms_immutable_data_]
identifier[params] = identifier[dat] [ literal[string] ]
identifier[values] = identifier[dat] [ literal[string] ]
identifier[consts] = ident... | def _imm_resolve_deps(cls):
"""
_imm_resolve_deps(imm_class) resolves the dependencies of the given immutable class imm_class
and edits the immutable metadata appropriately.
"""
dat = cls._pimms_immutable_data_
params = dat['params']
values = dat['values']
consts = dat['consts']
chec... |
def list_configs():
'''
List all available configs
CLI example:
.. code-block:: bash
salt '*' snapper.list_configs
'''
try:
configs = snapper.ListConfigs()
return dict((config[0], config[2]) for config in configs)
except dbus.DBusException as exc:
raise Com... | def function[list_configs, parameter[]]:
constant[
List all available configs
CLI example:
.. code-block:: bash
salt '*' snapper.list_configs
]
<ast.Try object at 0x7da2044c04f0> | keyword[def] identifier[list_configs] ():
literal[string]
keyword[try] :
identifier[configs] = identifier[snapper] . identifier[ListConfigs] ()
keyword[return] identifier[dict] (( identifier[config] [ literal[int] ], identifier[config] [ literal[int] ]) keyword[for] identifier[config] ... | def list_configs():
"""
List all available configs
CLI example:
.. code-block:: bash
salt '*' snapper.list_configs
"""
try:
configs = snapper.ListConfigs()
return dict(((config[0], config[2]) for config in configs)) # depends on [control=['try'], data=[]]
except d... |
def is_diacritic(char, strict=True):
"""
Check whether the character is a diacritic (as opposed to a letter or a
suprasegmental).
In strict mode return True only if the diacritic is part of the IPA spec.
"""
if char in chart.diacritics:
return True
if not strict:
return (unicodedata.category(char) in ['Lm'... | def function[is_diacritic, parameter[char, strict]]:
constant[
Check whether the character is a diacritic (as opposed to a letter or a
suprasegmental).
In strict mode return True only if the diacritic is part of the IPA spec.
]
if compare[name[char] in name[chart].diacritics] begin[:]
retur... | keyword[def] identifier[is_diacritic] ( identifier[char] , identifier[strict] = keyword[True] ):
literal[string]
keyword[if] identifier[char] keyword[in] identifier[chart] . identifier[diacritics] :
keyword[return] keyword[True]
keyword[if] keyword[not] identifier[strict] :
keyword[return] ( iden... | def is_diacritic(char, strict=True):
"""
Check whether the character is a diacritic (as opposed to a letter or a
suprasegmental).
In strict mode return True only if the diacritic is part of the IPA spec.
"""
if char in chart.diacritics:
return True # depends on [control=['if'], data=[]]
if not... |
def _parse_blocks(instream):
"""Parse an alignment block from the given file handle.
Block looks like:
[0_(1)=fa2cma(8){go=10000,gx=2000,pn=1000.0,lf=0,rf=0}:
(209)***********************************************...
... sequences, numbered 1-8 ...
_0].
"""
ilines = sugar.unblank(instr... | def function[_parse_blocks, parameter[instream]]:
constant[Parse an alignment block from the given file handle.
Block looks like:
[0_(1)=fa2cma(8){go=10000,gx=2000,pn=1000.0,lf=0,rf=0}:
(209)***********************************************...
... sequences, numbered 1-8 ...
_0].
]
... | keyword[def] identifier[_parse_blocks] ( identifier[instream] ):
literal[string]
identifier[ilines] = identifier[sugar] . identifier[unblank] ( identifier[instream] )
keyword[for] identifier[line] keyword[in] identifier[ilines] :
keyword[if] identifier[line] . identifier[startswith] ( lit... | def _parse_blocks(instream):
"""Parse an alignment block from the given file handle.
Block looks like:
[0_(1)=fa2cma(8){go=10000,gx=2000,pn=1000.0,lf=0,rf=0}:
(209)***********************************************...
... sequences, numbered 1-8 ...
_0].
"""
ilines = sugar.unblank(instr... |
async def on_step(self, iteration):
self.combinedActions = []
"""
- depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount... | <ast.AsyncFunctionDef object at 0x7da204567e50> | keyword[async] keyword[def] identifier[on_step] ( identifier[self] , identifier[iteration] ):
identifier[self] . identifier[combinedActions] =[]
literal[string]
keyword[if] identifier[self] . identifier[supply_left] < literal[int] keyword[and] identifier[self] . identifier[townhalls] ... | async def on_step(self, iteration):
self.combinedActions = []
'\n - depots when low on remaining supply\n - townhalls contains commandcenter and orbitalcommand\n - self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount\n ... |
def move(self, d_xyz):
"""
Translate the Polyhedron in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Polyhedron``
"""
polygon = np.array([[0,0], [0,1], [1,1], [0,1]])
... | def function[move, parameter[self, d_xyz]]:
constant[
Translate the Polyhedron in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Polyhedron``
]
variable[polygon] assign[=] call[name[np... | keyword[def] identifier[move] ( identifier[self] , identifier[d_xyz] ):
literal[string]
identifier[polygon] = identifier[np] . identifier[array] ([[ literal[int] , literal[int] ],[ literal[int] , literal[int] ],[ literal[int] , literal[int] ],[ literal[int] , literal[int] ]])
identifier... | def move(self, d_xyz):
"""
Translate the Polyhedron in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Polyhedron``
"""
polygon = np.array([[0, 0], [0, 1], [1, 1], [0, 1]])
space = Space(Pl... |
def _run_down(self, path, migration, pretend=False):
"""
Run "down" a migration instance.
"""
migration_file = migration["migration"]
instance = self._resolve(path, migration_file)
if pretend:
return self._pretend_to_run(instance, "down")
if instanc... | def function[_run_down, parameter[self, path, migration, pretend]]:
constant[
Run "down" a migration instance.
]
variable[migration_file] assign[=] call[name[migration]][constant[migration]]
variable[instance] assign[=] call[name[self]._resolve, parameter[name[path], name[migrati... | keyword[def] identifier[_run_down] ( identifier[self] , identifier[path] , identifier[migration] , identifier[pretend] = keyword[False] ):
literal[string]
identifier[migration_file] = identifier[migration] [ literal[string] ]
identifier[instance] = identifier[self] . identifier[_resolve] ... | def _run_down(self, path, migration, pretend=False):
"""
Run "down" a migration instance.
"""
migration_file = migration['migration']
instance = self._resolve(path, migration_file)
if pretend:
return self._pretend_to_run(instance, 'down') # depends on [control=['if'], data=[]]
... |
def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, s... | def function[start, parameter[self, players]]:
constant[
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds... | keyword[def] identifier[start] ( identifier[self] , identifier[players] ):
literal[string]
keyword[from] . identifier[boardbuilder] keyword[import] identifier[Opt]
identifier[self] . identifier[reset] ()
keyword[if] identifier[self] . identifier[board] . identifier[opts] . ide... | def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets ... |
def safe_execute_script(driver, script):
""" When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. """
try:
driver.execute_script(script)
except Exception:
... | def function[safe_execute_script, parameter[driver, script]]:
constant[ When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. ]
<ast.Try object at 0x7da1b1bbab60> | keyword[def] identifier[safe_execute_script] ( identifier[driver] , identifier[script] ):
literal[string]
keyword[try] :
identifier[driver] . identifier[execute_script] ( identifier[script] )
keyword[except] identifier[Exception] :
identifier[activate_jquery] ( identifier[drive... | def safe_execute_script(driver, script):
""" When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. """
try:
driver.execute_script(script) # depends on [control=['try... |
def is_merged(self):
"""Checks to see if the pull request was merged.
:returns: bool
"""
url = self._build_url('merge', base_url=self._api)
return self._boolean(self._get(url), 204, 404) | def function[is_merged, parameter[self]]:
constant[Checks to see if the pull request was merged.
:returns: bool
]
variable[url] assign[=] call[name[self]._build_url, parameter[constant[merge]]]
return[call[name[self]._boolean, parameter[call[name[self]._get, parameter[name[url]]], c... | keyword[def] identifier[is_merged] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[_build_url] ( literal[string] , identifier[base_url] = identifier[self] . identifier[_api] )
keyword[return] identifier[self] . identifier[_boolean] ( identifier[self] ... | def is_merged(self):
"""Checks to see if the pull request was merged.
:returns: bool
"""
url = self._build_url('merge', base_url=self._api)
return self._boolean(self._get(url), 204, 404) |
def _make_stream_reader(cls, stream):
"""
Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header.
"""
endian = cls._detect_endian(stream)
return StreamReader(stream, endia... | def function[_make_stream_reader, parameter[cls, stream]]:
constant[
Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header.
]
variable[endian] assign[=] call[name[cls]._detect_en... | keyword[def] identifier[_make_stream_reader] ( identifier[cls] , identifier[stream] ):
literal[string]
identifier[endian] = identifier[cls] . identifier[_detect_endian] ( identifier[stream] )
keyword[return] identifier[StreamReader] ( identifier[stream] , identifier[endian] ) | def _make_stream_reader(cls, stream):
"""
Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header.
"""
endian = cls._detect_endian(stream)
return StreamReader(stream, endian) |
def absent(name, auth=None, **kwargs):
'''
Ensure a security group does not exist
name
Name of the security group
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['ne... | def function[absent, parameter[name, auth]]:
constant[
Ensure a security group does not exist
name
Name of the security group
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da1b215c490>, <ast.Constant object at 0x7da1b215f070>, <ast.Constant object at 0x7da1b215dd... | keyword[def] identifier[absent] ( identifier[name] , identifier[auth] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[True] ,
literal[string] : literal[string] }
identifier[... | def absent(name, auth=None, **kwargs):
"""
Ensure a security group does not exist
name
Name of the security group
"""
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['neutronng.setup_clouds'](auth)
kw... |
def _start_tracer(self, origin):
"""
Start a new Tracer object, and store it in self.tracers.
"""
tracer = self._tracer_class(log=self.log)
tracer.data = self.data
fn = tracer.start(origin)
self.tracers.append(tracer)
return fn | def function[_start_tracer, parameter[self, origin]]:
constant[
Start a new Tracer object, and store it in self.tracers.
]
variable[tracer] assign[=] call[name[self]._tracer_class, parameter[]]
name[tracer].data assign[=] name[self].data
variable[fn] assign[=] call[name[t... | keyword[def] identifier[_start_tracer] ( identifier[self] , identifier[origin] ):
literal[string]
identifier[tracer] = identifier[self] . identifier[_tracer_class] ( identifier[log] = identifier[self] . identifier[log] )
identifier[tracer] . identifier[data] = identifier[self] . identifier... | def _start_tracer(self, origin):
"""
Start a new Tracer object, and store it in self.tracers.
"""
tracer = self._tracer_class(log=self.log)
tracer.data = self.data
fn = tracer.start(origin)
self.tracers.append(tracer)
return fn |
def _strip_line_sep(self, s):
"""Strip trailing line separators from s, but no other whitespaces."""
if s[-2:] == b'\r\n':
return s[:-2]
elif s[-1:] == b'\n':
return s[:-1]
else:
return s | def function[_strip_line_sep, parameter[self, s]]:
constant[Strip trailing line separators from s, but no other whitespaces.]
if compare[call[name[s]][<ast.Slice object at 0x7da1b1b0fca0>] equal[==] constant[b'\r\n']] begin[:]
return[call[name[s]][<ast.Slice object at 0x7da1b1b0e980>]] | keyword[def] identifier[_strip_line_sep] ( identifier[self] , identifier[s] ):
literal[string]
keyword[if] identifier[s] [- literal[int] :]== literal[string] :
keyword[return] identifier[s] [:- literal[int] ]
keyword[elif] identifier[s] [- literal[int] :]== literal[string] ... | def _strip_line_sep(self, s):
"""Strip trailing line separators from s, but no other whitespaces."""
if s[-2:] == b'\r\n':
return s[:-2] # depends on [control=['if'], data=[]]
elif s[-1:] == b'\n':
return s[:-1] # depends on [control=['if'], data=[]]
else:
return s |
def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | def function[git_tag_to_semver, parameter[git_tag]]:
constant[
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
]
variable[pattern] assign[=] call[name[re].compile, parameter[constant[[0-9]+\.[0... | keyword[def] identifier[git_tag_to_semver] ( identifier[git_tag] : identifier[str] )-> identifier[SemVer] :
literal[string]
identifier[pattern] = identifier[re] . identifier[compile] ( literal[string] )
identifier[match] = identifier[pattern] . identifier[search] ( identifier[git_tag] )
keyword[i... | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile('[0-9]+\\.[0-9]+\\.[0-9]+$')
match = pattern.search(git_tag)
if match... |
def _input_valid(input_, operation, message, output_condition_uri=None):
"""Validates a single Input against a single Output.
Note:
In case of a `CREATE` Transaction, this method
does not validate against `output_condition_uri`.
Args:
inp... | def function[_input_valid, parameter[input_, operation, message, output_condition_uri]]:
constant[Validates a single Input against a single Output.
Note:
In case of a `CREATE` Transaction, this method
does not validate against `output_condition_uri`.
Arg... | keyword[def] identifier[_input_valid] ( identifier[input_] , identifier[operation] , identifier[message] , identifier[output_condition_uri] = keyword[None] ):
literal[string]
identifier[ccffill] = identifier[input_] . identifier[fulfillment]
keyword[try] :
identifier[parsed_f... | def _input_valid(input_, operation, message, output_condition_uri=None):
"""Validates a single Input against a single Output.
Note:
In case of a `CREATE` Transaction, this method
does not validate against `output_condition_uri`.
Args:
input_ ... |
def add_provider(self, share, provider, readonly=False):
"""Add a provider to the provider_map routing table."""
# Make sure share starts with, or is '/'
share = "/" + share.strip("/")
assert share not in self.provider_map
if compat.is_basestring(provider):
# Syntax:... | def function[add_provider, parameter[self, share, provider, readonly]]:
constant[Add a provider to the provider_map routing table.]
variable[share] assign[=] binary_operation[constant[/] + call[name[share].strip, parameter[constant[/]]]]
assert[compare[name[share] <ast.NotIn object at 0x7da2590d7190... | keyword[def] identifier[add_provider] ( identifier[self] , identifier[share] , identifier[provider] , identifier[readonly] = keyword[False] ):
literal[string]
identifier[share] = literal[string] + identifier[share] . identifier[strip] ( literal[string] )
keyword[assert] identifie... | def add_provider(self, share, provider, readonly=False):
"""Add a provider to the provider_map routing table."""
# Make sure share starts with, or is '/'
share = '/' + share.strip('/')
assert share not in self.provider_map
if compat.is_basestring(provider):
# Syntax:
# <mount_path>... |
def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get("blog_id")
if blog_id is None:
raise CommandError("Usage is import_blogger %s" % self.args)
try:
from gdata import service
except ImportError:
... | def function[handle_import, parameter[self, options]]:
constant[
Gets posts from Blogger.
]
variable[blog_id] assign[=] call[name[options].get, parameter[constant[blog_id]]]
if compare[name[blog_id] is constant[None]] begin[:]
<ast.Raise object at 0x7da20e9542e0>
<ast... | keyword[def] identifier[handle_import] ( identifier[self] , identifier[options] ):
literal[string]
identifier[blog_id] = identifier[options] . identifier[get] ( literal[string] )
keyword[if] identifier[blog_id] keyword[is] keyword[None] :
keyword[raise] identifier[Command... | def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get('blog_id')
if blog_id is None:
raise CommandError('Usage is import_blogger %s' % self.args) # depends on [control=['if'], data=[]]
try:
from gdata import service # depends on [contr... |
def to_inference_data(self):
"""Convert all available data to an InferenceData object.
Note that if groups can not be created (i.e., there is no `trace`, so
the `posterior` and `sample_stats` can not be extracted), then the InferenceData
will not have those groups.
"""
... | def function[to_inference_data, parameter[self]]:
constant[Convert all available data to an InferenceData object.
Note that if groups can not be created (i.e., there is no `trace`, so
the `posterior` and `sample_stats` can not be extracted), then the InferenceData
will not have those gr... | keyword[def] identifier[to_inference_data] ( identifier[self] ):
literal[string]
keyword[return] identifier[InferenceData] (
**{
literal[string] : identifier[self] . identifier[posterior_to_xarray] (),
literal[string] : identifier[self] . identifier[sample_stats_to_x... | def to_inference_data(self):
"""Convert all available data to an InferenceData object.
Note that if groups can not be created (i.e., there is no `trace`, so
the `posterior` and `sample_stats` can not be extracted), then the InferenceData
will not have those groups.
"""
return In... |
def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated."""
def outer(fun):
msg = "psutil.%s is deprecated" % fun.__name__
if replacement is not None:
msg += "; use %s instead" % replacement
if fun.__doc__ is None:
fun.__... | def function[deprecated, parameter[replacement]]:
constant[A decorator which can be used to mark functions as deprecated.]
def function[outer, parameter[fun]]:
variable[msg] assign[=] binary_operation[constant[psutil.%s is deprecated] <ast.Mod object at 0x7da2590d6920> name[fun].__name__... | keyword[def] identifier[deprecated] ( identifier[replacement] = keyword[None] ):
literal[string]
keyword[def] identifier[outer] ( identifier[fun] ):
identifier[msg] = literal[string] % identifier[fun] . identifier[__name__]
keyword[if] identifier[replacement] keyword[is] keyword[not]... | def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated."""
def outer(fun):
msg = 'psutil.%s is deprecated' % fun.__name__
if replacement is not None:
msg += '; use %s instead' % replacement # depends on [control=['if'], data=['replacement... |
def plot_polarbar(scores, labels=None, labels_size=15, colors="default", distribution_means=None, distribution_sds=None, treshold=1.28, fig_size=(15, 15)):
"""
Polar bar chart.
Parameters
----------
scores : list or dict
Scores to plot.
labels : list
List of labels to be used fo... | def function[plot_polarbar, parameter[scores, labels, labels_size, colors, distribution_means, distribution_sds, treshold, fig_size]]:
constant[
Polar bar chart.
Parameters
----------
scores : list or dict
Scores to plot.
labels : list
List of labels to be used for ticks.
... | keyword[def] identifier[plot_polarbar] ( identifier[scores] , identifier[labels] = keyword[None] , identifier[labels_size] = literal[int] , identifier[colors] = literal[string] , identifier[distribution_means] = keyword[None] , identifier[distribution_sds] = keyword[None] , identifier[treshold] = literal[int] , ident... | def plot_polarbar(scores, labels=None, labels_size=15, colors='default', distribution_means=None, distribution_sds=None, treshold=1.28, fig_size=(15, 15)):
"""
Polar bar chart.
Parameters
----------
scores : list or dict
Scores to plot.
labels : list
List of labels to be used fo... |
def _remove_features(layer):
"""Remove features which do not have information for InaSAFE or an invalid
geometry.
:param layer: The vector layer.
:type layer: QgsVectorLayer
"""
# Get the layer purpose of the layer.
layer_purpose = layer.keywords['layer_purpose']
layer_subcategory = lay... | def function[_remove_features, parameter[layer]]:
constant[Remove features which do not have information for InaSAFE or an invalid
geometry.
:param layer: The vector layer.
:type layer: QgsVectorLayer
]
variable[layer_purpose] assign[=] call[name[layer].keywords][constant[layer_purpose]... | keyword[def] identifier[_remove_features] ( identifier[layer] ):
literal[string]
identifier[layer_purpose] = identifier[layer] . identifier[keywords] [ literal[string] ]
identifier[layer_subcategory] = identifier[layer] . identifier[keywords] . identifier[get] ( identifier[layer_purpose] )
... | def _remove_features(layer):
"""Remove features which do not have information for InaSAFE or an invalid
geometry.
:param layer: The vector layer.
:type layer: QgsVectorLayer
"""
# Get the layer purpose of the layer.
layer_purpose = layer.keywords['layer_purpose']
layer_subcategory = lay... |
def request(self, endpoint, method="GET", data="",
raw=False, params=None, retries=None, client=None,
headers=None, timeout=None, **kwargs):
""" Make request to endpoint with OAuth.
Returns dictionary with response data.
:param endpoint: endpoint path, or a fully... | def function[request, parameter[self, endpoint, method, data, raw, params, retries, client, headers, timeout]]:
constant[ Make request to endpoint with OAuth.
Returns dictionary with response data.
:param endpoint: endpoint path, or a fully qualified URL if raw=True.
:param method: GET ... | keyword[def] identifier[request] ( identifier[self] , identifier[endpoint] , identifier[method] = literal[string] , identifier[data] = literal[string] ,
identifier[raw] = keyword[False] , identifier[params] = keyword[None] , identifier[retries] = keyword[None] , identifier[client] = keyword[None] ,
identifier[heade... | def request(self, endpoint, method='GET', data='', raw=False, params=None, retries=None, client=None, headers=None, timeout=None, **kwargs):
""" Make request to endpoint with OAuth.
Returns dictionary with response data.
:param endpoint: endpoint path, or a fully qualified URL if raw=True.
... |
def update_user_pool(UserPoolId=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfiguration=None, SmsConfiguration=None, ... | def function[update_user_pool, parameter[UserPoolId, Policies, LambdaConfig, AutoVerifiedAttributes, SmsVerificationMessage, EmailVerificationMessage, EmailVerificationSubject, SmsAuthenticationMessage, MfaConfiguration, DeviceConfiguration, EmailConfiguration, SmsConfiguration, UserPoolTags, AdminCreateUserConfig]]:
... | keyword[def] identifier[update_user_pool] ( identifier[UserPoolId] = keyword[None] , identifier[Policies] = keyword[None] , identifier[LambdaConfig] = keyword[None] , identifier[AutoVerifiedAttributes] = keyword[None] , identifier[SmsVerificationMessage] = keyword[None] , identifier[EmailVerificationMessage] = keywor... | def update_user_pool(UserPoolId=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfiguration=None, SmsConfiguration=None, ... |
def expand_entry(entry, ignore_xs=0x0):
"""Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and
``1``\ s.
The following will expand any Xs in bits ``1..3``\ ::
>>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100)
>>> list(expand_entry(entry, 0xfffffff1)) == [
... | def function[expand_entry, parameter[entry, ignore_xs]]:
constant[Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and
``1``\ s.
The following will expand any Xs in bits ``1..3``\ ::
>>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100)
>>> list(expand_entry(en... | keyword[def] identifier[expand_entry] ( identifier[entry] , identifier[ignore_xs] = literal[int] ):
literal[string]
identifier[xs] =(~ identifier[entry] . identifier[key] &~ identifier[entry] . identifier[mask] )&~ identifier[ignore_xs]
keyword[for] identifier[bit] keyword[in] ( literal[... | def expand_entry(entry, ignore_xs=0):
"""Turn all Xs which are not marked in `ignore_xs` into ``0``\\ s and
``1``\\ s.
The following will expand any Xs in bits ``1..3``\\ ::
>>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100)
>>> list(expand_entry(entry, 0xfffffff1)) == [
... |
def user_organization_membership_make_default(self, id, membership_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#set-membership-as-default"
api_path = "/api/v2/users/{id}/organization_memberships/{membership_id}/make_default.json"
api_path = api_... | def function[user_organization_membership_make_default, parameter[self, id, membership_id, data]]:
constant[https://developer.zendesk.com/rest_api/docs/core/organization_memberships#set-membership-as-default]
variable[api_path] assign[=] constant[/api/v2/users/{id}/organization_memberships/{membership_i... | keyword[def] identifier[user_organization_membership_make_default] ( identifier[self] , identifier[id] , identifier[membership_id] , identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[f... | def user_organization_membership_make_default(self, id, membership_id, data, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/organization_memberships#set-membership-as-default"""
api_path = '/api/v2/users/{id}/organization_memberships/{membership_id}/make_default.json'
api_path = api_path.for... |
def url_defaults(self, fn):
"""
Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place.
"""
self._defer(lambda app: app.url_defaults(fn))
return fn | def function[url_defaults, parameter[self, fn]]:
constant[
Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place.
]
call[name[self]._defer, parameter[<ast.Lambda... | keyword[def] identifier[url_defaults] ( identifier[self] , identifier[fn] ):
literal[string]
identifier[self] . identifier[_defer] ( keyword[lambda] identifier[app] : identifier[app] . identifier[url_defaults] ( identifier[fn] ))
keyword[return] identifier[fn] | def url_defaults(self, fn):
"""
Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place.
"""
self._defer(lambda app: app.url_defaults(fn))
return fn |
def _read_para_hip_transport_mode(self, code, cbit, clen, *, desc, length, version):
"""Read HIP HIP_TRANSPORT_MODE parameter.
Structure of HIP HIP_TRANSPORT_MODE parameter [RFC 6261]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 ... | def function[_read_para_hip_transport_mode, parameter[self, code, cbit, clen]]:
constant[Read HIP HIP_TRANSPORT_MODE parameter.
Structure of HIP HIP_TRANSPORT_MODE parameter [RFC 6261]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4... | keyword[def] identifier[_read_para_hip_transport_mode] ( identifier[self] , identifier[code] , identifier[cbit] , identifier[clen] ,*, identifier[desc] , identifier[length] , identifier[version] ):
literal[string]
keyword[if] identifier[clen] % literal[int] != literal[int] :
keyword[r... | def _read_para_hip_transport_mode(self, code, cbit, clen, *, desc, length, version):
"""Read HIP HIP_TRANSPORT_MODE parameter.
Structure of HIP HIP_TRANSPORT_MODE parameter [RFC 6261]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ... |
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-con... | def function[ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[ip] assign[=] call[name[ET].SubElement, parameter[name[c... | keyword[def] identifier[ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ip] = identifier[ET] . identifier[... | def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
ip = ET.SubElement(config, 'ip', xmlns='urn:brocade.com:mgmt:brocade-common-def')
rtm_config = ET.SubElement(ip, 'rtm-config', xmlns='urn... |
def equal(actual, expected):
'''
Compare actual and expected using ==
>>> expect = Expector([])
>>> expect(1).to_not(equal, 2)
(True, 'equal: expect 1 == 2')
>>> expect(1).to(equal, 1)
(True, 'equal: expect 1 == 1')
'''
is_passing = (actual == expected)
types_to_diff = (str, d... | def function[equal, parameter[actual, expected]]:
constant[
Compare actual and expected using ==
>>> expect = Expector([])
>>> expect(1).to_not(equal, 2)
(True, 'equal: expect 1 == 2')
>>> expect(1).to(equal, 1)
(True, 'equal: expect 1 == 1')
]
variable[is_passing] assign[=... | keyword[def] identifier[equal] ( identifier[actual] , identifier[expected] ):
literal[string]
identifier[is_passing] =( identifier[actual] == identifier[expected] )
identifier[types_to_diff] =( identifier[str] , identifier[dict] , identifier[list] , identifier[tuple] )
keyword[if] keyword[not] ... | def equal(actual, expected):
"""
Compare actual and expected using ==
>>> expect = Expector([])
>>> expect(1).to_not(equal, 2)
(True, 'equal: expect 1 == 2')
>>> expect(1).to(equal, 1)
(True, 'equal: expect 1 == 1')
"""
is_passing = actual == expected
types_to_diff = (str, dict... |
def gamma(arr, g):
r"""
Gamma correction is a nonlinear operation that
adjusts the image's channel values pixel-by-pixel according
to a power-law:
.. math:: pixel_{out} = pixel_{in} ^ {\gamma}
Setting gamma (:math:`\gamma`) to be less than 1.0 darkens the image and
setting gamma to be grea... | def function[gamma, parameter[arr, g]]:
constant[
Gamma correction is a nonlinear operation that
adjusts the image's channel values pixel-by-pixel according
to a power-law:
.. math:: pixel_{out} = pixel_{in} ^ {\gamma}
Setting gamma (:math:`\gamma`) to be less than 1.0 darkens the image an... | keyword[def] identifier[gamma] ( identifier[arr] , identifier[g] ):
literal[string]
keyword[if] ( identifier[arr] . identifier[max] ()> literal[int] + identifier[epsilon] ) keyword[or] ( identifier[arr] . identifier[min] ()< literal[int] - identifier[epsilon] ):
keyword[raise] identifier[ValueErr... | def gamma(arr, g):
"""
Gamma correction is a nonlinear operation that
adjusts the image's channel values pixel-by-pixel according
to a power-law:
.. math:: pixel_{out} = pixel_{in} ^ {\\gamma}
Setting gamma (:math:`\\gamma`) to be less than 1.0 darkens the image and
setting gamma to be gre... |
def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_... | def function[get_data_object, parameter[data_id, use_data_config]]:
constant[
Normalize the data_id and query the server.
If that is unavailable try the raw ID
]
variable[normalized_data_reference] assign[=] call[name[normalize_data_name], parameter[name[data_id]]]
variable[client] a... | keyword[def] identifier[get_data_object] ( identifier[data_id] , identifier[use_data_config] = keyword[True] ):
literal[string]
identifier[normalized_data_reference] = identifier[normalize_data_name] ( identifier[data_id] , identifier[use_data_config] = identifier[use_data_config] )
identifier[client]... | def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_... |
def BE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''32-bit field, Big endian encoded'''
return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | def function[BE32, parameter[value, min_value, max_value, fuzzable, name, full_range]]:
constant[32-bit field, Big endian encoded]
return[call[name[UInt32], parameter[name[value]]]] | keyword[def] identifier[BE32] ( identifier[value] , identifier[min_value] = keyword[None] , identifier[max_value] = keyword[None] , identifier[fuzzable] = keyword[True] , identifier[name] = keyword[None] , identifier[full_range] = keyword[False] ):
literal[string]
keyword[return] identifier[UInt32] ( iden... | def BE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
"""32-bit field, Big endian encoded"""
return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) |
def getMonth(s):
"""
Known formats:
Month ("%b")
Month Day ("%b %d")
Month-Month ("%b-%b") --- this gets coerced to the first %b, dropping the month range
Season ("%s") --- this gets coerced to use the first month of the given season
Month Day Year ("%b %d %Y")
Month Year ("%b %Y")
Y... | def function[getMonth, parameter[s]]:
constant[
Known formats:
Month ("%b")
Month Day ("%b %d")
Month-Month ("%b-%b") --- this gets coerced to the first %b, dropping the month range
Season ("%s") --- this gets coerced to use the first month of the given season
Month Day Year ("%b %d %Y")... | keyword[def] identifier[getMonth] ( identifier[s] ):
literal[string]
identifier[monthOrSeason] = identifier[s] . identifier[split] ( literal[string] )[ literal[int] ]. identifier[upper] ()
keyword[if] identifier[monthOrSeason] keyword[in] identifier[monthDict] :
keyword[return] identifier... | def getMonth(s):
"""
Known formats:
Month ("%b")
Month Day ("%b %d")
Month-Month ("%b-%b") --- this gets coerced to the first %b, dropping the month range
Season ("%s") --- this gets coerced to use the first month of the given season
Month Day Year ("%b %d %Y")
Month Year ("%b %Y")
Y... |
def unzip(self, directory):
"""
Write contents of zipfile to directory
"""
if not os.path.exists(directory):
os.makedirs(directory)
shutil.copytree(self.src_dir, directory) | def function[unzip, parameter[self, directory]]:
constant[
Write contents of zipfile to directory
]
if <ast.UnaryOp object at 0x7da18f720e50> begin[:]
call[name[os].makedirs, parameter[name[directory]]]
call[name[shutil].copytree, parameter[name[self].src_dir, nam... | keyword[def] identifier[unzip] ( identifier[self] , identifier[directory] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[directory] ):
identifier[os] . identifier[makedirs] ( identifier[directory] )
identifier[... | def unzip(self, directory):
"""
Write contents of zipfile to directory
"""
if not os.path.exists(directory):
os.makedirs(directory) # depends on [control=['if'], data=[]]
shutil.copytree(self.src_dir, directory) |
def render_confirm_form(self):
"""
Second step of ExpressCheckout. Display an order confirmation form which
contains hidden fields with the token / PayerID from PayPal.
"""
warn_untested()
initial = dict(token=self.request.GET['token'], PayerID=self.request.GET['PayerID']... | def function[render_confirm_form, parameter[self]]:
constant[
Second step of ExpressCheckout. Display an order confirmation form which
contains hidden fields with the token / PayerID from PayPal.
]
call[name[warn_untested], parameter[]]
variable[initial] assign[=] call[na... | keyword[def] identifier[render_confirm_form] ( identifier[self] ):
literal[string]
identifier[warn_untested] ()
identifier[initial] = identifier[dict] ( identifier[token] = identifier[self] . identifier[request] . identifier[GET] [ literal[string] ], identifier[PayerID] = identifier[self] ... | def render_confirm_form(self):
"""
Second step of ExpressCheckout. Display an order confirmation form which
contains hidden fields with the token / PayerID from PayPal.
"""
warn_untested()
initial = dict(token=self.request.GET['token'], PayerID=self.request.GET['PayerID'])
self.c... |
def item_perceel_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Perceel` to json.
"""
return {
'id': obj.id,
'sectie': {
'id': obj.sectie.id,
'afdeling': {
'id': obj.sectie.afdeling.id,
... | def function[item_perceel_adapter, parameter[obj, request]]:
constant[
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Perceel` to json.
]
return[dictionary[[<ast.Constant object at 0x7da1b0a65600>, <ast.Constant object at 0x7da1b0a65210>, <ast.Constant object at 0x7da1b0a6545... | keyword[def] identifier[item_perceel_adapter] ( identifier[obj] , identifier[request] ):
literal[string]
keyword[return] {
literal[string] : identifier[obj] . identifier[id] ,
literal[string] :{
literal[string] : identifier[obj] . identifier[sectie] . identifier[id] ,
literal[string] :{... | def item_perceel_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Perceel` to json.
"""
return {'id': obj.id, 'sectie': {'id': obj.sectie.id, 'afdeling': {'id': obj.sectie.afdeling.id, 'naam': obj.sectie.afdeling.naam, 'gemeente': {'id': obj.sectie.afdeli... |
def eeg_select_electrodes(eeg, include="all", exclude=None, hemisphere="both", central=True):
"""
Returns electrodes/sensors names of selected region (according to a 10-20 EEG montage).
Parameters
----------
eeg : mne.Raw or mne.Epochs
EEG data.
include : str ot list
Sensor area... | def function[eeg_select_electrodes, parameter[eeg, include, exclude, hemisphere, central]]:
constant[
Returns electrodes/sensors names of selected region (according to a 10-20 EEG montage).
Parameters
----------
eeg : mne.Raw or mne.Epochs
EEG data.
include : str ot list
Sen... | keyword[def] identifier[eeg_select_electrodes] ( identifier[eeg] , identifier[include] = literal[string] , identifier[exclude] = keyword[None] , identifier[hemisphere] = literal[string] , identifier[central] = keyword[True] ):
literal[string]
identifier[eeg] = identifier[eeg] . identifier[copy] (). id... | def eeg_select_electrodes(eeg, include='all', exclude=None, hemisphere='both', central=True):
"""
Returns electrodes/sensors names of selected region (according to a 10-20 EEG montage).
Parameters
----------
eeg : mne.Raw or mne.Epochs
EEG data.
include : str ot list
Sensor area... |
def setOverlayTransformOverlayRelative(self, ulOverlayHandle, ulOverlayHandleParent):
"""Sets the transform to relative to the transform of the specified overlay. This overlays visibility will also track the parents visibility"""
fn = self.function_table.setOverlayTransformOverlayRelative
pmatP... | def function[setOverlayTransformOverlayRelative, parameter[self, ulOverlayHandle, ulOverlayHandleParent]]:
constant[Sets the transform to relative to the transform of the specified overlay. This overlays visibility will also track the parents visibility]
variable[fn] assign[=] name[self].function_table.... | keyword[def] identifier[setOverlayTransformOverlayRelative] ( identifier[self] , identifier[ulOverlayHandle] , identifier[ulOverlayHandleParent] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[setOverlayTransformOverlayRelative]
identifier[p... | def setOverlayTransformOverlayRelative(self, ulOverlayHandle, ulOverlayHandleParent):
"""Sets the transform to relative to the transform of the specified overlay. This overlays visibility will also track the parents visibility"""
fn = self.function_table.setOverlayTransformOverlayRelative
pmatParentOverlayT... |
def next_page(self):
"""Return the next `Page` after this one in the result sequence
it's from.
If the current page is the last page in the sequence, calling
this method raises a `ValueError`.
"""
try:
next_url = self.next_url
except AttributeError:
... | def function[next_page, parameter[self]]:
constant[Return the next `Page` after this one in the result sequence
it's from.
If the current page is the last page in the sequence, calling
this method raises a `ValueError`.
]
<ast.Try object at 0x7da1b0395cf0>
return[call[n... | keyword[def] identifier[next_page] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[next_url] = identifier[self] . identifier[next_url]
keyword[except] identifier[AttributeError] :
keyword[raise] identifier[PageError] ( literal[string] % identifi... | def next_page(self):
"""Return the next `Page` after this one in the result sequence
it's from.
If the current page is the last page in the sequence, calling
this method raises a `ValueError`.
"""
try:
next_url = self.next_url # depends on [control=['try'], data=[]]
... |
def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
"""
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translat... | def function[_save_translations, parameter[sender, instance]]:
constant[
This signal saves model translations.
]
if call[name[site_is_monolingual], parameter[]] begin[:]
return[constant[False]]
variable[cls] assign[=] name[sender]
if <ast.UnaryOp object at 0x7da18dc99870> begin... | keyword[def] identifier[_save_translations] ( identifier[sender] , identifier[instance] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[site_is_monolingual] ():
keyword[return] keyword[False]
identifier[cls] = identifier[sender]
keyword[if] keyword[not] id... | def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
""" # If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False # depends on [control=['if'], data=[]]
cls = sender # If its class has ... |
def plotExampleInputOutput(sp, inputVectors, saveFigPrefix=None):
"""
Plot example input & output
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors
"""
numInputVector, inputSize = inputVectors.shape
numColumns = np.prod(sp.getColumnDimensions())
outputColumns = np.zeros(... | def function[plotExampleInputOutput, parameter[sp, inputVectors, saveFigPrefix]]:
constant[
Plot example input & output
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors
]
<ast.Tuple object at 0x7da1b0860c10> assign[=] name[inputVectors].shape
variable[num... | keyword[def] identifier[plotExampleInputOutput] ( identifier[sp] , identifier[inputVectors] , identifier[saveFigPrefix] = keyword[None] ):
literal[string]
identifier[numInputVector] , identifier[inputSize] = identifier[inputVectors] . identifier[shape]
identifier[numColumns] = identifier[np] . identifier[p... | def plotExampleInputOutput(sp, inputVectors, saveFigPrefix=None):
"""
Plot example input & output
@param sp: an spatial pooler instance
@param inputVectors: a set of input vectors
"""
(numInputVector, inputSize) = inputVectors.shape
numColumns = np.prod(sp.getColumnDimensions())
outputColumns = ... |
def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
# (value is True or value is False) is ~5x faster than isinstance(value, bool)
if value is True or value is False:
raise TypeError('value must be a Number, not a boolean.')
r... | def function[_format_num, parameter[self, value]]:
constant[Return the number value for value, given this field's `num_type`.]
if <ast.BoolOp object at 0x7da18dc047f0> begin[:]
<ast.Raise object at 0x7da18dc046a0>
return[call[name[self].num_type, parameter[name[value]]]] | keyword[def] identifier[_format_num] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[True] keyword[or] identifier[value] keyword[is] keyword[False] :
keyword[raise] identifier[TypeError] ( literal[string] )
... | def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
# (value is True or value is False) is ~5x faster than isinstance(value, bool)
if value is True or value is False:
raise TypeError('value must be a Number, not a boolean.') # depends on [control=['... |
def getNym(self, nym, role=None, isCommitted=True):
"""
Get a nym, if role is provided then get nym with that role
:param nym:
:param role:
:param isCommitted:
:return:
"""
try:
seqNo, txnTime, ta, actual_role, verkey = self.get(nym, isCommitte... | def function[getNym, parameter[self, nym, role, isCommitted]]:
constant[
Get a nym, if role is provided then get nym with that role
:param nym:
:param role:
:param isCommitted:
:return:
]
<ast.Try object at 0x7da2054a4970>
if <ast.BoolOp object at 0x7d... | keyword[def] identifier[getNym] ( identifier[self] , identifier[nym] , identifier[role] = keyword[None] , identifier[isCommitted] = keyword[True] ):
literal[string]
keyword[try] :
identifier[seqNo] , identifier[txnTime] , identifier[ta] , identifier[actual_role] , identifier[verkey] = ... | def getNym(self, nym, role=None, isCommitted=True):
"""
Get a nym, if role is provided then get nym with that role
:param nym:
:param role:
:param isCommitted:
:return:
"""
try:
(seqNo, txnTime, ta, actual_role, verkey) = self.get(nym, isCommitted) # depe... |
def _poll(self):
"""
Poll Trusted Advisor (Support) API for limit checks.
Return a dict of service name (string) keys to nested dict vals, where
each key is a limit name and each value the current numeric limit.
e.g.:
::
{
'EC2': {
... | def function[_poll, parameter[self]]:
constant[
Poll Trusted Advisor (Support) API for limit checks.
Return a dict of service name (string) keys to nested dict vals, where
each key is a limit name and each value the current numeric limit.
e.g.:
::
{
... | keyword[def] identifier[_poll] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[tmp] = identifier[self] . identifier[_get_limit_check_id] ()
keyword[if] keyword[not] identifier[self] . identifier[have_ta] :
i... | def _poll(self):
"""
Poll Trusted Advisor (Support) API for limit checks.
Return a dict of service name (string) keys to nested dict vals, where
each key is a limit name and each value the current numeric limit.
e.g.:
::
{
'EC2': {
... |
def RgbToPil(r, g, b):
'''Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>... | def function[RgbToPil, parameter[r, g, b]]:
constant[Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compati... | keyword[def] identifier[RgbToPil] ( identifier[r] , identifier[g] , identifier[b] ):
literal[string]
identifier[r] , identifier[g] , identifier[b] =[ identifier[min] ( identifier[int] ( identifier[round] ( identifier[v] * literal[int] )), literal[int] ) keyword[for] identifier[v] keyword[in] ( identifier... | def RgbToPil(r, g, b):
"""Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>... |
def _block_shape(values, ndim=1, shape=None):
""" guarantee the shape of the values to be at least 1 d """
if values.ndim < ndim:
if shape is None:
shape = values.shape
if not is_extension_array_dtype(values):
# TODO: https://github.com/pandas-dev/pandas/issues/23023
... | def function[_block_shape, parameter[values, ndim, shape]]:
constant[ guarantee the shape of the values to be at least 1 d ]
if compare[name[values].ndim less[<] name[ndim]] begin[:]
if compare[name[shape] is constant[None]] begin[:]
variable[shape] assign[=] name... | keyword[def] identifier[_block_shape] ( identifier[values] , identifier[ndim] = literal[int] , identifier[shape] = keyword[None] ):
literal[string]
keyword[if] identifier[values] . identifier[ndim] < identifier[ndim] :
keyword[if] identifier[shape] keyword[is] keyword[None] :
iden... | def _block_shape(values, ndim=1, shape=None):
""" guarantee the shape of the values to be at least 1 d """
if values.ndim < ndim:
if shape is None:
shape = values.shape # depends on [control=['if'], data=['shape']]
if not is_extension_array_dtype(values):
# TODO: https:/... |
def get_email_content(file_path):
"""Email content in file
:param file_path: Path to file with email text
:return: Email text (html formatted)
"""
with open(file_path, "r") as in_file:
text = str(in_file.read())
return text.replace("\n\n", "<br>") | def function[get_email_content, parameter[file_path]]:
constant[Email content in file
:param file_path: Path to file with email text
:return: Email text (html formatted)
]
with call[name[open], parameter[name[file_path], constant[r]]] begin[:]
variable[text] assign[=] call[n... | keyword[def] identifier[get_email_content] ( identifier[file_path] ):
literal[string]
keyword[with] identifier[open] ( identifier[file_path] , literal[string] ) keyword[as] identifier[in_file] :
identifier[text] = identifier[str] ( identifier[in_file] . identifier[read] ())
keyword[retu... | def get_email_content(file_path):
"""Email content in file
:param file_path: Path to file with email text
:return: Email text (html formatted)
"""
with open(file_path, 'r') as in_file:
text = str(in_file.read())
return text.replace('\n\n', '<br>') # depends on [control=['with'], da... |
def load_commands(self, namespace):
"""Load all the commands from an entrypoint"""
for ep in pkg_resources.iter_entry_points(namespace):
LOG.debug('found command %r', ep.name)
cmd_name = (ep.name.replace('_', ' ')
if self.convert_underscores
... | def function[load_commands, parameter[self, namespace]]:
constant[Load all the commands from an entrypoint]
for taget[name[ep]] in starred[call[name[pkg_resources].iter_entry_points, parameter[name[namespace]]]] begin[:]
call[name[LOG].debug, parameter[constant[found command %r], name[ep... | keyword[def] identifier[load_commands] ( identifier[self] , identifier[namespace] ):
literal[string]
keyword[for] identifier[ep] keyword[in] identifier[pkg_resources] . identifier[iter_entry_points] ( identifier[namespace] ):
identifier[LOG] . identifier[debug] ( literal[string] , i... | def load_commands(self, namespace):
"""Load all the commands from an entrypoint"""
for ep in pkg_resources.iter_entry_points(namespace):
LOG.debug('found command %r', ep.name)
cmd_name = ep.name.replace('_', ' ') if self.convert_underscores else ep.name
self.commands[cmd_name] = ep # de... |
def monitor(self):
"""
Access the Monitor Twilio Domain
:returns: Monitor Twilio Domain
:rtype: twilio.rest.monitor.Monitor
"""
if self._monitor is None:
from twilio.rest.monitor import Monitor
self._monitor = Monitor(self)
return self._mo... | def function[monitor, parameter[self]]:
constant[
Access the Monitor Twilio Domain
:returns: Monitor Twilio Domain
:rtype: twilio.rest.monitor.Monitor
]
if compare[name[self]._monitor is constant[None]] begin[:]
from relative_module[twilio.rest.monitor] import mo... | keyword[def] identifier[monitor] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_monitor] keyword[is] keyword[None] :
keyword[from] identifier[twilio] . identifier[rest] . identifier[monitor] keyword[import] identifier[Monitor]
ident... | def monitor(self):
"""
Access the Monitor Twilio Domain
:returns: Monitor Twilio Domain
:rtype: twilio.rest.monitor.Monitor
"""
if self._monitor is None:
from twilio.rest.monitor import Monitor
self._monitor = Monitor(self) # depends on [control=['if'], data=[]]... |
def enforce_type(cls, jobject, intf_or_class):
"""
Raises an exception if the object does not implement the specified interface or is not a subclass.
:param jobject: the Java object to check
:type jobject: JB_Object
:param intf_or_class: the classname in Java notation (eg "weka... | def function[enforce_type, parameter[cls, jobject, intf_or_class]]:
constant[
Raises an exception if the object does not implement the specified interface or is not a subclass.
:param jobject: the Java object to check
:type jobject: JB_Object
:param intf_or_class: the classname... | keyword[def] identifier[enforce_type] ( identifier[cls] , identifier[jobject] , identifier[intf_or_class] ):
literal[string]
keyword[if] keyword[not] identifier[cls] . identifier[check_type] ( identifier[jobject] , identifier[intf_or_class] ):
keyword[raise] identifier[TypeError] ( ... | def enforce_type(cls, jobject, intf_or_class):
"""
Raises an exception if the object does not implement the specified interface or is not a subclass.
:param jobject: the Java object to check
:type jobject: JB_Object
:param intf_or_class: the classname in Java notation (eg "weka.cor... |
def psetex(self, key, milliseconds, value):
""":meth:`~tredis.RedisClient.psetex` works exactly like
:meth:`~tredis.RedisClient.psetex` with the sole difference that the
expire time is specified in milliseconds instead of seconds.
.. versionadded:: 0.2.0
.. note:: **Time comple... | def function[psetex, parameter[self, key, milliseconds, value]]:
constant[:meth:`~tredis.RedisClient.psetex` works exactly like
:meth:`~tredis.RedisClient.psetex` with the sole difference that the
expire time is specified in milliseconds instead of seconds.
.. versionadded:: 0.2.0
... | keyword[def] identifier[psetex] ( identifier[self] , identifier[key] , identifier[milliseconds] , identifier[value] ):
literal[string]
keyword[return] identifier[self] . identifier[_execute] (
[ literal[string] , identifier[key] , identifier[ascii] ( identifier[milliseconds] ), identifier[... | def psetex(self, key, milliseconds, value):
""":meth:`~tredis.RedisClient.psetex` works exactly like
:meth:`~tredis.RedisClient.psetex` with the sole difference that the
expire time is specified in milliseconds instead of seconds.
.. versionadded:: 0.2.0
.. note:: **Time complexity... |
def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/p... | def function[_parse_q2r, parameter[self, f]]:
constant[Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
... | keyword[def] identifier[_parse_q2r] ( identifier[self] , identifier[f] ):
literal[string]
identifier[natom] , identifier[dim] , identifier[epsilon] , identifier[borns] = identifier[self] . identifier[_parse_parameters] ( identifier[f] )
identifier[fc_dct] ={ literal[string] : identifier[s... | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/piper... |
def hessian(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: hessian function object
"""
def hessian_f(*args, **kwargs):
if len(args) == 1:
... | def function[hessian, parameter[f, delta]]:
constant[
Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: hessian function object
]
def function[hessian_f, parameter[]]:
... | keyword[def] identifier[hessian] ( identifier[f] , identifier[delta] = identifier[DELTA] ):
literal[string]
keyword[def] identifier[hessian_f] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
identifier[x] ,= identifier[... | def hessian(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: hessian function object
"""
def hessian_f(*args, **kwargs):
if len(args) == 1:
... |
def _set_interface_hello_interval(self, v, load=False):
"""
Setter method for interface_hello_interval, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello_interval (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfa... | def function[_set_interface_hello_interval, parameter[self, v, load]]:
constant[
Setter method for interface_hello_interval, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello_interval (list)
If this variable is read-only (config: false) in the
source YAN... | keyword[def] identifier[_set_interface_hello_interval] ( 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_interface_hello_interval(self, v, load=False):
"""
Setter method for interface_hello_interval, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello_interval (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfa... |
def resolve_dns(opts, fallback=True):
'''
Resolves the master_ip and master_uri options
'''
ret = {}
check_dns = True
if (opts.get('file_client', 'remote') == 'local' and
not opts.get('use_master_when_local', False)):
check_dns = False
# Since salt.log is imported below, ... | def function[resolve_dns, parameter[opts, fallback]]:
constant[
Resolves the master_ip and master_uri options
]
variable[ret] assign[=] dictionary[[], []]
variable[check_dns] assign[=] constant[True]
if <ast.BoolOp object at 0x7da1b1f94a30> begin[:]
variable[check... | keyword[def] identifier[resolve_dns] ( identifier[opts] , identifier[fallback] = keyword[True] ):
literal[string]
identifier[ret] ={}
identifier[check_dns] = keyword[True]
keyword[if] ( identifier[opts] . identifier[get] ( literal[string] , literal[string] )== literal[string] keyword[and]
... | def resolve_dns(opts, fallback=True):
"""
Resolves the master_ip and master_uri options
"""
ret = {}
check_dns = True
if opts.get('file_client', 'remote') == 'local' and (not opts.get('use_master_when_local', False)):
check_dns = False # depends on [control=['if'], data=[]]
# Since ... |
def build_attachment1():
"""Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content.
Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md"""
attachment = Attachment()
attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3I... | def function[build_attachment1, parameter[]]:
constant[Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content.
Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md]
variable[attachment] assign[=] call[name[At... | keyword[def] identifier[build_attachment1] ():
literal[string]
identifier[attachment] = identifier[Attachment] ()
identifier[attachment] . identifier[content] =( literal[string]
literal[string] )
identifier[attachment] . identifier[type] = literal[string]
identifier[attachment] . iden... | def build_attachment1():
"""Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content.
Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md"""
attachment = Attachment()
attachment.content = 'TG9yZW0gaXBzdW0gZG9sb3Ig... |
def set_mask(self, mask_img):
"""Sets a mask img to this. So every operation to self, this mask will be taken into account.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
Can either be:
... | def function[set_mask, parameter[self, mask_img]]:
constant[Sets a mask img to this. So every operation to self, this mask will be taken into account.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
... | keyword[def] identifier[set_mask] ( identifier[self] , identifier[mask_img] ):
literal[string]
identifier[mask] = identifier[load_mask] ( identifier[mask_img] , identifier[allow_empty] = keyword[True] )
identifier[check_img_compatibility] ( identifier[self] . identifier[img] , identifier[m... | def set_mask(self, mask_img):
"""Sets a mask img to this. So every operation to self, this mask will be taken into account.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
Can either be:
... |
def destroy(self):
""" A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
"""
widget = self.widget
if widget is not None:
parent = self.parent_widget()
if parent is not None:
... | def function[destroy, parameter[self]]:
constant[ A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
]
variable[widget] assign[=] name[self].widget
if compare[name[widget] is_not constant[None]] begin[:... | keyword[def] identifier[destroy] ( identifier[self] ):
literal[string]
identifier[widget] = identifier[self] . identifier[widget]
keyword[if] identifier[widget] keyword[is] keyword[not] keyword[None] :
identifier[parent] = identifier[self] . identifier[parent_widget] ()
... | def destroy(self):
""" A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
"""
widget = self.widget
if widget is not None:
parent = self.parent_widget()
if parent is not None:
parent.remo... |
def _get_capirca_platform(): # pylint: disable=too-many-return-statements
'''
Given the following NAPALM grains, we can determine the Capirca platform name:
- vendor
- device model
- operating system
Not the most optimal.
'''
vendor = __grains__['vendor'].lower()
os_ = __grains__[... | def function[_get_capirca_platform, parameter[]]:
constant[
Given the following NAPALM grains, we can determine the Capirca platform name:
- vendor
- device model
- operating system
Not the most optimal.
]
variable[vendor] assign[=] call[call[name[__grains__]][constant[vendor]]... | keyword[def] identifier[_get_capirca_platform] ():
literal[string]
identifier[vendor] = identifier[__grains__] [ literal[string] ]. identifier[lower] ()
identifier[os_] = identifier[__grains__] [ literal[string] ]. identifier[lower] ()
identifier[model] = identifier[__grains__] [ literal[string] ... | def _get_capirca_platform(): # pylint: disable=too-many-return-statements
'\n Given the following NAPALM grains, we can determine the Capirca platform name:\n\n - vendor\n - device model\n - operating system\n\n Not the most optimal.\n '
vendor = __grains__['vendor'].lower()
os_ = __grain... |
def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
... | def function[porthistory, parameter[port_number, start_date, end_date, return_format]]:
constant[Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique or... | keyword[def] identifier[porthistory] ( identifier[port_number] , identifier[start_date] = keyword[None] , identifier[end_date] = keyword[None] , identifier[return_format] = keyword[None] ):
literal[string]
identifier[uri] = literal[string] . identifier[format] ( identifier[port] = identifier[port_number] )... | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.