code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def update(self):
"""Calculate the smoothing parameter value.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> highestremotedischarge(1.0)
>>> highestremotetolerance(0.0)
... | def function[update, parameter[self]]:
constant[Calculate the smoothing parameter value.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> highestremotedischarge(1.0)
>>> highest... | keyword[def] identifier[update] ( identifier[self] ):
literal[string]
identifier[control] = identifier[self] . identifier[subpars] . identifier[pars] . identifier[control]
keyword[if] identifier[numpy] . identifier[isinf] ( identifier[control] . identifier[highestremotedischarge] ):
... | def update(self):
"""Calculate the smoothing parameter value.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> highestremotedischarge(1.0)
>>> highestremotetolerance(0.0)
>>... |
def niftilist_mask_to_array(img_filelist, mask_file=None, outdtype=None):
"""From the list of absolute paths to nifti files, creates a Numpy array
with the masked data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti files must have
... | def function[niftilist_mask_to_array, parameter[img_filelist, mask_file, outdtype]]:
constant[From the list of absolute paths to nifti files, creates a Numpy array
with the masked data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti... | keyword[def] identifier[niftilist_mask_to_array] ( identifier[img_filelist] , identifier[mask_file] = keyword[None] , identifier[outdtype] = keyword[None] ):
literal[string]
identifier[img] = identifier[check_img] ( identifier[img_filelist] [ literal[int] ])
keyword[if] keyword[not] identifier[outdt... | def niftilist_mask_to_array(img_filelist, mask_file=None, outdtype=None):
"""From the list of absolute paths to nifti files, creates a Numpy array
with the masked data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti files must have
... |
def status(zpool=None):
'''
Return the status of the named zpool
zpool : string
optional name of storage pool
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' zpool.status myzpool
'''
ret = OrderedDict()
## collect status output
res = _... | def function[status, parameter[zpool]]:
constant[
Return the status of the named zpool
zpool : string
optional name of storage pool
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' zpool.status myzpool
]
variable[ret] assign[=] call[name... | keyword[def] identifier[status] ( identifier[zpool] = keyword[None] ):
literal[string]
identifier[ret] = identifier[OrderedDict] ()
identifier[res] = identifier[__salt__] [ literal[string] ](
identifier[__utils__] [ literal[string] ]( literal[string] , identifier[target] = identifier[zpool]... | def status(zpool=None):
"""
Return the status of the named zpool
zpool : string
optional name of storage pool
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' zpool.status myzpool
"""
ret = OrderedDict()
## collect status output
res = __... |
def _return_value(content, ns):
"""Find the return value in a CIM response.
The xmlns is needed because everything in CIM is a million levels
of namespace indirection.
"""
doc = ElementTree.fromstring(content)
query = './/{%(ns)s}%(item)s' % {'ns': ns, 'item': 'ReturnValue'}
rv = doc.find(q... | def function[_return_value, parameter[content, ns]]:
constant[Find the return value in a CIM response.
The xmlns is needed because everything in CIM is a million levels
of namespace indirection.
]
variable[doc] assign[=] call[name[ElementTree].fromstring, parameter[name[content]]]
v... | keyword[def] identifier[_return_value] ( identifier[content] , identifier[ns] ):
literal[string]
identifier[doc] = identifier[ElementTree] . identifier[fromstring] ( identifier[content] )
identifier[query] = literal[string] %{ literal[string] : identifier[ns] , literal[string] : literal[string] }
... | def _return_value(content, ns):
"""Find the return value in a CIM response.
The xmlns is needed because everything in CIM is a million levels
of namespace indirection.
"""
doc = ElementTree.fromstring(content)
query = './/{%(ns)s}%(item)s' % {'ns': ns, 'item': 'ReturnValue'}
rv = doc.find(q... |
def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function
name.
Valid function names are 'sum', 'average', 'min', and 'max'.
When a graph is drawn where width of the graph size in pixels is smaller
than the numb... | def function[consolidateBy, parameter[requestContext, seriesList, consolidationFunc]]:
constant[
Takes one metric or a wildcard seriesList and a consolidation function
name.
Valid function names are 'sum', 'average', 'min', and 'max'.
When a graph is drawn where width of the graph size in pixe... | keyword[def] identifier[consolidateBy] ( identifier[requestContext] , identifier[seriesList] , identifier[consolidationFunc] ):
literal[string]
keyword[for] identifier[series] keyword[in] identifier[seriesList] :
identifier[series] . identifier[consolidationFunc] = identifier[consolid... | def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function
name.
Valid function names are 'sum', 'average', 'min', and 'max'.
When a graph is drawn where width of the graph size in pixels is smaller
than the numb... |
def check_program(name):
"""
Uses the shell program "which" to determine whether the named program
is available on the shell PATH.
"""
with open(os.devnull, "w") as null:
try:
subprocess.check_call(("which", name), stdout=null, stderr=null)
except subprocess.CalledPr... | def function[check_program, parameter[name]]:
constant[
Uses the shell program "which" to determine whether the named program
is available on the shell PATH.
]
with call[name[open], parameter[name[os].devnull, constant[w]]] begin[:]
<ast.Try object at 0x7da1b14da2c0>
return[... | keyword[def] identifier[check_program] ( identifier[name] ):
literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[devnull] , literal[string] ) keyword[as] identifier[null] :
keyword[try] :
identifier[subprocess] . identifier[check_call] (( literal[string] , i... | def check_program(name):
"""
Uses the shell program "which" to determine whether the named program
is available on the shell PATH.
"""
with open(os.devnull, 'w') as null:
try:
subprocess.check_call(('which', name), stdout=null, stderr=null) # depends on [control=['try'], da... |
def wd_addr(self):
"""
Gets the interface and direction as a `WINDIVERT_ADDRESS` structure.
:return: The `WINDIVERT_ADDRESS` structure.
"""
address = windivert_dll.WinDivertAddress()
address.IfIdx, address.SubIfIdx = self.interface
address.Direction = self.directi... | def function[wd_addr, parameter[self]]:
constant[
Gets the interface and direction as a `WINDIVERT_ADDRESS` structure.
:return: The `WINDIVERT_ADDRESS` structure.
]
variable[address] assign[=] call[name[windivert_dll].WinDivertAddress, parameter[]]
<ast.Tuple object at 0x... | keyword[def] identifier[wd_addr] ( identifier[self] ):
literal[string]
identifier[address] = identifier[windivert_dll] . identifier[WinDivertAddress] ()
identifier[address] . identifier[IfIdx] , identifier[address] . identifier[SubIfIdx] = identifier[self] . identifier[interface]
... | def wd_addr(self):
"""
Gets the interface and direction as a `WINDIVERT_ADDRESS` structure.
:return: The `WINDIVERT_ADDRESS` structure.
"""
address = windivert_dll.WinDivertAddress()
(address.IfIdx, address.SubIfIdx) = self.interface
address.Direction = self.direction
return ... |
def _create_models_for_relation_step(self, rel_model_name,
rel_key, rel_value, model):
"""
Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
... | def function[_create_models_for_relation_step, parameter[self, rel_model_name, rel_key, rel_value, model]]:
constant[
Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
An... | keyword[def] identifier[_create_models_for_relation_step] ( identifier[self] , identifier[rel_model_name] ,
identifier[rel_key] , identifier[rel_value] , identifier[model] ):
literal[string]
identifier[model] = identifier[get_model] ( identifier[model] )
identifier[lookup] ={ identifier[rel_key] : i... | def _create_models_for_relation_step(self, rel_model_name, rel_key, rel_value, model):
"""
Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
And project with name "Ball Proje... |
def download_icon_font(icon_font, directory):
"""Download given (implemented) icon font into passed directory"""
try:
downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory)
downloader.download_files()
return downloader
except KeyError: # pragma: no cover
raise... | def function[download_icon_font, parameter[icon_font, directory]]:
constant[Download given (implemented) icon font into passed directory]
<ast.Try object at 0x7da18f720640> | keyword[def] identifier[download_icon_font] ( identifier[icon_font] , identifier[directory] ):
literal[string]
keyword[try] :
identifier[downloader] = identifier[AVAILABLE_ICON_FONTS] [ identifier[icon_font] ][ literal[string] ]( identifier[directory] )
identifier[downloader] . identifier... | def download_icon_font(icon_font, directory):
"""Download given (implemented) icon font into passed directory"""
try:
downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory)
downloader.download_files()
return downloader # depends on [control=['try'], data=[]]
except Ke... |
def check_matching_coordinates(func):
"""Decorate a function to make sure all given DataArrays have matching coordinates."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
data_arrays = ([a for a in args if isinstance(a, xr.DataArray)]
+ [a for a in kwargs.values() if is... | def function[check_matching_coordinates, parameter[func]]:
constant[Decorate a function to make sure all given DataArrays have matching coordinates.]
def function[wrapper, parameter[]]:
variable[data_arrays] assign[=] binary_operation[<ast.ListComp object at 0x7da1b22968c0> + <ast.ListCo... | keyword[def] identifier[check_matching_coordinates] ( identifier[func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[data_arrays] =([ identifier[a] keyword[for] id... | def check_matching_coordinates(func):
"""Decorate a function to make sure all given DataArrays have matching coordinates."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
data_arrays = [a for a in args if isinstance(a, xr.DataArray)] + [a for a in kwargs.values() if isinstance(a, xr.DataArra... |
def _match_modes(self, remote_path, l_st):
"""Match mod, utime and uid/gid with locals one."""
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gi... | def function[_match_modes, parameter[self, remote_path, l_st]]:
constant[Match mod, utime and uid/gid with locals one.]
call[name[self].sftp.chmod, parameter[name[remote_path], call[name[S_IMODE], parameter[name[l_st].st_mode]]]]
call[name[self].sftp.utime, parameter[name[remote_path], tuple[[<a... | keyword[def] identifier[_match_modes] ( identifier[self] , identifier[remote_path] , identifier[l_st] ):
literal[string]
identifier[self] . identifier[sftp] . identifier[chmod] ( identifier[remote_path] , identifier[S_IMODE] ( identifier[l_st] . identifier[st_mode] ))
identifier[self] . id... | def _match_modes(self, remote_path, l_st):
"""Match mod, utime and uid/gid with locals one."""
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gid) # depends on [con... |
def write_stats (self):
"""Write check statistic info."""
self.writeln()
self.writeln(_("Statistics:"))
if self.stats.downloaded_bytes is not None:
self.writeln(_("Downloaded: %s.") % strformat.strsize(self.stats.downloaded_bytes))
if self.stats.number > 0:
... | def function[write_stats, parameter[self]]:
constant[Write check statistic info.]
call[name[self].writeln, parameter[]]
call[name[self].writeln, parameter[call[name[_], parameter[constant[Statistics:]]]]]
if compare[name[self].stats.downloaded_bytes is_not constant[None]] begin[:]
... | keyword[def] identifier[write_stats] ( identifier[self] ):
literal[string]
identifier[self] . identifier[writeln] ()
identifier[self] . identifier[writeln] ( identifier[_] ( literal[string] ))
keyword[if] identifier[self] . identifier[stats] . identifier[downloaded_bytes] keywor... | def write_stats(self):
"""Write check statistic info."""
self.writeln()
self.writeln(_('Statistics:'))
if self.stats.downloaded_bytes is not None:
self.writeln(_('Downloaded: %s.') % strformat.strsize(self.stats.downloaded_bytes)) # depends on [control=['if'], data=[]]
if self.stats.number ... |
def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | def function[render_config, parameter[config, indent]]:
constant[
Pretty-print a config in sort-of-JSON+comments.
]
variable[new_indent] assign[=] binary_operation[name[indent] + constant[ ]]
return[call[constant[].join, parameter[list[[<ast.Constant object at 0x7da204347ee0>, <ast.IfExp ... | keyword[def] identifier[render_config] ( identifier[config] : identifier[Config] , identifier[indent] : identifier[str] = literal[string] )-> identifier[str] :
literal[string]
identifier[new_indent] = identifier[indent] + literal[string]
keyword[return] literal[string] . identifier[join] ([
... | def render_config(config: Config, indent: str='') -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + ' '
# opening brace + newline
# "type": "...", (if present)
# render each item
# indent and close the brace
... |
def extract_subsection(im, shape):
r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to e... | def function[extract_subsection, parameter[im, shape]]:
constant[
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
... | keyword[def] identifier[extract_subsection] ( identifier[im] , identifier[shape] ):
literal[string]
identifier[shape] = identifier[sp] . identifier[array] ( identifier[shape] )
keyword[if] identifier[shape] [ literal[int] ]< literal[int] :
identifier[shape] = identifier[sp] . identifier... | def extract_subsection(im, shape):
"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to ex... |
def team_2_json(self):
"""
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Team.team_2_json")
json_obj = {
'teamID': self.id,
'teamName': self.name,
'teamDescription': self.descrip... | def function[team_2_json, parameter[self]]:
constant[
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
]
call[name[LOGGER].debug, parameter[constant[Team.team_2_json]]]
variable[json_obj] assign[=] dictionary[[<ast.Constant object at 0... | keyword[def] identifier[team_2_json] ( identifier[self] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[json_obj] ={
literal[string] : identifier[self] . identifier[id] ,
literal[string] : identifier[self] . identifier[name] ,
... | def team_2_json(self):
"""
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug('Team.team_2_json')
json_obj = {'teamID': self.id, 'teamName': self.name, 'teamDescription': self.description, 'teamColorCode': self.color_code, 'teamOSIn... |
def getPassage(self, urn, inventory=None, context=None):
""" Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at th... | def function[getPassage, parameter[self, urn, inventory, context]]:
constant[ Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of cit... | keyword[def] identifier[getPassage] ( identifier[self] , identifier[urn] , identifier[inventory] = keyword[None] , identifier[context] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[call] ({
literal[string] : identifier[inventory] ,
literal[strin... | def getPassage(self, urn, inventory=None, context=None):
""" Retrieve a passage
:param urn: URN identifying the text's passage (Minimum depth : 1)
:type urn: text
:param inventory: Name of the inventory
:type inventory: text
:param context: Number of citation units at the sa... |
def get_nsx_controller(self):
"""
Get/Set nsx controller name
Args:
name: (str) : Name of the nsx-controller
callback (function): A function executed upon completion of the
method.
Returns: Return dictionary containing nsx-controller inform... | def function[get_nsx_controller, parameter[self]]:
constant[
Get/Set nsx controller name
Args:
name: (str) : Name of the nsx-controller
callback (function): A function executed upon completion of the
method.
Returns: Return dictionary conta... | keyword[def] identifier[get_nsx_controller] ( identifier[self] ):
literal[string]
identifier[urn] = literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , ident... | def get_nsx_controller(self):
"""
Get/Set nsx controller name
Args:
name: (str) : Name of the nsx-controller
callback (function): A function executed upon completion of the
method.
Returns: Return dictionary containing nsx-controller informatio... |
def _determine_datatype(fields):
"""Determine the numpy dtype of the data."""
# Convert the NRRD type string identifier into a NumPy string identifier using a map
np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']]
# This is only added if the datatype has more than one byte and is not using ASCII enco... | def function[_determine_datatype, parameter[fields]]:
constant[Determine the numpy dtype of the data.]
variable[np_typestring] assign[=] call[name[_TYPEMAP_NRRD2NUMPY]][call[name[fields]][constant[type]]]
if <ast.BoolOp object at 0x7da18dc99060> begin[:]
if compare[constant[endia... | keyword[def] identifier[_determine_datatype] ( identifier[fields] ):
literal[string]
identifier[np_typestring] = identifier[_TYPEMAP_NRRD2NUMPY] [ identifier[fields] [ literal[string] ]]
keyword[if] identifier[np] . identifier[dtype] ( identifier[np_typestring] ). identifier[itemsize... | def _determine_datatype(fields):
"""Determine the numpy dtype of the data."""
# Convert the NRRD type string identifier into a NumPy string identifier using a map
np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']]
# This is only added if the datatype has more than one byte and is not using ASCII encodi... |
def parse_region(self, include, region_type, region_end, line):
"""
Extract a Shape from a region string
"""
if self.coordsys is None:
raise DS9RegionParserError("No coordinate system specified and a"
" region has been found.")
e... | def function[parse_region, parameter[self, include, region_type, region_end, line]]:
constant[
Extract a Shape from a region string
]
if compare[name[self].coordsys is constant[None]] begin[:]
<ast.Raise object at 0x7da18dc05ab0> | keyword[def] identifier[parse_region] ( identifier[self] , identifier[include] , identifier[region_type] , identifier[region_end] , identifier[line] ):
literal[string]
keyword[if] identifier[self] . identifier[coordsys] keyword[is] keyword[None] :
keyword[raise] identifier[DS9Regio... | def parse_region(self, include, region_type, region_end, line):
"""
Extract a Shape from a region string
"""
if self.coordsys is None:
raise DS9RegionParserError('No coordinate system specified and a region has been found.') # depends on [control=['if'], data=[]]
else:
helpe... |
def create_schema(self, check_if_exists=False, sync_schema=True,
verbosity=1):
"""
Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise.
"... | def function[create_schema, parameter[self, check_if_exists, sync_schema, verbosity]]:
constant[
Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise.
]
... | keyword[def] identifier[create_schema] ( identifier[self] , identifier[check_if_exists] = keyword[False] , identifier[sync_schema] = keyword[True] ,
identifier[verbosity] = literal[int] ):
literal[string]
identifier[_check_schema_name] ( identifier[self] . identifier[schema_name] )
... | def create_schema(self, check_if_exists=False, sync_schema=True, verbosity=1):
"""
Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise.
"""
# safety check
... |
def start_monitoring(seconds_frozen=SECONDS_FROZEN,
test_interval=TEST_INTERVAL):
"""Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in millisec... | def function[start_monitoring, parameter[seconds_frozen, test_interval]]:
constant[Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in milliseconds)
- defaul... | keyword[def] identifier[start_monitoring] ( identifier[seconds_frozen] = identifier[SECONDS_FROZEN] ,
identifier[test_interval] = identifier[TEST_INTERVAL] ):
literal[string]
identifier[thread] = identifier[StoppableThread] ( identifier[target] = identifier[monitor] , identifier[args] =( identifier[secon... | def start_monitoring(seconds_frozen=SECONDS_FROZEN, test_interval=TEST_INTERVAL):
"""Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in milliseconds)
- default(... |
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
"""Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``."""
csvwriter = csv.writer(fileobj, dialect=dialect)
csv_writerows(csvwriter, rows, encoding) | def function[write_csv, parameter[fileobj, rows, encoding, dialect]]:
constant[Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.]
variable[csvwriter] assign[=] call[name[csv].writer, parameter[name[fileobj]]]
call[name[csv_writerows], parameter[name[csvwriter], name[rows]... | keyword[def] identifier[write_csv] ( identifier[fileobj] , identifier[rows] , identifier[encoding] = identifier[ENCODING] , identifier[dialect] = identifier[DIALECT] ):
literal[string]
identifier[csvwriter] = identifier[csv] . identifier[writer] ( identifier[fileobj] , identifier[dialect] = identifier[dial... | def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
"""Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``."""
csvwriter = csv.writer(fileobj, dialect=dialect)
csv_writerows(csvwriter, rows, encoding) |
def collapse_initials(name):
"""Remove the space between initials, eg T. A. --> T.A."""
if len(name.split(".")) > 1:
name = re.sub(r'([A-Z]\.)[\s\-]+(?=[A-Z]\.)', r'\1', name)
return name | def function[collapse_initials, parameter[name]]:
constant[Remove the space between initials, eg T. A. --> T.A.]
if compare[call[name[len], parameter[call[name[name].split, parameter[constant[.]]]]] greater[>] constant[1]] begin[:]
variable[name] assign[=] call[name[re].sub, parameter[co... | keyword[def] identifier[collapse_initials] ( identifier[name] ):
literal[string]
keyword[if] identifier[len] ( identifier[name] . identifier[split] ( literal[string] ))> literal[int] :
identifier[name] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[name] )
... | def collapse_initials(name):
"""Remove the space between initials, eg T. A. --> T.A."""
if len(name.split('.')) > 1:
name = re.sub('([A-Z]\\.)[\\s\\-]+(?=[A-Z]\\.)', '\\1', name) # depends on [control=['if'], data=[]]
return name |
def M(self, t, tips=None, gaps=None):
"""See docs for method in `Model` abstract base class."""
assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t)
with scipy.errstate(under='ignore'): # don't worry if some values 0
if ('expD', t) not in self._cached:
se... | def function[M, parameter[self, t, tips, gaps]]:
constant[See docs for method in `Model` abstract base class.]
assert[<ast.BoolOp object at 0x7da18fe91f60>]
with call[name[scipy].errstate, parameter[]] begin[:]
if compare[tuple[[<ast.Constant object at 0x7da18fe933d0>, <ast.Name obje... | keyword[def] identifier[M] ( identifier[self] , identifier[t] , identifier[tips] = keyword[None] , identifier[gaps] = keyword[None] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[t] , identifier[float] ) keyword[and] identifier[t] > literal[int] , literal[string] . identif... | def M(self, t, tips=None, gaps=None):
"""See docs for method in `Model` abstract base class."""
assert isinstance(t, float) and t > 0, 'Invalid t: {0}'.format(t)
with scipy.errstate(under='ignore'): # don't worry if some values 0
if ('expD', t) not in self._cached:
self._cached['expD', ... |
def get_command_info(self, peer_jid, command_name):
"""
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :cla... | def function[get_command_info, parameter[self, peer_jid, command_name]]:
constant[
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class... | keyword[def] identifier[get_command_info] ( identifier[self] , identifier[peer_jid] , identifier[command_name] ):
literal[string]
identifier[disco] = identifier[self] . identifier[dependencies] [ identifier[aioxmpp] . identifier[disco] . identifier[DiscoClient] ]
identifier[response] = ke... | def get_command_info(self, peer_jid, command_name):
"""
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :class:`... |
def mainview(request, **criterias):
'View that handles all page requests.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_mainview)(request, view_data, **cri... | def function[mainview, parameter[request]]:
constant[View that handles all page requests.]
variable[view_data] assign[=] call[name[initview], parameter[name[request]]]
variable[wrap] assign[=] <ast.Lambda object at 0x7da2041d9870>
return[call[call[call[name[condition], parameter[]], paramete... | keyword[def] identifier[mainview] ( identifier[request] ,** identifier[criterias] ):
literal[string]
identifier[view_data] = identifier[initview] ( identifier[request] )
identifier[wrap] = keyword[lambda] identifier[func] : identifier[ft] . identifier[partial] ( identifier[func] , identifier[_view_data] = ide... | def mainview(request, **criterias):
"""View that handles all page requests."""
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified))(_mainview)(request, view_data, *... |
def dump(self):
'''Regurgitate the tables and rows'''
for table in self.tables:
print("*** %s ***" % table.name)
table.dump() | def function[dump, parameter[self]]:
constant[Regurgitate the tables and rows]
for taget[name[table]] in starred[name[self].tables] begin[:]
call[name[print], parameter[binary_operation[constant[*** %s ***] <ast.Mod object at 0x7da2590d6920> name[table].name]]]
call[name[... | keyword[def] identifier[dump] ( identifier[self] ):
literal[string]
keyword[for] identifier[table] keyword[in] identifier[self] . identifier[tables] :
identifier[print] ( literal[string] % identifier[table] . identifier[name] )
identifier[table] . identifier[dump] () | def dump(self):
"""Regurgitate the tables and rows"""
for table in self.tables:
print('*** %s ***' % table.name)
table.dump() # depends on [control=['for'], data=['table']] |
def deaggregate_record(decoded_data):
'''Given a Kinesis record data that is decoded, deaggregate if it was packed using the
Kinesis Producer Library into individual records. This method will be a no-op for any
records that are not aggregated (but will still return them).
decoded_data - the base64... | def function[deaggregate_record, parameter[decoded_data]]:
constant[Given a Kinesis record data that is decoded, deaggregate if it was packed using the
Kinesis Producer Library into individual records. This method will be a no-op for any
records that are not aggregated (but will still return them).
... | keyword[def] identifier[deaggregate_record] ( identifier[decoded_data] ):
literal[string]
identifier[is_aggregated] = keyword[True]
identifier[data_magic] = keyword[None]
keyword[if] ( identifier[len] ( identifier[decoded_data] )>= identifier[len] ( identifier[aws_kinesis_agg] . identifi... | def deaggregate_record(decoded_data):
"""Given a Kinesis record data that is decoded, deaggregate if it was packed using the
Kinesis Producer Library into individual records. This method will be a no-op for any
records that are not aggregated (but will still return them).
decoded_data - the base64... |
def is_valid_mpls_label(label):
"""Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NULL Label".
A value of 3 repr... | def function[is_valid_mpls_label, parameter[label]]:
constant[Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NUL... | keyword[def] identifier[is_valid_mpls_label] ( identifier[label] ):
literal[string]
keyword[if] ( keyword[not] identifier[isinstance] ( identifier[label] , identifier[numbers] . identifier[Integral] ) keyword[or]
( literal[int] <= identifier[label] <= literal[int] ) keyword[or]
( identifier[labe... | def is_valid_mpls_label(label):
"""Validates `label` according to MPLS label rules
RFC says:
This 20-bit field.
A value of 0 represents the "IPv4 Explicit NULL Label".
A value of 1 represents the "Router Alert Label".
A value of 2 represents the "IPv6 Explicit NULL Label".
A value of 3 repr... |
def generate_slug(value):
"""
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
"""
alphabet = app_settings.SLUG_ALPHABET
... | def function[generate_slug, parameter[value]]:
constant[
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
]
varia... | keyword[def] identifier[generate_slug] ( identifier[value] ):
literal[string]
identifier[alphabet] = identifier[app_settings] . identifier[SLUG_ALPHABET]
identifier[salt] = identifier[app_settings] . identifier[SLUG_SALT]
identifier[hashids] = identifier[Hashids] ( identifier[alphabet] = ident... | def generate_slug(value):
"""
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
"""
alphabet = app_settings.SLUG_ALPHABET
... |
def generational_replacement(random, population, parents, offspring, args):
"""Performs generational replacement with optional weak elitism.
This function performs generational replacement, which means that
the entire existing population is replaced by the offspring,
truncating to the population si... | def function[generational_replacement, parameter[random, population, parents, offspring, args]]:
constant[Performs generational replacement with optional weak elitism.
This function performs generational replacement, which means that
the entire existing population is replaced by the offspring,
... | keyword[def] identifier[generational_replacement] ( identifier[random] , identifier[population] , identifier[parents] , identifier[offspring] , identifier[args] ):
literal[string]
identifier[num_elites] = identifier[args] . identifier[setdefault] ( literal[string] , literal[int] )
identifier[populatio... | def generational_replacement(random, population, parents, offspring, args):
"""Performs generational replacement with optional weak elitism.
This function performs generational replacement, which means that
the entire existing population is replaced by the offspring,
truncating to the population si... |
def as_list(cls, protocol=Protocol.http, *args, **kwargs):
''' returns list views '''
return cls.as_view('list', protocol, *args, **kwargs) | def function[as_list, parameter[cls, protocol]]:
constant[ returns list views ]
return[call[name[cls].as_view, parameter[constant[list], name[protocol], <ast.Starred object at 0x7da20c6c7010>]]] | keyword[def] identifier[as_list] ( identifier[cls] , identifier[protocol] = identifier[Protocol] . identifier[http] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[cls] . identifier[as_view] ( literal[string] , identifier[protocol] ,* identifier[args] ,** i... | def as_list(cls, protocol=Protocol.http, *args, **kwargs):
""" returns list views """
return cls.as_view('list', protocol, *args, **kwargs) |
def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
... | def function[_create_value, parameter[self, data, name, spec]]:
constant[ Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
]
variable[field] assign[=... | keyword[def] identifier[_create_value] ( identifier[self] , identifier[data] , identifier[name] , identifier[spec] ):
literal[string]
identifier[field] = identifier[getattr] ( identifier[self] , literal[string] + identifier[name] , keyword[None] )
keyword[if] identifier[field] :
... | def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
if fiel... |
def addvector(self, vec):
"""
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
-------
"""
ve... | def function[addvector, parameter[self, vec]]:
constant[
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
----... | keyword[def] identifier[addvector] ( identifier[self] , identifier[vec] ):
literal[string]
identifier[vec] . identifier[layer] . identifier[ResetReading] ()
keyword[for] identifier[feature] keyword[in] identifier[vec] . identifier[layer] :
identifier[self] . identifier[laye... | def addvector(self, vec):
"""
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
-------
"""
vec.layer.... |
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(... | def function[apply_master_config, parameter[overrides, defaults]]:
constant[
Returns master configurations dict.
]
if compare[name[defaults] is constant[None]] begin[:]
variable[defaults] assign[=] call[name[DEFAULT_MASTER_OPTS].copy, parameter[]]
if compare[name[override... | keyword[def] identifier[apply_master_config] ( identifier[overrides] = keyword[None] , identifier[defaults] = keyword[None] ):
literal[string]
keyword[if] identifier[defaults] keyword[is] keyword[None] :
identifier[defaults] = identifier[DEFAULT_MASTER_OPTS] . identifier[copy] ()
keyword[i... | def apply_master_config(overrides=None, defaults=None):
"""
Returns master configurations dict.
"""
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy() # depends on [control=['if'], data=['defaults']]
if overrides is None:
overrides = {} # depends on [control=['if'], data=['... |
def patch_spyder3(verbose=False):
'''Patch spyder to make it work with sos files and sos kernel '''
try:
# patch spyder/config/utils.py for file extension
from spyder.config import utils
src_file = utils.__file__
spyder_dir = os.path.dirname(os.path.dirname(src_file))
pat... | def function[patch_spyder3, parameter[verbose]]:
constant[Patch spyder to make it work with sos files and sos kernel ]
<ast.Try object at 0x7da18f723130> | keyword[def] identifier[patch_spyder3] ( identifier[verbose] = keyword[False] ):
literal[string]
keyword[try] :
keyword[from] identifier[spyder] . identifier[config] keyword[import] identifier[utils]
identifier[src_file] = identifier[utils] . identifier[__file__]
identi... | def patch_spyder3(verbose=False):
"""Patch spyder to make it work with sos files and sos kernel """
try:
# patch spyder/config/utils.py for file extension
from spyder.config import utils
src_file = utils.__file__
spyder_dir = os.path.dirname(os.path.dirname(src_file))
pat... |
def roundfrac(intpart, fraction, digs):
"""Round or extend the fraction to size digs."""
f = len(fraction)
if f <= digs:
return intpart, fraction + '0'*(digs-f)
i = len(intpart)
if i+digs < 0:
return '0'*-digs, ''
total = intpart + fraction
nextdigit = total[i+digs]
if ne... | def function[roundfrac, parameter[intpart, fraction, digs]]:
constant[Round or extend the fraction to size digs.]
variable[f] assign[=] call[name[len], parameter[name[fraction]]]
if compare[name[f] less_or_equal[<=] name[digs]] begin[:]
return[tuple[[<ast.Name object at 0x7da18f812260>, ... | keyword[def] identifier[roundfrac] ( identifier[intpart] , identifier[fraction] , identifier[digs] ):
literal[string]
identifier[f] = identifier[len] ( identifier[fraction] )
keyword[if] identifier[f] <= identifier[digs] :
keyword[return] identifier[intpart] , identifier[fraction] + literal... | def roundfrac(intpart, fraction, digs):
"""Round or extend the fraction to size digs."""
f = len(fraction)
if f <= digs:
return (intpart, fraction + '0' * (digs - f)) # depends on [control=['if'], data=['f', 'digs']]
i = len(intpart)
if i + digs < 0:
return ('0' * -digs, '') # depe... |
def get_gosubdag(gosubdag=None):
"""Gets a GoSubDag initialized for use by a Grouper object."""
if gosubdag is not None:
if gosubdag.rcntobj is not None:
return gosubdag
else:
gosubdag.init_auxobjs()
return gosubdag
else:
... | def function[get_gosubdag, parameter[gosubdag]]:
constant[Gets a GoSubDag initialized for use by a Grouper object.]
if compare[name[gosubdag] is_not constant[None]] begin[:]
if compare[name[gosubdag].rcntobj is_not constant[None]] begin[:]
return[name[gosubdag]] | keyword[def] identifier[get_gosubdag] ( identifier[gosubdag] = keyword[None] ):
literal[string]
keyword[if] identifier[gosubdag] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[gosubdag] . identifier[rcntobj] keyword[is] keyword[not] keyword[None] :
... | def get_gosubdag(gosubdag=None):
"""Gets a GoSubDag initialized for use by a Grouper object."""
if gosubdag is not None:
if gosubdag.rcntobj is not None:
return gosubdag # depends on [control=['if'], data=[]]
else:
gosubdag.init_auxobjs()
return gosubdag # d... |
def __allocate_clusters(self):
"""!
@brief Performs cluster allocation using leafs of tree in BANG directory (the smallest cells).
"""
leaf_blocks = self.__directory.get_leafs()
unhandled_block_indexes = set([i for i in range(len(leaf_blocks)) if leaf_blocks[i].get_density... | def function[__allocate_clusters, parameter[self]]:
constant[!
@brief Performs cluster allocation using leafs of tree in BANG directory (the smallest cells).
]
variable[leaf_blocks] assign[=] call[name[self].__directory.get_leafs, parameter[]]
variable[unhandled_block_indexes] a... | keyword[def] identifier[__allocate_clusters] ( identifier[self] ):
literal[string]
identifier[leaf_blocks] = identifier[self] . identifier[__directory] . identifier[get_leafs] ()
identifier[unhandled_block_indexes] = identifier[set] ([ identifier[i] keyword[for] identifier[i] keyword... | def __allocate_clusters(self):
"""!
@brief Performs cluster allocation using leafs of tree in BANG directory (the smallest cells).
"""
leaf_blocks = self.__directory.get_leafs()
unhandled_block_indexes = set([i for i in range(len(leaf_blocks)) if leaf_blocks[i].get_density() > self.__densit... |
def stop_broadcast(self, broadcast_id):
"""
Use this method to stop a live broadcast of an OpenTok session
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, creat... | def function[stop_broadcast, parameter[self, broadcast_id]]:
constant[
Use this method to stop a live broadcast of an OpenTok session
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, session... | keyword[def] identifier[stop_broadcast] ( identifier[self] , identifier[broadcast_id] ):
literal[string]
identifier[endpoint] = identifier[self] . identifier[endpoints] . identifier[broadcast_url] ( identifier[broadcast_id] , identifier[stop] = keyword[True] )
identifier[response] = identi... | def stop_broadcast(self, broadcast_id):
"""
Use this method to stop a live broadcast of an OpenTok session
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, createdAt... |
def parse_impl(self):
"""
Parses the HTML content as a stream. This is far less memory
intensive than loading the entire HTML file into memory, like
BeautifulSoup does.
"""
# Cast to str to ensure not unicode under Python 2, as the parser
# doesn't like that.
... | def function[parse_impl, parameter[self]]:
constant[
Parses the HTML content as a stream. This is far less memory
intensive than loading the entire HTML file into memory, like
BeautifulSoup does.
]
variable[parser] assign[=] call[name[XMLParser], parameter[]]
vari... | keyword[def] identifier[parse_impl] ( identifier[self] ):
literal[string]
identifier[parser] = identifier[XMLParser] ( identifier[encoding] = identifier[str] ( literal[string] ))
identifier[element_iter] = identifier[ET] . identifier[iterparse] ( identifier[self] . ident... | def parse_impl(self):
"""
Parses the HTML content as a stream. This is far less memory
intensive than loading the entire HTML file into memory, like
BeautifulSoup does.
"""
# Cast to str to ensure not unicode under Python 2, as the parser
# doesn't like that.
parser = XML... |
def _compile_dimension_size(self, base_index, array,
property, sized_elements):
"""Build one set of col widths or row heights."""
sort_index = base_index + 2
sized_elements.sort(key=lambda x: x[sort_index])
for element_data in sized_elements:
s... | def function[_compile_dimension_size, parameter[self, base_index, array, property, sized_elements]]:
constant[Build one set of col widths or row heights.]
variable[sort_index] assign[=] binary_operation[name[base_index] + constant[2]]
call[name[sized_elements].sort, parameter[]]
for tage... | keyword[def] identifier[_compile_dimension_size] ( identifier[self] , identifier[base_index] , identifier[array] ,
identifier[property] , identifier[sized_elements] ):
literal[string]
identifier[sort_index] = identifier[base_index] + literal[int]
identifier[sized_elements] . identifier[s... | def _compile_dimension_size(self, base_index, array, property, sized_elements):
"""Build one set of col widths or row heights."""
sort_index = base_index + 2
sized_elements.sort(key=lambda x: x[sort_index])
for element_data in sized_elements:
(start, end) = (element_data[base_index], element_dat... |
def _logstash(url, data):
'''
Issues HTTP queries to the logstash server.
'''
result = salt.utils.http.query(
url,
'POST',
header_dict=_HEADERS,
data=salt.utils.json.dumps(data),
decode=True,
status=True,
opts=__opts__
)
return result | def function[_logstash, parameter[url, data]]:
constant[
Issues HTTP queries to the logstash server.
]
variable[result] assign[=] call[name[salt].utils.http.query, parameter[name[url], constant[POST]]]
return[name[result]] | keyword[def] identifier[_logstash] ( identifier[url] , identifier[data] ):
literal[string]
identifier[result] = identifier[salt] . identifier[utils] . identifier[http] . identifier[query] (
identifier[url] ,
literal[string] ,
identifier[header_dict] = identifier[_HEADERS] ,
identifier[d... | def _logstash(url, data):
"""
Issues HTTP queries to the logstash server.
"""
result = salt.utils.http.query(url, 'POST', header_dict=_HEADERS, data=salt.utils.json.dumps(data), decode=True, status=True, opts=__opts__)
return result |
def corrupt_input(data, sess, corrtype, corrfrac):
"""Corrupt a fraction of data according to the chosen noise method.
:return: corrupted data
"""
corruption_ratio = np.round(corrfrac * data.shape[1]).astype(np.int)
if corrtype == 'none':
return np.copy(data)
if corrfrac > 0.0:
... | def function[corrupt_input, parameter[data, sess, corrtype, corrfrac]]:
constant[Corrupt a fraction of data according to the chosen noise method.
:return: corrupted data
]
variable[corruption_ratio] assign[=] call[call[name[np].round, parameter[binary_operation[name[corrfrac] * call[name[data].... | keyword[def] identifier[corrupt_input] ( identifier[data] , identifier[sess] , identifier[corrtype] , identifier[corrfrac] ):
literal[string]
identifier[corruption_ratio] = identifier[np] . identifier[round] ( identifier[corrfrac] * identifier[data] . identifier[shape] [ literal[int] ]). identifier[astype]... | def corrupt_input(data, sess, corrtype, corrfrac):
"""Corrupt a fraction of data according to the chosen noise method.
:return: corrupted data
"""
corruption_ratio = np.round(corrfrac * data.shape[1]).astype(np.int)
if corrtype == 'none':
return np.copy(data) # depends on [control=['if'], ... |
def add_data_set(self, data, series_type="line", name=None, **kwargs):
"""set data for series option in highcharts"""
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if series_type == 'treemap':
... | def function[add_data_set, parameter[self, data, series_type, name]]:
constant[set data for series option in highcharts]
<ast.AugAssign object at 0x7da1b1de2080>
if <ast.UnaryOp object at 0x7da1b1de1870> begin[:]
variable[name] assign[=] binary_operation[constant[Series %d] <ast.Mod ... | keyword[def] identifier[add_data_set] ( identifier[self] , identifier[data] , identifier[series_type] = literal[string] , identifier[name] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[data_set_count] += literal[int]
keyword[if] keyword[not] id... | def add_data_set(self, data, series_type='line', name=None, **kwargs):
"""set data for series option in highcharts"""
self.data_set_count += 1
if not name:
name = 'Series %d' % self.data_set_count # depends on [control=['if'], data=[]]
kwargs.update({'name': name})
if series_type == 'treema... |
def step(self, thumb=False):
"""Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raises:
JLinkException: ... | def function[step, parameter[self, thumb]]:
constant[Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raises:
... | keyword[def] identifier[step] ( identifier[self] , identifier[thumb] = keyword[False] ):
literal[string]
identifier[method] = identifier[self] . identifier[_dll] . identifier[JLINKARM_Step]
keyword[if] identifier[thumb] :
identifier[method] = identifier[self] . identifier[_d... | def step(self, thumb=False):
"""Executes a single step.
Steps even if there is a breakpoint.
Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode
Returns:
``None``
Raises:
JLinkException: on e... |
def serialize_op( cls, opcode, opdata, opfields, verbose=True ):
"""
Given an opcode (byte), associated data (dict), and the operation
fields to serialize (opfields), convert it
into its canonical serialized form (i.e. in order to
generate a consensus hash.
opdata is a... | def function[serialize_op, parameter[cls, opcode, opdata, opfields, verbose]]:
constant[
Given an opcode (byte), associated data (dict), and the operation
fields to serialize (opfields), convert it
into its canonical serialized form (i.e. in order to
generate a consensus hash.
... | keyword[def] identifier[serialize_op] ( identifier[cls] , identifier[opcode] , identifier[opdata] , identifier[opfields] , identifier[verbose] = keyword[True] ):
literal[string]
identifier[fields] = identifier[opfields] . identifier[get] ( identifier[opcode] , keyword[None] )
keyword[if] ... | def serialize_op(cls, opcode, opdata, opfields, verbose=True):
"""
Given an opcode (byte), associated data (dict), and the operation
fields to serialize (opfields), convert it
into its canonical serialized form (i.e. in order to
generate a consensus hash.
opdata is allowed... |
def get_endpoint(self, endpoint=None):
"""Return interface URL endpoint."""
base_url = self.api_config.api_url
if not endpoint:
if 'localhost' in base_url:
endpoint = ''
else:
endpoint = ENDPOINTS[self.endpoint_type]
endpoint = '/'... | def function[get_endpoint, parameter[self, endpoint]]:
constant[Return interface URL endpoint.]
variable[base_url] assign[=] name[self].api_config.api_url
if <ast.UnaryOp object at 0x7da1b0947190> begin[:]
if compare[constant[localhost] in name[base_url]] begin[:]
... | keyword[def] identifier[get_endpoint] ( identifier[self] , identifier[endpoint] = keyword[None] ):
literal[string]
identifier[base_url] = identifier[self] . identifier[api_config] . identifier[api_url]
keyword[if] keyword[not] identifier[endpoint] :
keyword[if] literal[str... | def get_endpoint(self, endpoint=None):
"""Return interface URL endpoint."""
base_url = self.api_config.api_url
if not endpoint:
if 'localhost' in base_url:
endpoint = '' # depends on [control=['if'], data=[]]
else:
endpoint = ENDPOINTS[self.endpoint_type] # depends ... |
def delete_topic(self, project, topic, fail_if_not_exists=False):
"""Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{projec... | def function[delete_topic, parameter[self, project, topic, fail_if_not_exists]]:
constant[Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include t... | keyword[def] identifier[delete_topic] ( identifier[self] , identifier[project] , identifier[topic] , identifier[fail_if_not_exists] = keyword[False] ):
literal[string]
identifier[service] = identifier[self] . identifier[get_conn] ()
identifier[full_topic] = identifier[_format_topic] ( iden... | def delete_topic(self, project, topic, fail_if_not_exists=False):
"""Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{project}/t... |
def deploy():
"""Deploy to production."""
_require_root()
if not confirm("This will apply any available migrations to the database. Has the database been backed up?"):
abort("Aborted.")
if not confirm("Are you sure you want to deploy?"):
abort("Aborted.")
with lcd(PRODUCTION_DOCUME... | def function[deploy, parameter[]]:
constant[Deploy to production.]
call[name[_require_root], parameter[]]
if <ast.UnaryOp object at 0x7da1b02e5c90> begin[:]
call[name[abort], parameter[constant[Aborted.]]]
if <ast.UnaryOp object at 0x7da1b02e4e20> begin[:]
... | keyword[def] identifier[deploy] ():
literal[string]
identifier[_require_root] ()
keyword[if] keyword[not] identifier[confirm] ( literal[string] ):
identifier[abort] ( literal[string] )
keyword[if] keyword[not] identifier[confirm] ( literal[string] ):
identifier[abort] ( lit... | def deploy():
"""Deploy to production."""
_require_root()
if not confirm('This will apply any available migrations to the database. Has the database been backed up?'):
abort('Aborted.') # depends on [control=['if'], data=[]]
if not confirm('Are you sure you want to deploy?'):
abort('Abo... |
def chain_user_names(users, exclude_user, truncate=35):
"""Tag to return a truncated chain of user names."""
if not users or not isinstance(exclude_user, get_user_model()):
return ''
return truncatechars(
', '.join(u'{}'.format(u) for u in users.exclude(pk=exclude_user.pk)),
truncate... | def function[chain_user_names, parameter[users, exclude_user, truncate]]:
constant[Tag to return a truncated chain of user names.]
if <ast.BoolOp object at 0x7da20e9b3a90> begin[:]
return[constant[]]
return[call[name[truncatechars], parameter[call[constant[, ].join, parameter[<ast.GeneratorE... | keyword[def] identifier[chain_user_names] ( identifier[users] , identifier[exclude_user] , identifier[truncate] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[users] keyword[or] keyword[not] identifier[isinstance] ( identifier[exclude_user] , identifier[get_user_model] ()):
... | def chain_user_names(users, exclude_user, truncate=35):
"""Tag to return a truncated chain of user names."""
if not users or not isinstance(exclude_user, get_user_model()):
return '' # depends on [control=['if'], data=[]]
return truncatechars(', '.join((u'{}'.format(u) for u in users.exclude(pk=exc... |
def get_span(docgraph, node_id, debug=False):
"""
returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of token nodes (token node IDs)... | def function[get_span, parameter[docgraph, node_id, debug]]:
constant[
returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of tok... | keyword[def] identifier[get_span] ( identifier[docgraph] , identifier[node_id] , identifier[debug] = keyword[False] ):
literal[string]
keyword[if] identifier[debug] keyword[is] keyword[True] keyword[and] identifier[is_directed_acyclic_graph] ( identifier[docgraph] ) keyword[is] keyword[False] :
... | def get_span(docgraph, node_id, debug=False):
"""
returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of token nodes (token node IDs)... |
def resourceprep(string, allow_unassigned=False):
"""
Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised.
"""
chars = list(string)
_resourceprep_do_mapping(chars)
do_normalizati... | def function[resourceprep, parameter[string, allow_unassigned]]:
constant[
Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised.
]
variable[chars] assign[=] call[name[list], parame... | keyword[def] identifier[resourceprep] ( identifier[string] , identifier[allow_unassigned] = keyword[False] ):
literal[string]
identifier[chars] = identifier[list] ( identifier[string] )
identifier[_resourceprep_do_mapping] ( identifier[chars] )
identifier[do_normalization] ( identifier[chars] )
... | def resourceprep(string, allow_unassigned=False):
"""
Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised.
"""
chars = list(string)
_resourceprep_do_mapping(chars)
do_normalizatio... |
def send_message(self, output):
"""
Send a message to the socket
"""
file_system_event = None
if self.my_action_input:
file_system_event = self.my_action_input.file_system_event or None
output_action = ActionInput(file_system_event,
... | def function[send_message, parameter[self, output]]:
constant[
Send a message to the socket
]
variable[file_system_event] assign[=] constant[None]
if name[self].my_action_input begin[:]
variable[file_system_event] assign[=] <ast.BoolOp object at 0x7da1b2428340>
... | keyword[def] identifier[send_message] ( identifier[self] , identifier[output] ):
literal[string]
identifier[file_system_event] = keyword[None]
keyword[if] identifier[self] . identifier[my_action_input] :
identifier[file_system_event] = identifier[self] . identifier[my_actio... | def send_message(self, output):
"""
Send a message to the socket
"""
file_system_event = None
if self.my_action_input:
file_system_event = self.my_action_input.file_system_event or None # depends on [control=['if'], data=[]]
output_action = ActionInput(file_system_event, output,... |
def getStats(self):
"""Runs varnishstats command to get stats from Varnish Cache.
@return: Dictionary of stats.
"""
info_dict = {}
args = [varnishstatCmd, '-1']
if self._instance is not None:
args.extend(['-n', self._instance])
output = util.... | def function[getStats, parameter[self]]:
constant[Runs varnishstats command to get stats from Varnish Cache.
@return: Dictionary of stats.
]
variable[info_dict] assign[=] dictionary[[], []]
variable[args] assign[=] list[[<ast.Name object at 0x7da1b10b1f30>, <ast.Constan... | keyword[def] identifier[getStats] ( identifier[self] ):
literal[string]
identifier[info_dict] ={}
identifier[args] =[ identifier[varnishstatCmd] , literal[string] ]
keyword[if] identifier[self] . identifier[_instance] keyword[is] keyword[not] keyword[None] :
ident... | def getStats(self):
"""Runs varnishstats command to get stats from Varnish Cache.
@return: Dictionary of stats.
"""
info_dict = {}
args = [varnishstatCmd, '-1']
if self._instance is not None:
args.extend(['-n', self._instance]) # depends on [control=['if'], data=[]]
... |
def posix_to_dt_str(posix):
"""Reverse of str_to_datetime.
This is used by GCS stub to generate GET bucket XML response.
Args:
posix: A float of secs from unix epoch.
Returns:
A datetime str.
"""
dt = datetime.datetime.utcfromtimestamp(posix)
dt_str = dt.strftime(_DT_FORMAT)
return dt_str + '... | def function[posix_to_dt_str, parameter[posix]]:
constant[Reverse of str_to_datetime.
This is used by GCS stub to generate GET bucket XML response.
Args:
posix: A float of secs from unix epoch.
Returns:
A datetime str.
]
variable[dt] assign[=] call[name[datetime].datetime.utcfromtimes... | keyword[def] identifier[posix_to_dt_str] ( identifier[posix] ):
literal[string]
identifier[dt] = identifier[datetime] . identifier[datetime] . identifier[utcfromtimestamp] ( identifier[posix] )
identifier[dt_str] = identifier[dt] . identifier[strftime] ( identifier[_DT_FORMAT] )
keyword[return] identifi... | def posix_to_dt_str(posix):
"""Reverse of str_to_datetime.
This is used by GCS stub to generate GET bucket XML response.
Args:
posix: A float of secs from unix epoch.
Returns:
A datetime str.
"""
dt = datetime.datetime.utcfromtimestamp(posix)
dt_str = dt.strftime(_DT_FORMAT)
return dt... |
def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
... | def function[default_token_user_loader, parameter[self, token]]:
constant[
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherw... | keyword[def] identifier[default_token_user_loader] ( identifier[self] , identifier[token] ):
literal[string]
keyword[try] :
identifier[data] = identifier[self] . identifier[decode_token] ( identifier[token] )
keyword[except] identifier[jwt] . identifier[exceptions] . identifi... | def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
... |
def append(self, obj):
"""Append an object to end. If the object is a string, appends a
:class:`Word <Word>` object.
"""
if isinstance(obj, basestring):
return self._collection.append(Word(obj))
else:
return self._collection.append(obj) | def function[append, parameter[self, obj]]:
constant[Append an object to end. If the object is a string, appends a
:class:`Word <Word>` object.
]
if call[name[isinstance], parameter[name[obj], name[basestring]]] begin[:]
return[call[name[self]._collection.append, parameter[call[name[Word... | keyword[def] identifier[append] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[basestring] ):
keyword[return] identifier[self] . identifier[_collection] . identifier[append] ( identifier[Word] ( identifier[obj] ))
ke... | def append(self, obj):
"""Append an object to end. If the object is a string, appends a
:class:`Word <Word>` object.
"""
if isinstance(obj, basestring):
return self._collection.append(Word(obj)) # depends on [control=['if'], data=[]]
else:
return self._collection.append(obj) |
def restore_expanded_state(self):
"""Restore all items expanded state"""
if self.__expanded_state is None:
return
for item in self.get_items()+self.get_top_level_items():
user_text = get_item_user_text(item)
is_expanded = self.__expanded_state.get(hash(u... | def function[restore_expanded_state, parameter[self]]:
constant[Restore all items expanded state]
if compare[name[self].__expanded_state is constant[None]] begin[:]
return[None]
for taget[name[item]] in starred[binary_operation[call[name[self].get_items, parameter[]] + call[name[self].ge... | keyword[def] identifier[restore_expanded_state] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__expanded_state] keyword[is] keyword[None] :
keyword[return]
keyword[for] identifier[item] keyword[in] identifier[self] . identifier[get_... | def restore_expanded_state(self):
"""Restore all items expanded state"""
if self.__expanded_state is None:
return # depends on [control=['if'], data=[]]
for item in self.get_items() + self.get_top_level_items():
user_text = get_item_user_text(item)
is_expanded = self.__expanded_stat... |
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for translation in orm['people.PersonTranslation'].objects.all():
if translation.language in ['en', 'de']:
translation.ro... | def function[forwards, parameter[self, orm]]:
constant[Write your forwards methods here.]
for taget[name[translation]] in starred[call[call[name[orm]][constant[people.PersonTranslation]].objects.all, parameter[]]] begin[:]
if compare[name[translation].language in list[[<ast.Constant obje... | keyword[def] identifier[forwards] ( identifier[self] , identifier[orm] ):
literal[string]
keyword[for] identifier[translation] keyword[in] identifier[orm] [ literal[string] ]. identifier[objects] . identifier[all] ():
keyword[if] identifier[translation] . identifier[langua... | def forwards(self, orm):
"""Write your forwards methods here."""
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for translation in orm['people.PersonTranslation'].objects.all():
if translation.language in ['en', 'de']:
translation.roman_first_name =... |
def start(self):
"""Get the start key of the first range.
None if RangeMap is empty or unbounded to the left.
"""
if self._values[0] is NOT_SET:
try:
return self._keys[1]
except IndexError:
# This is empty or everything is mapped to a single value
return None
else:
# This is unbounded to... | def function[start, parameter[self]]:
constant[Get the start key of the first range.
None if RangeMap is empty or unbounded to the left.
]
if compare[call[name[self]._values][constant[0]] is name[NOT_SET]] begin[:]
<ast.Try object at 0x7da1b26a5600> | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_values] [ literal[int] ] keyword[is] identifier[NOT_SET] :
keyword[try] :
keyword[return] identifier[self] . identifier[_keys] [ literal[int] ]
keyword[except] identifier[IndexError]... | def start(self):
"""Get the start key of the first range.
None if RangeMap is empty or unbounded to the left.
"""
if self._values[0] is NOT_SET:
try:
return self._keys[1] # depends on [control=['try'], data=[]]
except IndexError: # This is empty or everything is mapped to a si... |
def _do_zero_width(self):
"""Fetch and update zero width tables."""
self._do_retrieve(self.UCD_URL, self.UCD_IN)
(version, date, values) = self._parse_category(
fname=self.UCD_IN,
categories=('Me', 'Mn',)
)
table = self._make_table(values)
self._do... | def function[_do_zero_width, parameter[self]]:
constant[Fetch and update zero width tables.]
call[name[self]._do_retrieve, parameter[name[self].UCD_URL, name[self].UCD_IN]]
<ast.Tuple object at 0x7da18f58fc70> assign[=] call[name[self]._parse_category, parameter[]]
variable[table] assign... | keyword[def] identifier[_do_zero_width] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_do_retrieve] ( identifier[self] . identifier[UCD_URL] , identifier[self] . identifier[UCD_IN] )
( identifier[version] , identifier[date] , identifier[values] )= identifier[self] . id... | def _do_zero_width(self):
"""Fetch and update zero width tables."""
self._do_retrieve(self.UCD_URL, self.UCD_IN)
(version, date, values) = self._parse_category(fname=self.UCD_IN, categories=('Me', 'Mn'))
table = self._make_table(values)
self._do_write(self.ZERO_OUT, 'ZERO_WIDTH', version, date, tabl... |
def getFormattedResult(self, specs=None, decimalmark='.', sciformat=1,
html=True):
"""Formatted result:
1. If the result is a detection limit, returns '< LDL' or '> UDL'
2. Print ResultText of matching ResultOptions
3. If the result is not floatable, return it ... | def function[getFormattedResult, parameter[self, specs, decimalmark, sciformat, html]]:
constant[Formatted result:
1. If the result is a detection limit, returns '< LDL' or '> UDL'
2. Print ResultText of matching ResultOptions
3. If the result is not floatable, return it without being fo... | keyword[def] identifier[getFormattedResult] ( identifier[self] , identifier[specs] = keyword[None] , identifier[decimalmark] = literal[string] , identifier[sciformat] = literal[int] ,
identifier[html] = keyword[True] ):
literal[string]
identifier[result] = identifier[self] . identifier[getResult] ... | def getFormattedResult(self, specs=None, decimalmark='.', sciformat=1, html=True):
"""Formatted result:
1. If the result is a detection limit, returns '< LDL' or '> UDL'
2. Print ResultText of matching ResultOptions
3. If the result is not floatable, return it without being formatted
... |
def process_user_input(self):
"""
This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs.
Examples:
All of the following inputs would have the same result:
* 1,2,3,4
* 1-4
* 1-2,3-4
* 1 -... | def function[process_user_input, parameter[self]]:
constant[
This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs.
Examples:
All of the following inputs would have the same result:
* 1,2,3,4
* 1-4
* 1-... | keyword[def] identifier[process_user_input] ( identifier[self] ):
literal[string]
identifier[user_input] = identifier[self] . identifier[screen] . identifier[input] ()
keyword[try] :
identifier[indexes] = identifier[self] . identifier[__parse_range_list] ( identifier[user_inp... | def process_user_input(self):
"""
This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs.
Examples:
All of the following inputs would have the same result:
* 1,2,3,4
* 1-4
* 1-2,3-4
* 1 - 4
... |
def count(self, sqlTail = '') :
"Compile filters and counts the number of results. You can use sqlTail to add things such as order by"
sql, sqlValues = self.getSQLQuery(count = True)
return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0]) | def function[count, parameter[self, sqlTail]]:
constant[Compile filters and counts the number of results. You can use sqlTail to add things such as order by]
<ast.Tuple object at 0x7da1b0a84940> assign[=] call[name[self].getSQLQuery, parameter[]]
return[call[name[int], parameter[call[call[call[name[... | keyword[def] identifier[count] ( identifier[self] , identifier[sqlTail] = literal[string] ):
literal[string]
identifier[sql] , identifier[sqlValues] = identifier[self] . identifier[getSQLQuery] ( identifier[count] = keyword[True] )
keyword[return] identifier[int] ( identifier[self] . identifier[con] . iden... | def count(self, sqlTail=''):
"""Compile filters and counts the number of results. You can use sqlTail to add things such as order by"""
(sql, sqlValues) = self.getSQLQuery(count=True)
return int(self.con.execute('%s %s' % (sql, sqlTail), sqlValues).fetchone()[0]) |
def _extract_error(self, resp):
"""
Extract the actual error message from a solr response.
"""
reason = resp.headers.get('reason', None)
full_response = None
if reason is None:
try:
# if response is in json format
reason = resp... | def function[_extract_error, parameter[self, resp]]:
constant[
Extract the actual error message from a solr response.
]
variable[reason] assign[=] call[name[resp].headers.get, parameter[constant[reason], constant[None]]]
variable[full_response] assign[=] constant[None]
if... | keyword[def] identifier[_extract_error] ( identifier[self] , identifier[resp] ):
literal[string]
identifier[reason] = identifier[resp] . identifier[headers] . identifier[get] ( literal[string] , keyword[None] )
identifier[full_response] = keyword[None]
keyword[if] identifier[re... | def _extract_error(self, resp):
"""
Extract the actual error message from a solr response.
"""
reason = resp.headers.get('reason', None)
full_response = None
if reason is None:
try:
# if response is in json format
reason = resp.json()['error']['msg'] # de... |
def set_cfme_caselevel(testcase, caselevels):
"""Converts tier to caselevel."""
tier = testcase.get("caselevel")
if tier is None:
return
try:
caselevel = caselevels[int(tier)]
except IndexError:
# invalid value
caselevel = "component"
except ValueError:
#... | def function[set_cfme_caselevel, parameter[testcase, caselevels]]:
constant[Converts tier to caselevel.]
variable[tier] assign[=] call[name[testcase].get, parameter[constant[caselevel]]]
if compare[name[tier] is constant[None]] begin[:]
return[None]
<ast.Try object at 0x7da204346740>... | keyword[def] identifier[set_cfme_caselevel] ( identifier[testcase] , identifier[caselevels] ):
literal[string]
identifier[tier] = identifier[testcase] . identifier[get] ( literal[string] )
keyword[if] identifier[tier] keyword[is] keyword[None] :
keyword[return]
keyword[try] :
... | def set_cfme_caselevel(testcase, caselevels):
"""Converts tier to caselevel."""
tier = testcase.get('caselevel')
if tier is None:
return # depends on [control=['if'], data=[]]
try:
caselevel = caselevels[int(tier)] # depends on [control=['try'], data=[]]
except IndexError:
... |
def _random_point(self):
"""Find an approximately random point in the flux cone."""
idx = np.random.randint(self.n_warmup,
size=min(2, np.ceil(np.sqrt(self.n_warmup))))
return self.warmup[idx, :].mean(axis=0) | def function[_random_point, parameter[self]]:
constant[Find an approximately random point in the flux cone.]
variable[idx] assign[=] call[name[np].random.randint, parameter[name[self].n_warmup]]
return[call[call[name[self].warmup][tuple[[<ast.Name object at 0x7da1b0060d90>, <ast.Slice object at 0x7d... | keyword[def] identifier[_random_point] ( identifier[self] ):
literal[string]
identifier[idx] = identifier[np] . identifier[random] . identifier[randint] ( identifier[self] . identifier[n_warmup] ,
identifier[size] = identifier[min] ( literal[int] , identifier[np] . identifier[ceil] ( iden... | def _random_point(self):
"""Find an approximately random point in the flux cone."""
idx = np.random.randint(self.n_warmup, size=min(2, np.ceil(np.sqrt(self.n_warmup))))
return self.warmup[idx, :].mean(axis=0) |
def assemble(experiments,
backend=None,
qobj_id=None, qobj_header=None, # common run options
shots=1024, memory=False, max_credits=None, seed_simulator=None,
default_qubit_los=None, default_meas_los=None, # schedule run options
schedule_los=None, meas_l... | def function[assemble, parameter[experiments, backend, qobj_id, qobj_header, shots, memory, max_credits, seed_simulator, default_qubit_los, default_meas_los, schedule_los, meas_level, meas_return, memory_slots, memory_slot_size, rep_time, parameter_binds, config, seed]]:
constant[Assemble a list of circuits or ... | keyword[def] identifier[assemble] ( identifier[experiments] ,
identifier[backend] = keyword[None] ,
identifier[qobj_id] = keyword[None] , identifier[qobj_header] = keyword[None] ,
identifier[shots] = literal[int] , identifier[memory] = keyword[False] , identifier[max_credits] = keyword[None] , identifier[seed_simu... | def assemble(experiments, backend=None, qobj_id=None, qobj_header=None, shots=1024, memory=False, max_credits=None, seed_simulator=None, default_qubit_los=None, default_meas_los=None, schedule_los=None, meas_level=2, meas_return='avg', memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None, config... |
def exclude_times(self, *tuples):
"""Adds multiple excluded times by tuple of (start, end, days) or by
TimeRange instance.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
... | def function[exclude_times, parameter[self]]:
constant[Adds multiple excluded times by tuple of (start, end, days) or by
TimeRange instance.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased... | keyword[def] identifier[exclude_times] ( identifier[self] ,* identifier[tuples] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[tuples] :
keyword[if] identifier[isinstance] ( identifier[item] , identifier[TimeRange] ):
identifier[self] . ide... | def exclude_times(self, *tuples):
"""Adds multiple excluded times by tuple of (start, end, days) or by
TimeRange instance.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
... |
def _append_html_element(self, item, element, html, glue=" ",
after=True):
"""Appends an html value after or before the element in the item dict
:param item: dictionary that represents an analysis row
:param element: id of the element the html must be added the... | def function[_append_html_element, parameter[self, item, element, html, glue, after]]:
constant[Appends an html value after or before the element in the item dict
:param item: dictionary that represents an analysis row
:param element: id of the element the html must be added thereafter
... | keyword[def] identifier[_append_html_element] ( identifier[self] , identifier[item] , identifier[element] , identifier[html] , identifier[glue] = literal[string] ,
identifier[after] = keyword[True] ):
literal[string]
identifier[position] = identifier[after] keyword[and] literal[string] keyword[... | def _append_html_element(self, item, element, html, glue=' ', after=True):
"""Appends an html value after or before the element in the item dict
:param item: dictionary that represents an analysis row
:param element: id of the element the html must be added thereafter
:param html: elem... |
def _pep425_get_abi():
"""
:return:
A unicode string of the system abi. Will be something like: "cp27m",
"cp33m", etc.
"""
try:
soabi = sysconfig.get_config_var('SOABI')
if soabi:
if soabi.startswith('cpython-'):
return 'cp%s' % soabi.split('-... | def function[_pep425_get_abi, parameter[]]:
constant[
:return:
A unicode string of the system abi. Will be something like: "cp27m",
"cp33m", etc.
]
<ast.Try object at 0x7da1b08aee60>
variable[impl] assign[=] call[name[_pep425_implementation], parameter[]]
variable[suf... | keyword[def] identifier[_pep425_get_abi] ():
literal[string]
keyword[try] :
identifier[soabi] = identifier[sysconfig] . identifier[get_config_var] ( literal[string] )
keyword[if] identifier[soabi] :
keyword[if] identifier[soabi] . identifier[startswith] ( literal[string] )... | def _pep425_get_abi():
"""
:return:
A unicode string of the system abi. Will be something like: "cp27m",
"cp33m", etc.
"""
try:
soabi = sysconfig.get_config_var('SOABI')
if soabi:
if soabi.startswith('cpython-'):
return 'cp%s' % soabi.split('-'... |
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
should_post = not has_callbacks
... | def function[_did_receive_response, parameter[self, connection]]:
constant[ Receive a response from the connection ]
if name[connection].has_timeouted begin[:]
call[name[bambou_logger].info, parameter[constant[NURESTConnection has timeout.]]]
return[None]
variable[has_cal... | keyword[def] identifier[_did_receive_response] ( identifier[self] , identifier[connection] ):
literal[string]
keyword[if] identifier[connection] . identifier[has_timeouted] :
identifier[bambou_logger] . identifier[info] ( literal[string] )
keyword[return]
iden... | def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info('NURESTConnection has timeout.')
return # depends on [control=['if'], data=[]]
has_callbacks = connection.has_callbacks()
should_post = not has_cal... |
def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a ... | def function[validate, parameter[self]]:
constant[Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all ke... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[vendor] , identifier[text_type] ):
keyword[if] identifier[PY3] :
keyword[raise] identifier[ValueError] ( literal... | def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a stri... |
def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of di... | def function[call, parameter[self, req, props]]:
constant[
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The reques... | keyword[def] identifier[call] ( identifier[self] , identifier[req] , identifier[props] = keyword[None] ):
literal[string]
identifier[resp] = keyword[None]
keyword[if] identifier[self] . identifier[log] . identifier[isEnabledFor] ( identifier[logging] . identifier[DEBUG] ):
... | def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of dicts,... |
def build_graph (json_iter):
"""
construct the TextRank graph from parsed paragraphs
"""
global DEBUG, WordNode
graph = nx.DiGraph()
for meta in json_iter:
if DEBUG:
print(meta["graf"])
for pair in get_tiles(map(WordNode._make, meta["graf"])):
if DEBUG:
... | def function[build_graph, parameter[json_iter]]:
constant[
construct the TextRank graph from parsed paragraphs
]
<ast.Global object at 0x7da1b0191390>
variable[graph] assign[=] call[name[nx].DiGraph, parameter[]]
for taget[name[meta]] in starred[name[json_iter]] begin[:]
... | keyword[def] identifier[build_graph] ( identifier[json_iter] ):
literal[string]
keyword[global] identifier[DEBUG] , identifier[WordNode]
identifier[graph] = identifier[nx] . identifier[DiGraph] ()
keyword[for] identifier[meta] keyword[in] identifier[json_iter] :
keyword[if] identi... | def build_graph(json_iter):
"""
construct the TextRank graph from parsed paragraphs
"""
global DEBUG, WordNode
graph = nx.DiGraph()
for meta in json_iter:
if DEBUG:
print(meta['graf']) # depends on [control=['if'], data=[]]
for pair in get_tiles(map(WordNode._make, m... |
def create_tenant(self, tenant_id, retentions=None):
"""
Create a tenant. Currently nothing can be set (to be fixed after the master
version of Hawkular-Metrics has fixed implementation.
:param retentions: A set of retention settings, see Hawkular-Metrics documentation for more info
... | def function[create_tenant, parameter[self, tenant_id, retentions]]:
constant[
Create a tenant. Currently nothing can be set (to be fixed after the master
version of Hawkular-Metrics has fixed implementation.
:param retentions: A set of retention settings, see Hawkular-Metrics documenta... | keyword[def] identifier[create_tenant] ( identifier[self] , identifier[tenant_id] , identifier[retentions] = keyword[None] ):
literal[string]
identifier[item] ={ literal[string] : identifier[tenant_id] }
keyword[if] identifier[retentions] keyword[is] keyword[not] keyword[None] :
... | def create_tenant(self, tenant_id, retentions=None):
"""
Create a tenant. Currently nothing can be set (to be fixed after the master
version of Hawkular-Metrics has fixed implementation.
:param retentions: A set of retention settings, see Hawkular-Metrics documentation for more info
... |
def get(self):
'''Get a task from queue when bucket available'''
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
... | def function[get, parameter[self]]:
constant[Get a task from queue when bucket available]
if compare[call[name[self].bucket.get, parameter[]] less[<] constant[1]] begin[:]
return[constant[None]]
variable[now] assign[=] call[name[time].time, parameter[]]
call[name[self].mutex.acqu... | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[bucket] . identifier[get] ()< literal[int] :
keyword[return] keyword[None]
identifier[now] = identifier[time] . identifier[time] ()
identifier[self] . ident... | def get(self):
"""Get a task from queue when bucket available"""
if self.bucket.get() < 1:
return None # depends on [control=['if'], data=[]]
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc() # depends on [control=['try']... |
def items(self):
"""
Returns an iterator over the named bitfields in the structure as
2-tuples of (key, value). Uses a clone so as to only read from
the underlying data once.
"""
temp = self.clone()
return [(f, getattr(temp, f)) for f in iter(self)] | def function[items, parameter[self]]:
constant[
Returns an iterator over the named bitfields in the structure as
2-tuples of (key, value). Uses a clone so as to only read from
the underlying data once.
]
variable[temp] assign[=] call[name[self].clone, parameter[... | keyword[def] identifier[items] ( identifier[self] ):
literal[string]
identifier[temp] = identifier[self] . identifier[clone] ()
keyword[return] [( identifier[f] , identifier[getattr] ( identifier[temp] , identifier[f] )) keyword[for] identifier[f] keyword[in] identifier[iter] ( identifi... | def items(self):
"""
Returns an iterator over the named bitfields in the structure as
2-tuples of (key, value). Uses a clone so as to only read from
the underlying data once.
"""
temp = self.clone()
return [(f, getattr(temp, f)) for f in iter(self)] |
def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):
"""Called when descriptor value was read or updated."""
logger.debug('peripheral_didUpdateValueForDescriptor_error called')
# Stop if there was some kind of error.
if error is not None:
re... | def function[peripheral_didUpdateValueForDescriptor_error_, parameter[self, peripheral, descriptor, error]]:
constant[Called when descriptor value was read or updated.]
call[name[logger].debug, parameter[constant[peripheral_didUpdateValueForDescriptor_error called]]]
if compare[name[error] is_no... | keyword[def] identifier[peripheral_didUpdateValueForDescriptor_error_] ( identifier[self] , identifier[peripheral] , identifier[descriptor] , identifier[error] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[error] keyword[is]... | def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):
"""Called when descriptor value was read or updated."""
logger.debug('peripheral_didUpdateValueForDescriptor_error called')
# Stop if there was some kind of error.
if error is not None:
return # depends on [... |
def sanitize_date(publication_date: str) -> str:
"""Sanitize lots of different date strings into ISO-8601."""
if re1.search(publication_date):
return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d')
if re2.search(publication_date):
return datetime.strptime(publication_da... | def function[sanitize_date, parameter[publication_date]]:
constant[Sanitize lots of different date strings into ISO-8601.]
if call[name[re1].search, parameter[name[publication_date]]] begin[:]
return[call[call[name[datetime].strptime, parameter[name[publication_date], constant[%Y %b %d]]].strfti... | keyword[def] identifier[sanitize_date] ( identifier[publication_date] : identifier[str] )-> identifier[str] :
literal[string]
keyword[if] identifier[re1] . identifier[search] ( identifier[publication_date] ):
keyword[return] identifier[datetime] . identifier[strptime] ( identifier[publication_da... | def sanitize_date(publication_date: str) -> str:
"""Sanitize lots of different date strings into ISO-8601."""
if re1.search(publication_date):
return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d') # depends on [control=['if'], data=[]]
if re2.search(publication_date):
... |
def create_azure_storage_credentials(config, general_options):
# type: (dict, blobxfer.models.options.General) ->
# blobxfer.operations.azure.StorageCredentials
"""Create an Azure StorageCredentials object from configuration
:param dict config: config dict
:param blobxfer.models.options.Gener... | def function[create_azure_storage_credentials, parameter[config, general_options]]:
constant[Create an Azure StorageCredentials object from configuration
:param dict config: config dict
:param blobxfer.models.options.General: general options
:rtype: blobxfer.operations.azure.StorageCredentials
:... | keyword[def] identifier[create_azure_storage_credentials] ( identifier[config] , identifier[general_options] ):
literal[string]
identifier[creds] = identifier[blobxfer] . identifier[operations] . identifier[azure] . identifier[StorageCredentials] ( identifier[general_options] )
identifier[endpoint] ... | def create_azure_storage_credentials(config, general_options):
# type: (dict, blobxfer.models.options.General) ->
# blobxfer.operations.azure.StorageCredentials
'Create an Azure StorageCredentials object from configuration\n :param dict config: config dict\n :param blobxfer.models.options.Gener... |
def build(self, builder):
"""Build XML by appending to builder
:Example:
<FormData FormOID="MH" TransactionType="Update">
"""
params = dict(FormOID=self.formoid)
if self.transaction_type is not None:
params["TransactionType"] = self.transaction_type
... | def function[build, parameter[self, builder]]:
constant[Build XML by appending to builder
:Example:
<FormData FormOID="MH" TransactionType="Update">
]
variable[params] assign[=] call[name[dict], parameter[]]
if compare[name[self].transaction_type is_not constant[None]] b... | keyword[def] identifier[build] ( identifier[self] , identifier[builder] ):
literal[string]
identifier[params] = identifier[dict] ( identifier[FormOID] = identifier[self] . identifier[formoid] )
keyword[if] identifier[self] . identifier[transaction_type] keyword[is] keyword[not] keywor... | def build(self, builder):
"""Build XML by appending to builder
:Example:
<FormData FormOID="MH" TransactionType="Update">
"""
params = dict(FormOID=self.formoid)
if self.transaction_type is not None:
params['TransactionType'] = self.transaction_type # depends on [control=['... |
def publish(self, topic, payload, QoS):
"""
**Description**
Publish a new message to the desired topic with QoS.
**Syntax**
.. code:: python
# Publish a QoS0 message "myPayload" to topic "myTopic"
myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0)
... | def function[publish, parameter[self, topic, payload, QoS]]:
constant[
**Description**
Publish a new message to the desired topic with QoS.
**Syntax**
.. code:: python
# Publish a QoS0 message "myPayload" to topic "myTopic"
myAWSIoTMQTTClient.publish("myTo... | keyword[def] identifier[publish] ( identifier[self] , identifier[topic] , identifier[payload] , identifier[QoS] ):
literal[string]
keyword[return] identifier[self] . identifier[_mqtt_core] . identifier[publish] ( identifier[topic] , identifier[payload] , identifier[QoS] , keyword[False] ) | def publish(self, topic, payload, QoS):
"""
**Description**
Publish a new message to the desired topic with QoS.
**Syntax**
.. code:: python
# Publish a QoS0 message "myPayload" to topic "myTopic"
myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0)
... |
def _load_cpp4(self, filename):
"""Initializes Grid from a CCP4 file."""
ccp4 = CCP4.CCP4()
ccp4.read(filename)
grid, edges = ccp4.histogramdd()
self.__init__(grid=grid, edges=edges, metadata=self.metadata) | def function[_load_cpp4, parameter[self, filename]]:
constant[Initializes Grid from a CCP4 file.]
variable[ccp4] assign[=] call[name[CCP4].CCP4, parameter[]]
call[name[ccp4].read, parameter[name[filename]]]
<ast.Tuple object at 0x7da1b00fb250> assign[=] call[name[ccp4].histogramdd, param... | keyword[def] identifier[_load_cpp4] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[ccp4] = identifier[CCP4] . identifier[CCP4] ()
identifier[ccp4] . identifier[read] ( identifier[filename] )
identifier[grid] , identifier[edges] = identifier[ccp4] . identif... | def _load_cpp4(self, filename):
"""Initializes Grid from a CCP4 file."""
ccp4 = CCP4.CCP4()
ccp4.read(filename)
(grid, edges) = ccp4.histogramdd()
self.__init__(grid=grid, edges=edges, metadata=self.metadata) |
def get_supported(versions=None, noarch=False):
"""Return a list of supported tags for each version specified in
`versions`.
:param versions: a list of string versions, of the form ["33", "32"],
or None. The first version will be assumed to support our ABI.
"""
supported = []
# Version... | def function[get_supported, parameter[versions, noarch]]:
constant[Return a list of supported tags for each version specified in
`versions`.
:param versions: a list of string versions, of the form ["33", "32"],
or None. The first version will be assumed to support our ABI.
]
variabl... | keyword[def] identifier[get_supported] ( identifier[versions] = keyword[None] , identifier[noarch] = keyword[False] ):
literal[string]
identifier[supported] =[]
keyword[if] identifier[versions] keyword[is] keyword[None] :
identifier[versions] =[]
identifier[major] = identifi... | def get_supported(versions=None, noarch=False):
"""Return a list of supported tags for each version specified in
`versions`.
:param versions: a list of string versions, of the form ["33", "32"],
or None. The first version will be assumed to support our ABI.
"""
supported = []
# Versions... |
def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split('\n')]
for idx, line in enumerate(lines):
... | def function[process_tls, parameter[self, data, name]]:
constant[
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
]
variable[ret] assign[=] list[[]]
<ast.Try object at 0x7da18f720130>
return[name[ret]] | keyword[def] identifier[process_tls] ( identifier[self] , identifier[data] , identifier[name] ):
literal[string]
identifier[ret] =[]
keyword[try] :
identifier[lines] =[ identifier[x] . identifier[strip] () keyword[for] identifier[x] keyword[in] identifier[data] . identifier... | def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split('\n')]
for (idx, line) in enumerate(lines):
if line == '':
... |
def _run_somatic(paired, ref_file, target, out_file):
"""Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config
"""
align_bams = paired.tu... | def function[_run_somatic, parameter[paired, ref_file, target, out_file]]:
constant[Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config
... | keyword[def] identifier[_run_somatic] ( identifier[paired] , identifier[ref_file] , identifier[target] , identifier[out_file] ):
literal[string]
identifier[align_bams] = identifier[paired] . identifier[tumor_bam]
keyword[if] identifier[paired] . identifier[normal_bam] :
identifier[align_bam... | def _run_somatic(paired, ref_file, target, out_file):
"""Run somatic calling with octopus, handling both paired and tumor-only cases.
Tweaks for low frequency, tumor only and UMI calling documented in:
https://github.com/luntergroup/octopus/blob/develop/configs/UMI.config
"""
align_bams = paired.tu... |
def _set_statistics_oam(self, v, load=False):
"""
Setter method for statistics_oam, mapped from YANG variable /mpls_state/statistics_oam (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_statistics_oam is considered as a private
method. Backends looking to ... | def function[_set_statistics_oam, parameter[self, v, load]]:
constant[
Setter method for statistics_oam, mapped from YANG variable /mpls_state/statistics_oam (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_statistics_oam is considered as a private
met... | keyword[def] identifier[_set_statistics_oam] ( 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_statistics_oam(self, v, load=False):
"""
Setter method for statistics_oam, mapped from YANG variable /mpls_state/statistics_oam (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_statistics_oam is considered as a private
method. Backends looking to ... |
def get(self, sid):
"""
Constructs a TranscriptionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext
:rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext
"""
... | def function[get, parameter[self, sid]]:
constant[
Constructs a TranscriptionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext
:rtype: twilio.rest.api.v2010.account.transcription.Transcr... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[TranscriptionContext] ( identifier[self] . identifier[_version] , identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[sid] = identifier[sid... | def get(self, sid):
"""
Constructs a TranscriptionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext
:rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext
"""
r... |
def validate(self, folder):
"""Validate files and folders contained in this folder
It validates all of the files and folders contained in this
folder if some observers are interested in them.
"""
for observer in list(self.observers):
observer.validate(folder) | def function[validate, parameter[self, folder]]:
constant[Validate files and folders contained in this folder
It validates all of the files and folders contained in this
folder if some observers are interested in them.
]
for taget[name[observer]] in starred[call[name[list], par... | keyword[def] identifier[validate] ( identifier[self] , identifier[folder] ):
literal[string]
keyword[for] identifier[observer] keyword[in] identifier[list] ( identifier[self] . identifier[observers] ):
identifier[observer] . identifier[validate] ( identifier[folder] ) | def validate(self, folder):
"""Validate files and folders contained in this folder
It validates all of the files and folders contained in this
folder if some observers are interested in them.
"""
for observer in list(self.observers):
observer.validate(folder) # depends on [con... |
def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy):
"""Creates a proxy for a variable.
XXX create and cache nested proxies also here.
"""
# FIXME why not just use gensym here?
proxy_val_name = "PROXY_VAL%d__" % self._proxy_count
self._proxy_count +=... | def function[_make_proxy, parameter[self, varname, parent, constructor]]:
constant[Creates a proxy for a variable.
XXX create and cache nested proxies also here.
]
variable[proxy_val_name] assign[=] binary_operation[constant[PROXY_VAL%d__] <ast.Mod object at 0x7da2590d6920> name[self]._... | keyword[def] identifier[_make_proxy] ( identifier[self] , identifier[varname] , identifier[parent] = keyword[None] , identifier[constructor] = identifier[MlabObjectProxy] ):
literal[string]
identifier[proxy_val_name] = literal[string] % identifier[self] . identifier[_proxy_count]
... | def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy):
"""Creates a proxy for a variable.
XXX create and cache nested proxies also here.
"""
# FIXME why not just use gensym here?
proxy_val_name = 'PROXY_VAL%d__' % self._proxy_count
self._proxy_count += 1
mlabraw.e... |
def init(paths, output, **kwargs):
"""Init data package from list of files.
It will also infer tabular data's schemas from their contents.
"""
dp = goodtables.init_datapackage(paths)
click.secho(
json_module.dumps(dp.descriptor, indent=4),
file=output
)
exit(dp.valid) | def function[init, parameter[paths, output]]:
constant[Init data package from list of files.
It will also infer tabular data's schemas from their contents.
]
variable[dp] assign[=] call[name[goodtables].init_datapackage, parameter[name[paths]]]
call[name[click].secho, parameter[call[nam... | keyword[def] identifier[init] ( identifier[paths] , identifier[output] ,** identifier[kwargs] ):
literal[string]
identifier[dp] = identifier[goodtables] . identifier[init_datapackage] ( identifier[paths] )
identifier[click] . identifier[secho] (
identifier[json_module] . identifier[dumps] ( iden... | def init(paths, output, **kwargs):
"""Init data package from list of files.
It will also infer tabular data's schemas from their contents.
"""
dp = goodtables.init_datapackage(paths)
click.secho(json_module.dumps(dp.descriptor, indent=4), file=output)
exit(dp.valid) |
def multi_plot_time(DataArray, SubSampleN=1, units='s', xlim=None, ylim=None, LabelArray=[], show_fig=True):
"""
plot the time trace for multiple data sets on the same axes.
Parameters
----------
DataArray : array-like
array of DataObject instances for which to plot the PSDs
SubSampleN ... | def function[multi_plot_time, parameter[DataArray, SubSampleN, units, xlim, ylim, LabelArray, show_fig]]:
constant[
plot the time trace for multiple data sets on the same axes.
Parameters
----------
DataArray : array-like
array of DataObject instances for which to plot the PSDs
SubS... | keyword[def] identifier[multi_plot_time] ( identifier[DataArray] , identifier[SubSampleN] = literal[int] , identifier[units] = literal[string] , identifier[xlim] = keyword[None] , identifier[ylim] = keyword[None] , identifier[LabelArray] =[], identifier[show_fig] = keyword[True] ):
literal[string]
identifi... | def multi_plot_time(DataArray, SubSampleN=1, units='s', xlim=None, ylim=None, LabelArray=[], show_fig=True):
"""
plot the time trace for multiple data sets on the same axes.
Parameters
----------
DataArray : array-like
array of DataObject instances for which to plot the PSDs
SubSampleN ... |
def visit_set(self, node):
"""return an astroid.Set node as string"""
return "{%s}" % ", ".join(child.accept(self) for child in node.elts) | def function[visit_set, parameter[self, node]]:
constant[return an astroid.Set node as string]
return[binary_operation[constant[{%s}] <ast.Mod object at 0x7da2590d6920> call[constant[, ].join, parameter[<ast.GeneratorExp object at 0x7da1b1e77ac0>]]]] | keyword[def] identifier[visit_set] ( identifier[self] , identifier[node] ):
literal[string]
keyword[return] literal[string] % literal[string] . identifier[join] ( identifier[child] . identifier[accept] ( identifier[self] ) keyword[for] identifier[child] keyword[in] identifier[node] . identifier... | def visit_set(self, node):
"""return an astroid.Set node as string"""
return '{%s}' % ', '.join((child.accept(self) for child in node.elts)) |
def pad_length(s):
"""
Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string.
"""
padding_chars... | def function[pad_length, parameter[s]]:
constant[
Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded st... | keyword[def] identifier[pad_length] ( identifier[s] ):
literal[string]
identifier[padding_chars] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
... | def pad_length(s):
"""
Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string.
""" # ﹎: CENTRELINE ... |
def promote_owner(self, stream_id, user_id):
''' promote user to owner in stream '''
req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'
req_args = '{ "id": %s }' % user_id
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: ... | def function[promote_owner, parameter[self, stream_id, user_id]]:
constant[ promote user to owner in stream ]
variable[req_hook] assign[=] binary_operation[binary_operation[constant[pod/v1/room/] + name[stream_id]] + constant[/membership/promoteOwner]]
variable[req_args] assign[=] binary_operati... | keyword[def] identifier[promote_owner] ( identifier[self] , identifier[stream_id] , identifier[user_id] ):
literal[string]
identifier[req_hook] = literal[string] + identifier[stream_id] + literal[string]
identifier[req_args] = literal[string] % identifier[user_id]
identifier[sta... | def promote_owner(self, stream_id, user_id):
""" promote user to owner in stream """
req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'
req_args = '{ "id": %s }' % user_id
(status_code, response) = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code... |
def write_patch_file(self, patch_file, lines_to_write):
"""Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: list[str]
... | def function[write_patch_file, parameter[self, patch_file, lines_to_write]]:
constant[Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be
terminated
:type lines_to... | keyword[def] identifier[write_patch_file] ( identifier[self] , identifier[patch_file] , identifier[lines_to_write] ):
literal[string]
keyword[with] identifier[open] ( identifier[patch_file] , literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[writelines] ( ident... | def write_patch_file(self, patch_file, lines_to_write):
"""Write lines_to_write to a the file called patch_file
:param patch_file: file name of the patch to generate
:param lines_to_write: lines to write to the file - they should be
terminated
:type lines_to_write: list[str]
:ret... |
def devicecore(self):
"""Property providing access to the :class:`.DeviceCoreAPI`"""
if self._devicecore_api is None:
self._devicecore_api = self.get_devicecore_api()
return self._devicecore_api | def function[devicecore, parameter[self]]:
constant[Property providing access to the :class:`.DeviceCoreAPI`]
if compare[name[self]._devicecore_api is constant[None]] begin[:]
name[self]._devicecore_api assign[=] call[name[self].get_devicecore_api, parameter[]]
return[name[self]._dev... | keyword[def] identifier[devicecore] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_devicecore_api] keyword[is] keyword[None] :
identifier[self] . identifier[_devicecore_api] = identifier[self] . identifier[get_devicecore_api] ()
keyword[ret... | def devicecore(self):
"""Property providing access to the :class:`.DeviceCoreAPI`"""
if self._devicecore_api is None:
self._devicecore_api = self.get_devicecore_api() # depends on [control=['if'], data=[]]
return self._devicecore_api |
def stream(self, muted=values.unset, hold=values.unset, coaching=values.unset,
limit=None, page_size=None):
"""
Streams ParticipantInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached... | def function[stream, parameter[self, muted, hold, coaching, limit, page_size]]:
constant[
Streams ParticipantInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as... | keyword[def] identifier[stream] ( identifier[self] , identifier[muted] = identifier[values] . identifier[unset] , identifier[hold] = identifier[values] . identifier[unset] , identifier[coaching] = identifier[values] . identifier[unset] ,
identifier[limit] = keyword[None] , identifier[page_size] = keyword[None] ):
... | def stream(self, muted=values.unset, hold=values.unset, coaching=values.unset, limit=None, page_size=None):
"""
Streams ParticipantInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The resul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.