code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def registerIcon(self, fileName, glyph, isOpen=None):
""" Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
:param glyph: a s... | def function[registerIcon, parameter[self, fileName, glyph, isOpen]]:
constant[ Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
... | keyword[def] identifier[registerIcon] ( identifier[self] , identifier[fileName] , identifier[glyph] , identifier[isOpen] = keyword[None] ):
literal[string]
identifier[check_class] ( identifier[isOpen] , identifier[bool] , identifier[allow_none] = keyword[True] )
keyword[if] identifier[fi... | def registerIcon(self, fileName, glyph, isOpen=None):
""" Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
:param glyph: a strin... |
def principal_direction_extent(points):
'''Calculate the extent of a set of 3D points.
The extent is defined as the maximum distance between
the projections on the principal directions of the covariance matrix
of the points.
Parameter:
points : a 2D numpy array of points
Returns:
ext... | def function[principal_direction_extent, parameter[points]]:
constant[Calculate the extent of a set of 3D points.
The extent is defined as the maximum distance between
the projections on the principal directions of the covariance matrix
of the points.
Parameter:
points : a 2D numpy array of... | keyword[def] identifier[principal_direction_extent] ( identifier[points] ):
literal[string]
identifier[points] = identifier[np] . identifier[copy] ( identifier[points] )
identifier[points] -= identifier[np] . identifier[mean] ( identifier[points] , identifier[axis] = literal[int] )
ide... | def principal_direction_extent(points):
"""Calculate the extent of a set of 3D points.
The extent is defined as the maximum distance between
the projections on the principal directions of the covariance matrix
of the points.
Parameter:
points : a 2D numpy array of points
Returns:
ext... |
def search(d, recursive=True, store_meta=True):
'''
Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
['1.2.340.500067... | def function[search, parameter[d, recursive, store_meta]]:
constant[
Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
... | keyword[def] identifier[search] ( identifier[d] , identifier[recursive] = keyword[True] , identifier[store_meta] = keyword[True] ):
literal[string]
identifier[scans] = identifier[col] . identifier[defaultdict] ( keyword[lambda] : identifier[col] . identifier[defaultdict] ( keyword[lambda] : identifier... | def search(d, recursive=True, store_meta=True):
"""
Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
['1.2.340.500067... |
def fixup_comments(self):
"""Remove any style bytes that are marked as commented but have no
comment, and add any style bytes where there's a comment but it isn't
marked in the style data.
This happens on the base data, so only need to do this on one segment
that uses this base ... | def function[fixup_comments, parameter[self]]:
constant[Remove any style bytes that are marked as commented but have no
comment, and add any style bytes where there's a comment but it isn't
marked in the style data.
This happens on the base data, so only need to do this on one segment
... | keyword[def] identifier[fixup_comments] ( identifier[self] ):
literal[string]
identifier[style_base] = identifier[self] . identifier[rawdata] . identifier[style_base]
identifier[comment_text_indexes] = identifier[np] . identifier[asarray] ( identifier[list] ( identifier[self] . identifier... | def fixup_comments(self):
"""Remove any style bytes that are marked as commented but have no
comment, and add any style bytes where there's a comment but it isn't
marked in the style data.
This happens on the base data, so only need to do this on one segment
that uses this base data... |
def _verify_include_files_used(self, file_uses, included_files):
"""Find all #include files that are unnecessary."""
for include_file, use in file_uses.items():
if not use & USES_DECLARATION:
node, module = included_files[include_file]
if module.ast_list is no... | def function[_verify_include_files_used, parameter[self, file_uses, included_files]]:
constant[Find all #include files that are unnecessary.]
for taget[tuple[[<ast.Name object at 0x7da1b0b9d360>, <ast.Name object at 0x7da1b0b9cf10>]]] in starred[call[name[file_uses].items, parameter[]]] begin[:]
... | keyword[def] identifier[_verify_include_files_used] ( identifier[self] , identifier[file_uses] , identifier[included_files] ):
literal[string]
keyword[for] identifier[include_file] , identifier[use] keyword[in] identifier[file_uses] . identifier[items] ():
keyword[if] keyword[not] ... | def _verify_include_files_used(self, file_uses, included_files):
"""Find all #include files that are unnecessary."""
for (include_file, use) in file_uses.items():
if not use & USES_DECLARATION:
(node, module) = included_files[include_file]
if module.ast_list is not None:
... |
def index_scan_prefix_and_return_key(self, idx_name, val_prefix):
'''Returns ids that match a prefix of an indexed value, and the
specific key that matched the search prefix.
Returns a generator of (index key, content identifier) that
have an entry in the index ``idx_name`` with prefix
... | def function[index_scan_prefix_and_return_key, parameter[self, idx_name, val_prefix]]:
constant[Returns ids that match a prefix of an indexed value, and the
specific key that matched the search prefix.
Returns a generator of (index key, content identifier) that
have an entry in the inde... | keyword[def] identifier[index_scan_prefix_and_return_key] ( identifier[self] , identifier[idx_name] , identifier[val_prefix] ):
literal[string]
keyword[return] identifier[self] . identifier[_index_scan_prefix_impl] (
identifier[idx_name] , identifier[val_prefix] , keyword[lambda] identif... | def index_scan_prefix_and_return_key(self, idx_name, val_prefix):
"""Returns ids that match a prefix of an indexed value, and the
specific key that matched the search prefix.
Returns a generator of (index key, content identifier) that
have an entry in the index ``idx_name`` with prefix
... |
def get_celery_app(name=None, **kwargs): # nocv
# pylint: disable=import-error
'''
Function to return celery-app. Works only if celery installed.
:param name: Application name
:param kwargs: overrided env-settings
:return: Celery-app object
'''
from celery import Celery
prepare_envi... | def function[get_celery_app, parameter[name]]:
constant[
Function to return celery-app. Works only if celery installed.
:param name: Application name
:param kwargs: overrided env-settings
:return: Celery-app object
]
from relative_module[celery] import module[Celery]
call[name[pr... | keyword[def] identifier[get_celery_app] ( identifier[name] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[celery] keyword[import] identifier[Celery]
identifier[prepare_environment] (** identifier[kwargs] )
identifier[name] = identifier[name] keyword[or] ... | def get_celery_app(name=None, **kwargs): # nocv
# pylint: disable=import-error
'\n Function to return celery-app. Works only if celery installed.\n :param name: Application name\n :param kwargs: overrided env-settings\n :return: Celery-app object\n '
from celery import Celery
prepare_env... |
def _format_explain(self):
""" Format the results of an EXPLAIN """
lines = []
for (command, kwargs) in self._call_list:
lines.append(command + " " + pformat(kwargs))
return "\n".join(lines) | def function[_format_explain, parameter[self]]:
constant[ Format the results of an EXPLAIN ]
variable[lines] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b26af370>, <ast.Name object at 0x7da1b26ae4d0>]]] in starred[name[self]._call_list] begin[:]
call[name[lines]... | keyword[def] identifier[_format_explain] ( identifier[self] ):
literal[string]
identifier[lines] =[]
keyword[for] ( identifier[command] , identifier[kwargs] ) keyword[in] identifier[self] . identifier[_call_list] :
identifier[lines] . identifier[append] ( identifier[command] ... | def _format_explain(self):
""" Format the results of an EXPLAIN """
lines = []
for (command, kwargs) in self._call_list:
lines.append(command + ' ' + pformat(kwargs)) # depends on [control=['for'], data=[]]
return '\n'.join(lines) |
def get_state_model_by_path(self, path):
"""Returns the `StateModel` for the given `path`
Searches a `StateModel` in the state machine, who's path is given by `path`.
:param str path: Path of the searched state
:return: The state with that path
:rtype: StateMo... | def function[get_state_model_by_path, parameter[self, path]]:
constant[Returns the `StateModel` for the given `path`
Searches a `StateModel` in the state machine, who's path is given by `path`.
:param str path: Path of the searched state
:return: The state with that p... | keyword[def] identifier[get_state_model_by_path] ( identifier[self] , identifier[path] ):
literal[string]
identifier[path_elements] = identifier[path] . identifier[split] ( literal[string] )
identifier[path_elements] . identifier[pop] ( literal[int] )
identifier[current_state_mode... | def get_state_model_by_path(self, path):
"""Returns the `StateModel` for the given `path`
Searches a `StateModel` in the state machine, who's path is given by `path`.
:param str path: Path of the searched state
:return: The state with that path
:rtype: StateModel
... |
def addOptionString(self, name, value, append=False):
"""
.. _addOptionString:
Add a string option.
:param name: The name of the option. Option names are case insensitive and must be unique.
:type name: str
:param value: The value of the option.
:type value: st... | def function[addOptionString, parameter[self, name, value, append]]:
constant[
.. _addOptionString:
Add a string option.
:param name: The name of the option. Option names are case insensitive and must be unique.
:type name: str
:param value: The value of the option.
... | keyword[def] identifier[addOptionString] ( identifier[self] , identifier[name] , identifier[value] , identifier[append] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[options] . identifier[AddOptionString] (
identifier[str_to_cppstr] ( identifier[name] )... | def addOptionString(self, name, value, append=False):
"""
.. _addOptionString:
Add a string option.
:param name: The name of the option. Option names are case insensitive and must be unique.
:type name: str
:param value: The value of the option.
:type value: str
... |
def draw_tree(node,
child_iter=lambda n: n.children,
text_str=str):
"""Support asciitree 0.2 API.
This function solely exist to not break old code (using asciitree 0.2).
Its use is deprecated."""
return LeftAligned(traverse=Traversal(get_text=text_str,
... | def function[draw_tree, parameter[node, child_iter, text_str]]:
constant[Support asciitree 0.2 API.
This function solely exist to not break old code (using asciitree 0.2).
Its use is deprecated.]
return[call[call[name[LeftAligned], parameter[]], parameter[name[node]]]] | keyword[def] identifier[draw_tree] ( identifier[node] ,
identifier[child_iter] = keyword[lambda] identifier[n] : identifier[n] . identifier[children] ,
identifier[text_str] = identifier[str] ):
literal[string]
keyword[return] identifier[LeftAligned] ( identifier[traverse] = identifier[Traversal] ( iden... | def draw_tree(node, child_iter=lambda n: n.children, text_str=str):
"""Support asciitree 0.2 API.
This function solely exist to not break old code (using asciitree 0.2).
Its use is deprecated."""
return LeftAligned(traverse=Traversal(get_text=text_str, get_children=child_iter), draw=LegacyStyle())(node... |
def initialize_communities_bucket():
"""Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
"""
bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID'])
if Bucket.query.get(bucket_id):
raise FilesException("Bucket with UUID {} already exists."... | def function[initialize_communities_bucket, parameter[]]:
constant[Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
]
variable[bucket_id] assign[=] call[name[UUID], parameter[call[name[current_app].config][constant[COMMUNITIES_BUCKET_UUID]]]]
i... | keyword[def] identifier[initialize_communities_bucket] ():
literal[string]
identifier[bucket_id] = identifier[UUID] ( identifier[current_app] . identifier[config] [ literal[string] ])
keyword[if] identifier[Bucket] . identifier[query] . identifier[get] ( identifier[bucket_id] ):
keyword[rai... | def initialize_communities_bucket():
"""Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
"""
bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID'])
if Bucket.query.get(bucket_id):
raise FilesException('Bucket with UUID {} already exists.'.... |
def gene_ids_of_gene_name(self, gene_name):
"""
What are the gene IDs associated with a given gene name?
(due to copy events, there might be multiple genes per name)
"""
results = self._query_gene_ids("gene_name", gene_name)
if len(results) == 0:
raise ValueEr... | def function[gene_ids_of_gene_name, parameter[self, gene_name]]:
constant[
What are the gene IDs associated with a given gene name?
(due to copy events, there might be multiple genes per name)
]
variable[results] assign[=] call[name[self]._query_gene_ids, parameter[constant[gene_... | keyword[def] identifier[gene_ids_of_gene_name] ( identifier[self] , identifier[gene_name] ):
literal[string]
identifier[results] = identifier[self] . identifier[_query_gene_ids] ( literal[string] , identifier[gene_name] )
keyword[if] identifier[len] ( identifier[results] )== literal[int] ... | def gene_ids_of_gene_name(self, gene_name):
"""
What are the gene IDs associated with a given gene name?
(due to copy events, there might be multiple genes per name)
"""
results = self._query_gene_ids('gene_name', gene_name)
if len(results) == 0:
raise ValueError('Gene name n... |
def logical_or(lhs, rhs):
"""Returns the result of element-wise **logical or** comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements or rhs elements
are true, otherwise return 0(false).
Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or... | def function[logical_or, parameter[lhs, rhs]]:
constant[Returns the result of element-wise **logical or** comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements or rhs elements
are true, otherwise return 0(false).
Equivalent to ``lhs or rhs`` a... | keyword[def] identifier[logical_or] ( identifier[lhs] , identifier[rhs] ):
literal[string]
keyword[return] identifier[_ufunc_helper] (
identifier[lhs] ,
identifier[rhs] ,
identifier[op] . identifier[broadcast_logical_or] ,
keyword[lambda] identifier[x] , identifier[y] : literal[i... | def logical_or(lhs, rhs):
"""Returns the result of element-wise **logical or** comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements or rhs elements
are true, otherwise return 0(false).
Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or... |
def spectral_entropy(X, Band, Fs, Power_Ratio=None):
"""Compute spectral entropy of a time series from either two cases below:
1. X, the time series (default)
2. Power_Ratio, a list of normalized signal power in a set of frequency
bins defined in Band (if Power_Ratio is provided, recommended to speed up... | def function[spectral_entropy, parameter[X, Band, Fs, Power_Ratio]]:
constant[Compute spectral entropy of a time series from either two cases below:
1. X, the time series (default)
2. Power_Ratio, a list of normalized signal power in a set of frequency
bins defined in Band (if Power_Ratio is provide... | keyword[def] identifier[spectral_entropy] ( identifier[X] , identifier[Band] , identifier[Fs] , identifier[Power_Ratio] = keyword[None] ):
literal[string]
keyword[if] identifier[Power_Ratio] keyword[is] keyword[None] :
identifier[Power] , identifier[Power_Ratio] = identifier[bin_power] ( ident... | def spectral_entropy(X, Band, Fs, Power_Ratio=None):
"""Compute spectral entropy of a time series from either two cases below:
1. X, the time series (default)
2. Power_Ratio, a list of normalized signal power in a set of frequency
bins defined in Band (if Power_Ratio is provided, recommended to speed up... |
def get_child_bin_ids(self, bin_id):
"""Gets the child ``Ids`` of the given bin.
arg: bin_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bin
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
rais... | def function[get_child_bin_ids, parameter[self, bin_id]]:
constant[Gets the child ``Ids`` of the given bin.
arg: bin_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bin
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id... | keyword[def] identifier[get_child_bin_ids] ( identifier[self] , identifier[bin_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_catalog_sessi... | def get_child_bin_ids(self, bin_id):
"""Gets the child ``Ids`` of the given bin.
arg: bin_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bin
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
raise: ... |
def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult o... | def function[discover, parameter[uri]]:
constant[Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
... | keyword[def] identifier[discover] ( identifier[uri] ):
literal[string]
identifier[result] = identifier[DiscoveryResult] ( identifier[uri] )
identifier[resp] = identifier[fetchers] . identifier[fetch] ( identifier[uri] , identifier[headers] ={ literal[string] : identifier[YADIS_ACCEPT_HEADER] })
k... | def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult o... |
def time_limited(limit_seconds, iterable):
"""
Yield items from *iterable* until *limit_seconds* have passed.
>>> from time import sleep
>>> def generator():
... yield 1
... yield 2
... sleep(0.2)
... yield 3
>>> iterable = generator()
>>> list(time_limited(0.1, ... | def function[time_limited, parameter[limit_seconds, iterable]]:
constant[
Yield items from *iterable* until *limit_seconds* have passed.
>>> from time import sleep
>>> def generator():
... yield 1
... yield 2
... sleep(0.2)
... yield 3
>>> iterable = generator()
... | keyword[def] identifier[time_limited] ( identifier[limit_seconds] , identifier[iterable] ):
literal[string]
keyword[if] identifier[limit_seconds] < literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[start_time] = identifier[monotonic] ()
keyword[for] ... | def time_limited(limit_seconds, iterable):
"""
Yield items from *iterable* until *limit_seconds* have passed.
>>> from time import sleep
>>> def generator():
... yield 1
... yield 2
... sleep(0.2)
... yield 3
>>> iterable = generator()
>>> list(time_limited(0.1, ... |
def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
gold_labels: List[str]):
""... | def function[write_to_conll_eval_file, parameter[prediction_file, gold_file, verb_index, sentence, prediction, gold_labels]]:
constant[
Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
Parameters
----------
pr... | keyword[def] identifier[write_to_conll_eval_file] ( identifier[prediction_file] : identifier[TextIO] ,
identifier[gold_file] : identifier[TextIO] ,
identifier[verb_index] : identifier[Optional] [ identifier[int] ],
identifier[sentence] : identifier[List] [ identifier[str] ],
identifier[prediction] : identifier[Li... | def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]):
"""
Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
... |
async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
... | <ast.AsyncFunctionDef object at 0x7da18f58c6a0> | keyword[async] keyword[def] identifier[increment] ( identifier[self] , identifier[key] , identifier[delta] = literal[int] , identifier[namespace] = keyword[None] , identifier[_conn] = keyword[None] ):
literal[string]
identifier[start] = identifier[time] . identifier[monotonic] ()
identifi... | async def increment(self, key, delta=1, namespace=None, _conn=None):
"""
Increments value stored in key by delta (can be negative). If key doesn't
exist, it creates the key with delta as value.
:param key: str key to check
:param delta: int amount to increment/decrement
:par... |
def save_estimations(file_struct, times, labels, boundaries_id, labels_id,
**params):
"""Saves the segment estimations in a JAMS file.
Parameters
----------
file_struct : FileStruct
Object with the different file paths of the current file.
times : np.array or list
... | def function[save_estimations, parameter[file_struct, times, labels, boundaries_id, labels_id]]:
constant[Saves the segment estimations in a JAMS file.
Parameters
----------
file_struct : FileStruct
Object with the different file paths of the current file.
times : np.array or list
... | keyword[def] identifier[save_estimations] ( identifier[file_struct] , identifier[times] , identifier[labels] , identifier[boundaries_id] , identifier[labels_id] ,
** identifier[params] ):
literal[string]
identifier[params] . identifier[pop] ( literal[string] , keyword[None] )
identifier[dur... | def save_estimations(file_struct, times, labels, boundaries_id, labels_id, **params):
"""Saves the segment estimations in a JAMS file.
Parameters
----------
file_struct : FileStruct
Object with the different file paths of the current file.
times : np.array or list
Estimated boundary... |
def set_global(self, name, value):
"""Set a global variable.
Equivalent to ``! global`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable.
"""
if val... | def function[set_global, parameter[self, name, value]]:
constant[Set a global variable.
Equivalent to ``! global`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable.... | keyword[def] identifier[set_global] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_global] :
k... | def set_global(self, name, value):
"""Set a global variable.
Equivalent to ``! global`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable.
"""
if value is No... |
def toYearFraction(date):
"""Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal
year.
Parameters
==========
date : :class:`datetime.date` or :class:`datetime.datetime`
Returns
=======
year : float
Decimal year
Notes
=====
The algorithm is take... | def function[toYearFraction, parameter[date]]:
constant[Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal
year.
Parameters
==========
date : :class:`datetime.date` or :class:`datetime.datetime`
Returns
=======
year : float
Decimal year
Notes
... | keyword[def] identifier[toYearFraction] ( identifier[date] ):
literal[string]
keyword[def] identifier[sinceEpoch] ( identifier[date] ):
literal[string]
keyword[return] identifier[time] . identifier[mktime] ( identifier[date] . identifier[timetuple] ())
identifier[year] = identifi... | def toYearFraction(date):
"""Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal
year.
Parameters
==========
date : :class:`datetime.date` or :class:`datetime.datetime`
Returns
=======
year : float
Decimal year
Notes
=====
The algorithm is take... |
def get_last_month_range():
""" Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively.
"""
today = date.today()
# Get the last day for the previous month.
... | def function[get_last_month_range, parameter[]]:
constant[ Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively.
]
variable[today] assign[=] call[name[da... | keyword[def] identifier[get_last_month_range] ():
literal[string]
identifier[today] = identifier[date] . identifier[today] ()
identifier[end_of_last_month] = identifier[snap_to_beginning_of_month] ( identifier[today] )- identifier[timedelta] ( identifier[days] = literal[int] )
identifier[sta... | def get_last_month_range():
""" Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively.
"""
today = date.today()
# Get the last day for the previous month.
... |
def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.strin... | def function[has_aligned_reads, parameter[align_bam, region]]:
constant[Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
]
import module[pybedtools]
if compare[name[region] is... | keyword[def] identifier[has_aligned_reads] ( identifier[align_bam] , identifier[region] = keyword[None] ):
literal[string]
keyword[import] identifier[pybedtools]
keyword[if] identifier[region] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[isinstance] ( identifier[regi... | def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.strin... |
def validate_body(schema):
"""Validate the body of incoming requests for a flask view.
An example usage might look like this::
from snapstore_schemas import validate_body
@validate_body({
'type': 'array',
'items': {
'type': 'object',
'p... | def function[validate_body, parameter[schema]]:
constant[Validate the body of incoming requests for a flask view.
An example usage might look like this::
from snapstore_schemas import validate_body
@validate_body({
'type': 'array',
'items': {
'type... | keyword[def] identifier[validate_body] ( identifier[schema] ):
literal[string]
identifier[location] = identifier[get_callsite_location] ()
keyword[def] identifier[decorator] ( identifier[fn] ):
identifier[validate_schema] ( identifier[schema] )
identifier[wrapper] = identifier[wrap... | def validate_body(schema):
"""Validate the body of incoming requests for a flask view.
An example usage might look like this::
from snapstore_schemas import validate_body
@validate_body({
'type': 'array',
'items': {
'type': 'object',
'p... |
def user_upsert(self, domain, userid, password=None, roles=None, name=None):
"""
Upsert a user in the cluster
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID
:param password: The user password
:param roles: A list of roles. A ... | def function[user_upsert, parameter[self, domain, userid, password, roles, name]]:
constant[
Upsert a user in the cluster
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID
:param password: The user password
:param roles: A list ... | keyword[def] identifier[user_upsert] ( identifier[self] , identifier[domain] , identifier[userid] , identifier[password] = keyword[None] , identifier[roles] = keyword[None] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[roles] keyword[or] keyword[not] ... | def user_upsert(self, domain, userid, password=None, roles=None, name=None):
"""
Upsert a user in the cluster
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID
:param password: The user password
:param roles: A list of roles. A role... |
def to_block(self, env, parent=None):
"""Convert the transient block to a :class:`ethereum.blocks.Block`"""
return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent) | def function[to_block, parameter[self, env, parent]]:
constant[Convert the transient block to a :class:`ethereum.blocks.Block`]
return[call[name[Block], parameter[name[self].header, name[self].transaction_list, name[self].uncles]]] | keyword[def] identifier[to_block] ( identifier[self] , identifier[env] , identifier[parent] = keyword[None] ):
literal[string]
keyword[return] identifier[Block] ( identifier[self] . identifier[header] , identifier[self] . identifier[transaction_list] , identifier[self] . identifier[uncles] , ident... | def to_block(self, env, parent=None):
"""Convert the transient block to a :class:`ethereum.blocks.Block`"""
return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent) |
def pull_status(self, param=None, must=[APIKEY]):
'''获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
'''
param = {} if param is N... | def function[pull_status, parameter[self, param, must]]:
constant[获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
]
variable[para... | keyword[def] identifier[pull_status] ( identifier[self] , identifier[param] = keyword[None] , identifier[must] =[ identifier[APIKEY] ]):
literal[string]
identifier[param] ={} keyword[if] identifier[param] keyword[is] keyword[None] keyword[else] identifier[param]
identifier[r] = ident... | def pull_status(self, param=None, must=[APIKEY]):
"""获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
"""
param = {} if param is None else... |
def extend(self, records):
"""
records - MUST HAVE FORM OF
[{"value":value}, ... {"value":value}] OR
[{"json":json}, ... {"json":json}]
OPTIONAL "id" PROPERTY IS ALSO ACCEPTED
"""
if self.settings.read_only:
Log.error("Index opened in read ... | def function[extend, parameter[self, records]]:
constant[
records - MUST HAVE FORM OF
[{"value":value}, ... {"value":value}] OR
[{"json":json}, ... {"json":json}]
OPTIONAL "id" PROPERTY IS ALSO ACCEPTED
]
if name[self].settings.read_only begin[:]
... | keyword[def] identifier[extend] ( identifier[self] , identifier[records] ):
literal[string]
keyword[if] identifier[self] . identifier[settings] . identifier[read_only] :
identifier[Log] . identifier[error] ( literal[string] )
identifier[lines] =[]
keyword[try] :
... | def extend(self, records):
"""
records - MUST HAVE FORM OF
[{"value":value}, ... {"value":value}] OR
[{"json":json}, ... {"json":json}]
OPTIONAL "id" PROPERTY IS ALSO ACCEPTED
"""
if self.settings.read_only:
Log.error('Index opened in read only mode, n... |
def _parse_process_name(name_str):
"""Parses the process string and returns the process name and its
directives
Process strings my contain directive information with the following
syntax::
proc_name={'directive':'val'}
This method parses this string and returns the... | def function[_parse_process_name, parameter[name_str]]:
constant[Parses the process string and returns the process name and its
directives
Process strings my contain directive information with the following
syntax::
proc_name={'directive':'val'}
This method parses ... | keyword[def] identifier[_parse_process_name] ( identifier[name_str] ):
literal[string]
identifier[directives] = keyword[None]
identifier[fields] = identifier[name_str] . identifier[split] ( literal[string] )
identifier[process_name] = identifier[fields] [ literal[int] ]
... | def _parse_process_name(name_str):
"""Parses the process string and returns the process name and its
directives
Process strings my contain directive information with the following
syntax::
proc_name={'directive':'val'}
This method parses this string and returns the pro... |
def function_trace(function_name):
"""
Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools.
"""
if newrelic:
nr_transaction = newrelic.agent.current_transaction()
with newrelic.agent.FunctionTrace(nr_transaction, function_name):
... | def function[function_trace, parameter[function_name]]:
constant[
Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools.
]
if name[newrelic] begin[:]
variable[nr_transaction] assign[=] call[name[newrelic].agent.current_transacti... | keyword[def] identifier[function_trace] ( identifier[function_name] ):
literal[string]
keyword[if] identifier[newrelic] :
identifier[nr_transaction] = identifier[newrelic] . identifier[agent] . identifier[current_transaction] ()
keyword[with] identifier[newrelic] . identifier[agent] . i... | def function_trace(function_name):
"""
Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools.
"""
if newrelic:
nr_transaction = newrelic.agent.current_transaction()
with newrelic.agent.FunctionTrace(nr_transaction, function_name):
... |
def finish_displayhook(self):
"""Finish up all displayhook activities."""
sys.stdout.flush()
sys.stderr.flush()
self.session.send(self.pub_socket, self.msg, ident=self.topic)
self.msg = None | def function[finish_displayhook, parameter[self]]:
constant[Finish up all displayhook activities.]
call[name[sys].stdout.flush, parameter[]]
call[name[sys].stderr.flush, parameter[]]
call[name[self].session.send, parameter[name[self].pub_socket, name[self].msg]]
name[self].msg as... | keyword[def] identifier[finish_displayhook] ( identifier[self] ):
literal[string]
identifier[sys] . identifier[stdout] . identifier[flush] ()
identifier[sys] . identifier[stderr] . identifier[flush] ()
identifier[self] . identifier[session] . identifier[send] ( identifier[self] . ... | def finish_displayhook(self):
"""Finish up all displayhook activities."""
sys.stdout.flush()
sys.stderr.flush()
self.session.send(self.pub_socket, self.msg, ident=self.topic)
self.msg = None |
def expect_column_values_to_be_decreasing(self,
column,
strictly=None,
parse_strings_as_datetimes=None,
mostly=None,
... | def function[expect_column_values_to_be_decreasing, parameter[self, column, strictly, parse_strings_as_datetimes, mostly, result_format, include_config, catch_exceptions, meta]]:
constant[Expect column values to be decreasing.
By default, this expectation only works for numeric or datetime data.
... | keyword[def] identifier[expect_column_values_to_be_decreasing] ( identifier[self] ,
identifier[column] ,
identifier[strictly] = keyword[None] ,
identifier[parse_strings_as_datetimes] = keyword[None] ,
identifier[mostly] = keyword[None] ,
identifier[result_format] = keyword[None] , identifier[include_config] = ke... | def expect_column_values_to_be_decreasing(self, column, strictly=None, parse_strings_as_datetimes=None, mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None):
"""Expect column values to be decreasing.
By default, this expectation only works for numeric or datetime data.
... |
def cyclic_time_shift(self, dt):
"""Shift the data and timestamps by a given number of seconds
Shift the data and timestamps in the time domain a given number of
seconds. To just change the time stamps, do ts.start_time += dt.
The time shift may be smaller than the intrinsic sample ra... | def function[cyclic_time_shift, parameter[self, dt]]:
constant[Shift the data and timestamps by a given number of seconds
Shift the data and timestamps in the time domain a given number of
seconds. To just change the time stamps, do ts.start_time += dt.
The time shift may be smaller t... | keyword[def] identifier[cyclic_time_shift] ( identifier[self] , identifier[dt] ):
literal[string]
keyword[from] identifier[pycbc] . identifier[waveform] keyword[import] identifier[apply_fseries_time_shift]
identifier[data] = identifier[apply_fseries_time_shift] ( identifier[self] , ide... | def cyclic_time_shift(self, dt):
"""Shift the data and timestamps by a given number of seconds
Shift the data and timestamps in the time domain a given number of
seconds. To just change the time stamps, do ts.start_time += dt.
The time shift may be smaller than the intrinsic sample rate o... |
def by_organizations(self, field=None):
"""
Used to seggregate the data acording to organizations. This method
pops the latest aggregation from the self.aggregations dict and
adds it as a nested aggregation under itself
:param field: the field to create the parent agg (optional)... | def function[by_organizations, parameter[self, field]]:
constant[
Used to seggregate the data acording to organizations. This method
pops the latest aggregation from the self.aggregations dict and
adds it as a nested aggregation under itself
:param field: the field to create the... | keyword[def] identifier[by_organizations] ( identifier[self] , identifier[field] = keyword[None] ):
literal[string]
identifier[agg_field] = identifier[field] keyword[if] identifier[field] keyword[else] literal[string]
identifier[agg_key] = literal[string] + identifier[agg_fi... | def by_organizations(self, field=None):
"""
Used to seggregate the data acording to organizations. This method
pops the latest aggregation from the self.aggregations dict and
adds it as a nested aggregation under itself
:param field: the field to create the parent agg (optional)
... |
def PublishSystem(self,
fromUserId,
toUserId,
objectName,
content,
pushContent=None,
pushData=None,
isPersisted=None,
isCounted=None):
"... | def function[PublishSystem, parameter[self, fromUserId, toUserId, objectName, content, pushContent, pushData, isPersisted, isCounted]]:
constant[
发送系统消息方法(一个用户向一个或多个用户发送系统消息,单条消息最大 128k,会话类型为 SYSTEM。每秒钟最多发送 100 条消息,每次最多同时向 100 人发送,如:一次发送 100 人时,示为 100 条消息。) 方法
@param fromUserId:发送人用户 Id。(必传)
... | keyword[def] identifier[PublishSystem] ( identifier[self] ,
identifier[fromUserId] ,
identifier[toUserId] ,
identifier[objectName] ,
identifier[content] ,
identifier[pushContent] = keyword[None] ,
identifier[pushData] = keyword[None] ,
identifier[isPersisted] = keyword[None] ,
identifier[isCounted] = keyword[... | def PublishSystem(self, fromUserId, toUserId, objectName, content, pushContent=None, pushData=None, isPersisted=None, isCounted=None):
"""
发送系统消息方法(一个用户向一个或多个用户发送系统消息,单条消息最大 128k,会话类型为 SYSTEM。每秒钟最多发送 100 条消息,每次最多同时向 100 人发送,如:一次发送 100 人时,示为 100 条消息。) 方法
@param fromUserId:发送人用户 Id。(必传)
@para... |
def loadb(b):
"""Deserialize ``b`` (instance of ``bytes``) to a Python object."""
assert isinstance(b, (bytes, bytearray))
return std_json.loads(b.decode('utf-8')) | def function[loadb, parameter[b]]:
constant[Deserialize ``b`` (instance of ``bytes``) to a Python object.]
assert[call[name[isinstance], parameter[name[b], tuple[[<ast.Name object at 0x7da20e955330>, <ast.Name object at 0x7da20e954d30>]]]]]
return[call[name[std_json].loads, parameter[call[name[b].decode... | keyword[def] identifier[loadb] ( identifier[b] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[b] ,( identifier[bytes] , identifier[bytearray] ))
keyword[return] identifier[std_json] . identifier[loads] ( identifier[b] . identifier[decode] ( literal[string] )) | def loadb(b):
"""Deserialize ``b`` (instance of ``bytes``) to a Python object."""
assert isinstance(b, (bytes, bytearray))
return std_json.loads(b.decode('utf-8')) |
def pcolor_axes(array, px_to_units=px_to_units):
"""
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
"""
# ======================================
# Coords need to be +1 larg... | def function[pcolor_axes, parameter[array, px_to_units]]:
constant[
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
]
variable[x_size] assign[=] binary_operation[call[na... | keyword[def] identifier[pcolor_axes] ( identifier[array] , identifier[px_to_units] = identifier[px_to_units] ):
literal[string]
identifier[x_size] = identifier[array] . identifier[shape] [ literal[int] ]+ literal[int]
identifier[y_size] = identifier[array] . identifier[shape] [ literal... | def pcolor_axes(array, px_to_units=px_to_units):
"""
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
"""
# ======================================
# Coords need to be +1 larg... |
def gradient(self):
"""Gradient operator of the functional."""
try:
op_to_return = self.functional.gradient
except NotImplementedError:
raise NotImplementedError(
'`self.functional.gradient` is not implemented for '
'`self.functional` {}'.f... | def function[gradient, parameter[self]]:
constant[Gradient operator of the functional.]
<ast.Try object at 0x7da1b20bf5b0>
variable[op_to_return] assign[=] binary_operation[name[op_to_return] - call[name[ConstantOperator], parameter[name[self].subgrad]]]
return[name[op_to_return]] | keyword[def] identifier[gradient] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[op_to_return] = identifier[self] . identifier[functional] . identifier[gradient]
keyword[except] identifier[NotImplementedError] :
keyword[raise] identifier[NotImp... | def gradient(self):
"""Gradient operator of the functional."""
try:
op_to_return = self.functional.gradient # depends on [control=['try'], data=[]]
except NotImplementedError:
raise NotImplementedError('`self.functional.gradient` is not implemented for `self.functional` {}'.format(self.func... |
def tryload(self, cfgstr=None, on_error='raise'):
"""
Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the cache
... | def function[tryload, parameter[self, cfgstr, on_error]]:
constant[
Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the ca... | keyword[def] identifier[tryload] ( identifier[self] , identifier[cfgstr] = keyword[None] , identifier[on_error] = literal[string] ):
literal[string]
identifier[cfgstr] = identifier[self] . identifier[_rectify_cfgstr] ( identifier[cfgstr] )
keyword[if] identifier[self] . identifier[enabled... | def tryload(self, cfgstr=None, on_error='raise'):
"""
Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the cache
... |
def _query(action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None):
'''
Make a web call to RallyDev.
'''
token = _get_token()
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('ral... | def function[_query, parameter[action, command, args, method, header_dict, data]]:
constant[
Make a web call to RallyDev.
]
variable[token] assign[=] call[name[_get_token], parameter[]]
variable[username] assign[=] call[call[name[__opts__].get, parameter[constant[rallydev], dictionary[[]... | keyword[def] identifier[_query] ( identifier[action] = keyword[None] ,
identifier[command] = keyword[None] ,
identifier[args] = keyword[None] ,
identifier[method] = literal[string] ,
identifier[header_dict] = keyword[None] ,
identifier[data] = keyword[None] ):
literal[string]
identifier[token] = ident... | def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None):
"""
Make a web call to RallyDev.
"""
token = _get_token()
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://r... |
def gaussian_deconvolve (smaj, smin, spa, bmaj, bmin, bpa):
"""Deconvolve two Gaussians analytically.
Given the shapes of 2-dimensional “source” and “beam” Gaussians, this
returns a deconvolved “result” Gaussian such that the convolution of
“beam” and “result” is “source”.
Arguments:
smaj
... | def function[gaussian_deconvolve, parameter[smaj, smin, spa, bmaj, bmin, bpa]]:
constant[Deconvolve two Gaussians analytically.
Given the shapes of 2-dimensional “source” and “beam” Gaussians, this
returns a deconvolved “result” Gaussian such that the convolution of
“beam” and “result” is “source”.... | keyword[def] identifier[gaussian_deconvolve] ( identifier[smaj] , identifier[smin] , identifier[spa] , identifier[bmaj] , identifier[bmin] , identifier[bpa] ):
literal[string]
keyword[from] identifier[numpy] keyword[import] identifier[cos] , identifier[sin] , identifier[sqrt] , identifie... | def gaussian_deconvolve(smaj, smin, spa, bmaj, bmin, bpa):
"""Deconvolve two Gaussians analytically.
Given the shapes of 2-dimensional “source” and “beam” Gaussians, this
returns a deconvolved “result” Gaussian such that the convolution of
“beam” and “result” is “source”.
Arguments:
smaj
... |
def _encode(values, salt, min_length, alphabet, separators, guards):
"""Helper function that does the hash building without argument checks."""
len_alphabet = len(alphabet)
len_separators = len(separators)
values_hash = sum(x % (i + 100) for i, x in enumerate(values))
encoded = lottery = alphabet[v... | def function[_encode, parameter[values, salt, min_length, alphabet, separators, guards]]:
constant[Helper function that does the hash building without argument checks.]
variable[len_alphabet] assign[=] call[name[len], parameter[name[alphabet]]]
variable[len_separators] assign[=] call[name[len], ... | keyword[def] identifier[_encode] ( identifier[values] , identifier[salt] , identifier[min_length] , identifier[alphabet] , identifier[separators] , identifier[guards] ):
literal[string]
identifier[len_alphabet] = identifier[len] ( identifier[alphabet] )
identifier[len_separators] = identifier[len] ( ... | def _encode(values, salt, min_length, alphabet, separators, guards):
"""Helper function that does the hash building without argument checks."""
len_alphabet = len(alphabet)
len_separators = len(separators)
values_hash = sum((x % (i + 100) for (i, x) in enumerate(values)))
encoded = lottery = alphabe... |
def set(obj, path, value, create_missing=True, afilter=None):
"""Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then a... | def function[set, parameter[obj, path, value, create_missing, afilter]]:
constant[Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the defa... | keyword[def] identifier[set] ( identifier[obj] , identifier[path] , identifier[value] , identifier[create_missing] = keyword[True] , identifier[afilter] = keyword[None] ):
literal[string]
identifier[cur] = identifier[obj]
identifier[traversed] =[]
keyword[def] identifier[_presence_test_dict] (... | def set(obj, path, value, create_missing=True, afilter=None):
"""Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then a... |
def delete_entitlement(owner, repo, identifier):
"""Delete an entitlement from a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
_, _, headers = client.entitlements_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratel... | def function[delete_entitlement, parameter[owner, repo, identifier]]:
constant[Delete an entitlement from a repository.]
variable[client] assign[=] call[name[get_entitlements_api], parameter[]]
with call[name[catch_raise_api_exception], parameter[]] begin[:]
<ast.Tuple object at ... | keyword[def] identifier[delete_entitlement] ( identifier[owner] , identifier[repo] , identifier[identifier] ):
literal[string]
identifier[client] = identifier[get_entitlements_api] ()
keyword[with] identifier[catch_raise_api_exception] ():
identifier[_] , identifier[_] , identifier[headers]... | def delete_entitlement(owner, repo, identifier):
"""Delete an entitlement from a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
(_, _, headers) = client.entitlements_delete_with_http_info(owner=owner, repo=repo, identifier=identifier) # depends on [control=['with']... |
def clean_weight_files(cls):
"""
Cleans existing weight files.
"""
deleted = []
for f in cls._files:
try:
os.remove(f)
deleted.append(f)
except FileNotFoundError:
pass
print('Deleted %d weight files' ... | def function[clean_weight_files, parameter[cls]]:
constant[
Cleans existing weight files.
]
variable[deleted] assign[=] list[[]]
for taget[name[f]] in starred[name[cls]._files] begin[:]
<ast.Try object at 0x7da1b079b400>
call[name[print], parameter[binary_operatio... | keyword[def] identifier[clean_weight_files] ( identifier[cls] ):
literal[string]
identifier[deleted] =[]
keyword[for] identifier[f] keyword[in] identifier[cls] . identifier[_files] :
keyword[try] :
identifier[os] . identifier[remove] ( identifier[f] )
... | def clean_weight_files(cls):
"""
Cleans existing weight files.
"""
deleted = []
for f in cls._files:
try:
os.remove(f)
deleted.append(f) # depends on [control=['try'], data=[]]
except FileNotFoundError:
pass # depends on [control=['except... |
def replace_countries_geo_zone_by_id(cls, countries_geo_zone_id, countries_geo_zone, **kwargs):
"""Replace CountriesGeoZone
Replace all attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | def function[replace_countries_geo_zone_by_id, parameter[cls, countries_geo_zone_id, countries_geo_zone]]:
constant[Replace CountriesGeoZone
Replace all attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please p... | keyword[def] identifier[replace_countries_geo_zone_by_id] ( identifier[cls] , identifier[countries_geo_zone_id] , identifier[countries_geo_zone] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get... | def replace_countries_geo_zone_by_id(cls, countries_geo_zone_id, countries_geo_zone, **kwargs):
"""Replace CountriesGeoZone
Replace all attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... |
def add_model_file(self, model_fpath, position=1, file_id=None):
"""Add a kappa model from a file at given path to the project."""
if file_id is None:
file_id = self.make_unique_id('file_input')
ret_data = self.file_create(File.from_file(model_fpath, position,
... | def function[add_model_file, parameter[self, model_fpath, position, file_id]]:
constant[Add a kappa model from a file at given path to the project.]
if compare[name[file_id] is constant[None]] begin[:]
variable[file_id] assign[=] call[name[self].make_unique_id, parameter[constant[file_in... | keyword[def] identifier[add_model_file] ( identifier[self] , identifier[model_fpath] , identifier[position] = literal[int] , identifier[file_id] = keyword[None] ):
literal[string]
keyword[if] identifier[file_id] keyword[is] keyword[None] :
identifier[file_id] = identifier[self] . id... | def add_model_file(self, model_fpath, position=1, file_id=None):
"""Add a kappa model from a file at given path to the project."""
if file_id is None:
file_id = self.make_unique_id('file_input') # depends on [control=['if'], data=['file_id']]
ret_data = self.file_create(File.from_file(model_fpath, ... |
def field_columns(self, well_row, well_column):
"""Field columns for given well. Equivalent to --X in files.
Parameters
----------
well_row : int
Starts at 0. Same as --V in files.
well_column : int
Starts at 0. Same as --U in files.
Returns
... | def function[field_columns, parameter[self, well_row, well_column]]:
constant[Field columns for given well. Equivalent to --X in files.
Parameters
----------
well_row : int
Starts at 0. Same as --V in files.
well_column : int
Starts at 0. Same as --U in f... | keyword[def] identifier[field_columns] ( identifier[self] , identifier[well_row] , identifier[well_column] ):
literal[string]
identifier[imgs] = identifier[self] . identifier[well_images] ( identifier[well_row] , identifier[well_column] )
keyword[return] identifier[list] ( identifier[set]... | def field_columns(self, well_row, well_column):
"""Field columns for given well. Equivalent to --X in files.
Parameters
----------
well_row : int
Starts at 0. Same as --V in files.
well_column : int
Starts at 0. Same as --U in files.
Returns
... |
def _attempt_connect(host, port, timeout, verify, **kwargs):
"""
Internal function to attempt
:param host: <str> "localhost" or IPAddress
:param port: <int>
:param timeout: <int>
:param verify: <bool>
:param kwargs: <**dict> rethinkdb keyword args
:return: <connection> or <NoneType>
... | def function[_attempt_connect, parameter[host, port, timeout, verify]]:
constant[
Internal function to attempt
:param host: <str> "localhost" or IPAddress
:param port: <int>
:param timeout: <int>
:param verify: <bool>
:param kwargs: <**dict> rethinkdb keyword args
:return: <connectio... | keyword[def] identifier[_attempt_connect] ( identifier[host] , identifier[port] , identifier[timeout] , identifier[verify] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[connection] = identifier[rethinkdb] . identifier[connect] ( identifier[host] ,
identifier[port] ,
... | def _attempt_connect(host, port, timeout, verify, **kwargs):
"""
Internal function to attempt
:param host: <str> "localhost" or IPAddress
:param port: <int>
:param timeout: <int>
:param verify: <bool>
:param kwargs: <**dict> rethinkdb keyword args
:return: <connection> or <NoneType>
... |
def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True):
'''
Attempt to retrieve the named value from grains, if the named value is not
available return the passed default. The default return is an empty string.
The value can also represent a value in a nested dict using a ":" delimiter
... | def function[get, parameter[key, default, delimiter, ordered]]:
constant[
Attempt to retrieve the named value from grains, if the named value is not
available return the passed default. The default return is an empty string.
The value can also represent a value in a nested dict using a ":" delimite... | keyword[def] identifier[get] ( identifier[key] , identifier[default] = literal[string] , identifier[delimiter] = identifier[DEFAULT_TARGET_DELIM] , identifier[ordered] = keyword[True] ):
literal[string]
keyword[if] identifier[ordered] keyword[is] keyword[True] :
identifier[grains] = identifier[... | def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True):
"""
Attempt to retrieve the named value from grains, if the named value is not
available return the passed default. The default return is an empty string.
The value can also represent a value in a nested dict using a ":" delimiter
... |
def removeEventListener(self, event: str, listener: _EventListenerType
) -> None:
"""Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched.
"""
self._remove_event_listener(event, listener) | def function[removeEventListener, parameter[self, event, listener]]:
constant[Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched.
]
call[name[self]._remove_event_listener, parameter[name[event], name[listener]]] | keyword[def] identifier[removeEventListener] ( identifier[self] , identifier[event] : identifier[str] , identifier[listener] : identifier[_EventListenerType]
)-> keyword[None] :
literal[string]
identifier[self] . identifier[_remove_event_listener] ( identifier[event] , identifier[listener] ) | def removeEventListener(self, event: str, listener: _EventListenerType) -> None:
"""Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched.
"""
self._remove_event_listener(event, listener) |
def create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=None):
"""
Determines the u... | def function[create_cross_sectional_bootstrap_samples, parameter[obs_id_array, alt_id_array, choice_array, num_samples, seed]]:
constant[
Determines the unique observations that will be present in each bootstrap
sample. This function DOES NOT create the new design matrices or a new
long-format dataf... | keyword[def] identifier[create_cross_sectional_bootstrap_samples] ( identifier[obs_id_array] ,
identifier[alt_id_array] ,
identifier[choice_array] ,
identifier[num_samples] ,
identifier[seed] = keyword[None] ):
literal[string]
identifier[chosen_alts_to_obs_ids] = identifier[relate_obs_ids_to_chose... | def create_cross_sectional_bootstrap_samples(obs_id_array, alt_id_array, choice_array, num_samples, seed=None):
"""
Determines the unique observations that will be present in each bootstrap
sample. This function DOES NOT create the new design matrices or a new
long-format dataframe for each bootstrap sa... |
def color_scale(color, level):
"""
Scale RGB tuple by level, 0 - 256
"""
return tuple([int(i * level) >> 8 for i in list(color)]) | def function[color_scale, parameter[color, level]]:
constant[
Scale RGB tuple by level, 0 - 256
]
return[call[name[tuple], parameter[<ast.ListComp object at 0x7da1b010ae00>]]] | keyword[def] identifier[color_scale] ( identifier[color] , identifier[level] ):
literal[string]
keyword[return] identifier[tuple] ([ identifier[int] ( identifier[i] * identifier[level] )>> literal[int] keyword[for] identifier[i] keyword[in] identifier[list] ( identifier[color] )]) | def color_scale(color, level):
"""
Scale RGB tuple by level, 0 - 256
"""
return tuple([int(i * level) >> 8 for i in list(color)]) |
def from_dict(cls, d):
"""
Invokes
"""
entry_type = d["entry_type"]
if entry_type == "Ion":
entry = IonEntry.from_dict(d["entry"])
else:
entry = PDEntry.from_dict(d["entry"])
entry_id = d["entry_id"]
concentration = d["concentration... | def function[from_dict, parameter[cls, d]]:
constant[
Invokes
]
variable[entry_type] assign[=] call[name[d]][constant[entry_type]]
if compare[name[entry_type] equal[==] constant[Ion]] begin[:]
variable[entry] assign[=] call[name[IonEntry].from_dict, parameter[call... | keyword[def] identifier[from_dict] ( identifier[cls] , identifier[d] ):
literal[string]
identifier[entry_type] = identifier[d] [ literal[string] ]
keyword[if] identifier[entry_type] == literal[string] :
identifier[entry] = identifier[IonEntry] . identifier[from_dict] ( identi... | def from_dict(cls, d):
"""
Invokes
"""
entry_type = d['entry_type']
if entry_type == 'Ion':
entry = IonEntry.from_dict(d['entry']) # depends on [control=['if'], data=[]]
else:
entry = PDEntry.from_dict(d['entry'])
entry_id = d['entry_id']
concentration = d['conce... |
def send(self, command, payload):
"""
Send a WorkRequest to containing command and payload to the queue specified in config.
:param command: str: name of the command we want run by WorkQueueProcessor
:param payload: object: pickable data to be used when running the command
"""
... | def function[send, parameter[self, command, payload]]:
constant[
Send a WorkRequest to containing command and payload to the queue specified in config.
:param command: str: name of the command we want run by WorkQueueProcessor
:param payload: object: pickable data to be used when running... | keyword[def] identifier[send] ( identifier[self] , identifier[command] , identifier[payload] ):
literal[string]
identifier[request] = identifier[WorkRequest] ( identifier[command] , identifier[payload] )
identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identi... | def send(self, command, payload):
"""
Send a WorkRequest to containing command and payload to the queue specified in config.
:param command: str: name of the command we want run by WorkQueueProcessor
:param payload: object: pickable data to be used when running the command
"""
re... |
def abup_se_plot(mod,species):
"""
plot species from one ABUPP file and the se file.
You must use this function in the directory where the ABP files
are and an ABUP file for model mod must exist.
Parameters
----------
mod : integer
Model to plot, yo... | def function[abup_se_plot, parameter[mod, species]]:
constant[
plot species from one ABUPP file and the se file.
You must use this function in the directory where the ABP files
are and an ABUP file for model mod must exist.
Parameters
----------
mod : integer
... | keyword[def] identifier[abup_se_plot] ( identifier[mod] , identifier[species] ):
literal[string]
identifier[species] = literal[string]
identifier[filename] = literal[string] % identifier[mod]
identifier[print] ( identifier[filename] )
identifier[mas... | def abup_se_plot(mod, species):
"""
plot species from one ABUPP file and the se file.
You must use this function in the directory where the ABP files
are and an ABUP file for model mod must exist.
Parameters
----------
mod : integer
Model to plot, you ne... |
def nominatim_request(params, type = "search", pause_duration=1, timeout=30, error_pause_duration=180):
"""
Send a request to the Nominatim API via HTTP GET and return the JSON
response.
Parameters
----------
params : dict or OrderedDict
key-value pairs of parameters
type : string
... | def function[nominatim_request, parameter[params, type, pause_duration, timeout, error_pause_duration]]:
constant[
Send a request to the Nominatim API via HTTP GET and return the JSON
response.
Parameters
----------
params : dict or OrderedDict
key-value pairs of parameters
type... | keyword[def] identifier[nominatim_request] ( identifier[params] , identifier[type] = literal[string] , identifier[pause_duration] = literal[int] , identifier[timeout] = literal[int] , identifier[error_pause_duration] = literal[int] ):
literal[string]
identifier[known_requests] ={ literal[string] , literal... | def nominatim_request(params, type='search', pause_duration=1, timeout=30, error_pause_duration=180):
"""
Send a request to the Nominatim API via HTTP GET and return the JSON
response.
Parameters
----------
params : dict or OrderedDict
key-value pairs of parameters
type : string
... |
def _watchdog_time(self):
"""
标题时间显示
"""
while not self.quit:
self.data.time = self.player.time_pos
self.view.display()
time.sleep(1) | def function[_watchdog_time, parameter[self]]:
constant[
标题时间显示
]
while <ast.UnaryOp object at 0x7da18fe92950> begin[:]
name[self].data.time assign[=] name[self].player.time_pos
call[name[self].view.display, parameter[]]
call[name[time].sle... | keyword[def] identifier[_watchdog_time] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[quit] :
identifier[self] . identifier[data] . identifier[time] = identifier[self] . identifier[player] . identifier[time_pos]
identifi... | def _watchdog_time(self):
"""
标题时间显示
"""
while not self.quit:
self.data.time = self.player.time_pos
self.view.display()
time.sleep(1) # depends on [control=['while'], data=[]] |
def getCertificateExpireDate(self, CorpNum):
""" 공인인증서 만료일 확인, 등록여부 확인용도로 활용가능
args
CorpNum : 확인할 회원 사업자번호
return
등록시 만료일자, 미등록시 해당 PopbillException raise.
raise
PopbillException
"""
result = self._httpget('/Taxi... | def function[getCertificateExpireDate, parameter[self, CorpNum]]:
constant[ 공인인증서 만료일 확인, 등록여부 확인용도로 활용가능
args
CorpNum : 확인할 회원 사업자번호
return
등록시 만료일자, 미등록시 해당 PopbillException raise.
raise
PopbillException
]
vari... | keyword[def] identifier[getCertificateExpireDate] ( identifier[self] , identifier[CorpNum] ):
literal[string]
identifier[result] = identifier[self] . identifier[_httpget] ( literal[string] , identifier[CorpNum] )
keyword[return] identifier[datetime] . identifier[strptime] ( identifier[res... | def getCertificateExpireDate(self, CorpNum):
""" 공인인증서 만료일 확인, 등록여부 확인용도로 활용가능
args
CorpNum : 확인할 회원 사업자번호
return
등록시 만료일자, 미등록시 해당 PopbillException raise.
raise
PopbillException
"""
result = self._httpget('/Taxinvoice?c... |
def returnTradeHistoryPublic(self, currencyPair, start=None, end=None):
"""Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters."""
return super(Poloniex, self).returnTradeHistory(curre... | def function[returnTradeHistoryPublic, parameter[self, currencyPair, start, end]]:
constant[Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters.]
return[call[call[name[super], parameter[na... | keyword[def] identifier[returnTradeHistoryPublic] ( identifier[self] , identifier[currencyPair] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ):
literal[string]
keyword[return] identifier[super] ( identifier[Poloniex] , identifier[self] ). identifier[returnTradeHistory] ( i... | def returnTradeHistoryPublic(self, currencyPair, start=None, end=None):
"""Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters."""
return super(Poloniex, self).returnTradeHistory(currencyPair,... |
def spmatrix(self, reordered = True, symmetric = False):
"""
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
defaul... | def function[spmatrix, parameter[self, reordered, symmetric]]:
constant[
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
... | keyword[def] identifier[spmatrix] ( identifier[self] , identifier[reordered] = keyword[True] , identifier[symmetric] = keyword[False] ):
literal[string]
identifier[n] = identifier[self] . identifier[symb] . identifier[n]
identifier[snptr] = identifier[self] . identifier[symb] . identifier... | def spmatrix(self, reordered=True, symmetric=False):
"""
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
default option... |
def op_list_venvs(self):
"""Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments
"""
self.logger.info('Listing known virtual environments ...')
venvs = self.get_venvs()
for venv in venvs:
self... | def function[op_list_venvs, parameter[self]]:
constant[Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments
]
call[name[self].logger.info, parameter[constant[Listing known virtual environments ...]]]
variable[ven... | keyword[def] identifier[op_list_venvs] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] )
identifier[venvs] = identifier[self] . identifier[get_venvs] ()
keyword[for] identifier[venv] keyword[in] identifier[venvs] ... | def op_list_venvs(self):
"""Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments
"""
self.logger.info('Listing known virtual environments ...')
venvs = self.get_venvs()
for venv in venvs:
self.logger.info('Found ... |
def Bezier(points, at):
"""Build Bézier curve from points.
Deprecated. CatmulClark builds nicer splines
"""
at = np.asarray(at)
at_flat = at.ravel()
N = len(points)
curve = np.zeros((at_flat.shape[0], 2))
for ii in range(N):
curve += np.outer(Bernstein(N - 1, ii)(at_flat), points... | def function[Bezier, parameter[points, at]]:
constant[Build Bézier curve from points.
Deprecated. CatmulClark builds nicer splines
]
variable[at] assign[=] call[name[np].asarray, parameter[name[at]]]
variable[at_flat] assign[=] call[name[at].ravel, parameter[]]
variable[N] assign... | keyword[def] identifier[Bezier] ( identifier[points] , identifier[at] ):
literal[string]
identifier[at] = identifier[np] . identifier[asarray] ( identifier[at] )
identifier[at_flat] = identifier[at] . identifier[ravel] ()
identifier[N] = identifier[len] ( identifier[points] )
identifier[curv... | def Bezier(points, at):
"""Build Bézier curve from points.
Deprecated. CatmulClark builds nicer splines
"""
at = np.asarray(at)
at_flat = at.ravel()
N = len(points)
curve = np.zeros((at_flat.shape[0], 2))
for ii in range(N):
curve += np.outer(Bernstein(N - 1, ii)(at_flat), points... |
def logdebug(logger, msg, *args, **kwargs):
'''
Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO).
'''
if esgfpid.defaults.LOG_DEBUG_TO_INFO:
logger.info('DEBUG %s ' % msg, *args, **kwargs)
else:
logger.debug(... | def function[logdebug, parameter[logger, msg]]:
constant[
Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO).
]
if name[esgfpid].defaults.LOG_DEBUG_TO_INFO begin[:]
call[name[logger].info, parameter[binary_... | keyword[def] identifier[logdebug] ( identifier[logger] , identifier[msg] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[esgfpid] . identifier[defaults] . identifier[LOG_DEBUG_TO_INFO] :
identifier[logger] . identifier[info] ( literal[string] % identifier[msg]... | def logdebug(logger, msg, *args, **kwargs):
"""
Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO).
"""
if esgfpid.defaults.LOG_DEBUG_TO_INFO:
logger.info('DEBUG %s ' % msg, *args, **kwargs) # depends on [control=['if'], ... |
def _input_handler_decorator(self, data):
"""Adds positional parameters to selected input_handler's results.
"""
input_handler = getattr(self, self.__InputHandler)
input_parts = [
self.Parameters['taxonomy_file'],
input_handler(data),
self.Parameters['... | def function[_input_handler_decorator, parameter[self, data]]:
constant[Adds positional parameters to selected input_handler's results.
]
variable[input_handler] assign[=] call[name[getattr], parameter[name[self], name[self].__InputHandler]]
variable[input_parts] assign[=] list[[<ast.Sub... | keyword[def] identifier[_input_handler_decorator] ( identifier[self] , identifier[data] ):
literal[string]
identifier[input_handler] = identifier[getattr] ( identifier[self] , identifier[self] . identifier[__InputHandler] )
identifier[input_parts] =[
identifier[self] . identifier[... | def _input_handler_decorator(self, data):
"""Adds positional parameters to selected input_handler's results.
"""
input_handler = getattr(self, self.__InputHandler)
input_parts = [self.Parameters['taxonomy_file'], input_handler(data), self.Parameters['training_set_id'], self.Parameters['taxonomy_vers... |
def radpress_get_markup_descriptions():
"""
Provides markup options. It used for adding descriptions in admin and
zen mode.
:return: list
"""
result = []
for markup in get_markup_choices():
markup_name = markup[0]
result.append({
'name': markup_name,
... | def function[radpress_get_markup_descriptions, parameter[]]:
constant[
Provides markup options. It used for adding descriptions in admin and
zen mode.
:return: list
]
variable[result] assign[=] list[[]]
for taget[name[markup]] in starred[call[name[get_markup_choices], parameter[... | keyword[def] identifier[radpress_get_markup_descriptions] ():
literal[string]
identifier[result] =[]
keyword[for] identifier[markup] keyword[in] identifier[get_markup_choices] ():
identifier[markup_name] = identifier[markup] [ literal[int] ]
identifier[result] . identifier[append]... | def radpress_get_markup_descriptions():
"""
Provides markup options. It used for adding descriptions in admin and
zen mode.
:return: list
"""
result = []
for markup in get_markup_choices():
markup_name = markup[0]
result.append({'name': markup_name, 'title': markup[1], 'desc... |
def range_for_length(self, length):
"""If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`.
"""
if self.units != "bytes" or length is None or len(self.ranges) != 1:
... | def function[range_for_length, parameter[self, length]]:
constant[If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`.
]
if <ast.BoolOp object at 0x7da20c6a87c0> begin[:]
... | keyword[def] identifier[range_for_length] ( identifier[self] , identifier[length] ):
literal[string]
keyword[if] identifier[self] . identifier[units] != literal[string] keyword[or] identifier[length] keyword[is] keyword[None] keyword[or] identifier[len] ( identifier[self] . identifier[ranges... | def range_for_length(self, length):
"""If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`.
"""
if self.units != 'bytes' or length is None or len(self.ranges) != 1:
return No... |
def set_many(self, block, update_dict):
"""
Update many fields on an XBlock simultaneously.
:param block: the block to update
:type block: :class:`~xblock.core.XBlock`
:param update_dict: A map of field names to their new values
:type update_dict: dict
"""
... | def function[set_many, parameter[self, block, update_dict]]:
constant[
Update many fields on an XBlock simultaneously.
:param block: the block to update
:type block: :class:`~xblock.core.XBlock`
:param update_dict: A map of field names to their new values
:type update_di... | keyword[def] identifier[set_many] ( identifier[self] , identifier[block] , identifier[update_dict] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[six] . identifier[iteritems] ( identifier[update_dict] ):
identifier[self] . identifier[set] ... | def set_many(self, block, update_dict):
"""
Update many fields on an XBlock simultaneously.
:param block: the block to update
:type block: :class:`~xblock.core.XBlock`
:param update_dict: A map of field names to their new values
:type update_dict: dict
"""
for (k... |
def get_amount_normal(self, billing_cycle):
"""Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
"""
if self.is_one_off():
... | def function[get_amount_normal, parameter[self, billing_cycle]]:
constant[Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
]
if ca... | keyword[def] identifier[get_amount_normal] ( identifier[self] , identifier[billing_cycle] ):
literal[string]
keyword[if] identifier[self] . identifier[is_one_off] ():
identifier[billing_cycle_number] = identifier[self] . identifier[_get_billing_cycle_number] ( identifier[billing_cycle... | def get_amount_normal(self, billing_cycle):
"""Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
"""
if self.is_one_off():
billing_... |
def faster_minimum_distance2(hull_a, center_a, hull_b, center_b):
'''Do the minimum distance using the bimodal property of hull ordering
'''
#
# Find the farthest vertex in b from some point within A. Find the
# vertices within A visible from this point in B. If the point in A
# is within B... | def function[faster_minimum_distance2, parameter[hull_a, center_a, hull_b, center_b]]:
constant[Do the minimum distance using the bimodal property of hull ordering
]
if call[name[within_hull], parameter[name[center_a], name[hull_b]]] begin[:]
return[constant[0]]
variable[farthes... | keyword[def] identifier[faster_minimum_distance2] ( identifier[hull_a] , identifier[center_a] , identifier[hull_b] , identifier[center_b] ):
literal[string]
keyword[if] identifier[within_hull] ( identifier[center_a] , identifier[hull_b] ):
keyword[return] literal[in... | def faster_minimum_distance2(hull_a, center_a, hull_b, center_b):
"""Do the minimum distance using the bimodal property of hull ordering
"""
#
# Find the farthest vertex in b from some point within A. Find the
# vertices within A visible from this point in B. If the point in A
# is within B... |
def run(self):
"""
Run sdist, then 'rpmbuild' the tar.gz
"""
os.system("cp python-bugzilla.spec /tmp")
try:
os.system("rm -rf python-bugzilla-%s" % get_version())
self.run_command('sdist')
os.system('rpmbuild -ta --clean dist/python-bugzilla-%s... | def function[run, parameter[self]]:
constant[
Run sdist, then 'rpmbuild' the tar.gz
]
call[name[os].system, parameter[constant[cp python-bugzilla.spec /tmp]]]
<ast.Try object at 0x7da1b0dbe0e0> | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[os] . identifier[system] ( literal[string] )
keyword[try] :
identifier[os] . identifier[system] ( literal[string] % identifier[get_version] ())
identifier[self] . identifier[run_command]... | def run(self):
"""
Run sdist, then 'rpmbuild' the tar.gz
"""
os.system('cp python-bugzilla.spec /tmp')
try:
os.system('rm -rf python-bugzilla-%s' % get_version())
self.run_command('sdist')
os.system('rpmbuild -ta --clean dist/python-bugzilla-%s.tar.gz' % get_version()... |
def cancel(self, contacts):
"""Wrapper to call raise_cancel_downtime_log_entry for ref (host/service)
set can_be_deleted to True
set is_in_effect to False
:return: None
"""
self.is_in_effect = False
contact = contacts[self.ref]
contact.raise_cancel_downti... | def function[cancel, parameter[self, contacts]]:
constant[Wrapper to call raise_cancel_downtime_log_entry for ref (host/service)
set can_be_deleted to True
set is_in_effect to False
:return: None
]
name[self].is_in_effect assign[=] constant[False]
variable[contac... | keyword[def] identifier[cancel] ( identifier[self] , identifier[contacts] ):
literal[string]
identifier[self] . identifier[is_in_effect] = keyword[False]
identifier[contact] = identifier[contacts] [ identifier[self] . identifier[ref] ]
identifier[contact] . identifier[raise_cance... | def cancel(self, contacts):
"""Wrapper to call raise_cancel_downtime_log_entry for ref (host/service)
set can_be_deleted to True
set is_in_effect to False
:return: None
"""
self.is_in_effect = False
contact = contacts[self.ref]
contact.raise_cancel_downtime_log_entry()
... |
def create_data_file_by_format(directory_path = None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for root, subdirs, files in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
... | def function[create_data_file_by_format, parameter[directory_path]]:
constant[
Browse subdirectories to extract stata and sas files
]
variable[stata_files] assign[=] list[[]]
variable[sas_files] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da18dc994e0>, <ast.Name ob... | keyword[def] identifier[create_data_file_by_format] ( identifier[directory_path] = keyword[None] ):
literal[string]
identifier[stata_files] =[]
identifier[sas_files] =[]
keyword[for] identifier[root] , identifier[subdirs] , identifier[files] keyword[in] identifier[os] . identifier[walk] ( ide... | def create_data_file_by_format(directory_path=None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for (root, subdirs, files) in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
... |
def _read_depth_images(self, num_images):
""" Reads depth images from the device """
depth_images = self._ros_read_images(self._depth_image_buffer, num_images, self.staleness_limit)
for i in range(0, num_images):
depth_images[i] = depth_images[i] * MM_TO_METERS # convert to meters
... | def function[_read_depth_images, parameter[self, num_images]]:
constant[ Reads depth images from the device ]
variable[depth_images] assign[=] call[name[self]._ros_read_images, parameter[name[self]._depth_image_buffer, name[num_images], name[self].staleness_limit]]
for taget[name[i]] in starred[... | keyword[def] identifier[_read_depth_images] ( identifier[self] , identifier[num_images] ):
literal[string]
identifier[depth_images] = identifier[self] . identifier[_ros_read_images] ( identifier[self] . identifier[_depth_image_buffer] , identifier[num_images] , identifier[self] . identifier[stalene... | def _read_depth_images(self, num_images):
""" Reads depth images from the device """
depth_images = self._ros_read_images(self._depth_image_buffer, num_images, self.staleness_limit)
for i in range(0, num_images):
depth_images[i] = depth_images[i] * MM_TO_METERS # convert to meters
if self._... |
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value | def function[subtract_weeks, parameter[self, weeks]]:
constant[ Subtracts number of weeks from the current value ]
name[self].value assign[=] binary_operation[name[self].value - call[name[timedelta], parameter[]]]
return[name[self].value] | keyword[def] identifier[subtract_weeks] ( identifier[self] , identifier[weeks] : identifier[int] )-> identifier[datetime] :
literal[string]
identifier[self] . identifier[value] = identifier[self] . identifier[value] - identifier[timedelta] ( identifier[weeks] = identifier[weeks] )
keyword[... | def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value |
def _rebuild_all_command_chains(self):
"""
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in ... | def function[_rebuild_all_command_chains, parameter[self]]:
constant[
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (ty... | keyword[def] identifier[_rebuild_all_command_chains] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_commands_by_name] ={}
keyword[for] identifier[command] keyword[in] identifier[self] . identifier[_commands] :
identifier[self] . identifier[_build_comma... | def _rebuild_all_command_chains(self):
"""
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in abst... |
def imfrombytes(content, flag='color'):
"""Read an image from bytes.
Args:
content (bytes): Image bytes got from files or other streams.
flag (str): Same as :func:`imread`.
Returns:
ndarray: Loaded image array.
"""
img_np = np.frombuffer(content, np.uint8)
flag = imread... | def function[imfrombytes, parameter[content, flag]]:
constant[Read an image from bytes.
Args:
content (bytes): Image bytes got from files or other streams.
flag (str): Same as :func:`imread`.
Returns:
ndarray: Loaded image array.
]
variable[img_np] assign[=] call[na... | keyword[def] identifier[imfrombytes] ( identifier[content] , identifier[flag] = literal[string] ):
literal[string]
identifier[img_np] = identifier[np] . identifier[frombuffer] ( identifier[content] , identifier[np] . identifier[uint8] )
identifier[flag] = identifier[imread_flags] [ identifier[flag] ] ... | def imfrombytes(content, flag='color'):
"""Read an image from bytes.
Args:
content (bytes): Image bytes got from files or other streams.
flag (str): Same as :func:`imread`.
Returns:
ndarray: Loaded image array.
"""
img_np = np.frombuffer(content, np.uint8)
flag = imread... |
def resizeEvent(self, event):
"""
Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing.
"""
curr_item = self.currentItem()
self.closePersistentEditor(curr_item)
super(XMultiTagE... | def function[resizeEvent, parameter[self, event]]:
constant[
Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing.
]
variable[curr_item] assign[=] call[name[self].currentItem, parameter[]]
call[name[self... | keyword[def] identifier[resizeEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[curr_item] = identifier[self] . identifier[currentItem] ()
identifier[self] . identifier[closePersistentEditor] ( identifier[curr_item] )
identifier[super] ( identifier[... | def resizeEvent(self, event):
"""
Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing.
"""
curr_item = self.currentItem()
self.closePersistentEditor(curr_item)
super(XMultiTagEdit, self).resizeEvent(event) |
def get_device_name_list():
"""Returns a list of device names installed."""
dev_names = ctypes.create_string_buffer(1024)
pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))
return dev_names.value.split(', ') | def function[get_device_name_list, parameter[]]:
constant[Returns a list of device names installed.]
variable[dev_names] assign[=] call[name[ctypes].create_string_buffer, parameter[constant[1024]]]
call[name[pydaq].DAQmxGetSysDevNames, parameter[name[dev_names], call[name[len], parameter[name[de... | keyword[def] identifier[get_device_name_list] ():
literal[string]
identifier[dev_names] = identifier[ctypes] . identifier[create_string_buffer] ( literal[int] )
identifier[pydaq] . identifier[DAQmxGetSysDevNames] ( identifier[dev_names] , identifier[len] ( identifier[dev_names] ))
keyword[return]... | def get_device_name_list():
"""Returns a list of device names installed."""
dev_names = ctypes.create_string_buffer(1024)
pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))
return dev_names.value.split(', ') |
def show(self):
"""
Pretty-print instance data
"""
if not self.data:
return
if self.data.get('continue'):
return
ptitle = self.params.get('title')
dtitle = self.data.get('title')
pageid = self.params.get('pageid')
seed = ... | def function[show, parameter[self]]:
constant[
Pretty-print instance data
]
if <ast.UnaryOp object at 0x7da1b1206170> begin[:]
return[None]
if call[name[self].data.get, parameter[constant[continue]]] begin[:]
return[None]
variable[ptitle] assign[=] call[na... | keyword[def] identifier[show] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[data] :
keyword[return]
keyword[if] identifier[self] . identifier[data] . identifier[get] ( literal[string] ):
keyword[return]
... | def show(self):
"""
Pretty-print instance data
"""
if not self.data:
return # depends on [control=['if'], data=[]]
if self.data.get('continue'):
return # depends on [control=['if'], data=[]]
ptitle = self.params.get('title')
dtitle = self.data.get('title')
pagei... |
def extra_prepare(self, configuration, args_dict):
"""Called before the configuration.converters are activated"""
aws_syncr = args_dict.pop("aws_syncr")
self.configuration.update(
{ "$@": aws_syncr.get("extra", "")
, "aws_syncr": aws_syncr
, "templates": {}
... | def function[extra_prepare, parameter[self, configuration, args_dict]]:
constant[Called before the configuration.converters are activated]
variable[aws_syncr] assign[=] call[name[args_dict].pop, parameter[constant[aws_syncr]]]
call[name[self].configuration.update, parameter[dictionary[[<ast.Cons... | keyword[def] identifier[extra_prepare] ( identifier[self] , identifier[configuration] , identifier[args_dict] ):
literal[string]
identifier[aws_syncr] = identifier[args_dict] . identifier[pop] ( literal[string] )
identifier[self] . identifier[configuration] . identifier[update] (
... | def extra_prepare(self, configuration, args_dict):
"""Called before the configuration.converters are activated"""
aws_syncr = args_dict.pop('aws_syncr')
self.configuration.update({'$@': aws_syncr.get('extra', ''), 'aws_syncr': aws_syncr, 'templates': {}, 'config_folder': self.configuration_folder}, source='... |
def preferences_view(request, semester, targetUsername, profile=None):
"""
Show the user their preferences for the given semester.
"""
# TODO: Change template to show descriptions in tooltip / ajax show box?
wprofile = get_object_or_404(
WorkshiftProfile,
user__username=targetUsernam... | def function[preferences_view, parameter[request, semester, targetUsername, profile]]:
constant[
Show the user their preferences for the given semester.
]
variable[wprofile] assign[=] call[name[get_object_or_404], parameter[name[WorkshiftProfile]]]
variable[full_management] assign[=] cal... | keyword[def] identifier[preferences_view] ( identifier[request] , identifier[semester] , identifier[targetUsername] , identifier[profile] = keyword[None] ):
literal[string]
identifier[wprofile] = identifier[get_object_or_404] (
identifier[WorkshiftProfile] ,
identifier[user__username] = iden... | def preferences_view(request, semester, targetUsername, profile=None):
"""
Show the user their preferences for the given semester.
"""
# TODO: Change template to show descriptions in tooltip / ajax show box?
wprofile = get_object_or_404(WorkshiftProfile, user__username=targetUsername)
full_manag... |
def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... | def function[to_float, parameter[s, default, allow_nan]]:
constant[
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
... | keyword[def] identifier[to_float] ( identifier[s] , identifier[default] = literal[int] , identifier[allow_nan] = keyword[False] ):
literal[string]
keyword[try] :
identifier[f] = identifier[float] ( identifier[s] )
keyword[except] ( identifier[TypeError] , identifier[ValueError] ):
ke... | def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... |
def python_sidebar(python_input):
"""
Create the `Layout` for the sidebar with the configurable options.
"""
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.title', ... | def function[python_sidebar, parameter[python_input]]:
constant[
Create the `Layout` for the sidebar with the configurable options.
]
def function[get_text_fragments, parameter[]]:
variable[tokens] assign[=] list[[]]
def function[append_category, parameter[categor... | keyword[def] identifier[python_sidebar] ( identifier[python_input] ):
literal[string]
keyword[def] identifier[get_text_fragments] ():
identifier[tokens] =[]
keyword[def] identifier[append_category] ( identifier[category] ):
identifier[tokens] . identifier[extend] ([
... | def python_sidebar(python_input):
"""
Create the `Layout` for the sidebar with the configurable options.
"""
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([('class:sidebar', ' '), ('class:sidebar.title', ' %-36s' % category.title), ('... |
def match(self, text, noprefix=False):
"""Matches date/datetime string against date patterns and returns pattern and parsed date if matched.
It's not indeded for common usage, since if successful it returns date as array of numbers and pattern
that matched this date
:param text:
... | def function[match, parameter[self, text, noprefix]]:
constant[Matches date/datetime string against date patterns and returns pattern and parsed date if matched.
It's not indeded for common usage, since if successful it returns date as array of numbers and pattern
that matched this date
... | keyword[def] identifier[match] ( identifier[self] , identifier[text] , identifier[noprefix] = keyword[False] ):
literal[string]
identifier[n] = identifier[len] ( identifier[text] )
keyword[if] identifier[self] . identifier[cachedpats] keyword[is] keyword[not] keyword[None] :
... | def match(self, text, noprefix=False):
"""Matches date/datetime string against date patterns and returns pattern and parsed date if matched.
It's not indeded for common usage, since if successful it returns date as array of numbers and pattern
that matched this date
:param text:
... |
def cmd_all(args):
"""List everything recursively"""
for penlist in penStore.data:
puts(penlist)
with indent(4, ' -'):
for penfile in penStore.data[penlist]:
puts(penfile) | def function[cmd_all, parameter[args]]:
constant[List everything recursively]
for taget[name[penlist]] in starred[name[penStore].data] begin[:]
call[name[puts], parameter[name[penlist]]]
with call[name[indent], parameter[constant[4], constant[ -]]] begin[:]
... | keyword[def] identifier[cmd_all] ( identifier[args] ):
literal[string]
keyword[for] identifier[penlist] keyword[in] identifier[penStore] . identifier[data] :
identifier[puts] ( identifier[penlist] )
keyword[with] identifier[indent] ( literal[int] , literal[string] ):
keyw... | def cmd_all(args):
"""List everything recursively"""
for penlist in penStore.data:
puts(penlist)
with indent(4, ' -'):
for penfile in penStore.data[penlist]:
puts(penfile) # depends on [control=['for'], data=['penfile']] # depends on [control=['with'], data=[]] # ... |
def _event_funcs(self, event: str) -> Iterable[Callable]:
""" Returns an Iterable of the functions subscribed to a event.
:param event: Name of the event.
:type event: str
:return: A iterable to do things with.
:rtype: Iterable
"""
for func in self._events[event... | def function[_event_funcs, parameter[self, event]]:
constant[ Returns an Iterable of the functions subscribed to a event.
:param event: Name of the event.
:type event: str
:return: A iterable to do things with.
:rtype: Iterable
]
for taget[name[func]] in starred... | keyword[def] identifier[_event_funcs] ( identifier[self] , identifier[event] : identifier[str] )-> identifier[Iterable] [ identifier[Callable] ]:
literal[string]
keyword[for] identifier[func] keyword[in] identifier[self] . identifier[_events] [ identifier[event] ]:
keyword[yield] i... | def _event_funcs(self, event: str) -> Iterable[Callable]:
""" Returns an Iterable of the functions subscribed to a event.
:param event: Name of the event.
:type event: str
:return: A iterable to do things with.
:rtype: Iterable
"""
for func in self._events[event]:
... |
def setattr(self, req, ino, attr, to_set, fi):
"""Set file attributes
Valid replies:
reply_attr
reply_err
"""
self.reply_err(req, errno.EROFS) | def function[setattr, parameter[self, req, ino, attr, to_set, fi]]:
constant[Set file attributes
Valid replies:
reply_attr
reply_err
]
call[name[self].reply_err, parameter[name[req], name[errno].EROFS]] | keyword[def] identifier[setattr] ( identifier[self] , identifier[req] , identifier[ino] , identifier[attr] , identifier[to_set] , identifier[fi] ):
literal[string]
identifier[self] . identifier[reply_err] ( identifier[req] , identifier[errno] . identifier[EROFS] ) | def setattr(self, req, ino, attr, to_set, fi):
"""Set file attributes
Valid replies:
reply_attr
reply_err
"""
self.reply_err(req, errno.EROFS) |
def _set_alignment(self, group_size, bit_offset=0, auto_align=False):
""" Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Decimal` field within t... | def function[_set_alignment, parameter[self, group_size, bit_offset, auto_align]]:
constant[ Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Deci... | keyword[def] identifier[_set_alignment] ( identifier[self] , identifier[group_size] , identifier[bit_offset] = literal[int] , identifier[auto_align] = keyword[False] ):
literal[string]
identifier[field_offset] = identifier[int] ( identifier[bit_offset] )
keyword[if] ide... | def _set_alignment(self, group_size, bit_offset=0, auto_align=False):
""" Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Decimal` field within the
... |
def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):... | def function[get, parameter[url, params]]:
constant[Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
]
variable[request_url... | keyword[def] identifier[get] ( identifier[url] , identifier[params] ={}):
literal[string]
identifier[request_url] = identifier[url]
keyword[if] identifier[len] ( identifier[params] ):
identifier[request_url] = literal[string] . identifier[format] ( identifier[url] , identif... | def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):
requ... |
def get_string(self, distance=6, velocity=8, charge=3):
"""
Returns the string representation of LammpsData, essentially
the string to be written to a file.
Args:
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atom... | def function[get_string, parameter[self, distance, velocity, charge]]:
constant[
Returns the string representation of LammpsData, essentially
the string to be written to a file.
Args:
distance (int): No. of significant figures to output for
box settings (boun... | keyword[def] identifier[get_string] ( identifier[self] , identifier[distance] = literal[int] , identifier[velocity] = literal[int] , identifier[charge] = literal[int] ):
literal[string]
identifier[file_template] = literal[string]
identifier[box] = identifier[self] . identifier[box] . iden... | def get_string(self, distance=6, velocity=8, charge=3):
"""
Returns the string representation of LammpsData, essentially
the string to be written to a file.
Args:
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic c... |
def stacked_node_layout(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,x_position=None,y_start_position=None,verbose=None):
"""
Execute the Stacked Node Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be ... | def function[stacked_node_layout, parameter[self, EdgeAttribute, network, NodeAttribute, nodeList, x_position, y_start_position, verbose]]:
constant[
Execute the Stacked Node Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be... | keyword[def] identifier[stacked_node_layout] ( identifier[self] , identifier[EdgeAttribute] = keyword[None] , identifier[network] = keyword[None] , identifier[NodeAttribute] = keyword[None] , identifier[nodeList] = keyword[None] , identifier[x_position] = keyword[None] , identifier[y_start_position] = keyword[None] ,... | def stacked_node_layout(self, EdgeAttribute=None, network=None, NodeAttribute=None, nodeList=None, x_position=None, y_start_position=None, verbose=None):
"""
Execute the Stacked Node Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that wil... |
def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
row, col = event.GetRow(), event.Get... | def function[on_left_click, parameter[self, event, grid, choices]]:
constant[
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
]
<ast.Tuple ... | keyword[def] identifier[on_left_click] ( identifier[self] , identifier[event] , identifier[grid] , identifier[choices] ):
literal[string]
identifier[row] , identifier[col] = identifier[event] . identifier[GetRow] (), identifier[event] . identifier[GetCol] ()
keyword[if] identifier[col] ==... | def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
(row, col) = (event.GetRow(), event.GetCol()... |
def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge((each, other))):
self... | def function[complete, parameter[self]]:
constant[
Make the graph a complete graph.
@attention: This will modify the current graph.
]
for taget[name[each]] in starred[call[name[self].nodes, parameter[]]] begin[:]
for taget[name[other]] in starred[call[nam... | keyword[def] identifier[complete] ( identifier[self] ):
literal[string]
keyword[for] identifier[each] keyword[in] identifier[self] . identifier[nodes] ():
keyword[for] identifier[other] keyword[in] identifier[self] . identifier[nodes] ():
keyword[if] ( identifier... | def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if each != other and (not self.has_edge((each, other))):
self.add_edge((each, oth... |
def write_model(self, filename='scores', filepath='', output_format='csv'):
"""
This method calculates the scores and writes them to a file the data frame received. If the output format
is other than 'csv' it will print the scores.
:param filename: the name to give to the fi... | def function[write_model, parameter[self, filename, filepath, output_format]]:
constant[
This method calculates the scores and writes them to a file the data frame received. If the output format
is other than 'csv' it will print the scores.
:param filename: the name to give ... | keyword[def] identifier[write_model] ( identifier[self] , identifier[filename] = literal[string] , identifier[filepath] = literal[string] , identifier[output_format] = literal[string] ):
literal[string]
identifier[scores_array] = identifier[np] . identifier[array] ([])
keyword[for] identi... | def write_model(self, filename='scores', filepath='', output_format='csv'):
"""
This method calculates the scores and writes them to a file the data frame received. If the output format
is other than 'csv' it will print the scores.
:param filename: the name to give to the file
... |
def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original):
"""
Generate BigQuery JSON fields define
:param name_case: name case type
* DdlParse.NAME_CASE.original : Return to no convert
* DdlParse.NAME_CASE.lower : Return to lower
* DdlParse.NAM... | def function[to_bigquery_fields, parameter[self, name_case]]:
constant[
Generate BigQuery JSON fields define
:param name_case: name case type
* DdlParse.NAME_CASE.original : Return to no convert
* DdlParse.NAME_CASE.lower : Return to lower
* DdlParse.NAME_CAS... | keyword[def] identifier[to_bigquery_fields] ( identifier[self] , identifier[name_case] = identifier[DdlParseBase] . identifier[NAME_CASE] . identifier[original] ):
literal[string]
keyword[return] identifier[self] . identifier[_columns] . identifier[to_bigquery_fields] ( identifier[name_case] ) | def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original):
"""
Generate BigQuery JSON fields define
:param name_case: name case type
* DdlParse.NAME_CASE.original : Return to no convert
* DdlParse.NAME_CASE.lower : Return to lower
* DdlParse.NAME_CA... |
def find_neighbors(neighbors, coords, I, source_files, f, sides):
"""Find the tile neighbors based on filenames
Parameters
-----------
neighbors : dict
Dictionary that stores the neighbors. Format is
neighbors["source_file_name"]["side"] = "neighbor_source_file_name"
coords : list
... | def function[find_neighbors, parameter[neighbors, coords, I, source_files, f, sides]]:
constant[Find the tile neighbors based on filenames
Parameters
-----------
neighbors : dict
Dictionary that stores the neighbors. Format is
neighbors["source_file_name"]["side"] = "neighbor_source... | keyword[def] identifier[find_neighbors] ( identifier[neighbors] , identifier[coords] , identifier[I] , identifier[source_files] , identifier[f] , identifier[sides] ):
literal[string]
keyword[for] identifier[i] , identifier[c1] keyword[in] identifier[enumerate] ( identifier[coords] ):
identifier... | def find_neighbors(neighbors, coords, I, source_files, f, sides):
"""Find the tile neighbors based on filenames
Parameters
-----------
neighbors : dict
Dictionary that stores the neighbors. Format is
neighbors["source_file_name"]["side"] = "neighbor_source_file_name"
coords : list
... |
def laser_mirrors(rows, cols, mir):
"""Orienting mirrors to allow reachability by laser beam
:param int rows:
:param int cols: rows and cols are the dimension of the grid
:param mir: list of mirror coordinates, except
mir[0]= laser entrance,
mir[-1]= laser exit.
:com... | def function[laser_mirrors, parameter[rows, cols, mir]]:
constant[Orienting mirrors to allow reachability by laser beam
:param int rows:
:param int cols: rows and cols are the dimension of the grid
:param mir: list of mirror coordinates, except
mir[0]= laser entrance,
... | keyword[def] identifier[laser_mirrors] ( identifier[rows] , identifier[cols] , identifier[mir] ):
literal[string]
identifier[n] = identifier[len] ( identifier[mir] )
identifier[orien] =[ keyword[None] ]*( identifier[n] + literal[int] )
identifier[orien] [ identifier[n] ]= literal[int]
... | def laser_mirrors(rows, cols, mir):
"""Orienting mirrors to allow reachability by laser beam
:param int rows:
:param int cols: rows and cols are the dimension of the grid
:param mir: list of mirror coordinates, except
mir[0]= laser entrance,
mir[-1]= laser exit.
:com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.