code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def release(self):
"""Release the lock."""
success, _ = self.etcd_client.transaction(
compare=[
self.etcd_client.transactions.value(self.key) == self.uuid
],
success=[self.etcd_client.transactions.delete(self.key)],
failure=[]
)
... | def function[release, parameter[self]]:
constant[Release the lock.]
<ast.Tuple object at 0x7da20c794d60> assign[=] call[name[self].etcd_client.transaction, parameter[]]
return[name[success]] | keyword[def] identifier[release] ( identifier[self] ):
literal[string]
identifier[success] , identifier[_] = identifier[self] . identifier[etcd_client] . identifier[transaction] (
identifier[compare] =[
identifier[self] . identifier[etcd_client] . identifier[transactions] . identi... | def release(self):
"""Release the lock."""
(success, _) = self.etcd_client.transaction(compare=[self.etcd_client.transactions.value(self.key) == self.uuid], success=[self.etcd_client.transactions.delete(self.key)], failure=[])
return success |
def push(self, index=None):
"""Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
"""
for ind in self.indexes:
if index and not isinstance(ind, index):
continue
ind.push() | def function[push, parameter[self, index]]:
constant[Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
]
for taget[name[ind]] in starred[name[self].indexes] begin[:]
if <ast.BoolOp object at 0x7da1b19089d0> begin[:]
... | keyword[def] identifier[push] ( identifier[self] , identifier[index] = keyword[None] ):
literal[string]
keyword[for] identifier[ind] keyword[in] identifier[self] . identifier[indexes] :
keyword[if] identifier[index] keyword[and] keyword[not] identifier[isinstance] ( identifier[i... | def push(self, index=None):
"""Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
"""
for ind in self.indexes:
if index and (not isinstance(ind, index)):
continue # depends on [control=['if'], data=[]]
ind.push() # dep... |
def find_transported_elements(rxn):
"""
Return a dictionary showing the amount of transported elements of a rxn.
Collects the elements for each metabolite participating in a reaction,
multiplies the amount by the metabolite's stoichiometry in the reaction and
bins the result according to the compar... | def function[find_transported_elements, parameter[rxn]]:
constant[
Return a dictionary showing the amount of transported elements of a rxn.
Collects the elements for each metabolite participating in a reaction,
multiplies the amount by the metabolite's stoichiometry in the reaction and
bins the... | keyword[def] identifier[find_transported_elements] ( identifier[rxn] ):
literal[string]
identifier[element_dist] = identifier[defaultdict] ()
keyword[for] identifier[met] keyword[in] identifier[rxn] . identifier[metabolites] :
keyword[if] identifier[met] . identifier[compartment] ke... | def find_transported_elements(rxn):
"""
Return a dictionary showing the amount of transported elements of a rxn.
Collects the elements for each metabolite participating in a reaction,
multiplies the amount by the metabolite's stoichiometry in the reaction and
bins the result according to the compar... |
def files(self):
""" File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
"""
files = FormsDict()
for name, item in self.POST.allitems():
if isinstance(item, FileUpload):
... | def function[files, parameter[self]]:
constant[ File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
]
variable[files] assign[=] call[name[FormsDict], parameter[]]
for taget[tuple[[<ast.Name object ... | keyword[def] identifier[files] ( identifier[self] ):
literal[string]
identifier[files] = identifier[FormsDict] ()
keyword[for] identifier[name] , identifier[item] keyword[in] identifier[self] . identifier[POST] . identifier[allitems] ():
keyword[if] identifier[isinstance] ... | def files(self):
""" File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
"""
files = FormsDict()
for (name, item) in self.POST.allitems():
if isinstance(item, FileUpload):
files[name] = ite... |
def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for opt... | def function[setup, parameter[self]]:
constant[ performs data collection for qpid broker ]
variable[options] assign[=] constant[]
variable[amqps_prefix] assign[=] constant[]
if call[name[self].get_option, parameter[constant[ssl]]] begin[:]
variable[amqps_prefix] assign[=]... | keyword[def] identifier[setup] ( identifier[self] ):
literal[string]
identifier[options] = literal[string]
identifier[amqps_prefix] = literal[string]
keyword[if] identifier[self] . identifier[get_option] ( literal[string] ):
identifier[amqps_prefix] = literal[strin... | def setup(self):
""" performs data collection for qpid broker """
options = ''
amqps_prefix = '' # set amqps:// when SSL is used
if self.get_option('ssl'):
amqps_prefix = 'amqps://' # depends on [control=['if'], data=[]]
# for either present option, add --option=value to 'options' variable... |
def samplesheet(self):
"""
Create a custom sample sheet based on the original sample sheet for the run, but only including the samples
that did not pass the quality threshold on the previous iteration
"""
if self.demultiplex:
make_path(self.samplesheetpath)
... | def function[samplesheet, parameter[self]]:
constant[
Create a custom sample sheet based on the original sample sheet for the run, but only including the samples
that did not pass the quality threshold on the previous iteration
]
if name[self].demultiplex begin[:]
... | keyword[def] identifier[samplesheet] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[demultiplex] :
identifier[make_path] ( identifier[self] . identifier[samplesheetpath] )
identifier[self] . identifier[customsamplesheet] = identifier[os] .... | def samplesheet(self):
"""
Create a custom sample sheet based on the original sample sheet for the run, but only including the samples
that did not pass the quality threshold on the previous iteration
"""
if self.demultiplex:
make_path(self.samplesheetpath)
self.customsam... |
def get_contacts(self):
"""
Returns list of contacts
Returns:
dict: the roster of contacts
"""
for jid, item in self.roster.items.items():
try:
self._contacts[jid.bare()].update(item.export_as_json())
except KeyError:
... | def function[get_contacts, parameter[self]]:
constant[
Returns list of contacts
Returns:
dict: the roster of contacts
]
for taget[tuple[[<ast.Name object at 0x7da1b0790b20>, <ast.Name object at 0x7da1b0790b50>]]] in starred[call[name[self].roster.items.items, paramete... | keyword[def] identifier[get_contacts] ( identifier[self] ):
literal[string]
keyword[for] identifier[jid] , identifier[item] keyword[in] identifier[self] . identifier[roster] . identifier[items] . identifier[items] ():
keyword[try] :
identifier[self] . identifier[_co... | def get_contacts(self):
"""
Returns list of contacts
Returns:
dict: the roster of contacts
"""
for (jid, item) in self.roster.items.items():
try:
self._contacts[jid.bare()].update(item.export_as_json()) # depends on [control=['try'], data=[]]
exce... |
def create_recomended_articles(main_article, article_list):
'''
Creates recommended article objects from article_list
and _prepends_ to existing recommended articles.
'''
# store existing recommended articles
existing_recommended_articles = [
ra.recommended_article.specific
for ... | def function[create_recomended_articles, parameter[main_article, article_list]]:
constant[
Creates recommended article objects from article_list
and _prepends_ to existing recommended articles.
]
variable[existing_recommended_articles] assign[=] <ast.ListComp object at 0x7da1b036b430>
... | keyword[def] identifier[create_recomended_articles] ( identifier[main_article] , identifier[article_list] ):
literal[string]
identifier[existing_recommended_articles] =[
identifier[ra] . identifier[recommended_article] . identifier[specific]
keyword[for] identifier[ra] keyword[in] ident... | def create_recomended_articles(main_article, article_list):
"""
Creates recommended article objects from article_list
and _prepends_ to existing recommended articles.
"""
# store existing recommended articles
existing_recommended_articles = [ra.recommended_article.specific for ra in main_article... |
def available_discounts(cls, user, categories, products):
''' Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. '''
filtered_clauses = cls._f... | def function[available_discounts, parameter[cls, user, categories, products]]:
constant[ Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. ]
v... | keyword[def] identifier[available_discounts] ( identifier[cls] , identifier[user] , identifier[categories] , identifier[products] ):
literal[string]
identifier[filtered_clauses] = identifier[cls] . identifier[_filtered_clauses] ( identifier[user] )
identifier[categories] = ident... | def available_discounts(cls, user, categories, products):
""" Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. """
filtered_clauses = cls._filtered_c... |
def _GetExtractionErrorsAsWarnings(self):
"""Retrieves errors from from the store, and converts them to warnings.
This method is for backwards compatibility with pre-20190309 storage format
stores which used ExtractionError attribute containers.
Yields:
ExtractionWarning: extraction warnings.
... | def function[_GetExtractionErrorsAsWarnings, parameter[self]]:
constant[Retrieves errors from from the store, and converts them to warnings.
This method is for backwards compatibility with pre-20190309 storage format
stores which used ExtractionError attribute containers.
Yields:
ExtractionW... | keyword[def] identifier[_GetExtractionErrorsAsWarnings] ( identifier[self] ):
literal[string]
keyword[for] identifier[extraction_error] keyword[in] identifier[self] . identifier[_GetAttributeContainers] (
identifier[self] . identifier[_CONTAINER_TYPE_EXTRACTION_ERROR] ):
identifier[error_att... | def _GetExtractionErrorsAsWarnings(self):
"""Retrieves errors from from the store, and converts them to warnings.
This method is for backwards compatibility with pre-20190309 storage format
stores which used ExtractionError attribute containers.
Yields:
ExtractionWarning: extraction warnings.
... |
def _type_repr(obj):
"""Return the repr() of an object, special-casing types (internal helper).
If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. For everything
else, we fall ... | def function[_type_repr, parameter[obj]]:
constant[Return the repr() of an object, special-casing types (internal helper).
If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. Fo... | keyword[def] identifier[_type_repr] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[type] ) keyword[and] keyword[not] identifier[isinstance] ( identifier[obj] , identifier[TypingMeta] ):
keyword[if] identifier[obj] . identifier[__module__]... | def _type_repr(obj):
"""Return the repr() of an object, special-casing types (internal helper).
If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. For everything
else, we fall ... |
def constant_time_cmp(a, b):
'''Compare two strings using constant time.'''
result = True
for x, y in zip(a, b):
result &= (x == y)
return result | def function[constant_time_cmp, parameter[a, b]]:
constant[Compare two strings using constant time.]
variable[result] assign[=] constant[True]
for taget[tuple[[<ast.Name object at 0x7da20e962470>, <ast.Name object at 0x7da20e962b90>]]] in starred[call[name[zip], parameter[name[a], name[b]]]] beg... | keyword[def] identifier[constant_time_cmp] ( identifier[a] , identifier[b] ):
literal[string]
identifier[result] = keyword[True]
keyword[for] identifier[x] , identifier[y] keyword[in] identifier[zip] ( identifier[a] , identifier[b] ):
identifier[result] &=( identifier[x] == identifier[y] ... | def constant_time_cmp(a, b):
"""Compare two strings using constant time."""
result = True
for (x, y) in zip(a, b):
result &= x == y # depends on [control=['for'], data=[]]
return result |
def validate(self):
"""
Check that the Xmrs is well-formed.
The Xmrs is analyzed and a list of problems is compiled. If
any problems exist, an :exc:`XmrsError` is raised with the list
joined as the error message. A well-formed Xmrs has the
following properties:
... | def function[validate, parameter[self]]:
constant[
Check that the Xmrs is well-formed.
The Xmrs is analyzed and a list of problems is compiled. If
any problems exist, an :exc:`XmrsError` is raised with the list
joined as the error message. A well-formed Xmrs has the
foll... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
identifier[errors] =[]
identifier[ivs] , identifier[bvs] ={},{}
identifier[_vars] = identifier[self] . identifier[_vars]
identifier[_hcons] = identifier[self] . identifier[_hcons]
identifie... | def validate(self):
"""
Check that the Xmrs is well-formed.
The Xmrs is analyzed and a list of problems is compiled. If
any problems exist, an :exc:`XmrsError` is raised with the list
joined as the error message. A well-formed Xmrs has the
following properties:
* Al... |
def download_shared_files(job, config):
"""
Downloads shared reference files for Toil Germline pipeline
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options
:return: Updated config with shared fileStoreIDS
:rtype: Namespace
... | def function[download_shared_files, parameter[job, config]]:
constant[
Downloads shared reference files for Toil Germline pipeline
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options
:return: Updated config with shared fileStor... | keyword[def] identifier[download_shared_files] ( identifier[job] , identifier[config] ):
literal[string]
identifier[job] . identifier[fileStore] . identifier[logToMaster] ( literal[string] )
identifier[shared_files] ={ literal[string] , literal[string] , literal[string] }
identifier[nonessential_... | def download_shared_files(job, config):
"""
Downloads shared reference files for Toil Germline pipeline
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options
:return: Updated config with shared fileStoreIDS
:rtype: Namespace
... |
def get_particles_featuring(feature_rad, state_name=None, im_name=None,
use_full_path=False, actual_rad=None, invert=True, featuring_params={},
**kwargs):
"""
Combines centroid featuring with the globals from a previous state.
Runs trackpy.locate on an image, sets the globals from a previou... | def function[get_particles_featuring, parameter[feature_rad, state_name, im_name, use_full_path, actual_rad, invert, featuring_params]]:
constant[
Combines centroid featuring with the globals from a previous state.
Runs trackpy.locate on an image, sets the globals from a previous state,
calls _tran... | keyword[def] identifier[get_particles_featuring] ( identifier[feature_rad] , identifier[state_name] = keyword[None] , identifier[im_name] = keyword[None] ,
identifier[use_full_path] = keyword[False] , identifier[actual_rad] = keyword[None] , identifier[invert] = keyword[True] , identifier[featuring_params] ={},
** i... | def get_particles_featuring(feature_rad, state_name=None, im_name=None, use_full_path=False, actual_rad=None, invert=True, featuring_params={}, **kwargs):
"""
Combines centroid featuring with the globals from a previous state.
Runs trackpy.locate on an image, sets the globals from a previous state,
cal... |
async def log(
self,
date: datetime.date = None,
days: int = None,
details: bool = False) -> list:
"""Get watering information for X days from Y date."""
endpoint = 'watering/log'
if details:
endpoint += '/details'
if date and ... | <ast.AsyncFunctionDef object at 0x7da18fe908e0> | keyword[async] keyword[def] identifier[log] (
identifier[self] ,
identifier[date] : identifier[datetime] . identifier[date] = keyword[None] ,
identifier[days] : identifier[int] = keyword[None] ,
identifier[details] : identifier[bool] = keyword[False] )-> identifier[list] :
literal[string]
iden... | async def log(self, date: datetime.date=None, days: int=None, details: bool=False) -> list:
"""Get watering information for X days from Y date."""
endpoint = 'watering/log'
if details:
endpoint += '/details' # depends on [control=['if'], data=[]]
if date and days:
endpoint = '{0}/{1}/{2... |
def eval_stdin():
'evaluate expressions read from stdin'
cmd = ['plash', 'eval']
p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout)
exit = p.wait()
if exit:
raise subprocess.CalledProcessError(exit, cmd) | def function[eval_stdin, parameter[]]:
constant[evaluate expressions read from stdin]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b1297250>, <ast.Constant object at 0x7da1b12953f0>]]
variable[p] assign[=] call[name[subprocess].Popen, parameter[name[cmd]]]
variable[exit] a... | keyword[def] identifier[eval_stdin] ():
literal[string]
identifier[cmd] =[ literal[string] , literal[string] ]
identifier[p] = identifier[subprocess] . identifier[Popen] ( identifier[cmd] , identifier[stdin] = identifier[sys] . identifier[stdin] , identifier[stdout] = identifier[sys] . identifier[stdo... | def eval_stdin():
"""evaluate expressions read from stdin"""
cmd = ['plash', 'eval']
p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout)
exit = p.wait()
if exit:
raise subprocess.CalledProcessError(exit, cmd) # depends on [control=['if'], data=[]] |
def _get_role(rolename):
"""Reads and parses a file containing a role"""
path = os.path.join('roles', rolename + '.json')
if not os.path.exists(path):
abort("Couldn't read role file {0}".format(path))
with open(path, 'r') as f:
try:
role = json.loads(f.read())
except ... | def function[_get_role, parameter[rolename]]:
constant[Reads and parses a file containing a role]
variable[path] assign[=] call[name[os].path.join, parameter[constant[roles], binary_operation[name[rolename] + constant[.json]]]]
if <ast.UnaryOp object at 0x7da1b12b8790> begin[:]
c... | keyword[def] identifier[_get_role] ( identifier[rolename] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( literal[string] , identifier[rolename] + literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifi... | def _get_role(rolename):
"""Reads and parses a file containing a role"""
path = os.path.join('roles', rolename + '.json')
if not os.path.exists(path):
abort("Couldn't read role file {0}".format(path)) # depends on [control=['if'], data=[]]
with open(path, 'r') as f:
try:
rol... |
def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Create an augmenter to add poisson noise to images.
Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from
a poisson distribution instead of... | def function[AdditivePoissonNoise, parameter[lam, per_channel, name, deterministic, random_state]]:
constant[
Create an augmenter to add poisson noise to images.
Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from
a poisson distribution ins... | keyword[def] identifier[AdditivePoissonNoise] ( identifier[lam] = literal[int] , identifier[per_channel] = keyword[False] , identifier[name] = keyword[None] , identifier[deterministic] = keyword[False] , identifier[random_state] = keyword[None] ):
literal[string]
identifier[lam2] = identifier[iap] . identi... | def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Create an augmenter to add poisson noise to images.
Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from
a poisson distribution instead of... |
def process_filter_directive(filter_operation_info, location, context):
"""Return a Filter basic block that corresponds to the filter operation in the directive.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
of the field ... | def function[process_filter_directive, parameter[filter_operation_info, location, context]]:
constant[Return a Filter basic block that corresponds to the filter operation in the directive.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
... | keyword[def] identifier[process_filter_directive] ( identifier[filter_operation_info] , identifier[location] , identifier[context] ):
literal[string]
identifier[op_name] , identifier[operator_params] = identifier[_get_filter_op_name_and_values] ( identifier[filter_operation_info] . identifier[directive] )
... | def process_filter_directive(filter_operation_info, location, context):
"""Return a Filter basic block that corresponds to the filter operation in the directive.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
of the field ... |
def _resample_residuals(self, stars, epsf):
"""
Compute normalized residual images for all the input stars.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object
The ePSF model.
Retu... | def function[_resample_residuals, parameter[self, stars, epsf]]:
constant[
Compute normalized residual images for all the input stars.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object
Th... | keyword[def] identifier[_resample_residuals] ( identifier[self] , identifier[stars] , identifier[epsf] ):
literal[string]
identifier[shape] =( identifier[stars] . identifier[n_good_stars] , identifier[epsf] . identifier[shape] [ literal[int] ], identifier[epsf] . identifier[shape] [ literal[int] ]... | def _resample_residuals(self, stars, epsf):
"""
Compute normalized residual images for all the input stars.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object
The ePSF model.
Returns
... |
def update(self):
"""Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
>>> from hydpy import rou... | def function[update, parameter[self]]:
constant[Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
... | keyword[def] identifier[update] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[subpars] . identifier[pars] . identifier[control]
identifier[self] ( identifier[con] . identifier[hinz] * identifier[con] . identifier[lai] ) | def update(self):
"""Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
>>> from hydpy import round_
... |
def getMonthName(self):
'''
This exists as a separate method because sometimes events should really
belong to more than one month (e.g. class series that persist over multiple months).
'''
class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrenc... | def function[getMonthName, parameter[self]]:
constant[
This exists as a separate method because sometimes events should really
belong to more than one month (e.g. class series that persist over multiple months).
]
variable[class_counter] assign[=] call[name[Counter], parameter[<a... | keyword[def] identifier[getMonthName] ( identifier[self] ):
literal[string]
identifier[class_counter] = identifier[Counter] ([( identifier[x] . identifier[startTime] . identifier[year] , identifier[x] . identifier[startTime] . identifier[month] ) keyword[for] identifier[x] keyword[in] identifier... | def getMonthName(self):
"""
This exists as a separate method because sometimes events should really
belong to more than one month (e.g. class series that persist over multiple months).
"""
class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrence_set.al... |
def init_widget(self):
""" Bind the on property to the checked state """
super(UiKitSlider, self).init_widget()
d = self.declaration
if d.min:
self.set_min(d.min)
if d.max:
self.set_max(d.max)
if d.progress:
self.set_progress(d.progres... | def function[init_widget, parameter[self]]:
constant[ Bind the on property to the checked state ]
call[call[name[super], parameter[name[UiKitSlider], name[self]]].init_widget, parameter[]]
variable[d] assign[=] name[self].declaration
if name[d].min begin[:]
call[name[self... | keyword[def] identifier[init_widget] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[UiKitSlider] , identifier[self] ). identifier[init_widget] ()
identifier[d] = identifier[self] . identifier[declaration]
keyword[if] identifier[d] . identifier[min] :
... | def init_widget(self):
""" Bind the on property to the checked state """
super(UiKitSlider, self).init_widget()
d = self.declaration
if d.min:
self.set_min(d.min) # depends on [control=['if'], data=[]]
if d.max:
self.set_max(d.max) # depends on [control=['if'], data=[]]
if d.pr... |
def articles(self):
"""
articles getter
"""
if self._articles is None:
self._articles = []
for doc in self.docs:
# ensure all fields in the "fl" are in the doc to address
# issue #38
for k in set(self.fl).difference(... | def function[articles, parameter[self]]:
constant[
articles getter
]
if compare[name[self]._articles is constant[None]] begin[:]
name[self]._articles assign[=] list[[]]
for taget[name[doc]] in starred[name[self].docs] begin[:]
for t... | keyword[def] identifier[articles] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_articles] keyword[is] keyword[None] :
identifier[self] . identifier[_articles] =[]
keyword[for] identifier[doc] keyword[in] identifier[self] . identifie... | def articles(self):
"""
articles getter
"""
if self._articles is None:
self._articles = []
for doc in self.docs:
# ensure all fields in the "fl" are in the doc to address
# issue #38
for k in set(self.fl).difference(doc.keys()):
... |
def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the code
tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE)
tables = [tbl
for block in tabl... | def function[extract_table_names, parameter[query]]:
constant[ Extract table names from an SQL query. ]
variable[tables_blocks] assign[=] call[name[re].findall, parameter[constant[(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)], name[query], name[re].IGNORECASE]]
variable[tables] assign[=] <ast.ListComp o... | keyword[def] identifier[extract_table_names] ( identifier[query] ):
literal[string]
identifier[tables_blocks] = identifier[re] . identifier[findall] ( literal[string] , identifier[query] , identifier[re] . identifier[IGNORECASE] )
identifier[tables] =[ identifier[tbl]
keyword[for] identifi... | def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the code
tables_blocks = re.findall('(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)
tables = [tbl for block in tables_blocks ... |
def emit(self, *args, **kwargs):
"""
Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration.
"""
for callback in self.callbacks:
... | def function[emit, parameter[self]]:
constant[
Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration.
]
for taget[name[callback]] in star... | keyword[def] identifier[emit] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[callback] keyword[in] identifier[self] . identifier[callbacks] :
identifier[callback] (* identifier[args] ,** identifier[kwargs] ) | def emit(self, *args, **kwargs):
"""
Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration.
"""
for callback in self.callbacks:
callback(... |
def write_def_decl(self, node, identifiers):
"""write a locally-available callable referencing a top-level def"""
funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(as_call=True)
if not self.in_def and (
... | def function[write_def_decl, parameter[self, node, identifiers]]:
constant[write a locally-available callable referencing a top-level def]
variable[funcname] assign[=] name[node].funcname
variable[namedecls] assign[=] call[name[node].get_argument_expressions, parameter[]]
variable[namear... | keyword[def] identifier[write_def_decl] ( identifier[self] , identifier[node] , identifier[identifiers] ):
literal[string]
identifier[funcname] = identifier[node] . identifier[funcname]
identifier[namedecls] = identifier[node] . identifier[get_argument_expressions] ()
identifier[... | def write_def_decl(self, node, identifiers):
"""write a locally-available callable referencing a top-level def"""
funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(as_call=True)
if not self.in_def and (len(self.identifiers.locally_assigned)... |
def get_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns a list of all (leaves and internal) descendant nodes."""
return [n for n in self.iter_descendants(
strategy=strategy, is_leaf_fn=is_leaf_fn)] | def function[get_descendants, parameter[self, strategy, is_leaf_fn]]:
constant[ Returns a list of all (leaves and internal) descendant nodes.]
return[<ast.ListComp object at 0x7da1b0fec880>] | keyword[def] identifier[get_descendants] ( identifier[self] , identifier[strategy] = literal[string] , identifier[is_leaf_fn] = keyword[None] ):
literal[string]
keyword[return] [ identifier[n] keyword[for] identifier[n] keyword[in] identifier[self] . identifier[iter_descendants] (
iden... | def get_descendants(self, strategy='levelorder', is_leaf_fn=None):
""" Returns a list of all (leaves and internal) descendant nodes."""
return [n for n in self.iter_descendants(strategy=strategy, is_leaf_fn=is_leaf_fn)] |
def switch(poi):
"""
Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product within this
container is a... | def function[switch, parameter[poi]]:
constant[
Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product... | keyword[def] identifier[switch] ( identifier[poi] ):
literal[string]
identifier[parts] = identifier[poi] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[parts] )== literal[int] :
identifier[container_name] , identifier[product_name] = identifier[parts]
... | def switch(poi):
"""
Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product within this
container is a... |
def set(self, subject_id, entity_id, info, timestamp=0):
""" Stores session information in the cache. Assumes that the subject_id
is unique within the context of the Service Provider.
:param subject_id: The subject identifier
:param entity_id: The identifier of the entity_id/receiver of... | def function[set, parameter[self, subject_id, entity_id, info, timestamp]]:
constant[ Stores session information in the cache. Assumes that the subject_id
is unique within the context of the Service Provider.
:param subject_id: The subject identifier
:param entity_id: The identifier of ... | keyword[def] identifier[set] ( identifier[self] , identifier[subject_id] , identifier[entity_id] , identifier[info] , identifier[timestamp] = literal[int] ):
literal[string]
identifier[entities] = identifier[self] . identifier[_cache] . identifier[get] ( identifier[subject_id] )
keyword[if... | def set(self, subject_id, entity_id, info, timestamp=0):
""" Stores session information in the cache. Assumes that the subject_id
is unique within the context of the Service Provider.
:param subject_id: The subject identifier
:param entity_id: The identifier of the entity_id/receiver of an
... |
def items_overlap_with_suffix(left, lsuffix, right, rsuffix):
"""
If two indices overlap, add suffixes to overlapping entries.
If corresponding suffix is empty, the entry is simply converted to string.
"""
to_rename = left.intersection(right)
if len(to_rename) == 0:
return left, right
... | def function[items_overlap_with_suffix, parameter[left, lsuffix, right, rsuffix]]:
constant[
If two indices overlap, add suffixes to overlapping entries.
If corresponding suffix is empty, the entry is simply converted to string.
]
variable[to_rename] assign[=] call[name[left].intersection,... | keyword[def] identifier[items_overlap_with_suffix] ( identifier[left] , identifier[lsuffix] , identifier[right] , identifier[rsuffix] ):
literal[string]
identifier[to_rename] = identifier[left] . identifier[intersection] ( identifier[right] )
keyword[if] identifier[len] ( identifier[to_rename] )== li... | def items_overlap_with_suffix(left, lsuffix, right, rsuffix):
"""
If two indices overlap, add suffixes to overlapping entries.
If corresponding suffix is empty, the entry is simply converted to string.
"""
to_rename = left.intersection(right)
if len(to_rename) == 0:
return (left, right... |
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True):
# pylint: disable = attribute-defined-outside-init,arguments-differ
"""
Fit gradient boosting classifier
Parameters
----------
X : array_like
... | def function[fit, parameter[self, X, y, sample_weight, eval_set, eval_metric, early_stopping_rounds, verbose]]:
constant[
Fit gradient boosting classifier
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_wei... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] , identifier[sample_weight] = keyword[None] , identifier[eval_set] = keyword[None] , identifier[eval_metric] = keyword[None] ,
identifier[early_stopping_rounds] = keyword[None] , identifier[verbose] = keyword[True] ):
literal[s... | def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True):
# pylint: disable = attribute-defined-outside-init,arguments-differ
"\n Fit gradient boosting classifier\n\n Parameters\n ----------\n X : array_like\n Featu... |
def get_context(pid_file, daemon=False):
"""Get context of running notebook.
A context file is created when notebook starts.
:param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check.
:return: dict or None if the process is dead/not launcherd
"""
port_f... | def function[get_context, parameter[pid_file, daemon]]:
constant[Get context of running notebook.
A context file is created when notebook starts.
:param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check.
:return: dict or None if the process is dead/not lau... | keyword[def] identifier[get_context] ( identifier[pid_file] , identifier[daemon] = keyword[False] ):
literal[string]
identifier[port_file] = identifier[get_context_file_name] ( identifier[pid_file] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[port_f... | def get_context(pid_file, daemon=False):
"""Get context of running notebook.
A context file is created when notebook starts.
:param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check.
:return: dict or None if the process is dead/not launcherd
"""
port_f... |
def _select_labels(self, segmentation, labels=None):
""" Get selection of labels from input segmentation
:param segmentation:
:param labels:
:return:
"""
logger.debug("select_labels() started with labels={}".format(labels))
if self.slab is not None and labels is... | def function[_select_labels, parameter[self, segmentation, labels]]:
constant[ Get selection of labels from input segmentation
:param segmentation:
:param labels:
:return:
]
call[name[logger].debug, parameter[call[constant[select_labels() started with labels={}].format, ... | keyword[def] identifier[_select_labels] ( identifier[self] , identifier[segmentation] , identifier[labels] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[labels] ))
keyword[if] identifier[self] . identifier[sl... | def _select_labels(self, segmentation, labels=None):
""" Get selection of labels from input segmentation
:param segmentation:
:param labels:
:return:
"""
logger.debug('select_labels() started with labels={}'.format(labels))
if self.slab is not None and labels is not None:
... |
def logs(self, container_id, stderr=True, stream=True):
"""
acquire output (stdout, stderr) from provided container
:param container_id: str
:param stderr: True, False
:param stream: if True, return as generator
:return: either generator, or list of strings
"""
... | def function[logs, parameter[self, container_id, stderr, stream]]:
constant[
acquire output (stdout, stderr) from provided container
:param container_id: str
:param stderr: True, False
:param stream: if True, return as generator
:return: either generator, or list of stri... | keyword[def] identifier[logs] ( identifier[self] , identifier[container_id] , identifier[stderr] = keyword[True] , identifier[stream] = keyword[True] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[container_id] )
identifier[logger] . identifier[debu... | def logs(self, container_id, stderr=True, stream=True):
"""
acquire output (stdout, stderr) from provided container
:param container_id: str
:param stderr: True, False
:param stream: if True, return as generator
:return: either generator, or list of strings
"""
l... |
def find_package(name, installed, package=False):
'''Finds a package in the installed list.
If `package` is true, match package names, otherwise, match import paths.
'''
if package:
name = name.lower()
tests = (
lambda x: x.user and name == x.name.lower(),
lambda... | def function[find_package, parameter[name, installed, package]]:
constant[Finds a package in the installed list.
If `package` is true, match package names, otherwise, match import paths.
]
if name[package] begin[:]
variable[name] assign[=] call[name[name].lower, parameter[]]
... | keyword[def] identifier[find_package] ( identifier[name] , identifier[installed] , identifier[package] = keyword[False] ):
literal[string]
keyword[if] identifier[package] :
identifier[name] = identifier[name] . identifier[lower] ()
identifier[tests] =(
keyword[lambda] identifie... | def find_package(name, installed, package=False):
"""Finds a package in the installed list.
If `package` is true, match package names, otherwise, match import paths.
"""
if package:
name = name.lower()
tests = (lambda x: x.user and name == x.name.lower(), lambda x: x.local and name == x... |
def cli(ctx, organism_id, common_name, directory, blatdb="", species="", genus="", public=False):
"""Update an organism
Output:
a dictionary with information about the new organism
"""
return ctx.gi.organisms.update_organism(organism_id, common_name, directory, blatdb=blatdb, species=species, genus=ge... | def function[cli, parameter[ctx, organism_id, common_name, directory, blatdb, species, genus, public]]:
constant[Update an organism
Output:
a dictionary with information about the new organism
]
return[call[name[ctx].gi.organisms.update_organism, parameter[name[organism_id], name[common_name], nam... | keyword[def] identifier[cli] ( identifier[ctx] , identifier[organism_id] , identifier[common_name] , identifier[directory] , identifier[blatdb] = literal[string] , identifier[species] = literal[string] , identifier[genus] = literal[string] , identifier[public] = keyword[False] ):
literal[string]
keyword[re... | def cli(ctx, organism_id, common_name, directory, blatdb='', species='', genus='', public=False):
"""Update an organism
Output:
a dictionary with information about the new organism
"""
return ctx.gi.organisms.update_organism(organism_id, common_name, directory, blatdb=blatdb, species=species, genus=ge... |
def initialize(self,num_reals=1,enforce_bounds="reset",
parensemble=None,obsensemble=None,restart_obsensemble=None):
"""Initialize. Depending on arguments, draws or loads
initial parameter observations ensembles and runs the initial parameter
ensemble
Parameters
... | def function[initialize, parameter[self, num_reals, enforce_bounds, parensemble, obsensemble, restart_obsensemble]]:
constant[Initialize. Depending on arguments, draws or loads
initial parameter observations ensembles and runs the initial parameter
ensemble
Parameters
---------... | keyword[def] identifier[initialize] ( identifier[self] , identifier[num_reals] = literal[int] , identifier[enforce_bounds] = literal[string] ,
identifier[parensemble] = keyword[None] , identifier[obsensemble] = keyword[None] , identifier[restart_obsensemble] = keyword[None] ):
literal[string]
ide... | def initialize(self, num_reals=1, enforce_bounds='reset', parensemble=None, obsensemble=None, restart_obsensemble=None):
"""Initialize. Depending on arguments, draws or loads
initial parameter observations ensembles and runs the initial parameter
ensemble
Parameters
----------
... |
def _convert_xml_to_service_properties(xml):
'''
<?xml version="1.0" encoding="utf-8"?>
<StorageServiceProperties>
<Logging>
<Version>version-number</Version>
<Delete>true|false</Delete>
<Read>true|false</Read>
<Write>true|false</Write>
<Re... | def function[_convert_xml_to_service_properties, parameter[xml]]:
constant[
<?xml version="1.0" encoding="utf-8"?>
<StorageServiceProperties>
<Logging>
<Version>version-number</Version>
<Delete>true|false</Delete>
<Read>true|false</Read>
<Write>tru... | keyword[def] identifier[_convert_xml_to_service_properties] ( identifier[xml] ):
literal[string]
identifier[service_properties_element] = identifier[ETree] . identifier[fromstring] ( identifier[xml] )
identifier[service_properties] = identifier[ServiceProperties] ()
identifier[logging] = id... | def _convert_xml_to_service_properties(xml):
"""
<?xml version="1.0" encoding="utf-8"?>
<StorageServiceProperties>
<Logging>
<Version>version-number</Version>
<Delete>true|false</Delete>
<Read>true|false</Read>
<Write>true|false</Write>
<Re... |
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolida... | def function[_consolidate_repo_sources, parameter[sources]]:
constant[
Consolidate APT sources.
]
if <ast.UnaryOp object at 0x7da1b20468f0> begin[:]
<ast.Raise object at 0x7da1b2045d50>
variable[consolidated] assign[=] dictionary[[], []]
variable[delete_files] assign[=] c... | keyword[def] identifier[_consolidate_repo_sources] ( identifier[sources] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[sources] , identifier[sourceslist] . identifier[SourcesList] ):
keyword[raise] identifier[TypeError] (
literal[string] . identifier[f... | def _consolidate_repo_sources(sources):
"""
Consolidate APT sources.
"""
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError("'{0}' not a '{1}'".format(type(sources), sourceslist.SourcesList)) # depends on [control=['if'], data=[]]
consolidated = {}
delete_files = set()... |
def create_header(self, depth):
"""Create and return a widget that will be used as a header for the given depth
Override this method if you want to have header widgets.
The default implementation returns None.
You can return None if you do not want a header for the given depth
... | def function[create_header, parameter[self, depth]]:
constant[Create and return a widget that will be used as a header for the given depth
Override this method if you want to have header widgets.
The default implementation returns None.
You can return None if you do not want a header fo... | keyword[def] identifier[create_header] ( identifier[self] , identifier[depth] ):
literal[string]
keyword[if] keyword[not] ( identifier[depth] >= literal[int] keyword[and] identifier[depth] < identifier[len] ( identifier[self] . identifier[_headertexts] )):
keyword[return]
... | def create_header(self, depth):
"""Create and return a widget that will be used as a header for the given depth
Override this method if you want to have header widgets.
The default implementation returns None.
You can return None if you do not want a header for the given depth
:par... |
def wait_for_completion(self, timeout):
"""Waits until the task is done (including all sub-operations)
with a given timeout in milliseconds; specify -1 for an indefinite wait.
Note that the VirtualBox/XPCOM/COM/native event queues of the calling
thread are not processed while wa... | def function[wait_for_completion, parameter[self, timeout]]:
constant[Waits until the task is done (including all sub-operations)
with a given timeout in milliseconds; specify -1 for an indefinite wait.
Note that the VirtualBox/XPCOM/COM/native event queues of the calling
thread... | keyword[def] identifier[wait_for_completion] ( identifier[self] , identifier[timeout] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[timeout] , identifier[baseinteger] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[se... | def wait_for_completion(self, timeout):
"""Waits until the task is done (including all sub-operations)
with a given timeout in milliseconds; specify -1 for an indefinite wait.
Note that the VirtualBox/XPCOM/COM/native event queues of the calling
thread are not processed while waitin... |
def get_conf_file(self):
"""
Get config from local config file, first try cache, then fallback.
"""
for conf_file in [self.collection_rules_file, self.fallback_file]:
logger.debug("trying to read conf from: " + conf_file)
conf = self.try_disk(conf_file, self.gpg)
... | def function[get_conf_file, parameter[self]]:
constant[
Get config from local config file, first try cache, then fallback.
]
for taget[name[conf_file]] in starred[list[[<ast.Attribute object at 0x7da18dc98b50>, <ast.Attribute object at 0x7da18dc996f0>]]] begin[:]
call[nam... | keyword[def] identifier[get_conf_file] ( identifier[self] ):
literal[string]
keyword[for] identifier[conf_file] keyword[in] [ identifier[self] . identifier[collection_rules_file] , identifier[self] . identifier[fallback_file] ]:
identifier[logger] . identifier[debug] ( literal[string... | def get_conf_file(self):
"""
Get config from local config file, first try cache, then fallback.
"""
for conf_file in [self.collection_rules_file, self.fallback_file]:
logger.debug('trying to read conf from: ' + conf_file)
conf = self.try_disk(conf_file, self.gpg)
if not c... |
def cancel_order(self, order_param):
"""Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
"""
order_id = order_param
if isinstance(order_param, zipline.protocol.Order):
order_id ... | def function[cancel_order, parameter[self, order_param]]:
constant[Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
]
variable[order_id] assign[=] name[order_param]
if call[name[isinstance]... | keyword[def] identifier[cancel_order] ( identifier[self] , identifier[order_param] ):
literal[string]
identifier[order_id] = identifier[order_param]
keyword[if] identifier[isinstance] ( identifier[order_param] , identifier[zipline] . identifier[protocol] . identifier[Order] ):
... | def cancel_order(self, order_param):
"""Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
"""
order_id = order_param
if isinstance(order_param, zipline.protocol.Order):
order_id = order_param.id... |
def _cas_1(self):
'''1 - The desired structure is entirely contained into one image.'''
lonc = self._format_lon(self.lonm)
latc = self._format_lat(self.latm)
img = self._format_name_map(lonc, latc)
img_map = BinaryTable(img, self.path_pdsfiles)
return img_map.extract_gr... | def function[_cas_1, parameter[self]]:
constant[1 - The desired structure is entirely contained into one image.]
variable[lonc] assign[=] call[name[self]._format_lon, parameter[name[self].lonm]]
variable[latc] assign[=] call[name[self]._format_lat, parameter[name[self].latm]]
variable[im... | keyword[def] identifier[_cas_1] ( identifier[self] ):
literal[string]
identifier[lonc] = identifier[self] . identifier[_format_lon] ( identifier[self] . identifier[lonm] )
identifier[latc] = identifier[self] . identifier[_format_lat] ( identifier[self] . identifier[latm] )
identi... | def _cas_1(self):
"""1 - The desired structure is entirely contained into one image."""
lonc = self._format_lon(self.lonm)
latc = self._format_lat(self.latm)
img = self._format_name_map(lonc, latc)
img_map = BinaryTable(img, self.path_pdsfiles)
return img_map.extract_grid(self.lonm, self.lonM, s... |
def export_to_xml(self, block, xmlfile):
"""
Export the block to XML, writing the XML to `xmlfile`.
"""
root = etree.Element("unknown_root", nsmap=XML_NAMESPACES)
tree = etree.ElementTree(root)
block.add_xml_to_node(root)
# write asides as children
for asi... | def function[export_to_xml, parameter[self, block, xmlfile]]:
constant[
Export the block to XML, writing the XML to `xmlfile`.
]
variable[root] assign[=] call[name[etree].Element, parameter[constant[unknown_root]]]
variable[tree] assign[=] call[name[etree].ElementTree, parameter[... | keyword[def] identifier[export_to_xml] ( identifier[self] , identifier[block] , identifier[xmlfile] ):
literal[string]
identifier[root] = identifier[etree] . identifier[Element] ( literal[string] , identifier[nsmap] = identifier[XML_NAMESPACES] )
identifier[tree] = identifier[etree] . iden... | def export_to_xml(self, block, xmlfile):
"""
Export the block to XML, writing the XML to `xmlfile`.
"""
root = etree.Element('unknown_root', nsmap=XML_NAMESPACES)
tree = etree.ElementTree(root)
block.add_xml_to_node(root)
# write asides as children
for aside in self.get_asides(bl... |
def getInstitutions(self, tags = None, seperator = ";", _getTag = False):
"""Returns a list with the names of the institution. The optional arguments are ignored
# Returns
`list [str]`
> A list with 1 entry the name of the institution
"""
if tags is None:
t... | def function[getInstitutions, parameter[self, tags, seperator, _getTag]]:
constant[Returns a list with the names of the institution. The optional arguments are ignored
# Returns
`list [str]`
> A list with 1 entry the name of the institution
]
if compare[name[tags] is c... | keyword[def] identifier[getInstitutions] ( identifier[self] , identifier[tags] = keyword[None] , identifier[seperator] = literal[string] , identifier[_getTag] = keyword[False] ):
literal[string]
keyword[if] identifier[tags] keyword[is] keyword[None] :
identifier[tags] =[]
k... | def getInstitutions(self, tags=None, seperator=';', _getTag=False):
"""Returns a list with the names of the institution. The optional arguments are ignored
# Returns
`list [str]`
> A list with 1 entry the name of the institution
"""
if tags is None:
tags = [] # depend... |
def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... | def function[return_hdr, parameter[self]]:
constant[Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
... | keyword[def] identifier[return_hdr] ( identifier[self] ):
literal[string]
identifier[orig] = identifier[dict] ()
identifier[subj_id] = identifier[str] ()
identifier[start_time] = identifier[datetime] . identifier[fromordinal] ( literal[int] )
keyword[try] :
... | def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... |
def _calc_sfnr(volume,
mask,
):
""" Calculate the the SFNR of a volume
Calculates the Signal to Fluctuation Noise Ratio, the mean divided
by the detrended standard deviation of each brain voxel. Based on
Friedman and Glover, 2006
Parameters
----------
volume :... | def function[_calc_sfnr, parameter[volume, mask]]:
constant[ Calculate the the SFNR of a volume
Calculates the Signal to Fluctuation Noise Ratio, the mean divided
by the detrended standard deviation of each brain voxel. Based on
Friedman and Glover, 2006
Parameters
----------
volume : ... | keyword[def] identifier[_calc_sfnr] ( identifier[volume] ,
identifier[mask] ,
):
literal[string]
identifier[brain_voxels] = identifier[volume] [ identifier[mask] > literal[int] ]
identifier[mean_voxels] = identifier[np] . identifier[nanmean] ( identifier[brain_voxels] , literal[int] )
... | def _calc_sfnr(volume, mask):
""" Calculate the the SFNR of a volume
Calculates the Signal to Fluctuation Noise Ratio, the mean divided
by the detrended standard deviation of each brain voxel. Based on
Friedman and Glover, 2006
Parameters
----------
volume : 4d array, float
Take a ... |
def cull_portals(self, stat, threshold=0.5, comparator=ge):
"""Delete portals whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
"""
comparator = self._lookup_co... | def function[cull_portals, parameter[self, stat, threshold, comparator]]:
constant[Delete portals whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
]
variable[c... | keyword[def] identifier[cull_portals] ( identifier[self] , identifier[stat] , identifier[threshold] = literal[int] , identifier[comparator] = identifier[ge] ):
literal[string]
identifier[comparator] = identifier[self] . identifier[_lookup_comparator] ( identifier[comparator] )
identifier[d... | def cull_portals(self, stat, threshold=0.5, comparator=ge):
"""Delete portals whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
"""
comparator = self._lookup_comparator... |
def apply_train(self, df:DataFrame):
"Transform `self.cat_names` columns in categorical."
self.categories = {}
for n in self.cat_names:
df.loc[:,n] = df.loc[:,n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories | def function[apply_train, parameter[self, df]]:
constant[Transform `self.cat_names` columns in categorical.]
name[self].categories assign[=] dictionary[[], []]
for taget[name[n]] in starred[name[self].cat_names] begin[:]
call[name[df].loc][tuple[[<ast.Slice object at 0x7da1b1ddb9... | keyword[def] identifier[apply_train] ( identifier[self] , identifier[df] : identifier[DataFrame] ):
literal[string]
identifier[self] . identifier[categories] ={}
keyword[for] identifier[n] keyword[in] identifier[self] . identifier[cat_names] :
identifier[df] . identifier[lo... | def apply_train(self, df: DataFrame):
"""Transform `self.cat_names` columns in categorical."""
self.categories = {}
for n in self.cat_names:
df.loc[:, n] = df.loc[:, n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories # depends on [control=['for'], data=['n']] |
def _register_jobs(self):
"""
This method extracts only the "ConcreteJob" class
from modules that were collected by ConfigReader._get_modules().
And, this method called Subject.notify(),
append "ConcreteJob" classes to JobObserver.jobs.
"""
# job_name is hard-cor... | def function[_register_jobs, parameter[self]]:
constant[
This method extracts only the "ConcreteJob" class
from modules that were collected by ConfigReader._get_modules().
And, this method called Subject.notify(),
append "ConcreteJob" classes to JobObserver.jobs.
]
... | keyword[def] identifier[_register_jobs] ( identifier[self] ):
literal[string]
identifier[job_name] = literal[string]
identifier[modules] = identifier[self] . identifier[_get_modules] ()
keyword[for] identifier[section] , identifier[options] keyword[in] identifier[se... | def _register_jobs(self):
"""
This method extracts only the "ConcreteJob" class
from modules that were collected by ConfigReader._get_modules().
And, this method called Subject.notify(),
append "ConcreteJob" classes to JobObserver.jobs.
"""
# job_name is hard-corded
j... |
def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable... | def function[_enum_from_op_string, parameter[op_string]]:
constant[Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a... | keyword[def] identifier[_enum_from_op_string] ( identifier[op_string] ):
literal[string]
keyword[try] :
keyword[return] identifier[_COMPARISON_OPERATORS] [ identifier[op_string] ]
keyword[except] identifier[KeyError] :
identifier[choices] = literal[string] . identifier[join] ( iden... | def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable... |
def full_path(path):
"""Get the real path, expanding links and bashisms"""
return os.path.realpath(os.path.expanduser(os.path.expandvars(path))) | def function[full_path, parameter[path]]:
constant[Get the real path, expanding links and bashisms]
return[call[name[os].path.realpath, parameter[call[name[os].path.expanduser, parameter[call[name[os].path.expandvars, parameter[name[path]]]]]]]] | keyword[def] identifier[full_path] ( identifier[path] ):
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[realpath] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[os] . identifier[path] . identifier[expandvars] ( identifier[path] ))) | def full_path(path):
"""Get the real path, expanding links and bashisms"""
return os.path.realpath(os.path.expanduser(os.path.expandvars(path))) |
def issubset(list1, list2):
"""
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
"""
n = len(list1)
for startpos in range(len(list2) - n + 1):
... | def function[issubset, parameter[list1, list2]]:
constant[
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
]
variable[n] assign[=] call[name[l... | keyword[def] identifier[issubset] ( identifier[list1] , identifier[list2] ):
literal[string]
identifier[n] = identifier[len] ( identifier[list1] )
keyword[for] identifier[startpos] keyword[in] identifier[range] ( identifier[len] ( identifier[list2] )- identifier[n] + literal[int] ):
keywor... | def issubset(list1, list2):
"""
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
"""
n = len(list1)
for startpos in range(len(list2) - n + 1):
... |
def context(self, *notes):
"""
A context manager that appends ``note`` to every diagnostic processed by
this engine.
"""
self._appended_notes += notes
yield
del self._appended_notes[-len(notes):] | def function[context, parameter[self]]:
constant[
A context manager that appends ``note`` to every diagnostic processed by
this engine.
]
<ast.AugAssign object at 0x7da18dc98910>
<ast.Yield object at 0x7da18bccba30>
<ast.Delete object at 0x7da18bcc9120> | keyword[def] identifier[context] ( identifier[self] ,* identifier[notes] ):
literal[string]
identifier[self] . identifier[_appended_notes] += identifier[notes]
keyword[yield]
keyword[del] identifier[self] . identifier[_appended_notes] [- identifier[len] ( identifier[notes] ):] | def context(self, *notes):
"""
A context manager that appends ``note`` to every diagnostic processed by
this engine.
"""
self._appended_notes += notes
yield
del self._appended_notes[-len(notes):] |
def from_response(self, response):
"""
Populates a given objects attributes from a parsed JSON API response.
This helper handles all necessary type coercions as it assigns
attribute values.
"""
for name in self.PROPERTIES:
attr = '_{0}'.format(name)
... | def function[from_response, parameter[self, response]]:
constant[
Populates a given objects attributes from a parsed JSON API response.
This helper handles all necessary type coercions as it assigns
attribute values.
]
for taget[name[name]] in starred[name[self].PROPERTIE... | keyword[def] identifier[from_response] ( identifier[self] , identifier[response] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[self] . identifier[PROPERTIES] :
identifier[attr] = literal[string] . identifier[format] ( identifier[name] )
identif... | def from_response(self, response):
"""
Populates a given objects attributes from a parsed JSON API response.
This helper handles all necessary type coercions as it assigns
attribute values.
"""
for name in self.PROPERTIES:
attr = '_{0}'.format(name)
transform = se... |
def setup_dirs(self, storage_dir):
'''Calculates all the storage and build dirs, and makes sure
the directories exist where necessary.'''
self.storage_dir = expanduser(storage_dir)
if ' ' in self.storage_dir:
raise ValueError('storage dir path cannot contain spaces, please '
... | def function[setup_dirs, parameter[self, storage_dir]]:
constant[Calculates all the storage and build dirs, and makes sure
the directories exist where necessary.]
name[self].storage_dir assign[=] call[name[expanduser], parameter[name[storage_dir]]]
if compare[constant[ ] in name[self].st... | keyword[def] identifier[setup_dirs] ( identifier[self] , identifier[storage_dir] ):
literal[string]
identifier[self] . identifier[storage_dir] = identifier[expanduser] ( identifier[storage_dir] )
keyword[if] literal[string] keyword[in] identifier[self] . identifier[storage_dir] :
... | def setup_dirs(self, storage_dir):
"""Calculates all the storage and build dirs, and makes sure
the directories exist where necessary."""
self.storage_dir = expanduser(storage_dir)
if ' ' in self.storage_dir:
raise ValueError('storage dir path cannot contain spaces, please specify a path wit... |
def bbin(obj: Union[str, Element]) -> str:
""" Boldify built in types
@param obj: object name or id
@return:
"""
return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj | def function[bbin, parameter[obj]]:
constant[ Boldify built in types
@param obj: object name or id
@return:
]
return[<ast.IfExp object at 0x7da1b0627af0>] | keyword[def] identifier[bbin] ( identifier[obj] : identifier[Union] [ identifier[str] , identifier[Element] ])-> identifier[str] :
literal[string]
keyword[return] identifier[obj] . identifier[name] keyword[if] identifier[isinstance] ( identifier[obj] , identifier[Element] ) keyword[else] litera... | def bbin(obj: Union[str, Element]) -> str:
""" Boldify built in types
@param obj: object name or id
@return:
"""
return obj.name if isinstance(obj, Element) else f'**{obj}**' if obj in builtin_names else obj |
def transform_log_prob_fn(log_prob_fn: PotentialFn,
bijector: BijectorNest,
init_state: State = None
) -> Union[PotentialFn, Tuple[PotentialFn, State]]:
"""Transforms a log-prob function using a bijector.
This takes a log-prob function an... | def function[transform_log_prob_fn, parameter[log_prob_fn, bijector, init_state]]:
constant[Transforms a log-prob function using a bijector.
This takes a log-prob function and creates a new log-prob function that now
takes takes state in the domain of the bijector, forward transforms that state
and calls... | keyword[def] identifier[transform_log_prob_fn] ( identifier[log_prob_fn] : identifier[PotentialFn] ,
identifier[bijector] : identifier[BijectorNest] ,
identifier[init_state] : identifier[State] = keyword[None]
)-> identifier[Union] [ identifier[PotentialFn] , identifier[Tuple] [ identifier[PotentialFn] , identifie... | def transform_log_prob_fn(log_prob_fn: PotentialFn, bijector: BijectorNest, init_state: State=None) -> Union[PotentialFn, Tuple[PotentialFn, State]]:
"""Transforms a log-prob function using a bijector.
This takes a log-prob function and creates a new log-prob function that now
takes takes state in the domain o... |
def setdiff(left, *rights, **kwargs):
"""
Exclude data from a collection, like `except` clause in SQL. All collections involved should
have same schema.
:param left: collection to drop data from
:param rights: collection or list of collections
:param distinct: whether to preserve duplicate entr... | def function[setdiff, parameter[left]]:
constant[
Exclude data from a collection, like `except` clause in SQL. All collections involved should
have same schema.
:param left: collection to drop data from
:param rights: collection or list of collections
:param distinct: whether to preserve du... | keyword[def] identifier[setdiff] ( identifier[left] ,* identifier[rights] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[time]
keyword[from] .. identifier[utils] keyword[import] identifier[output]
identifier[distinct] = identifier[kwargs] . identifier[get] ( literal[st... | def setdiff(left, *rights, **kwargs):
"""
Exclude data from a collection, like `except` clause in SQL. All collections involved should
have same schema.
:param left: collection to drop data from
:param rights: collection or list of collections
:param distinct: whether to preserve duplicate entr... |
def index_service(self, service_id):
"""
Index a service in search engine.
"""
from hypermap.aggregator.models import Service
service = Service.objects.get(id=service_id)
if not service.is_valid:
LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % servi... | def function[index_service, parameter[self, service_id]]:
constant[
Index a service in search engine.
]
from relative_module[hypermap.aggregator.models] import module[Service]
variable[service] assign[=] call[name[Service].objects.get, parameter[]]
if <ast.UnaryOp object at 0x7da18c4... | keyword[def] identifier[index_service] ( identifier[self] , identifier[service_id] ):
literal[string]
keyword[from] identifier[hypermap] . identifier[aggregator] . identifier[models] keyword[import] identifier[Service]
identifier[service] = identifier[Service] . identifier[objects] . identifier[g... | def index_service(self, service_id):
"""
Index a service in search engine.
"""
from hypermap.aggregator.models import Service
service = Service.objects.get(id=service_id)
if not service.is_valid:
LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % service... |
def dfa_dot_importer(input_file: str) -> dict:
""" Imports a DFA from a DOT file.
Of DOT files are recognized the following attributes:
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fake [style=invis... | def function[dfa_dot_importer, parameter[input_file]]:
constant[ Imports a DFA from a DOT file.
Of DOT files are recognized the following attributes:
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fa... | keyword[def] identifier[dfa_dot_importer] ( identifier[input_file] : identifier[str] )-> identifier[dict] :
literal[string]
identifier[g] = identifier[pydot] . identifier[graph_from_dot_file] ( identifier[input_file] )[ literal[int] ]
identifier[states] = identifier[set] ()
identifier[init... | def dfa_dot_importer(input_file: str) -> dict:
""" Imports a DFA from a DOT file.
Of DOT files are recognized the following attributes:
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fake [style=invis... |
def _cmp_fstruct(self, s1, s2, frac_tol, mask):
"""
Returns true if a matching exists between s2 and s2
under frac_tol. s2 should be a subset of s1
"""
if len(s2) > len(s1):
raise ValueError("s1 must be larger than s2")
if mask.shape != (len(s2), len(s1)):
... | def function[_cmp_fstruct, parameter[self, s1, s2, frac_tol, mask]]:
constant[
Returns true if a matching exists between s2 and s2
under frac_tol. s2 should be a subset of s1
]
if compare[call[name[len], parameter[name[s2]]] greater[>] call[name[len], parameter[name[s1]]]] begin[... | keyword[def] identifier[_cmp_fstruct] ( identifier[self] , identifier[s1] , identifier[s2] , identifier[frac_tol] , identifier[mask] ):
literal[string]
keyword[if] identifier[len] ( identifier[s2] )> identifier[len] ( identifier[s1] ):
keyword[raise] identifier[ValueError] ( literal[... | def _cmp_fstruct(self, s1, s2, frac_tol, mask):
"""
Returns true if a matching exists between s2 and s2
under frac_tol. s2 should be a subset of s1
"""
if len(s2) > len(s1):
raise ValueError('s1 must be larger than s2') # depends on [control=['if'], data=[]]
if mask.shape !=... |
def emit(self, content, request=None, emitter=None):
""" Serialize response.
:return response: Instance of django.http.Response
"""
# Get emitter for request
emitter = emitter or self.determine_emitter(request)
emitter = emitter(self, request=request, response=content)
... | def function[emit, parameter[self, content, request, emitter]]:
constant[ Serialize response.
:return response: Instance of django.http.Response
]
variable[emitter] assign[=] <ast.BoolOp object at 0x7da204621b10>
variable[emitter] assign[=] call[name[emitter], parameter[name[se... | keyword[def] identifier[emit] ( identifier[self] , identifier[content] , identifier[request] = keyword[None] , identifier[emitter] = keyword[None] ):
literal[string]
identifier[emitter] = identifier[emitter] keyword[or] identifier[self] . identifier[determine_emitter] ( identifier[reques... | def emit(self, content, request=None, emitter=None):
""" Serialize response.
:return response: Instance of django.http.Response
"""
# Get emitter for request
emitter = emitter or self.determine_emitter(request)
emitter = emitter(self, request=request, response=content)
# Serialize ... |
def ckw05(handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid,
sclkdp, packts, rate, nints, starts):
"""
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
... | def function[ckw05, parameter[handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid, sclkdp, packts, rate, nints, starts]]:
constant[
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
... | keyword[def] identifier[ckw05] ( identifier[handle] , identifier[subtype] , identifier[degree] , identifier[begtim] , identifier[endtim] , identifier[inst] , identifier[ref] , identifier[avflag] , identifier[segid] ,
identifier[sclkdp] , identifier[packts] , identifier[rate] , identifier[nints] , identifier[starts] ... | def ckw05(handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid, sclkdp, packts, rate, nints, starts):
"""
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param s... |
def combine_heads(self, x):
"""Combine tensor that has been split.
Args:
x: A tensor [batch_size, num_heads, length, hidden_size/num_heads]
Returns:
A tensor with shape [batch_size, length, hidden_size]
"""
with tf.name_scope("combine_heads"):
batch_size = tf.shape(x)[0]
le... | def function[combine_heads, parameter[self, x]]:
constant[Combine tensor that has been split.
Args:
x: A tensor [batch_size, num_heads, length, hidden_size/num_heads]
Returns:
A tensor with shape [batch_size, length, hidden_size]
]
with call[name[tf].name_scope, parameter[const... | keyword[def] identifier[combine_heads] ( identifier[self] , identifier[x] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[batch_size] = identifier[tf] . identifier[shape] ( identifier[x] )[ literal[int] ]
identifier[length] = identifie... | def combine_heads(self, x):
"""Combine tensor that has been split.
Args:
x: A tensor [batch_size, num_heads, length, hidden_size/num_heads]
Returns:
A tensor with shape [batch_size, length, hidden_size]
"""
with tf.name_scope('combine_heads'):
batch_size = tf.shape(x)[0]
... |
def template_name(self, path, base):
"""Find out the name of a JS template"""
if not base:
path = os.path.basename(path)
if path == base:
base = os.path.dirname(path)
name = re.sub(r"^%s[\/\\]?(.*)%s$" % (
re.escape(base), re.escape(settings.TEMPLATE_E... | def function[template_name, parameter[self, path, base]]:
constant[Find out the name of a JS template]
if <ast.UnaryOp object at 0x7da1b080a800> begin[:]
variable[path] assign[=] call[name[os].path.basename, parameter[name[path]]]
if compare[name[path] equal[==] name[base]] begin... | keyword[def] identifier[template_name] ( identifier[self] , identifier[path] , identifier[base] ):
literal[string]
keyword[if] keyword[not] identifier[base] :
identifier[path] = identifier[os] . identifier[path] . identifier[basename] ( identifier[path] )
keyword[if] identi... | def template_name(self, path, base):
"""Find out the name of a JS template"""
if not base:
path = os.path.basename(path) # depends on [control=['if'], data=[]]
if path == base:
base = os.path.dirname(path) # depends on [control=['if'], data=['path', 'base']]
name = re.sub('^%s[\\/\\\\]... |
def contains_relevant_concept(
s: Influence, relevant_concepts: List[str], cutoff=0.7
) -> bool:
""" Returns true if a given Influence statement has a relevant concept, and
false otherwise. """
return any(
map(lambda c: contains_concept(s, c, cutoff=cutoff), relevant_concepts)
) | def function[contains_relevant_concept, parameter[s, relevant_concepts, cutoff]]:
constant[ Returns true if a given Influence statement has a relevant concept, and
false otherwise. ]
return[call[name[any], parameter[call[name[map], parameter[<ast.Lambda object at 0x7da20c6a8b80>, name[relevant_concepts]... | keyword[def] identifier[contains_relevant_concept] (
identifier[s] : identifier[Influence] , identifier[relevant_concepts] : identifier[List] [ identifier[str] ], identifier[cutoff] = literal[int]
)-> identifier[bool] :
literal[string]
keyword[return] identifier[any] (
identifier[map] ( keyword[la... | def contains_relevant_concept(s: Influence, relevant_concepts: List[str], cutoff=0.7) -> bool:
""" Returns true if a given Influence statement has a relevant concept, and
false otherwise. """
return any(map(lambda c: contains_concept(s, c, cutoff=cutoff), relevant_concepts)) |
def print_brokers(cluster_config, brokers):
"""Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
"""
print("Will rest... | def function[print_brokers, parameter[cluster_config, brokers]]:
constant[Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host nam... | keyword[def] identifier[print_brokers] ( identifier[cluster_config] , identifier[brokers] ):
literal[string]
identifier[print] ( literal[string] . identifier[format] ( identifier[cluster_config] . identifier[name] ))
keyword[for] identifier[id] , identifier[host] keyword[in] identifier[brokers] :
... | def print_brokers(cluster_config, brokers):
"""Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
"""
print('Will rest... |
def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
Args:
input_shape: Shape tuple (tuple of integers) or list of shape tuples
(one per output tensor of the layer). Shape tuples can include None for
free dimensions, instead of an integer.
Returns:
... | def function[compute_output_shape, parameter[self, input_shape]]:
constant[Computes the output shape of the layer.
Args:
input_shape: Shape tuple (tuple of integers) or list of shape tuples
(one per output tensor of the layer). Shape tuples can include None for
free dimensions, instea... | keyword[def] identifier[compute_output_shape] ( identifier[self] , identifier[input_shape] ):
literal[string]
identifier[input_shape] = identifier[tf] . identifier[TensorShape] ( identifier[input_shape] ). identifier[as_list] ()
keyword[if] identifier[self] . identifier[data_format] == literal[string... | def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
Args:
input_shape: Shape tuple (tuple of integers) or list of shape tuples
(one per output tensor of the layer). Shape tuples can include None for
free dimensions, instead of an integer.
Returns:
... |
def ticket_field_options(self, field_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_fields#list-ticket-field-options"
api_path = "/api/v2/ticket_fields/{field_id}/options.json"
api_path = api_path.format(field_id=field_id)
return self.call(api_path, **kwargs) | def function[ticket_field_options, parameter[self, field_id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/ticket_fields#list-ticket-field-options]
variable[api_path] assign[=] constant[/api/v2/ticket_fields/{field_id}/options.json]
variable[api_path] assign[=] call[name[api_path].... | keyword[def] identifier[ticket_field_options] ( identifier[self] , identifier[field_id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[field_id] = identifier[field_id] )
... | def ticket_field_options(self, field_id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/ticket_fields#list-ticket-field-options"""
api_path = '/api/v2/ticket_fields/{field_id}/options.json'
api_path = api_path.format(field_id=field_id)
return self.call(api_path, **kwargs) |
def all_qubits(self) -> FrozenSet[ops.Qid]:
"""Returns the qubits acted upon by Operations in this circuit."""
return frozenset(q for m in self._moments for q in m.qubits) | def function[all_qubits, parameter[self]]:
constant[Returns the qubits acted upon by Operations in this circuit.]
return[call[name[frozenset], parameter[<ast.GeneratorExp object at 0x7da1b1cec220>]]] | keyword[def] identifier[all_qubits] ( identifier[self] )-> identifier[FrozenSet] [ identifier[ops] . identifier[Qid] ]:
literal[string]
keyword[return] identifier[frozenset] ( identifier[q] keyword[for] identifier[m] keyword[in] identifier[self] . identifier[_moments] keyword[for] identifier... | def all_qubits(self) -> FrozenSet[ops.Qid]:
"""Returns the qubits acted upon by Operations in this circuit."""
return frozenset((q for m in self._moments for q in m.qubits)) |
def process_wait_close(process, timeout=0):
"""
Pauses script execution until a given process does not exist.
:param process:
:param timeout:
:return:
"""
ret = AUTO_IT.AU3_ProcessWaitClose(LPCWSTR(process), INT(timeout))
return ret | def function[process_wait_close, parameter[process, timeout]]:
constant[
Pauses script execution until a given process does not exist.
:param process:
:param timeout:
:return:
]
variable[ret] assign[=] call[name[AUTO_IT].AU3_ProcessWaitClose, parameter[call[name[LPCWSTR], parameter[n... | keyword[def] identifier[process_wait_close] ( identifier[process] , identifier[timeout] = literal[int] ):
literal[string]
identifier[ret] = identifier[AUTO_IT] . identifier[AU3_ProcessWaitClose] ( identifier[LPCWSTR] ( identifier[process] ), identifier[INT] ( identifier[timeout] ))
keyword[return] id... | def process_wait_close(process, timeout=0):
"""
Pauses script execution until a given process does not exist.
:param process:
:param timeout:
:return:
"""
ret = AUTO_IT.AU3_ProcessWaitClose(LPCWSTR(process), INT(timeout))
return ret |
def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key]... | def function[merge_dicts, parameter[a, b, path]]:
constant[ Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
]
if compare[name[path] is constant[None]] begin[:]
variable[path] assign[=] list[[]]
for taget[name[key]] in starred[name[b]] be... | keyword[def] identifier[merge_dicts] ( identifier[a] , identifier[b] , identifier[path] = keyword[None] ):
literal[string]
keyword[if] identifier[path] keyword[is] keyword[None] :
identifier[path] =[]
keyword[for] identifier[key] keyword[in] identifier[b] :
keyword[if] identi... | def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = [] # depends on [control=['if'], data=['path']]
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[ke... |
def prettify(self, elem):
"""Parse xml elements for pretty printing"""
from xml.etree import ElementTree
from re import sub
rawString = ElementTree.tostring(elem, 'utf-8')
parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing ta... | def function[prettify, parameter[self, elem]]:
constant[Parse xml elements for pretty printing]
from relative_module[xml.etree] import module[ElementTree]
from relative_module[re] import module[sub]
variable[rawString] assign[=] call[name[ElementTree].tostring, parameter[name[elem], constant[utf... | keyword[def] identifier[prettify] ( identifier[self] , identifier[elem] ):
literal[string]
keyword[from] identifier[xml] . identifier[etree] keyword[import] identifier[ElementTree]
keyword[from] identifier[re] keyword[import] identifier[sub]
identifier[rawString] = ident... | def prettify(self, elem):
"""Parse xml elements for pretty printing"""
from xml.etree import ElementTree
from re import sub
rawString = ElementTree.tostring(elem, 'utf-8')
parsedString = sub('(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing tag
return parsedString[1:] |
def pointcut(self, value):
"""Change of pointcut.
"""
pointcut = getattr(self, Interceptor.POINTCUT)
# for all targets
for target in self.targets:
# unweave old advices
unweave(target, pointcut=pointcut, advices=self.intercepts)
# weave new a... | def function[pointcut, parameter[self, value]]:
constant[Change of pointcut.
]
variable[pointcut] assign[=] call[name[getattr], parameter[name[self], name[Interceptor].POINTCUT]]
for taget[name[target]] in starred[name[self].targets] begin[:]
call[name[unweave], parameter... | keyword[def] identifier[pointcut] ( identifier[self] , identifier[value] ):
literal[string]
identifier[pointcut] = identifier[getattr] ( identifier[self] , identifier[Interceptor] . identifier[POINTCUT] )
keyword[for] identifier[target] keyword[in] identifier[self] . identifi... | def pointcut(self, value):
"""Change of pointcut.
"""
pointcut = getattr(self, Interceptor.POINTCUT)
# for all targets
for target in self.targets:
# unweave old advices
unweave(target, pointcut=pointcut, advices=self.intercepts)
# weave new advices with new pointcut
... |
def log_exception(exc_info=None, stream=None):
"""Log the 'exc_info' tuple in the server log."""
exc_info = exc_info or sys.exc_info()
stream = stream or sys.stderr
try:
from traceback import print_exception
print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)
str... | def function[log_exception, parameter[exc_info, stream]]:
constant[Log the 'exc_info' tuple in the server log.]
variable[exc_info] assign[=] <ast.BoolOp object at 0x7da20c6aace0>
variable[stream] assign[=] <ast.BoolOp object at 0x7da20c6a8040>
<ast.Try object at 0x7da20c6a9600> | keyword[def] identifier[log_exception] ( identifier[exc_info] = keyword[None] , identifier[stream] = keyword[None] ):
literal[string]
identifier[exc_info] = identifier[exc_info] keyword[or] identifier[sys] . identifier[exc_info] ()
identifier[stream] = identifier[stream] keyword[or] identifier[sys... | def log_exception(exc_info=None, stream=None):
"""Log the 'exc_info' tuple in the server log."""
exc_info = exc_info or sys.exc_info()
stream = stream or sys.stderr
try:
from traceback import print_exception
print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)
str... |
def parse_response(self, response):
"""
Parse XMLRPC response
"""
parser, unmarshaller = self.getparser()
parser.feed(response.text.encode('utf-8'))
parser.close()
return unmarshaller.close() | def function[parse_response, parameter[self, response]]:
constant[
Parse XMLRPC response
]
<ast.Tuple object at 0x7da1b0dbf490> assign[=] call[name[self].getparser, parameter[]]
call[name[parser].feed, parameter[call[name[response].text.encode, parameter[constant[utf-8]]]]]
... | keyword[def] identifier[parse_response] ( identifier[self] , identifier[response] ):
literal[string]
identifier[parser] , identifier[unmarshaller] = identifier[self] . identifier[getparser] ()
identifier[parser] . identifier[feed] ( identifier[response] . identifier[text] . identifier[enco... | def parse_response(self, response):
"""
Parse XMLRPC response
"""
(parser, unmarshaller) = self.getparser()
parser.feed(response.text.encode('utf-8'))
parser.close()
return unmarshaller.close() |
def _construct_approximation(self, basis_kwargs, coefs_list):
"""
Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str: )
coefs_list : list(numpy.ndarray)
... | def function[_construct_approximation, parameter[self, basis_kwargs, coefs_list]]:
constant[
Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str: )
coefs_li... | keyword[def] identifier[_construct_approximation] ( identifier[self] , identifier[basis_kwargs] , identifier[coefs_list] ):
literal[string]
identifier[derivs] = identifier[self] . identifier[_construct_derivatives] ( identifier[coefs_list] ,** identifier[basis_kwargs] )
identifier[funcs] =... | def _construct_approximation(self, basis_kwargs, coefs_list):
"""
Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str: )
coefs_list : list(numpy.ndarray)
... |
def computeSVD(self, k, computeU=False, rCond=1e-9):
"""
Computes the singular value decomposition of the RowMatrix.
The given row matrix A of dimension (m X n) is decomposed into
U * s * V'T where
* U: (m X k) (left singular vectors) is a RowMatrix whose
columns a... | def function[computeSVD, parameter[self, k, computeU, rCond]]:
constant[
Computes the singular value decomposition of the RowMatrix.
The given row matrix A of dimension (m X n) is decomposed into
U * s * V'T where
* U: (m X k) (left singular vectors) is a RowMatrix whose
... | keyword[def] identifier[computeSVD] ( identifier[self] , identifier[k] , identifier[computeU] = keyword[False] , identifier[rCond] = literal[int] ):
literal[string]
identifier[j_model] = identifier[self] . identifier[_java_matrix_wrapper] . identifier[call] (
literal[string] , identifier[i... | def computeSVD(self, k, computeU=False, rCond=1e-09):
"""
Computes the singular value decomposition of the RowMatrix.
The given row matrix A of dimension (m X n) is decomposed into
U * s * V'T where
* U: (m X k) (left singular vectors) is a RowMatrix whose
columns are ... |
def MakeDynamicPotentialFunc(kBT_Gamma, density, SpringPotnlFunc):
"""
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the... | def function[MakeDynamicPotentialFunc, parameter[kBT_Gamma, density, SpringPotnlFunc]]:
constant[
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density... | keyword[def] identifier[MakeDynamicPotentialFunc] ( identifier[kBT_Gamma] , identifier[density] , identifier[SpringPotnlFunc] ):
literal[string]
keyword[def] identifier[PotentialFunc] ( identifier[xdata] , identifier[Radius] ):
literal[string]
identifier[mass] =(( literal[int] / literal... | def MakeDynamicPotentialFunc(kBT_Gamma, density, SpringPotnlFunc):
"""
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the... |
def patch(self, client=None):
"""Sends all changed properties in a PATCH request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... | def function[patch, parameter[self, client]]:
constant[Sends all changed properties in a PATCH request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.cl... | keyword[def] identifier[patch] ( identifier[self] , identifier[client] = keyword[None] ):
literal[string]
identifier[client] = identifier[self] . identifier[_require_client] ( identifier[client] )
identifier[query_params] = identifier[self] . identifier[_query_params]
... | def patch(self, client=None):
"""Sends all changed properties in a PATCH request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... |
def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False):
"""
Calculate the time taken to construct a given fleet
"""
unit_weights = {
UNIT_SCOUT: 1,
UNIT_DESTROYER: 13,
UNIT_BOMBER: 10,
UNIT_CRUISER: 85,
UNIT_STARBASE:... | def function[fleet_ttb, parameter[unit_type, quantity, factories, is_techno, is_dict, stasis_enabled]]:
constant[
Calculate the time taken to construct a given fleet
]
variable[unit_weights] assign[=] dictionary[[<ast.Name object at 0x7da20e9b1780>, <ast.Name object at 0x7da20e9b1d50>, <ast.Nam... | keyword[def] identifier[fleet_ttb] ( identifier[unit_type] , identifier[quantity] , identifier[factories] , identifier[is_techno] = keyword[False] , identifier[is_dict] = keyword[False] , identifier[stasis_enabled] = keyword[False] ):
literal[string]
identifier[unit_weights] ={
identifier[UNIT_SCOUT]... | def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False):
"""
Calculate the time taken to construct a given fleet
"""
unit_weights = {UNIT_SCOUT: 1, UNIT_DESTROYER: 13, UNIT_BOMBER: 10, UNIT_CRUISER: 85, UNIT_STARBASE: 1}
govt_weight = 80 if is_dict else 1... |
def getClassAllSupers(self, aURI):
"""
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
"""
aURI = aURI
try:
qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
WHERE {
{ <%s> rdfs:sub... | def function[getClassAllSupers, parameter[self, aURI]]:
constant[
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
]
variable[aURI] assign[=] name[aURI]
<ast.Try object at 0x7da1b112abf0>
return[call[name[list], parameter[name[qres]]]] | keyword[def] identifier[getClassAllSupers] ( identifier[self] , identifier[aURI] ):
literal[string]
identifier[aURI] = identifier[aURI]
keyword[try] :
identifier[qres] = identifier[self] . identifier[rdflib_graph] . identifier[query] ( literal[string] %( identifier[aURI] ))
... | def getClassAllSupers(self, aURI):
"""
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
"""
aURI = aURI
try:
qres = self.rdflib_graph.query('SELECT DISTINCT ?x\n WHERE {\n { <%s> rdfs:subClassOf+ ?x }\n ... |
def generate(env):
"""Add Builders and construction variables for dvips to an Environment."""
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR')
global DVIPSAction
if DVIPSAction is None:
DVIPSAction = SCons.Action.Action(DviPsFunction, strfun... | def function[generate, parameter[env]]:
constant[Add Builders and construction variables for dvips to an Environment.]
<ast.Global object at 0x7da18f58e890>
if compare[name[PSAction] is constant[None]] begin[:]
variable[PSAction] assign[=] call[name[SCons].Action.Action, parameter[co... | keyword[def] identifier[generate] ( identifier[env] ):
literal[string]
keyword[global] identifier[PSAction]
keyword[if] identifier[PSAction] keyword[is] keyword[None] :
identifier[PSAction] = identifier[SCons] . identifier[Action] . identifier[Action] ( literal[string] , literal[string] ... | def generate(env):
"""Add Builders and construction variables for dvips to an Environment."""
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR') # depends on [control=['if'], data=['PSAction']]
global DVIPSAction
if DVIPSAction is None:
DVIPSA... |
def update(connection=None, urls=None, force_download=False, taxids=None, silent=False):
"""Updates CTD database
:param urls: list of urls to download
:type urls: iterable
:param connection: custom database connection string
:type connection: str
:param force_download: force method to download
... | def function[update, parameter[connection, urls, force_download, taxids, silent]]:
constant[Updates CTD database
:param urls: list of urls to download
:type urls: iterable
:param connection: custom database connection string
:type connection: str
:param force_download: force method to downl... | keyword[def] identifier[update] ( identifier[connection] = keyword[None] , identifier[urls] = keyword[None] , identifier[force_download] = keyword[False] , identifier[taxids] = keyword[None] , identifier[silent] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[taxids] , ... | def update(connection=None, urls=None, force_download=False, taxids=None, silent=False):
"""Updates CTD database
:param urls: list of urls to download
:type urls: iterable
:param connection: custom database connection string
:type connection: str
:param force_download: force method to download
... |
def __get_dash_menu(self, kibiter_major):
"""Order the dashboard menu"""
# omenu = OrderedDict()
omenu = []
# Start with Overview
omenu.append(self.menu_panels_common['Overview'])
# Now the data _getsources
ds_menu = self.__get_menu_entries(kibiter_major)
... | def function[__get_dash_menu, parameter[self, kibiter_major]]:
constant[Order the dashboard menu]
variable[omenu] assign[=] list[[]]
call[name[omenu].append, parameter[call[name[self].menu_panels_common][constant[Overview]]]]
variable[ds_menu] assign[=] call[name[self].__get_menu_entries... | keyword[def] identifier[__get_dash_menu] ( identifier[self] , identifier[kibiter_major] ):
literal[string]
identifier[omenu] =[]
identifier[omenu] . identifier[append] ( identifier[self] . identifier[menu_panels_common] [ literal[string] ])
identifier[... | def __get_dash_menu(self, kibiter_major):
"""Order the dashboard menu"""
# omenu = OrderedDict()
omenu = []
# Start with Overview
omenu.append(self.menu_panels_common['Overview'])
# Now the data _getsources
ds_menu = self.__get_menu_entries(kibiter_major)
# Remove the kafka and community... |
def set(self, status_item, status):
""" sets the status item to the passed in paramaters
args:
status_item: the name if the item to set
status: boolean value to set the item
"""
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLeve... | def function[set, parameter[self, status_item, status]]:
constant[ sets the status item to the passed in paramaters
args:
status_item: the name if the item to set
status: boolean value to set the item
]
variable[lg] assign[=] call[name[logging].getLogger, paramet... | keyword[def] identifier[set] ( identifier[self] , identifier[status_item] , identifier[status] ):
literal[string]
identifier[lg] = identifier[logging] . identifier[getLogger] ( literal[string] %( identifier[self] . identifier[ln] , identifier[inspect] . identifier[stack] ()[ literal[int] ][ literal... | def set(self, status_item, status):
""" sets the status item to the passed in paramaters
args:
status_item: the name if the item to set
status: boolean value to set the item
"""
lg = logging.getLogger('%s.%s' % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_l... |
def get_resource_class_collection_attribute_iterator(rc):
"""
Returns an iterator over all terminal attributes in the given registered
resource.
"""
for attr in itervalues_(rc.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
yield attr | def function[get_resource_class_collection_attribute_iterator, parameter[rc]]:
constant[
Returns an iterator over all terminal attributes in the given registered
resource.
]
for taget[name[attr]] in starred[call[name[itervalues_], parameter[name[rc].__everest_attributes__]]] begin[:]
... | keyword[def] identifier[get_resource_class_collection_attribute_iterator] ( identifier[rc] ):
literal[string]
keyword[for] identifier[attr] keyword[in] identifier[itervalues_] ( identifier[rc] . identifier[__everest_attributes__] ):
keyword[if] identifier[attr] . identifier[kind] == identifier... | def get_resource_class_collection_attribute_iterator(rc):
"""
Returns an iterator over all terminal attributes in the given registered
resource.
"""
for attr in itervalues_(rc.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
yield attr # depends on [... |
def get_tags_of_letter_per_page(self, letter_id, per_page=1000, page=1):
"""
Get tags of letter per page
:param letter_id: the letter id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return... | def function[get_tags_of_letter_per_page, parameter[self, letter_id, per_page, page]]:
constant[
Get tags of letter per page
:param letter_id: the letter id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
... | keyword[def] identifier[get_tags_of_letter_per_page] ( identifier[self] , identifier[letter_id] , identifier[per_page] = literal[int] , identifier[page] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_resource_per_page] (
identifier[resource] = identif... | def get_tags_of_letter_per_page(self, letter_id, per_page=1000, page=1):
"""
Get tags of letter per page
:param letter_id: the letter id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._g... |
def _ctypes_assign(parameter):
"""Returns the Fortran code lines to allocate and assign values to the *original*
parameter ValueElement that exists now only as a local variable so that the
signatures match for the compiler.
"""
#If the array is set to only have intent(out), we don't want to allocate... | def function[_ctypes_assign, parameter[parameter]]:
constant[Returns the Fortran code lines to allocate and assign values to the *original*
parameter ValueElement that exists now only as a local variable so that the
signatures match for the compiler.
]
if <ast.BoolOp object at 0x7da20e954b50... | keyword[def] identifier[_ctypes_assign] ( identifier[parameter] ):
literal[string]
keyword[if] ( identifier[parameter] . identifier[direction] != literal[string] keyword[and] ( literal[string] keyword[in] identifier[parameter] . identifier[modifiers]
keyword[or] literal[string] keyword... | def _ctypes_assign(parameter):
"""Returns the Fortran code lines to allocate and assign values to the *original*
parameter ValueElement that exists now only as a local variable so that the
signatures match for the compiler.
"""
#If the array is set to only have intent(out), we don't want to allocate... |
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
... | def function[_check_timestamp, parameter[self, timestamp]]:
constant[Verify that timestamp is recentish.]
variable[timestamp] assign[=] call[name[int], parameter[name[timestamp]]]
variable[now] assign[=] call[name[int], parameter[call[name[time].time, parameter[]]]]
variable[lapsed] assi... | keyword[def] identifier[_check_timestamp] ( identifier[self] , identifier[timestamp] ):
literal[string]
identifier[timestamp] = identifier[int] ( identifier[timestamp] )
identifier[now] = identifier[int] ( identifier[time] . identifier[time] ())
identifier[lapsed] = identifier[now... | def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % ... |
def setDragTable(self, table):
"""
Sets the table that will be linked with the drag query for this
record. This information will be added to the drag & drop information
when this record is dragged from the tree and will be set into
the application/x-table format for mime da... | def function[setDragTable, parameter[self, table]]:
constant[
Sets the table that will be linked with the drag query for this
record. This information will be added to the drag & drop information
when this record is dragged from the tree and will be set into
the application/x-ta... | keyword[def] identifier[setDragTable] ( identifier[self] , identifier[table] ):
literal[string]
keyword[if] identifier[table] keyword[and] identifier[table] . identifier[schema] ():
identifier[self] . identifier[setDragData] ( literal[string] , identifier[table] . identifier[sche... | def setDragTable(self, table):
"""
Sets the table that will be linked with the drag query for this
record. This information will be added to the drag & drop information
when this record is dragged from the tree and will be set into
the application/x-table format for mime data.
... |
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None,
vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Check if a VPC peering connection is in the pending state, and requested from th... | def function[peering_connection_pending_from_vpc, parameter[conn_id, conn_name, vpc_id, vpc_name, region, key, keyid, profile]]:
constant[
Check if a VPC peering connection is in the pending state, and requested from the given VPC.
.. versionadded:: 2016.11.0
conn_id
The connection ID to c... | keyword[def] identifier[peering_connection_pending_from_vpc] ( identifier[conn_id] = keyword[None] , identifier[conn_name] = keyword[None] , identifier[vpc_id] = keyword[None] ,
identifier[vpc_name] = keyword[None] , identifier[region] = keyword[None] , identifier[key] = keyword[None] ,
identifier[keyid] = keyword[... | def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None):
"""
Check if a VPC peering connection is in the pending state, and requested from the given VPC.
.. versionadded:: 2016.11.0
conn_id
The connectio... |
def find_python_files(dirname):
"""Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname` was specified directly, so th... | def function[find_python_files, parameter[dirname]]:
constant[Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname... | keyword[def] identifier[find_python_files] ( identifier[dirname] ):
literal[string]
keyword[for] identifier[i] ,( identifier[dirpath] , identifier[dirnames] , identifier[filenames] ) keyword[in] identifier[enumerate] ( identifier[os] . identifier[walk] ( identifier[dirname] )):
keyword[if] iden... | def find_python_files(dirname):
"""Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname` was specified directly, so th... |
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(zmqHandler, self).get_default_config()
config.update({
'port': 1234,
})
return config | def function[get_default_config, parameter[self]]:
constant[
Return the default config for the handler
]
variable[config] assign[=] call[call[name[super], parameter[name[zmqHandler], name[self]]].get_default_config, parameter[]]
call[name[config].update, parameter[dictionary[[<as... | keyword[def] identifier[get_default_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[super] ( identifier[zmqHandler] , identifier[self] ). identifier[get_default_config] ()
identifier[config] . identifier[update] ({
literal[string] : literal[int] ,
... | def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(zmqHandler, self).get_default_config()
config.update({'port': 1234})
return config |
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingS... | def function[send_sms, parameter[request, to_number, body, callback_urlname]]:
constant[
Create :class:`OutgoingSMS` object and send SMS using Twilio.
]
variable[client] assign[=] call[name[TwilioRestClient], parameter[name[settings].TWILIO_ACCOUNT_SID, name[settings].TWILIO_AUTH_TOKEN]]
... | keyword[def] identifier[send_sms] ( identifier[request] , identifier[to_number] , identifier[body] , identifier[callback_urlname] = literal[string] ):
literal[string]
identifier[client] = identifier[TwilioRestClient] ( identifier[settings] . identifier[TWILIO_ACCOUNT_SID] , identifier[settings] . identifie... | def send_sms(request, to_number, body, callback_urlname='sms_status_callback'):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingSM... |
def reset_image_attribute(self, image_id, attribute='launchPermission'):
"""
Resets an attribute of an AMI to its default value.
:type image_id: string
:param image_id: ID of the AMI for which an attribute will be described
:type attribute: string
:param attribute: The ... | def function[reset_image_attribute, parameter[self, image_id, attribute]]:
constant[
Resets an attribute of an AMI to its default value.
:type image_id: string
:param image_id: ID of the AMI for which an attribute will be described
:type attribute: string
:param attribu... | keyword[def] identifier[reset_image_attribute] ( identifier[self] , identifier[image_id] , identifier[attribute] = literal[string] ):
literal[string]
identifier[params] ={ literal[string] : identifier[image_id] ,
literal[string] : identifier[attribute] }
keyword[return] identifie... | def reset_image_attribute(self, image_id, attribute='launchPermission'):
"""
Resets an attribute of an AMI to its default value.
:type image_id: string
:param image_id: ID of the AMI for which an attribute will be described
:type attribute: string
:param attribute: The attr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.