code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_schema(self, path, with_refs=False, resolved=False):
"""Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVE... | def function[get_schema, parameter[self, path, with_refs, resolved]]:
constant[Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSON... | keyword[def] identifier[get_schema] ( identifier[self] , identifier[path] , identifier[with_refs] = keyword[False] , identifier[resolved] = keyword[False] ):
literal[string]
keyword[if] identifier[path] keyword[not] keyword[in] identifier[self] . identifier[schemas] :
keyword[raise... | def get_schema(self, path, with_refs=False, resolved=False):
"""Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CL... |
def serialize(self, raw=False):
'''Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
'''
if raw:
return self._key.encode()
return self._key.encode(nacl.encoding.Base64Encoder... | def function[serialize, parameter[self, raw]]:
constant[Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
]
if name[raw] begin[:]
return[call[name[self]._key.encode, parameter[]]]
re... | keyword[def] identifier[serialize] ( identifier[self] , identifier[raw] = keyword[False] ):
literal[string]
keyword[if] identifier[raw] :
keyword[return] identifier[self] . identifier[_key] . identifier[encode] ()
keyword[return] identifier[self] . identifier[_key] . identi... | def serialize(self, raw=False):
"""Encode the private part of the key in a base64 format by default,
but when raw is True it will return hex encoded bytes.
@return: bytes
"""
if raw:
return self._key.encode() # depends on [control=['if'], data=[]]
return self._key.encode(nac... |
def layout_json_params(self):
"""Return layout.json params in a flattened dict with name param as key."""
if self._layout_json_params is None:
self._layout_json_params = {}
for i in self.layout_json.get('inputs', []):
for p in i.get('parameters', []):
... | def function[layout_json_params, parameter[self]]:
constant[Return layout.json params in a flattened dict with name param as key.]
if compare[name[self]._layout_json_params is constant[None]] begin[:]
name[self]._layout_json_params assign[=] dictionary[[], []]
for taget[n... | keyword[def] identifier[layout_json_params] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_layout_json_params] keyword[is] keyword[None] :
identifier[self] . identifier[_layout_json_params] ={}
keyword[for] identifier[i] keyword[in] ... | def layout_json_params(self):
"""Return layout.json params in a flattened dict with name param as key."""
if self._layout_json_params is None:
self._layout_json_params = {}
for i in self.layout_json.get('inputs', []):
for p in i.get('parameters', []):
self._layout_jso... |
def camera_position(self, pose=None):
'''
returns camera position in world coordinates using self.rvec and self.tvec
from http://stackoverflow.com/questions/14515200/python-opencv-solvepnp-yields-wrong-translation-vector
'''
if pose is None:
pose = self.pose()
... | def function[camera_position, parameter[self, pose]]:
constant[
returns camera position in world coordinates using self.rvec and self.tvec
from http://stackoverflow.com/questions/14515200/python-opencv-solvepnp-yields-wrong-translation-vector
]
if compare[name[pose] is constant[N... | keyword[def] identifier[camera_position] ( identifier[self] , identifier[pose] = keyword[None] ):
literal[string]
keyword[if] identifier[pose] keyword[is] keyword[None] :
identifier[pose] = identifier[self] . identifier[pose] ()
identifier[t] , identifier[r] = identifie... | def camera_position(self, pose=None):
"""
returns camera position in world coordinates using self.rvec and self.tvec
from http://stackoverflow.com/questions/14515200/python-opencv-solvepnp-yields-wrong-translation-vector
"""
if pose is None:
pose = self.pose() # depends on [cont... |
def foreign_key_sets(chain, node):
"""
When a Django model has a ForeignKey to another model, the target
of the foreign key gets a '<modelname>_set' attribute for accessing
a queryset of the model owning the foreign key - eg:
class ModelA(models.Model):
pass
class ModelB(models.Model):... | def function[foreign_key_sets, parameter[chain, node]]:
constant[
When a Django model has a ForeignKey to another model, the target
of the foreign key gets a '<modelname>_set' attribute for accessing
a queryset of the model owning the foreign key - eg:
class ModelA(models.Model):
pass
... | keyword[def] identifier[foreign_key_sets] ( identifier[chain] , identifier[node] ):
literal[string]
identifier[quack] = keyword[False]
keyword[if] identifier[node] . identifier[attrname] keyword[in] identifier[MANAGER_ATTRS] keyword[or] identifier[node] . identifier[attrname] . identifier[endsw... | def foreign_key_sets(chain, node):
"""
When a Django model has a ForeignKey to another model, the target
of the foreign key gets a '<modelname>_set' attribute for accessing
a queryset of the model owning the foreign key - eg:
class ModelA(models.Model):
pass
class ModelB(models.Model):... |
def append_checksum(self, f, checksum):
""" Append ESPLoader checksum to the just-written image """
align_file_position(f, 16)
f.write(struct.pack(b'B', checksum)) | def function[append_checksum, parameter[self, f, checksum]]:
constant[ Append ESPLoader checksum to the just-written image ]
call[name[align_file_position], parameter[name[f], constant[16]]]
call[name[f].write, parameter[call[name[struct].pack, parameter[constant[b'B'], name[checksum]]]]] | keyword[def] identifier[append_checksum] ( identifier[self] , identifier[f] , identifier[checksum] ):
literal[string]
identifier[align_file_position] ( identifier[f] , literal[int] )
identifier[f] . identifier[write] ( identifier[struct] . identifier[pack] ( literal[string] , identifier[ch... | def append_checksum(self, f, checksum):
""" Append ESPLoader checksum to the just-written image """
align_file_position(f, 16)
f.write(struct.pack(b'B', checksum)) |
def all_databases(client, exclude=['local']):
"""
Yield all databases except excluded (default
excludes 'local').
"""
return (
client[db_name]
for db_name in client.list_database_names()
if db_name not in exclude
) | def function[all_databases, parameter[client, exclude]]:
constant[
Yield all databases except excluded (default
excludes 'local').
]
return[<ast.GeneratorExp object at 0x7da1b2404130>] | keyword[def] identifier[all_databases] ( identifier[client] , identifier[exclude] =[ literal[string] ]):
literal[string]
keyword[return] (
identifier[client] [ identifier[db_name] ]
keyword[for] identifier[db_name] keyword[in] identifier[client] . identifier[list_database_names] ()
keyword[if] identifi... | def all_databases(client, exclude=['local']):
"""
Yield all databases except excluded (default
excludes 'local').
"""
return (client[db_name] for db_name in client.list_database_names() if db_name not in exclude) |
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder... | def function[decode, parameter[self, output_dict]]:
constant[
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder", where that decoder log... | keyword[def] identifier[decode] ( identifier[self] , identifier[output_dict] : identifier[Dict] [ identifier[str] , identifier[torch] . identifier[Tensor] ])-> identifier[Dict] [ identifier[str] , identifier[torch] . identifier[Tensor] ]:
literal[string]
identifier[action_mapping] = identifier[outp... | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder", w... |
def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
becomes " foo bar baz".
"""
if self.expand_tabs:
# tex... | def function[_munge_whitespace, parameter[self, text]]:
constant[_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
becomes " foo bar baz".
]
if name[self].ex... | keyword[def] identifier[_munge_whitespace] ( identifier[self] , identifier[text] ):
literal[string]
keyword[if] identifier[self] . identifier[expand_tabs] :
identifier[text] = literal[string] . identifier[join] (( literal[string] . identifier[join] ( identifier[text] . identi... | def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
becomes " foo bar baz".
"""
if self.expand_tabs:
# text = text.exp... |
def get_area_def(self, dsid):
"""Get the area definition of the dataset."""
geocoding = self.root.find('.//Tile_Geocoding')
epsg = geocoding.find('HORIZONTAL_CS_CODE').text
rows = int(geocoding.find('Size[@resolution="' + str(dsid.resolution) + '"]/NROWS').text)
cols = int(geocod... | def function[get_area_def, parameter[self, dsid]]:
constant[Get the area definition of the dataset.]
variable[geocoding] assign[=] call[name[self].root.find, parameter[constant[.//Tile_Geocoding]]]
variable[epsg] assign[=] call[name[geocoding].find, parameter[constant[HORIZONTAL_CS_CODE]]].text
... | keyword[def] identifier[get_area_def] ( identifier[self] , identifier[dsid] ):
literal[string]
identifier[geocoding] = identifier[self] . identifier[root] . identifier[find] ( literal[string] )
identifier[epsg] = identifier[geocoding] . identifier[find] ( literal[string] ). identifier[text... | def get_area_def(self, dsid):
"""Get the area definition of the dataset."""
geocoding = self.root.find('.//Tile_Geocoding')
epsg = geocoding.find('HORIZONTAL_CS_CODE').text
rows = int(geocoding.find('Size[@resolution="' + str(dsid.resolution) + '"]/NROWS').text)
cols = int(geocoding.find('Size[@reso... |
def append(self, value):
'''Add another value to the attribute'''
if self.__dict__['values']:
self.__dict__['changetype'] = MODIFY_REPLACE
self.__dict__['values'].append(value) | def function[append, parameter[self, value]]:
constant[Add another value to the attribute]
if call[name[self].__dict__][constant[values]] begin[:]
call[name[self].__dict__][constant[changetype]] assign[=] name[MODIFY_REPLACE]
call[call[name[self].__dict__][constant[values]].appen... | keyword[def] identifier[append] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[__dict__] [ literal[string] ]:
identifier[self] . identifier[__dict__] [ literal[string] ]= identifier[MODIFY_REPLACE]
identifier[self] . iden... | def append(self, value):
"""Add another value to the attribute"""
if self.__dict__['values']:
self.__dict__['changetype'] = MODIFY_REPLACE # depends on [control=['if'], data=[]]
self.__dict__['values'].append(value) |
def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) | def function[native, parameter[s, encoding, fallback]]:
constant[Convert a given string into a native string.]
if call[name[isinstance], parameter[name[s], name[str]]] begin[:]
return[name[s]]
if compare[name[str] is name[unicode]] begin[:]
return[call[name[unicodestr], parameter... | keyword[def] identifier[native] ( identifier[s] , identifier[encoding] = literal[string] , identifier[fallback] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[s] , identifier[str] ):
keyword[return] identifier[s]
keyword[if] identifier[str] keyword... | def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s # depends on [control=['if'], data=[]]
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback) # depends on [control=['if'], data=... |
def addAttachment(self, attachment):
"""Adds an attachment or a list of attachments to the Analysis Request
"""
if not isinstance(attachment, (list, tuple)):
attachment = [attachment]
original = self.getAttachment() or []
# Function addAttachment can accept brain, o... | def function[addAttachment, parameter[self, attachment]]:
constant[Adds an attachment or a list of attachments to the Analysis Request
]
if <ast.UnaryOp object at 0x7da204963af0> begin[:]
variable[attachment] assign[=] list[[<ast.Name object at 0x7da204960ac0>]]
variable[... | keyword[def] identifier[addAttachment] ( identifier[self] , identifier[attachment] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[attachment] ,( identifier[list] , identifier[tuple] )):
identifier[attachment] =[ identifier[attachment] ]
iden... | def addAttachment(self, attachment):
"""Adds an attachment or a list of attachments to the Analysis Request
"""
if not isinstance(attachment, (list, tuple)):
attachment = [attachment] # depends on [control=['if'], data=[]]
original = self.getAttachment() or []
# Function addAttachment c... |
def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'rule... | def function[_run_ids, parameter[runner, pcap]]:
constant[
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
]
variable[run] assign[=] dictionary[[<ast.Constant object at 0x7da20e9b2... | keyword[def] identifier[_run_ids] ( identifier[runner] , identifier[pcap] ):
literal[string]
identifier[run] ={ literal[string] : identifier[runner] . identifier[conf] . identifier[get] ( literal[string] ),
literal[string] : identifier[runner] . identifier[conf] . identifier[get] ( literal[string] ),
... | def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'), 'module': runner.conf.get('module'), 'ruleset': runner.conf.get(... |
def _evaluate_function(self, Ybus, V, Sbus, pv, pq):
""" Evaluates F(x).
"""
mis = multiply(V, conj(Ybus * V)) - Sbus
F = r_[mis[pv].real, mis[pq].real, mis[pq].imag]
return F | def function[_evaluate_function, parameter[self, Ybus, V, Sbus, pv, pq]]:
constant[ Evaluates F(x).
]
variable[mis] assign[=] binary_operation[call[name[multiply], parameter[name[V], call[name[conj], parameter[binary_operation[name[Ybus] * name[V]]]]]] - name[Sbus]]
variable[F] assign[=]... | keyword[def] identifier[_evaluate_function] ( identifier[self] , identifier[Ybus] , identifier[V] , identifier[Sbus] , identifier[pv] , identifier[pq] ):
literal[string]
identifier[mis] = identifier[multiply] ( identifier[V] , identifier[conj] ( identifier[Ybus] * identifier[V] ))- identifier[Sbus]... | def _evaluate_function(self, Ybus, V, Sbus, pv, pq):
""" Evaluates F(x).
"""
mis = multiply(V, conj(Ybus * V)) - Sbus
F = r_[mis[pv].real, mis[pq].real, mis[pq].imag]
return F |
def generate_options_map():
"""Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
This allows developers to expl... | def function[generate_options_map, parameter[]]:
constant[Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
... | keyword[def] identifier[generate_options_map] ():
literal[string]
keyword[try] :
keyword[return] identifier[settings] . identifier[PUENTE] [ literal[string] ]
keyword[except] identifier[KeyError] :
keyword[pass]
keyword[for] identifier[tmpl_config] keywor... | def generate_options_map():
"""Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
This allows developers to expl... |
def parse_gcs_url(gsurl):
"""
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a
tuple containing the corresponding bucket and blob.
"""
parsed_url = urlparse(gsurl)
if not parsed_url.netloc:
raise AirflowException('Please provide a bucket name... | def function[parse_gcs_url, parameter[gsurl]]:
constant[
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a
tuple containing the corresponding bucket and blob.
]
variable[parsed_url] assign[=] call[name[urlparse], parameter[name[gsurl]]]
if <ast.UnaryOp ob... | keyword[def] identifier[parse_gcs_url] ( identifier[gsurl] ):
literal[string]
identifier[parsed_url] = identifier[urlparse] ( identifier[gsurl] )
keyword[if] keyword[not] identifier[parsed_url] . identifier[netloc] :
keyword[raise] identifier[AirflowException] ( literal[str... | def parse_gcs_url(gsurl):
"""
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a
tuple containing the corresponding bucket and blob.
"""
parsed_url = urlparse(gsurl)
if not parsed_url.netloc:
raise AirflowException('Please provide a bucket name') # depends on... |
def execute(self, fn, *args, **kwargs):
"""Execute an operation and return the result."""
if not self.asynchronous:
return fn(*args, **kwargs)
raise NotImplementedError | def function[execute, parameter[self, fn]]:
constant[Execute an operation and return the result.]
if <ast.UnaryOp object at 0x7da18dc042e0> begin[:]
return[call[name[fn], parameter[<ast.Starred object at 0x7da18dc05cc0>]]]
<ast.Raise object at 0x7da18dc06740> | keyword[def] identifier[execute] ( identifier[self] , identifier[fn] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[asynchronous] :
keyword[return] identifier[fn] (* identifier[args] ,** identifier[kwargs] )
... | def execute(self, fn, *args, **kwargs):
"""Execute an operation and return the result."""
if not self.asynchronous:
return fn(*args, **kwargs) # depends on [control=['if'], data=[]]
raise NotImplementedError |
def _handle_shutdown_reply(self, msg):
""" Handle shutdown signal, only if from other console.
"""
self.log.debug("shutdown: %s", msg.get('content', ''))
if not self._hidden and not self._is_from_this_session(msg):
if self._local_kernel:
if not msg['content'][... | def function[_handle_shutdown_reply, parameter[self, msg]]:
constant[ Handle shutdown signal, only if from other console.
]
call[name[self].log.debug, parameter[constant[shutdown: %s], call[name[msg].get, parameter[constant[content], constant[]]]]]
if <ast.BoolOp object at 0x7da18fe90df0... | keyword[def] identifier[_handle_shutdown_reply] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[msg] . identifier[get] ( literal[string] , literal[string] ))
keyword[if] keyword[not] identifier[... | def _handle_shutdown_reply(self, msg):
""" Handle shutdown signal, only if from other console.
"""
self.log.debug('shutdown: %s', msg.get('content', ''))
if not self._hidden and (not self._is_from_this_session(msg)):
if self._local_kernel:
if not msg['content']['restart']:
... |
def create_key(self, title, key, read_only=False):
"""
:calls: `POST /repos/:owner/:repo/keys <http://developer.github.com/v3/repos/keys>`_
:param title: string
:param key: string
:param read_only: bool
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
... | def function[create_key, parameter[self, title, key, read_only]]:
constant[
:calls: `POST /repos/:owner/:repo/keys <http://developer.github.com/v3/repos/keys>`_
:param title: string
:param key: string
:param read_only: bool
:rtype: :class:`github.RepositoryKey.RepositoryK... | keyword[def] identifier[create_key] ( identifier[self] , identifier[title] , identifier[key] , identifier[read_only] = keyword[False] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[title] ,( identifier[str] , identifier[unicode] )), identifier[title]
keyword[asser... | def create_key(self, title, key, read_only=False):
"""
:calls: `POST /repos/:owner/:repo/keys <http://developer.github.com/v3/repos/keys>`_
:param title: string
:param key: string
:param read_only: bool
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
asser... |
def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP)
if self.prio & priority.CORO:
return self, coro
else:
... | def function[process, parameter[self, sched, coro]]:
constant[Add the given coroutine in the scheduler.]
call[call[name[super], parameter[name[AddCoro], name[self]]].process, parameter[name[sched], name[coro]]]
name[self].result assign[=] call[name[sched].add, parameter[name[self].coro, name[sel... | keyword[def] identifier[process] ( identifier[self] , identifier[sched] , identifier[coro] ):
literal[string]
identifier[super] ( identifier[AddCoro] , identifier[self] ). identifier[process] ( identifier[sched] , identifier[coro] )
identifier[self] . identifier[result] = identifier[sch... | def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP)
if self.prio & priority.CORO:
return (self, coro) # depends on [control=['if'], data=[]]
... |
def process_request(self, unused_request):
"""Called by Django before deciding which view to execute."""
# Compare to the first half of toplevel() in context.py.
tasklets._state.clear_all_pending()
# Create and install a new context.
ctx = tasklets.make_default_context()
tasklets.set_context(ctx... | def function[process_request, parameter[self, unused_request]]:
constant[Called by Django before deciding which view to execute.]
call[name[tasklets]._state.clear_all_pending, parameter[]]
variable[ctx] assign[=] call[name[tasklets].make_default_context, parameter[]]
call[name[tasklets].... | keyword[def] identifier[process_request] ( identifier[self] , identifier[unused_request] ):
literal[string]
identifier[tasklets] . identifier[_state] . identifier[clear_all_pending] ()
identifier[ctx] = identifier[tasklets] . identifier[make_default_context] ()
identifier[tasklets] . id... | def process_request(self, unused_request):
"""Called by Django before deciding which view to execute."""
# Compare to the first half of toplevel() in context.py.
tasklets._state.clear_all_pending()
# Create and install a new context.
ctx = tasklets.make_default_context()
tasklets.set_context(ctx... |
def config(_config=None, **kwargs):
"""
A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config.
"""
if _config is None:
_config = {}
_config.update(kwargs)
def wrapper(func):
func._config = _config
re... | def function[config, parameter[_config]]:
constant[
A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config.
]
if compare[name[_config] is constant[None]] begin[:]
variable[_config] assign[=] dictionary[[], []]... | keyword[def] identifier[config] ( identifier[_config] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[_config] keyword[is] keyword[None] :
identifier[_config] ={}
identifier[_config] . identifier[update] ( identifier[kwargs] )
keyword[def] identifier... | def config(_config=None, **kwargs):
"""
A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config.
"""
if _config is None:
_config = {} # depends on [control=['if'], data=['_config']]
_config.update(kwargs)
def wrapper... |
def view_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#create-view"
api_path = "/api/v2/views.json"
return self.call(api_path, method="POST", data=data, **kwargs) | def function[view_create, parameter[self, data]]:
constant[https://developer.zendesk.com/rest_api/docs/core/views#create-view]
variable[api_path] assign[=] constant[/api/v2/views.json]
return[call[name[self].call, parameter[name[api_path]]]] | keyword[def] identifier[view_create] ( identifier[self] , identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
keyword[return] identifier[self] . identifier[call] ( identifier[api_path] , identifier[method] = literal[string] , identifier[data]... | def view_create(self, data, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/views#create-view"""
api_path = '/api/v2/views.json'
return self.call(api_path, method='POST', data=data, **kwargs) |
def wait(self, timeout=None):
"""
Waits until all tasks completed or *timeout* seconds passed.
# Raises
Timeout: If the *timeout* is exceeded.
"""
t_start = time.clock()
if not wait_for_condition(self, lambda s: s._tasks == 0, timeout):
raise Timeout | def function[wait, parameter[self, timeout]]:
constant[
Waits until all tasks completed or *timeout* seconds passed.
# Raises
Timeout: If the *timeout* is exceeded.
]
variable[t_start] assign[=] call[name[time].clock, parameter[]]
if <ast.UnaryOp object at 0x7da18dc9b070> begin[... | keyword[def] identifier[wait] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[t_start] = identifier[time] . identifier[clock] ()
keyword[if] keyword[not] identifier[wait_for_condition] ( identifier[self] , keyword[lambda] identifier[s] : identifier[s] . ident... | def wait(self, timeout=None):
"""
Waits until all tasks completed or *timeout* seconds passed.
# Raises
Timeout: If the *timeout* is exceeded.
"""
t_start = time.clock()
if not wait_for_condition(self, lambda s: s._tasks == 0, timeout):
raise Timeout # depends on [control=['if'], d... |
def get(self, block=True, timeout=None):
"""get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
... | def function[get, parameter[self, block, timeout]]:
constant[get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param... | keyword[def] identifier[get] ( identifier[self] , identifier[block] = keyword[True] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_data] :
keyword[if] keyword[not] identifier[block] :
keyword[raise] ... | def get(self, block=True, timeout=None):
"""get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
w... |
def do_GEOHASHMEMBERS(self, geoh):
"""Return members of a geohash and its neighbors.
GEOHASHMEMBERS u09vej04 [NEIGHBORS 0]"""
geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
key = compute_geohash_key(geoh, with_neighbors != '0')
if key:
for id_ in DB.smem... | def function[do_GEOHASHMEMBERS, parameter[self, geoh]]:
constant[Return members of a geohash and its neighbors.
GEOHASHMEMBERS u09vej04 [NEIGHBORS 0]]
<ast.Tuple object at 0x7da1b26af7f0> assign[=] call[name[self]._match_option, parameter[constant[NEIGHBORS], name[geoh]]]
variable[key] a... | keyword[def] identifier[do_GEOHASHMEMBERS] ( identifier[self] , identifier[geoh] ):
literal[string]
identifier[geoh] , identifier[with_neighbors] = identifier[self] . identifier[_match_option] ( literal[string] , identifier[geoh] )
identifier[key] = identifier[compute_geohash_key] ( identi... | def do_GEOHASHMEMBERS(self, geoh):
"""Return members of a geohash and its neighbors.
GEOHASHMEMBERS u09vej04 [NEIGHBORS 0]"""
(geoh, with_neighbors) = self._match_option('NEIGHBORS', geoh)
key = compute_geohash_key(geoh, with_neighbors != '0')
if key:
for id_ in DB.smembers(key):
... |
def _accept(self, listen_socket):
"""
Accept new incoming connection.
"""
conn, addr = listen_socket.accept()
connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding)
self.connections.add(connection)
logger.info('New connection %r... | def function[_accept, parameter[self, listen_socket]]:
constant[
Accept new incoming connection.
]
<ast.Tuple object at 0x7da18f00f670> assign[=] call[name[listen_socket].accept, parameter[]]
variable[connection] assign[=] call[name[TelnetConnection], parameter[name[conn], name[a... | keyword[def] identifier[_accept] ( identifier[self] , identifier[listen_socket] ):
literal[string]
identifier[conn] , identifier[addr] = identifier[listen_socket] . identifier[accept] ()
identifier[connection] = identifier[TelnetConnection] ( identifier[conn] , identifier[addr] , identifie... | def _accept(self, listen_socket):
"""
Accept new incoming connection.
"""
(conn, addr) = listen_socket.accept()
connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding)
self.connections.add(connection)
logger.info('New connection %r %r', *addr) |
def __get_known_node_by_host(self, hostname):
'''
Determine if the node is already known by hostname.
If it is, return it.
'''
for n in self.nodes:
if (n.name == hostname):
return n
return None | def function[__get_known_node_by_host, parameter[self, hostname]]:
constant[
Determine if the node is already known by hostname.
If it is, return it.
]
for taget[name[n]] in starred[name[self].nodes] begin[:]
if compare[name[n].name equal[==] name[hostname]] begin... | keyword[def] identifier[__get_known_node_by_host] ( identifier[self] , identifier[hostname] ):
literal[string]
keyword[for] identifier[n] keyword[in] identifier[self] . identifier[nodes] :
keyword[if] ( identifier[n] . identifier[name] == identifier[hostname] ):
key... | def __get_known_node_by_host(self, hostname):
"""
Determine if the node is already known by hostname.
If it is, return it.
"""
for n in self.nodes:
if n.name == hostname:
return n # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['n']]
... |
def button_released(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is released.
:internal:
:param key_code:
The code specified when populating Button instance
:param prefix:
A... | def function[button_released, parameter[self, key_code, prefix]]:
constant[
Called from the controller classes to update the state of this button manager when a button is released.
:internal:
:param key_code:
The code specified when populating Button instance
:param... | keyword[def] identifier[button_released] ( identifier[self] , identifier[key_code] , identifier[prefix] = keyword[None] ):
literal[string]
keyword[if] identifier[prefix] keyword[is] keyword[not] keyword[None] :
identifier[state] = identifier[self] . identifier[buttons_by_code] . id... | def button_released(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is released.
:internal:
:param key_code:
The code specified when populating Button instance
:param prefix:
Appli... |
def random_word(tokens, tokenizer):
"""
Masking some random tokens for Language Model task with probabilities as in the original BERT paper.
:param tokens: list of str, tokenized sentence.
:param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)
:return: (list of str, list... | def function[random_word, parameter[tokens, tokenizer]]:
constant[
Masking some random tokens for Language Model task with probabilities as in the original BERT paper.
:param tokens: list of str, tokenized sentence.
:param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)
... | keyword[def] identifier[random_word] ( identifier[tokens] , identifier[tokenizer] ):
literal[string]
identifier[output_label] =[]
keyword[for] identifier[i] , identifier[token] keyword[in] identifier[enumerate] ( identifier[tokens] ):
identifier[prob] = identifier[random] . identifier[ran... | def random_word(tokens, tokenizer):
"""
Masking some random tokens for Language Model task with probabilities as in the original BERT paper.
:param tokens: list of str, tokenized sentence.
:param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)
:return: (list of str, list... |
def parse_unit(self, node):
"""
Parses <Unit>
@param node: Node containing the <Unit> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or the unit
specfications are incorrect.
@raise ModelError: When the unit refers to an u... | def function[parse_unit, parameter[self, node]]:
constant[
Parses <Unit>
@param node: Node containing the <Unit> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or the unit
specfications are incorrect.
@raise ModelError: W... | keyword[def] identifier[parse_unit] ( identifier[self] , identifier[node] ):
literal[string]
keyword[try] :
identifier[symbol] = identifier[node] . identifier[lattrib] [ literal[string] ]
identifier[dimension] = identifier[node] . identifier[lattrib] [ literal[string] ]
... | def parse_unit(self, node):
"""
Parses <Unit>
@param node: Node containing the <Unit> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or the unit
specfications are incorrect.
@raise ModelError: When the unit refers to an undef... |
def select_regexes(strings, regexes):
"""
select subset of strings matching a regex
treats strings as a set
"""
strings = set(strings)
select = set()
if isinstance(strings, collections.Iterable):
for r in regexes:
s = set(filter(re.compile('^' + r + '$').search, strings))... | def function[select_regexes, parameter[strings, regexes]]:
constant[
select subset of strings matching a regex
treats strings as a set
]
variable[strings] assign[=] call[name[set], parameter[name[strings]]]
variable[select] assign[=] call[name[set], parameter[]]
if call[name[... | keyword[def] identifier[select_regexes] ( identifier[strings] , identifier[regexes] ):
literal[string]
identifier[strings] = identifier[set] ( identifier[strings] )
identifier[select] = identifier[set] ()
keyword[if] identifier[isinstance] ( identifier[strings] , identifier[collections] . identi... | def select_regexes(strings, regexes):
"""
select subset of strings matching a regex
treats strings as a set
"""
strings = set(strings)
select = set()
if isinstance(strings, collections.Iterable):
for r in regexes:
s = set(filter(re.compile('^' + r + '$').search, strings))... |
def wrap_resource(self, pool, resource_wrapper):
"""
Return a resource wrapped in ``resource_wrapper``.
:param pool: A pool instance.
:type pool: :class:`CuttlePool`
:param resource_wrapper: A wrapper class for the resource.
:type resource_wrapper: :class:`Resource`
... | def function[wrap_resource, parameter[self, pool, resource_wrapper]]:
constant[
Return a resource wrapped in ``resource_wrapper``.
:param pool: A pool instance.
:type pool: :class:`CuttlePool`
:param resource_wrapper: A wrapper class for the resource.
:type resource_wrap... | keyword[def] identifier[wrap_resource] ( identifier[self] , identifier[pool] , identifier[resource_wrapper] ):
literal[string]
identifier[resource] = identifier[resource_wrapper] ( identifier[self] . identifier[resource] , identifier[pool] )
identifier[self] . identifier[_weakref] = identi... | def wrap_resource(self, pool, resource_wrapper):
"""
Return a resource wrapped in ``resource_wrapper``.
:param pool: A pool instance.
:type pool: :class:`CuttlePool`
:param resource_wrapper: A wrapper class for the resource.
:type resource_wrapper: :class:`Resource`
... |
def subscribe_param():
"""Print value of parameter"""
def print_data(data):
for parameter in data.parameters:
print(parameter)
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage2',
on_data=print_data) | def function[subscribe_param, parameter[]]:
constant[Print value of parameter]
def function[print_data, parameter[data]]:
for taget[name[parameter]] in starred[name[data].parameters] begin[:]
call[name[print], parameter[name[parameter]]]
call[name[processo... | keyword[def] identifier[subscribe_param] ():
literal[string]
keyword[def] identifier[print_data] ( identifier[data] ):
keyword[for] identifier[parameter] keyword[in] identifier[data] . identifier[parameters] :
identifier[print] ( identifier[parameter] )
identifier[processor]... | def subscribe_param():
"""Print value of parameter"""
def print_data(data):
for parameter in data.parameters:
print(parameter) # depends on [control=['for'], data=['parameter']]
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage2', on_data=print_data) |
def _hijack_gtk(self):
"""Hijack a few key functions in GTK for IPython integration.
Modifies pyGTK's main and main_quit with a dummy so user code does not
block IPython. This allows us to use %run to run arbitrary pygtk
scripts from a long-lived IPython session, and when they attempt ... | def function[_hijack_gtk, parameter[self]]:
constant[Hijack a few key functions in GTK for IPython integration.
Modifies pyGTK's main and main_quit with a dummy so user code does not
block IPython. This allows us to use %run to run arbitrary pygtk
scripts from a long-lived IPython sess... | keyword[def] identifier[_hijack_gtk] ( identifier[self] ):
literal[string]
keyword[def] identifier[dummy] (* identifier[args] ,** identifier[kw] ):
keyword[pass]
identifier[orig_main] , identifier[gtk] . identifier[main] = identifier[gtk] . identifier[main] , id... | def _hijack_gtk(self):
"""Hijack a few key functions in GTK for IPython integration.
Modifies pyGTK's main and main_quit with a dummy so user code does not
block IPython. This allows us to use %run to run arbitrary pygtk
scripts from a long-lived IPython session, and when they attempt to
... |
def generate_jupyter_js(self, cyjs_style=None, cyjs_layout=None):
"""Generate Javascript from a template to run in Jupyter notebooks.
Parameters
----------
cyjs_style : Optional[dict]
A dict that sets CytoscapeJS style as specified in
https://github.com/cytoscape... | def function[generate_jupyter_js, parameter[self, cyjs_style, cyjs_layout]]:
constant[Generate Javascript from a template to run in Jupyter notebooks.
Parameters
----------
cyjs_style : Optional[dict]
A dict that sets CytoscapeJS style as specified in
https://git... | keyword[def] identifier[generate_jupyter_js] ( identifier[self] , identifier[cyjs_style] = keyword[None] , identifier[cyjs_layout] = keyword[None] ):
literal[string]
identifier[cyjs_elements] = identifier[self] . identifier[export_to_cytoscapejs] ()
identifier[tempf] = id... | def generate_jupyter_js(self, cyjs_style=None, cyjs_layout=None):
"""Generate Javascript from a template to run in Jupyter notebooks.
Parameters
----------
cyjs_style : Optional[dict]
A dict that sets CytoscapeJS style as specified in
https://github.com/cytoscape/cyt... |
def server_main(loop, path):
"""Run in the client after the fork."""
loop.fork()
logger.debug('forked function')
sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored'))
sigintwatcher.start()
sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, ser... | def function[server_main, parameter[loop, path]]:
constant[Run in the client after the fork.]
call[name[loop].fork, parameter[]]
call[name[logger].debug, parameter[constant[forked function]]]
variable[sigintwatcher] assign[=] call[name[pyev].Signal, parameter[name[signal].SIGINT, name[lo... | keyword[def] identifier[server_main] ( identifier[loop] , identifier[path] ):
literal[string]
identifier[loop] . identifier[fork] ()
identifier[logger] . identifier[debug] ( literal[string] )
identifier[sigintwatcher] = identifier[pyev] . identifier[Signal] ( identifier[signal] . identifier[SIGIN... | def server_main(loop, path):
"""Run in the client after the fork."""
loop.fork()
logger.debug('forked function')
sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored'))
sigintwatcher.start()
sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, ser... |
def fetch(self):
"""
Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists)
"""
api = self.doapi_manager
... | def function[fetch, parameter[self]]:
constant[
Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists)
]
variab... | keyword[def] identifier[fetch] ( identifier[self] ):
literal[string]
identifier[api] = identifier[self] . identifier[doapi_manager]
keyword[return] identifier[api] . identifier[_ssh_key] ( identifier[api] . identifier[request] ( identifier[self] . identifier[url] )[ literal[string] ]) | def fetch(self):
"""
Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists)
"""
api = self.doapi_manager
return api... |
def apply_update(self, value, index):
"""
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param inde... | def function[apply_update, parameter[self, value, index]]:
constant[
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data... | keyword[def] identifier[apply_update] ( identifier[self] , identifier[value] , identifier[index] ):
literal[string]
identifier[_log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[type] ( identifier[value] ). identifier[__name__] , identifier[index] , identifier[value] . id... | def apply_update(self, value, index):
"""
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param index: (... |
def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size
if low is None:
low = high // 2
self._buffer_high = high
self._buffer_low = low | def function[set_buffer_limits, parameter[self, high, low]]:
constant[Set the low and high watermarks for the read buffer.]
if compare[name[high] is constant[None]] begin[:]
variable[high] assign[=] name[self].default_buffer_size
if compare[name[low] is constant[None]] begin[:]
... | keyword[def] identifier[set_buffer_limits] ( identifier[self] , identifier[high] = keyword[None] , identifier[low] = keyword[None] ):
literal[string]
keyword[if] identifier[high] keyword[is] keyword[None] :
identifier[high] = identifier[self] . identifier[default_buffer_size]
... | def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size # depends on [control=['if'], data=['high']]
if low is None:
low = high // 2 # depends on [control=['if'], data=['low']]
self._b... |
def find_ip_address(ipa_id=None, ipa_fqdn=None, ipa_ip_address=None, ipa_subnet_id=None, ipa_osi_id=None):
"""
find the IP Address (ipa) according ipa id (prioritary) or ipa ipAddress
:param ipa_id: the IP Address id
:param ipa_ip_address: the IP Address
:return: found IP Address... | def function[find_ip_address, parameter[ipa_id, ipa_fqdn, ipa_ip_address, ipa_subnet_id, ipa_osi_id]]:
constant[
find the IP Address (ipa) according ipa id (prioritary) or ipa ipAddress
:param ipa_id: the IP Address id
:param ipa_ip_address: the IP Address
:return: found IP Addre... | keyword[def] identifier[find_ip_address] ( identifier[ipa_id] = keyword[None] , identifier[ipa_fqdn] = keyword[None] , identifier[ipa_ip_address] = keyword[None] , identifier[ipa_subnet_id] = keyword[None] , identifier[ipa_osi_id] = keyword[None] ):
literal[string]
identifier[LOGGER] . identifier[d... | def find_ip_address(ipa_id=None, ipa_fqdn=None, ipa_ip_address=None, ipa_subnet_id=None, ipa_osi_id=None):
"""
find the IP Address (ipa) according ipa id (prioritary) or ipa ipAddress
:param ipa_id: the IP Address id
:param ipa_ip_address: the IP Address
:return: found IP Address or ... |
def decode(data, encoding=None, errors='strict', keep=False,
normalize=False, preserve_dict_class=False, preserve_tuples=False,
to_str=False):
'''
Generic function which will decode whichever type is passed, if necessary.
Optionally use to_str=True to ensure strings are str types and n... | def function[decode, parameter[data, encoding, errors, keep, normalize, preserve_dict_class, preserve_tuples, to_str]]:
constant[
Generic function which will decode whichever type is passed, if necessary.
Optionally use to_str=True to ensure strings are str types and not unicode
on Python 2.
If... | keyword[def] identifier[decode] ( identifier[data] , identifier[encoding] = keyword[None] , identifier[errors] = literal[string] , identifier[keep] = keyword[False] ,
identifier[normalize] = keyword[False] , identifier[preserve_dict_class] = keyword[False] , identifier[preserve_tuples] = keyword[False] ,
identifier... | def decode(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, preserve_tuples=False, to_str=False):
"""
Generic function which will decode whichever type is passed, if necessary.
Optionally use to_str=True to ensure strings are str types and not unicode
on Pyth... |
def get_fn_plan(callback=None, out_callback=None, name='pycbc_cufft', parameters=None):
""" Get the IFFT execute and plan functions
"""
if parameters is None:
parameters = []
source = fftsrc.render(input_callback=callback, output_callback=out_callback, parameters=parameters)
path = compile(s... | def function[get_fn_plan, parameter[callback, out_callback, name, parameters]]:
constant[ Get the IFFT execute and plan functions
]
if compare[name[parameters] is constant[None]] begin[:]
variable[parameters] assign[=] list[[]]
variable[source] assign[=] call[name[fftsrc].ren... | keyword[def] identifier[get_fn_plan] ( identifier[callback] = keyword[None] , identifier[out_callback] = keyword[None] , identifier[name] = literal[string] , identifier[parameters] = keyword[None] ):
literal[string]
keyword[if] identifier[parameters] keyword[is] keyword[None] :
identifier[param... | def get_fn_plan(callback=None, out_callback=None, name='pycbc_cufft', parameters=None):
""" Get the IFFT execute and plan functions
"""
if parameters is None:
parameters = [] # depends on [control=['if'], data=['parameters']]
source = fftsrc.render(input_callback=callback, output_callback=out_c... |
def instantiate_by_name(self, object_name):
""" Instantiate object from the environment, possibly giving some extra arguments """
if object_name not in self.instances:
instance = self.instantiate_from_data(self.environment[object_name])
self.instances[object_name] = instance
... | def function[instantiate_by_name, parameter[self, object_name]]:
constant[ Instantiate object from the environment, possibly giving some extra arguments ]
if compare[name[object_name] <ast.NotIn object at 0x7da2590d7190> name[self].instances] begin[:]
variable[instance] assign[=] call[na... | keyword[def] identifier[instantiate_by_name] ( identifier[self] , identifier[object_name] ):
literal[string]
keyword[if] identifier[object_name] keyword[not] keyword[in] identifier[self] . identifier[instances] :
identifier[instance] = identifier[self] . identifier[instantiate_from... | def instantiate_by_name(self, object_name):
""" Instantiate object from the environment, possibly giving some extra arguments """
if object_name not in self.instances:
instance = self.instantiate_from_data(self.environment[object_name])
self.instances[object_name] = instance
return insta... |
def _compute_sync_map_file_path(
self,
root,
hierarchy_type,
custom_id,
file_name
):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:p... | def function[_compute_sync_map_file_path, parameter[self, root, hierarchy_type, custom_id, file_name]]:
constant[
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job... | keyword[def] identifier[_compute_sync_map_file_path] (
identifier[self] ,
identifier[root] ,
identifier[hierarchy_type] ,
identifier[custom_id] ,
identifier[file_name]
):
literal[string]
identifier[prefix] = identifier[root]
keyword[if] identifier[hierarchy_type] == identifier[Hier... | def _compute_sync_map_file_path(self, root, hierarchy_type, custom_id, file_name):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type... |
def kill(self):
"""
Kill the current non blocking command
Raises:
TypeError: If command is blocking
"""
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
try:
self.process.kill()
except ProcessLookupError as exc:
... | def function[kill, parameter[self]]:
constant[
Kill the current non blocking command
Raises:
TypeError: If command is blocking
]
if name[self].block begin[:]
<ast.Raise object at 0x7da20c6abfd0>
<ast.Try object at 0x7da20c7cad10> | keyword[def] identifier[kill] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[block] :
keyword[raise] identifier[TypeError] ( identifier[NON_BLOCKING_ERROR_MESSAGE] )
keyword[try] :
identifier[self] . identifier[process] . identi... | def kill(self):
"""
Kill the current non blocking command
Raises:
TypeError: If command is blocking
"""
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE) # depends on [control=['if'], data=[]]
try:
self.process.kill() # depends on [control=['tr... |
def indicator_body(indicators):
"""Generate the appropriate dictionary content for POST of an File indicator
Args:
indicators (list): A list of one or more hash value(s).
"""
hash_patterns = {
'md5': re.compile(r'^([a-fA-F\d]{32})$'),
'sha1': re.compi... | def function[indicator_body, parameter[indicators]]:
constant[Generate the appropriate dictionary content for POST of an File indicator
Args:
indicators (list): A list of one or more hash value(s).
]
variable[hash_patterns] assign[=] dictionary[[<ast.Constant object at 0x7da... | keyword[def] identifier[indicator_body] ( identifier[indicators] ):
literal[string]
identifier[hash_patterns] ={
literal[string] : identifier[re] . identifier[compile] ( literal[string] ),
literal[string] : identifier[re] . identifier[compile] ( literal[string] ),
literal... | def indicator_body(indicators):
"""Generate the appropriate dictionary content for POST of an File indicator
Args:
indicators (list): A list of one or more hash value(s).
"""
hash_patterns = {'md5': re.compile('^([a-fA-F\\d]{32})$'), 'sha1': re.compile('^([a-fA-F\\d]{40})$'), 'sha25... |
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None):
"""Layer norm raw computation."""
# Save these before they get converted to tensors by the casting below
params = (scale, bias)
epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]
mean = tf.reduce_mean(x, axis=[-1],... | def function[layer_norm_compute, parameter[x, epsilon, scale, bias, layer_collection]]:
constant[Layer norm raw computation.]
variable[params] assign[=] tuple[[<ast.Name object at 0x7da18dc07130>, <ast.Name object at 0x7da18dc06740>]]
<ast.Tuple object at 0x7da18dc06230> assign[=] <ast.ListComp ... | keyword[def] identifier[layer_norm_compute] ( identifier[x] , identifier[epsilon] , identifier[scale] , identifier[bias] , identifier[layer_collection] = keyword[None] ):
literal[string]
identifier[params] =( identifier[scale] , identifier[bias] )
identifier[epsilon] , identifier[scale] , identifier[bi... | def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None):
"""Layer norm raw computation."""
# Save these before they get converted to tensors by the casting below
params = (scale, bias)
(epsilon, scale, bias) = [cast_like(t, x) for t in [epsilon, scale, bias]]
mean = tf.reduce_mean(x, ... |
def _select(self, pointer):
"""
Get a YAMLChunk referenced by a pointer.
"""
return YAMLChunk(
self._ruamelparsed,
pointer=pointer,
label=self._label,
strictparsed=self._strictparsed,
key_association=copy(self._key_association),... | def function[_select, parameter[self, pointer]]:
constant[
Get a YAMLChunk referenced by a pointer.
]
return[call[name[YAMLChunk], parameter[name[self]._ruamelparsed]]] | keyword[def] identifier[_select] ( identifier[self] , identifier[pointer] ):
literal[string]
keyword[return] identifier[YAMLChunk] (
identifier[self] . identifier[_ruamelparsed] ,
identifier[pointer] = identifier[pointer] ,
identifier[label] = identifier[self] . identifi... | def _select(self, pointer):
"""
Get a YAMLChunk referenced by a pointer.
"""
return YAMLChunk(self._ruamelparsed, pointer=pointer, label=self._label, strictparsed=self._strictparsed, key_association=copy(self._key_association)) |
def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'):
"""Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance wil... | def function[init, parameter[port, do_not_exit, disable_tls, log_level]]:
constant[Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance... | keyword[def] identifier[init] ( identifier[port] = keyword[None] , identifier[do_not_exit] = keyword[False] , identifier[disable_tls] = keyword[False] , identifier[log_level] = literal[string] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( literal[string] )
ident... | def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'):
"""Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance wil... |
def stdev(self, default=None):
"""
Calculate the standard deviation of the time series.
:param default: Value to return as a default should the calculation not be possible.
:return: Float representing the standard deviation value or `None`.
"""
return numpy.asscalar(nump... | def function[stdev, parameter[self, default]]:
constant[
Calculate the standard deviation of the time series.
:param default: Value to return as a default should the calculation not be possible.
:return: Float representing the standard deviation value or `None`.
]
return[<as... | keyword[def] identifier[stdev] ( identifier[self] , identifier[default] = keyword[None] ):
literal[string]
keyword[return] identifier[numpy] . identifier[asscalar] ( identifier[numpy] . identifier[std] ( identifier[self] . identifier[values] )) keyword[if] identifier[self] . identifier[values] k... | def stdev(self, default=None):
"""
Calculate the standard deviation of the time series.
:param default: Value to return as a default should the calculation not be possible.
:return: Float representing the standard deviation value or `None`.
"""
return numpy.asscalar(numpy.std(se... |
def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify... | def function[send, parameter[self, request]]:
constant[Send a given PreparedRequest.]
call[name[kwargs].setdefault, parameter[constant[stream], name[self].stream]]
call[name[kwargs].setdefault, parameter[constant[verify], name[self].verify]]
call[name[kwargs].setdefault, parameter[consta... | keyword[def] identifier[send] ( identifier[self] , identifier[request] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] . identifier[setdefault] ( literal[string] , identifier[self] . identifier[stream] )
identifier[kwargs] . identifier[setdefault] ( literal[s... | def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefa... |
def RangeFromChild(self, child) -> TextRange:
"""
Call IUIAutomationTextPattern::RangeFromChild.
child: `Control` or its subclass.
Return `TextRange` or None, a text range enclosing a child element such as an image,
hyperlink, Microsoft Excel spreadsheet, or other embedded ob... | def function[RangeFromChild, parameter[self, child]]:
constant[
Call IUIAutomationTextPattern::RangeFromChild.
child: `Control` or its subclass.
Return `TextRange` or None, a text range enclosing a child element such as an image,
hyperlink, Microsoft Excel spreadsheet, or oth... | keyword[def] identifier[RangeFromChild] ( identifier[self] , identifier[child] )-> identifier[TextRange] :
literal[string]
identifier[textRange] = identifier[self] . identifier[pattern] . identifier[RangeFromChild] ( identifier[Control] . identifier[Element] )
keyword[if] identifier[textR... | def RangeFromChild(self, child) -> TextRange:
"""
Call IUIAutomationTextPattern::RangeFromChild.
child: `Control` or its subclass.
Return `TextRange` or None, a text range enclosing a child element such as an image,
hyperlink, Microsoft Excel spreadsheet, or other embedded object... |
def check64bit(current_system="python"):
"""checks if you are on a 64 bit platform"""
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'): # recent Python (not... | def function[check64bit, parameter[current_system]]:
constant[checks if you are on a 64 bit platform]
if compare[name[current_system] equal[==] constant[python]] begin[:]
return[compare[name[sys].maxsize greater[>] constant[2147483647]]] | keyword[def] identifier[check64bit] ( identifier[current_system] = literal[string] ):
literal[string]
keyword[if] identifier[current_system] == literal[string] :
keyword[return] identifier[sys] . identifier[maxsize] > literal[int]
keyword[elif] identifier[current_system] == literal[string... | def check64bit(current_system='python'):
"""checks if you are on a 64 bit platform"""
if current_system == 'python':
return sys.maxsize > 2147483647 # depends on [control=['if'], data=[]]
elif current_system == 'os':
import platform
pm = platform.machine()
if pm != '..' and ... |
def trigger_created(self, filepath):
"""Triggers created event if file exists."""
if os.path.exists(filepath):
self._trigger('created', filepath) | def function[trigger_created, parameter[self, filepath]]:
constant[Triggers created event if file exists.]
if call[name[os].path.exists, parameter[name[filepath]]] begin[:]
call[name[self]._trigger, parameter[constant[created], name[filepath]]] | keyword[def] identifier[trigger_created] ( identifier[self] , identifier[filepath] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[filepath] ):
identifier[self] . identifier[_trigger] ( literal[string] , identifier[filepath] ) | def trigger_created(self, filepath):
"""Triggers created event if file exists."""
if os.path.exists(filepath):
self._trigger('created', filepath) # depends on [control=['if'], data=[]] |
def _parse_request_range(
range_header: str
) -> Optional[Tuple[Optional[int], Optional[int]]]:
"""Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>... | def function[_parse_request_range, parameter[range_header]]:
constant[Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>> start, end = _parse_request... | keyword[def] identifier[_parse_request_range] (
identifier[range_header] : identifier[str]
)-> identifier[Optional] [ identifier[Tuple] [ identifier[Optional] [ identifier[int] ], identifier[Optional] [ identifier[int] ]]]:
literal[string]
identifier[unit] , identifier[_] , identifier[value] = identifier... | def _parse_request_range(range_header: str) -> Optional[Tuple[Optional[int], Optional[int]]]:
"""Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>> star... |
def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config... | def function[get_custom_color_config_from_egrc, parameter[config]]:
constant[
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
]
variable[pound] assign[=] call[name[_get_color_from_config], parameter[name[config], name[CONFIG_NAMES].pound]]
variab... | keyword[def] identifier[get_custom_color_config_from_egrc] ( identifier[config] ):
literal[string]
identifier[pound] = identifier[_get_color_from_config] ( identifier[config] , identifier[CONFIG_NAMES] . identifier[pound] )
identifier[heading] = identifier[_get_color_from_config] ( identifier[config] ... | def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config... |
def orders_from_events(events, sell_delay=5, num_shares=100):
"""Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix)
Arguments:
events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing)
sell_delay (int): num... | def function[orders_from_events, parameter[events, sell_delay, num_shares]]:
constant[Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix)
Arguments:
events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing)
... | keyword[def] identifier[orders_from_events] ( identifier[events] , identifier[sell_delay] = literal[int] , identifier[num_shares] = literal[int] ):
literal[string]
identifier[buy] = identifier[events] . identifier[copy] ()* identifier[num_shares]
identifier[sell] =- literal[int] * identifier[pd] . i... | def orders_from_events(events, sell_delay=5, num_shares=100):
"""Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix)
Arguments:
events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing)
sell_delay (int): num... |
def create(dataset, target, model_name, features=None,
validation_set='auto', distributed='auto',
verbose=True, seed=None, **kwargs):
"""
Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements Su... | def function[create, parameter[dataset, target, model_name, features, validation_set, distributed, verbose, seed]]:
constant[
Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements SupervisedLearningModel This fun... | keyword[def] identifier[create] ( identifier[dataset] , identifier[target] , identifier[model_name] , identifier[features] = keyword[None] ,
identifier[validation_set] = literal[string] , identifier[distributed] = literal[string] ,
identifier[verbose] = keyword[True] , identifier[seed] = keyword[None] ,** identifie... | def create(dataset, target, model_name, features=None, validation_set='auto', distributed='auto', verbose=True, seed=None, **kwargs):
"""
Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements SupervisedLearningModel ... |
def call(self, *args, **kwargs):
"""Calls a redis command and returns a Future of the reply.
Args:
*args: full redis command as variable length argument list or
a Pipeline object (as a single argument).
**kwargs: internal private options (do not use).
Re... | def function[call, parameter[self]]:
constant[Calls a redis command and returns a Future of the reply.
Args:
*args: full redis command as variable length argument list or
a Pipeline object (as a single argument).
**kwargs: internal private options (do not use).
... | keyword[def] identifier[call] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_connected] ():
keyword[if] identifier[self] . identifier[autoconnect] :
... | def call(self, *args, **kwargs):
"""Calls a redis command and returns a Future of the reply.
Args:
*args: full redis command as variable length argument list or
a Pipeline object (as a single argument).
**kwargs: internal private options (do not use).
Return... |
def ion_or_solid_comp_object(formula):
"""
Returns either an ion object or composition object given
a formula.
Args:
formula: String formula. Eg. of ion: NaOH(aq), Na[+];
Eg. of solid: Fe2O3(s), Fe(s), Na2O
Returns:
Composition/Ion object
"""
m = re.search(r"\[(... | def function[ion_or_solid_comp_object, parameter[formula]]:
constant[
Returns either an ion object or composition object given
a formula.
Args:
formula: String formula. Eg. of ion: NaOH(aq), Na[+];
Eg. of solid: Fe2O3(s), Fe(s), Na2O
Returns:
Composition/Ion object
... | keyword[def] identifier[ion_or_solid_comp_object] ( identifier[formula] ):
literal[string]
identifier[m] = identifier[re] . identifier[search] ( literal[string] , identifier[formula] )
keyword[if] identifier[m] :
identifier[comp_obj] = identifier[Ion] . identifier[from_formula] ( identifier[... | def ion_or_solid_comp_object(formula):
"""
Returns either an ion object or composition object given
a formula.
Args:
formula: String formula. Eg. of ion: NaOH(aq), Na[+];
Eg. of solid: Fe2O3(s), Fe(s), Na2O
Returns:
Composition/Ion object
"""
m = re.search('\\[(... |
def load_yaml_file(i):
"""
Input: {
yaml_file - name of YAML file
}
Output: {
return - return code = 0, if successful
= 16, if file not found (may be warning)
> 0, if error
... | def function[load_yaml_file, parameter[i]]:
constant[
Input: {
yaml_file - name of YAML file
}
Output: {
return - return code = 0, if successful
= 16, if file not found (may be warning)
... | keyword[def] identifier[load_yaml_file] ( identifier[i] ):
literal[string]
keyword[import] identifier[yaml]
identifier[fn] = identifier[i] [ literal[string] ]
keyword[try] :
keyword[if] identifier[sys] . identifier[version_info] [ literal[int] ]> literal[int] :
identifier[f... | def load_yaml_file(i):
"""
Input: {
yaml_file - name of YAML file
}
Output: {
return - return code = 0, if successful
= 16, if file not found (may be warning)
> 0, if error
... |
def delete_namespaced_job(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_job # noqa: E501
delete a Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | def function[delete_namespaced_job, parameter[self, name, namespace]]:
constant[delete_namespaced_job # noqa: E501
delete a Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = a... | keyword[def] identifier[delete_namespaced_job] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def delete_namespaced_job(self, name, namespace, **kwargs): # noqa: E501
'delete_namespaced_job # noqa: E501\n\n delete a Job # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.d... |
def _attachChild(self, child):
"attach a child database, returning an identifier for it"
self._childCounter += 1
databaseName = 'child_db_%d' % (self._childCounter,)
self._attachedChildren[databaseName] = child
# ATTACH DATABASE statements can't use bind paramaters, blech.
... | def function[_attachChild, parameter[self, child]]:
constant[attach a child database, returning an identifier for it]
<ast.AugAssign object at 0x7da1b0d5b3d0>
variable[databaseName] assign[=] binary_operation[constant[child_db_%d] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x... | keyword[def] identifier[_attachChild] ( identifier[self] , identifier[child] ):
literal[string]
identifier[self] . identifier[_childCounter] += literal[int]
identifier[databaseName] = literal[string] %( identifier[self] . identifier[_childCounter] ,)
identifier[self] . identifier... | def _attachChild(self, child):
"""attach a child database, returning an identifier for it"""
self._childCounter += 1
databaseName = 'child_db_%d' % (self._childCounter,)
self._attachedChildren[databaseName] = child
# ATTACH DATABASE statements can't use bind paramaters, blech.
self.executeSQL("A... |
def modification_time(self):
"""dfdatetime.Filetime: modification time."""
timestamp = self._fsntfs_attribute.get_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) | def function[modification_time, parameter[self]]:
constant[dfdatetime.Filetime: modification time.]
variable[timestamp] assign[=] call[name[self]._fsntfs_attribute.get_modification_time_as_integer, parameter[]]
return[call[name[dfdatetime_filetime].Filetime, parameter[]]] | keyword[def] identifier[modification_time] ( identifier[self] ):
literal[string]
identifier[timestamp] = identifier[self] . identifier[_fsntfs_attribute] . identifier[get_modification_time_as_integer] ()
keyword[return] identifier[dfdatetime_filetime] . identifier[Filetime] ( identifier[timestamp] = ... | def modification_time(self):
"""dfdatetime.Filetime: modification time."""
timestamp = self._fsntfs_attribute.get_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) |
def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
... | def function[run_agent, parameter[device_type]]:
constant[Run a simple GPG-agent server.]
variable[p] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[p].add_argument, parameter[constant[--homedir]]]
call[name[p].add_argument, parameter[constant[-v], constant[--verbos... | keyword[def] identifier[run_agent] ( identifier[device_type] ):
literal[string]
identifier[p] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[p] . identifier[add_argument] ( literal[string] , identifier[default] = identifier[os] . identifier[environ] . identifier[get] ( literal[strin... | def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true', help='Use stdin/... |
def build_url(server_context, controller, action, container_path=None):
# type: (ServerContext, str, str, str) -> str
"""
Builds a URL from a controller and an action. Users the server context to determine domain,
context path, container, etc.
:param server_context: A LabKey server context. See util... | def function[build_url, parameter[server_context, controller, action, container_path]]:
constant[
Builds a URL from a controller and an action. Users the server context to determine domain,
context path, container, etc.
:param server_context: A LabKey server context. See utils.create_server_context.... | keyword[def] identifier[build_url] ( identifier[server_context] , identifier[controller] , identifier[action] , identifier[container_path] = keyword[None] ):
literal[string]
keyword[return] identifier[server_context] . identifier[build_url] ( identifier[controller] , identifier[action] , identifier[conta... | def build_url(server_context, controller, action, container_path=None):
# type: (ServerContext, str, str, str) -> str
'\n Builds a URL from a controller and an action. Users the server context to determine domain,\n context path, container, etc.\n :param server_context: A LabKey server context. See uti... |
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if ap... | def function[default_output_format, parameter[content_type, apply_globally, api, cli, http]]:
constant[A decorator that allows you to override the default output format for an API]
def function[decorator, parameter[formatter]]:
variable[formatter] assign[=] call[call[name[hug].output_for... | keyword[def] identifier[default_output_format] ( identifier[content_type] = literal[string] , identifier[apply_globally] = keyword[False] , identifier[api] = keyword[None] , identifier[cli] = keyword[False] , identifier[http] = keyword[True] ):
literal[string]
keyword[def] identifier[decorator] ( identifi... | def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if a... |
def get_api_key(client, username, secret):
"""Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
"""
# Try to use a client with username/api key
if len(secret) == 64:
try:
client['Account'].getCurrentUser()
... | def function[get_api_key, parameter[client, username, secret]]:
constant[Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
]
if compare[call[name[len], parameter[name[secret]]] equal[==] constant[64]] begin[:]
<ast.Try object a... | keyword[def] identifier[get_api_key] ( identifier[client] , identifier[username] , identifier[secret] ):
literal[string]
keyword[if] identifier[len] ( identifier[secret] )== literal[int] :
keyword[try] :
identifier[client] [ literal[string] ]. identifier[getCurrentUser] ()
... | def get_api_key(client, username, secret):
"""Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
"""
# Try to use a client with username/api key
if len(secret) == 64:
try:
client['Account'].getCurrentUser()
r... |
def learn(self, initial_state_key, limit=1000, game_n=1):
'''
Multi-Agent Learning.
Override.
Args:
initial_state_key: Initial state.
limit: Limit of the number of learning.
game_n: The number of games.
... | def function[learn, parameter[self, initial_state_key, limit, game_n]]:
constant[
Multi-Agent Learning.
Override.
Args:
initial_state_key: Initial state.
limit: Limit of the number of learning.
game_n: The number of ... | keyword[def] identifier[learn] ( identifier[self] , identifier[initial_state_key] , identifier[limit] = literal[int] , identifier[game_n] = literal[int] ):
literal[string]
identifier[end_flag] = keyword[False]
identifier[state_key_list] =[ keyword[None] ]* identifier[len] ( identifier[sel... | def learn(self, initial_state_key, limit=1000, game_n=1):
"""
Multi-Agent Learning.
Override.
Args:
initial_state_key: Initial state.
limit: Limit of the number of learning.
game_n: The number of games.
... |
def ida_spawn(ida_binary, filename, port=18861, mode='oneshot',
processor_type=None, logfile=None):
"""
Open IDA on the the file we want to analyse.
:param ida_binary: The binary name or path to ida
:param filename: The filename to open in IDA
:param port: The port on which... | def function[ida_spawn, parameter[ida_binary, filename, port, mode, processor_type, logfile]]:
constant[
Open IDA on the the file we want to analyse.
:param ida_binary: The binary name or path to ida
:param filename: The filename to open in IDA
:param port: The port on which to serve... | keyword[def] identifier[ida_spawn] ( identifier[ida_binary] , identifier[filename] , identifier[port] = literal[int] , identifier[mode] = literal[string] ,
identifier[processor_type] = keyword[None] , identifier[logfile] = keyword[None] ):
literal[string]
identifier[ida_progname] = identifier[_which] ( id... | def ida_spawn(ida_binary, filename, port=18861, mode='oneshot', processor_type=None, logfile=None):
"""
Open IDA on the the file we want to analyse.
:param ida_binary: The binary name or path to ida
:param filename: The filename to open in IDA
:param port: The port on which to serve rpc ... |
def upix_to_pix(upix):
"""Get the nside from a unique pixel number."""
nside = np.power(2, np.floor(np.log2(upix / 4)) / 2).astype(int)
pix = upix - 4 * np.power(nside, 2)
return pix, nside | def function[upix_to_pix, parameter[upix]]:
constant[Get the nside from a unique pixel number.]
variable[nside] assign[=] call[call[name[np].power, parameter[constant[2], binary_operation[call[name[np].floor, parameter[call[name[np].log2, parameter[binary_operation[name[upix] / constant[4]]]]]] / consta... | keyword[def] identifier[upix_to_pix] ( identifier[upix] ):
literal[string]
identifier[nside] = identifier[np] . identifier[power] ( literal[int] , identifier[np] . identifier[floor] ( identifier[np] . identifier[log2] ( identifier[upix] / literal[int] ))/ literal[int] ). identifier[astype] ( identifier[int... | def upix_to_pix(upix):
"""Get the nside from a unique pixel number."""
nside = np.power(2, np.floor(np.log2(upix / 4)) / 2).astype(int)
pix = upix - 4 * np.power(nside, 2)
return (pix, nside) |
def remove_synchronous(self, resource, force=False, timeout=-1):
"""
Deletes the resource specified by {id} synchronously.
Args:
resource: dict object to remove
force:
If set to true, the operation completes despite any problems with
net... | def function[remove_synchronous, parameter[self, resource, force, timeout]]:
constant[
Deletes the resource specified by {id} synchronously.
Args:
resource: dict object to remove
force:
If set to true, the operation completes despite any problems with
... | keyword[def] identifier[remove_synchronous] ( identifier[self] , identifier[resource] , identifier[force] = keyword[False] , identifier[timeout] =- literal[int] ):
literal[string]
identifier[uri] = identifier[self] . identifier[_client] . identifier[build_uri] ( identifier[resource] [ literal[strin... | def remove_synchronous(self, resource, force=False, timeout=-1):
"""
Deletes the resource specified by {id} synchronously.
Args:
resource: dict object to remove
force:
If set to true, the operation completes despite any problems with
network... |
def getEstablishments(self, city_id, **kwargs):
"""
:param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
- Using Z... | def function[getEstablishments, parameter[self, city_id]]:
constant[
:param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
... | keyword[def] identifier[getEstablishments] ( identifier[self] , identifier[city_id] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={ literal[string] : identifier[city_id] }
identifier[optional_params] =[ literal[string] , literal[string] ]
keyword[for] identifier[... | def getEstablishments(self, city_id, **kwargs):
"""
:param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
- Using Zomat... |
def compress(a, b):
"""Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to diff.
b (str or list): *e... | def function[compress, parameter[a, b]]:
constant[Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to di... | keyword[def] identifier[compress] ( identifier[a] , identifier[b] ):
literal[string]
keyword[from] identifier[difflib] keyword[import] identifier[ndiff]
identifier[left] = identifier[a] . identifier[splitlines] ( literal[int] ) keyword[if] identifier[isinstance] ( identifier[a] , identifier[strin... | def compress(a, b):
"""Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to diff.
b (str or list): *e... |
def _untrack_tendril(self, tendril):
"""
Removes the tendril from the set of tracked tendrils.
"""
try:
del self.tendrils[tendril._tendril_key]
except KeyError:
pass
# Also remove from _tendrils
try:
del self._tendrils[tendril... | def function[_untrack_tendril, parameter[self, tendril]]:
constant[
Removes the tendril from the set of tracked tendrils.
]
<ast.Try object at 0x7da18bcc8be0>
<ast.Try object at 0x7da18bccb8e0> | keyword[def] identifier[_untrack_tendril] ( identifier[self] , identifier[tendril] ):
literal[string]
keyword[try] :
keyword[del] identifier[self] . identifier[tendrils] [ identifier[tendril] . identifier[_tendril_key] ]
keyword[except] identifier[KeyError] :
k... | def _untrack_tendril(self, tendril):
"""
Removes the tendril from the set of tracked tendrils.
"""
try:
del self.tendrils[tendril._tendril_key] # depends on [control=['try'], data=[]]
except KeyError:
pass # depends on [control=['except'], data=[]]
# Also remove from _t... |
def __discovery_doc_descriptor(self, services, hostname=None):
"""Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaul... | def function[__discovery_doc_descriptor, parameter[self, services, hostname]]:
constant[Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
... | keyword[def] identifier[__discovery_doc_descriptor] ( identifier[self] , identifier[services] , identifier[hostname] = keyword[None] ):
literal[string]
identifier[merged_api_info] = identifier[self] . identifier[__get_merged_api_info] ( identifier[services] )
identifier[descriptor] = identifier[self] ... | def __discovery_doc_descriptor(self, services, hostname=None):
"""Builds a discovery doc for an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaul... |
def applicable_file_flags(self):
"""
Return the applicable file flags attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.APPLICABLE_FI... | def function[applicable_file_flags, parameter[self]]:
constant[
Return the applicable file flags attribute of the BFD file being
processed.
]
if <ast.UnaryOp object at 0x7da207f9aa70> begin[:]
<ast.Raise object at 0x7da207f9b0a0>
return[call[name[_bfd].get_bfd_attrib... | keyword[def] identifier[applicable_file_flags] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_ptr] :
keyword[raise] identifier[BfdException] ( literal[string] )
keyword[return] identifier[_bfd] . identifier[get_bfd_attribute]... | def applicable_file_flags(self):
"""
Return the applicable file flags attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException('BFD not initialized') # depends on [control=['if'], data=[]]
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.APP... |
def _update_list_store_entry(self, list_store, config_key, config_value):
"""Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list... | def function[_update_list_store_entry, parameter[self, list_store, config_key, config_value]]:
constant[Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
... | keyword[def] identifier[_update_list_store_entry] ( identifier[self] , identifier[list_store] , identifier[config_key] , identifier[config_value] ):
literal[string]
keyword[for] identifier[row_num] , identifier[row] keyword[in] identifier[enumerate] ( identifier[list_store] ):
keywo... | def _update_list_store_entry(self, list_store, config_key, config_value):
"""Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list sto... |
def cover(ctx, html=False):
'''Run tests suite with coverage'''
params = '--cov-report term --cov-report html' if html else ''
with ctx.cd(ROOT):
ctx.run('pytest --cov flask_fs {0}'.format(params), pty=True) | def function[cover, parameter[ctx, html]]:
constant[Run tests suite with coverage]
variable[params] assign[=] <ast.IfExp object at 0x7da1b0c50cd0>
with call[name[ctx].cd, parameter[name[ROOT]]] begin[:]
call[name[ctx].run, parameter[call[constant[pytest --cov flask_fs {0}].format... | keyword[def] identifier[cover] ( identifier[ctx] , identifier[html] = keyword[False] ):
literal[string]
identifier[params] = literal[string] keyword[if] identifier[html] keyword[else] literal[string]
keyword[with] identifier[ctx] . identifier[cd] ( identifier[ROOT] ):
identifier[ctx] . ... | def cover(ctx, html=False):
"""Run tests suite with coverage"""
params = '--cov-report term --cov-report html' if html else ''
with ctx.cd(ROOT):
ctx.run('pytest --cov flask_fs {0}'.format(params), pty=True) # depends on [control=['with'], data=[]] |
def _get_entity(service_instance, entity):
'''
Returns the entity associated with the entity dict representation
Supported entities: cluster, vcenter
Expected entity format:
.. code-block:: python
cluster:
{'type': 'cluster',
'datacenter': <datacenter_name>,
... | def function[_get_entity, parameter[service_instance, entity]]:
constant[
Returns the entity associated with the entity dict representation
Supported entities: cluster, vcenter
Expected entity format:
.. code-block:: python
cluster:
{'type': 'cluster',
'datac... | keyword[def] identifier[_get_entity] ( identifier[service_instance] , identifier[entity] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string] , identifier[entity] )
keyword[if] identifier[entity] [ literal[string] ]== literal[string] :
identifier[dc_ref] = identifier[sal... | def _get_entity(service_instance, entity):
"""
Returns the entity associated with the entity dict representation
Supported entities: cluster, vcenter
Expected entity format:
.. code-block:: python
cluster:
{'type': 'cluster',
'datacenter': <datacenter_name>,
... |
def node_changed(self):
"""
Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.node_changed` method.
:return: Method success.
:rtype: bool
"""
for model in umbra.ui.models.GraphModel.find_model(self):
model.node_changed(self)
return True | def function[node_changed, parameter[self]]:
constant[
Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.node_changed` method.
:return: Method success.
:rtype: bool
]
for taget[name[model]] in starred[call[name[umbra].ui.models.GraphModel.find_model, parameter... | keyword[def] identifier[node_changed] ( identifier[self] ):
literal[string]
keyword[for] identifier[model] keyword[in] identifier[umbra] . identifier[ui] . identifier[models] . identifier[GraphModel] . identifier[find_model] ( identifier[self] ):
identifier[model] . identifier[node... | def node_changed(self):
"""
Triggers the host model(s) :meth:`umbra.ui.models.GraphModel.node_changed` method.
:return: Method success.
:rtype: bool
"""
for model in umbra.ui.models.GraphModel.find_model(self):
model.node_changed(self) # depends on [control=['for'], dat... |
def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
... | def function[main, parameter[]]:
constant[Parser the command line and run the validator.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[--log]]]
call[name[parser].add_argument, parameter[constant[--version]]... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] + identifier[__version__] + literal[string] + identifier[__doc__] ,
identifier[prog] = literal[string] ,
)
identifier[parse... | def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(description='[v' + __version__ + '] ' + __doc__, prog='w3c_validator')
parser.add_argument('--log', default='INFO', help='log level: DEBUG, INFO or INFO (default: INFO)')
parser.add_argument('--version', ac... |
def encode(self, value):
'''
:param value: value to encode
'''
kassert.is_of_types(value, Bits)
remainder = len(value) % 8
if remainder:
value += Bits(bin='0' * (8 - remainder))
return value | def function[encode, parameter[self, value]]:
constant[
:param value: value to encode
]
call[name[kassert].is_of_types, parameter[name[value], name[Bits]]]
variable[remainder] assign[=] binary_operation[call[name[len], parameter[name[value]]] <ast.Mod object at 0x7da2590d6920> co... | keyword[def] identifier[encode] ( identifier[self] , identifier[value] ):
literal[string]
identifier[kassert] . identifier[is_of_types] ( identifier[value] , identifier[Bits] )
identifier[remainder] = identifier[len] ( identifier[value] )% literal[int]
keyword[if] identifier[rem... | def encode(self, value):
"""
:param value: value to encode
"""
kassert.is_of_types(value, Bits)
remainder = len(value) % 8
if remainder:
value += Bits(bin='0' * (8 - remainder)) # depends on [control=['if'], data=[]]
return value |
def find_model_by_table_name(name):
"""Find a model reference by its table name"""
for model in ModelBase._decl_class_registry.values():
if hasattr(model, '__table__') and model.__table__.fullname == name:
return model
return None | def function[find_model_by_table_name, parameter[name]]:
constant[Find a model reference by its table name]
for taget[name[model]] in starred[call[name[ModelBase]._decl_class_registry.values, parameter[]]] begin[:]
if <ast.BoolOp object at 0x7da1b0d0d0f0> begin[:]
return[name... | keyword[def] identifier[find_model_by_table_name] ( identifier[name] ):
literal[string]
keyword[for] identifier[model] keyword[in] identifier[ModelBase] . identifier[_decl_class_registry] . identifier[values] ():
keyword[if] identifier[hasattr] ( identifier[model] , literal[string] ) keyword[... | def find_model_by_table_name(name):
"""Find a model reference by its table name"""
for model in ModelBase._decl_class_registry.values():
if hasattr(model, '__table__') and model.__table__.fullname == name:
return model # depends on [control=['if'], data=[]] # depends on [control=['for'], d... |
def from_shortcode(cls, context: InstaloaderContext, shortcode: str):
"""Create a post object from a given shortcode"""
# pylint:disable=protected-access
post = cls(context, {'shortcode': shortcode})
post._node = post._full_metadata
return post | def function[from_shortcode, parameter[cls, context, shortcode]]:
constant[Create a post object from a given shortcode]
variable[post] assign[=] call[name[cls], parameter[name[context], dictionary[[<ast.Constant object at 0x7da20c6e7070>], [<ast.Name object at 0x7da20c6e77f0>]]]]
name[post]._nod... | keyword[def] identifier[from_shortcode] ( identifier[cls] , identifier[context] : identifier[InstaloaderContext] , identifier[shortcode] : identifier[str] ):
literal[string]
identifier[post] = identifier[cls] ( identifier[context] ,{ literal[string] : identifier[shortcode] })
iden... | def from_shortcode(cls, context: InstaloaderContext, shortcode: str):
"""Create a post object from a given shortcode"""
# pylint:disable=protected-access
post = cls(context, {'shortcode': shortcode})
post._node = post._full_metadata
return post |
def chimera_anticluster(m, n=None, t=4, multiplier=3.0,
cls=BinaryQuadraticModel, subgraph=None, seed=None):
"""Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
... | def function[chimera_anticluster, parameter[m, n, t, multiplier, cls, subgraph, seed]]:
constant[Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
m (int):
Number of rows... | keyword[def] identifier[chimera_anticluster] ( identifier[m] , identifier[n] = keyword[None] , identifier[t] = literal[int] , identifier[multiplier] = literal[int] ,
identifier[cls] = identifier[BinaryQuadraticModel] , identifier[subgraph] = keyword[None] , identifier[seed] = keyword[None] ):
literal[string]
... | def chimera_anticluster(m, n=None, t=4, multiplier=3.0, cls=BinaryQuadraticModel, subgraph=None, seed=None):
"""Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
m (int):
Num... |
def format_args_in_redis_protocol(*args):
"""Formats arguments into redis protocol...
This function makes and returns a string/buffer corresponding to
given arguments formated with the redis protocol.
integer, text, string or binary types are automatically converted
(using utf8 if necessary).
... | def function[format_args_in_redis_protocol, parameter[]]:
constant[Formats arguments into redis protocol...
This function makes and returns a string/buffer corresponding to
given arguments formated with the redis protocol.
integer, text, string or binary types are automatically converted
(usin... | keyword[def] identifier[format_args_in_redis_protocol] (* identifier[args] ):
literal[string]
identifier[buf] = identifier[WriteBuffer] ()
identifier[l] = literal[string] % identifier[len] ( identifier[args] )
keyword[if] identifier[six] . identifier[PY2] :
identifier[buf] . identifier[... | def format_args_in_redis_protocol(*args):
"""Formats arguments into redis protocol...
This function makes and returns a string/buffer corresponding to
given arguments formated with the redis protocol.
integer, text, string or binary types are automatically converted
(using utf8 if necessary).
... |
def _response(self, in_response_to, consumer_url=None, status=None,
issuer=None, sign=False, to_sign=None, sp_entity_id=None,
encrypt_assertion=False,
encrypt_assertion_self_contained=False,
encrypted_advice_attributes=False,
encr... | def function[_response, parameter[self, in_response_to, consumer_url, status, issuer, sign, to_sign, sp_entity_id, encrypt_assertion, encrypt_assertion_self_contained, encrypted_advice_attributes, encrypt_cert_advice, encrypt_cert_assertion, sign_assertion, pefim, sign_alg, digest_alg]]:
constant[ Create a Resp... | keyword[def] identifier[_response] ( identifier[self] , identifier[in_response_to] , identifier[consumer_url] = keyword[None] , identifier[status] = keyword[None] ,
identifier[issuer] = keyword[None] , identifier[sign] = keyword[False] , identifier[to_sign] = keyword[None] , identifier[sp_entity_id] = keyword[None] ... | def _response(self, in_response_to, consumer_url=None, status=None, issuer=None, sign=False, to_sign=None, sp_entity_id=None, encrypt_assertion=False, encrypt_assertion_self_contained=False, encrypted_advice_attributes=False, encrypt_cert_advice=None, encrypt_cert_assertion=None, sign_assertion=None, pefim=False, sign_... |
def get_tile_from_image(image, size, top_left_corner, tile_size):
"""
Returns a rectangular region of the given image as a separate image
If the tile goes off the edge of the image, it will be truncated. The new size is also returned.
:param image: The given image, as a list of (R,G,B) tuples
:param... | def function[get_tile_from_image, parameter[image, size, top_left_corner, tile_size]]:
constant[
Returns a rectangular region of the given image as a separate image
If the tile goes off the edge of the image, it will be truncated. The new size is also returned.
:param image: The given image, as a li... | keyword[def] identifier[get_tile_from_image] ( identifier[image] , identifier[size] , identifier[top_left_corner] , identifier[tile_size] ):
literal[string]
identifier[tile_pixels] =[]
identifier[tile_x] = identifier[min] ( identifier[size] [ literal[int] ]- identifier[top_left_corner] [ literal[... | def get_tile_from_image(image, size, top_left_corner, tile_size):
"""
Returns a rectangular region of the given image as a separate image
If the tile goes off the edge of the image, it will be truncated. The new size is also returned.
:param image: The given image, as a list of (R,G,B) tuples
:param... |
def update(self, params, values):
"""
Update the particles field given new parameter values
"""
#1. Figure out if we're going to do a global update, in which
# case we just draw from scratch.
global_update, particles = self._update_type(params)
# if we are doin... | def function[update, parameter[self, params, values]]:
constant[
Update the particles field given new parameter values
]
<ast.Tuple object at 0x7da18dc05480> assign[=] call[name[self]._update_type, parameter[name[params]]]
if name[global_update] begin[:]
call[name... | keyword[def] identifier[update] ( identifier[self] , identifier[params] , identifier[values] ):
literal[string]
identifier[global_update] , identifier[particles] = identifier[self] . identifier[_update_type] ( identifier[params] )
keyword[if] identifie... | def update(self, params, values):
"""
Update the particles field given new parameter values
"""
#1. Figure out if we're going to do a global update, in which
# case we just draw from scratch.
(global_update, particles) = self._update_type(params)
# if we are doing a global update, ... |
def watch_for_new_conf(self, timeout=0):
"""Check if a new configuration was sent to the daemon
This function is called on each daemon loop turn. Basically it is a sleep...
If a new configuration was posted, this function returns True
:param timeout: timeout to wait. Default is no wai... | def function[watch_for_new_conf, parameter[self, timeout]]:
constant[Check if a new configuration was sent to the daemon
This function is called on each daemon loop turn. Basically it is a sleep...
If a new configuration was posted, this function returns True
:param timeout: timeout t... | keyword[def] identifier[watch_for_new_conf] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[timeout] )
identifier[self] . identifier[make_a_pause] ( identifier[timeout] = identifier[timeout] , ... | def watch_for_new_conf(self, timeout=0):
"""Check if a new configuration was sent to the daemon
This function is called on each daemon loop turn. Basically it is a sleep...
If a new configuration was posted, this function returns True
:param timeout: timeout to wait. Default is no wait ti... |
def coarse_graining(network, state, internal_indices):
"""Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
t... | def function[coarse_graining, parameter[network, state, internal_indices]]:
constant[Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-... | keyword[def] identifier[coarse_graining] ( identifier[network] , identifier[state] , identifier[internal_indices] ):
literal[string]
identifier[max_phi] = identifier[float] ( literal[string] )
identifier[max_coarse_grain] = identifier[CoarseGrain] ((),())
keyword[for] identifier[coarse_grain] ... | def coarse_graining(network, state, internal_indices):
"""Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
t... |
def insert_many(self, items):
"""
Insert many items at once into a temporary table.
"""
return SessionContext.session.execute(
self.insert(values=[
to_dict(item, self.c)
for item in items
]),
).rowcount | def function[insert_many, parameter[self, items]]:
constant[
Insert many items at once into a temporary table.
]
return[call[name[SessionContext].session.execute, parameter[call[name[self].insert, parameter[]]]].rowcount] | keyword[def] identifier[insert_many] ( identifier[self] , identifier[items] ):
literal[string]
keyword[return] identifier[SessionContext] . identifier[session] . identifier[execute] (
identifier[self] . identifier[insert] ( identifier[values] =[
identifier[to_dict] ( identifier[item] , identifie... | def insert_many(self, items):
"""
Insert many items at once into a temporary table.
"""
return SessionContext.session.execute(self.insert(values=[to_dict(item, self.c) for item in items])).rowcount |
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(da... | def function[_import_data, parameter[data, axis, slice_step, first_slice_offset]]:
constant[
import ndarray or SimpleITK data
]
<ast.Try object at 0x7da1b271da50>
variable[data] assign[=] call[name[__select_slices], parameter[name[data], name[axis], name[slice_step]]]
return[name[data]] | keyword[def] identifier[_import_data] ( identifier[data] , identifier[axis] , identifier[slice_step] , identifier[first_slice_offset] = literal[int] ):
literal[string]
keyword[try] :
keyword[import] identifier[SimpleITK] keyword[as] identifier[sitk]
keyword[if] identifier[type] (... | def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data) # depends on [control=['if'], data=[]] # depends on [control=['t... |
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certif... | def function[remove_cert_binding, parameter[name, site, hostheader, ipaddress, port]]:
constant[
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thum... | keyword[def] identifier[remove_cert_binding] ( identifier[name] , identifier[site] , identifier[hostheader] = literal[string] , identifier[ipaddress] = literal[string] , identifier[port] = literal[int] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
... | def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
"""
Remove a certificate from an IIS binding.
.. note:
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
:param str name: The thumbprint of the certif... |
def delete_sched_block_instance(self, block_id):
"""Delete the specified Scheduling Block Instance.
Removes the Scheduling Block Instance, and all Processing Blocks
that belong to it from the database"""
LOG.debug('Deleting SBI %s', block_id)
scheduling_blocks = self._db.get_al... | def function[delete_sched_block_instance, parameter[self, block_id]]:
constant[Delete the specified Scheduling Block Instance.
Removes the Scheduling Block Instance, and all Processing Blocks
that belong to it from the database]
call[name[LOG].debug, parameter[constant[Deleting SBI %s],... | keyword[def] identifier[delete_sched_block_instance] ( identifier[self] , identifier[block_id] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[block_id] )
identifier[scheduling_blocks] = identifier[self] . identifier[_db] . identifier[get_all_blocks] ... | def delete_sched_block_instance(self, block_id):
"""Delete the specified Scheduling Block Instance.
Removes the Scheduling Block Instance, and all Processing Blocks
that belong to it from the database"""
LOG.debug('Deleting SBI %s', block_id)
scheduling_blocks = self._db.get_all_blocks(bloc... |
def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.in... | def function[last, parameter[self]]:
constant[Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
]
if compare[name[self]._last is name[UNDETERMINED]] begin[:]
name[self]._last assi... | keyword[def] identifier[last] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_last] keyword[is] identifier[UNDETERMINED] :
identifier[self] . identifier[_last] = identifier[self] . identifier[sdat] . identifier[tseries] . identifier[index] [... | def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.index[-1] # depen... |
def update_swarm(self, version, swarm_spec=None, rotate_worker_token=False,
rotate_manager_token=False):
"""
Update the Swarm's configuration
Args:
version (int): The version number of the swarm object being
updated. This is required to avoid con... | def function[update_swarm, parameter[self, version, swarm_spec, rotate_worker_token, rotate_manager_token]]:
constant[
Update the Swarm's configuration
Args:
version (int): The version number of the swarm object being
updated. This is required to avoid conflicting wr... | keyword[def] identifier[update_swarm] ( identifier[self] , identifier[version] , identifier[swarm_spec] = keyword[None] , identifier[rotate_worker_token] = keyword[False] ,
identifier[rotate_manager_token] = keyword[False] ):
literal[string]
identifier[url] = identifier[self] . identifier[_url] (... | def update_swarm(self, version, swarm_spec=None, rotate_worker_token=False, rotate_manager_token=False):
"""
Update the Swarm's configuration
Args:
version (int): The version number of the swarm object being
updated. This is required to avoid conflicting writes.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.