code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def GetClientConfig(self, context, validate=True, deploy_timestamp=True):
"""Generates the client config file for inclusion in deployable binaries."""
with utils.TempDirectory() as tmp_dir:
# Make sure we write the file in yaml format.
filename = os.path.join(
tmp_dir,
config.CON... | def function[GetClientConfig, parameter[self, context, validate, deploy_timestamp]]:
constant[Generates the client config file for inclusion in deployable binaries.]
with call[name[utils].TempDirectory, parameter[]] begin[:]
variable[filename] assign[=] call[name[os].path.join, parameter... | keyword[def] identifier[GetClientConfig] ( identifier[self] , identifier[context] , identifier[validate] = keyword[True] , identifier[deploy_timestamp] = keyword[True] ):
literal[string]
keyword[with] identifier[utils] . identifier[TempDirectory] () keyword[as] identifier[tmp_dir] :
identifie... | def GetClientConfig(self, context, validate=True, deploy_timestamp=True):
"""Generates the client config file for inclusion in deployable binaries."""
with utils.TempDirectory() as tmp_dir:
# Make sure we write the file in yaml format.
filename = os.path.join(tmp_dir, config.CONFIG.Get('ClientBu... |
def open_url(absolute_or_relative_url):
"""
Loads a web page in the current browser session.
:param absolgenerateute_or_relative_url:
an absolute url to web page in case of config.base_url is not specified,
otherwise - relative url correspondingly
:Usage:
open_url('http://mydoma... | def function[open_url, parameter[absolute_or_relative_url]]:
constant[
Loads a web page in the current browser session.
:param absolgenerateute_or_relative_url:
an absolute url to web page in case of config.base_url is not specified,
otherwise - relative url correspondingly
:Usage:
... | keyword[def] identifier[open_url] ( identifier[absolute_or_relative_url] ):
literal[string]
identifier[base_url] = identifier[selene] . identifier[config] . identifier[app_host] keyword[if] identifier[selene] . identifier[config] . identifier[app_host] keyword[else] identifier[selene] . identifier... | def open_url(absolute_or_relative_url):
"""
Loads a web page in the current browser session.
:param absolgenerateute_or_relative_url:
an absolute url to web page in case of config.base_url is not specified,
otherwise - relative url correspondingly
:Usage:
open_url('http://mydoma... |
def find_teradata_home():
"""
Attempts to find the Teradata install directory with the defaults
for a given platform. Should always return `None` when the defaults
are not present and the TERADATA_HOME environment variable wasn't
explicitly set to the correct install location.
"""
if platfo... | def function[find_teradata_home, parameter[]]:
constant[
Attempts to find the Teradata install directory with the defaults
for a given platform. Should always return `None` when the defaults
are not present and the TERADATA_HOME environment variable wasn't
explicitly set to the correct install ... | keyword[def] identifier[find_teradata_home] ():
literal[string]
keyword[if] identifier[platform] . identifier[system] ()== literal[string] :
keyword[if] identifier[is_64bit] ():
keyword[return] identifier[latest_teradata_version] ( literal[string] )
... | def find_teradata_home():
"""
Attempts to find the Teradata install directory with the defaults
for a given platform. Should always return `None` when the defaults
are not present and the TERADATA_HOME environment variable wasn't
explicitly set to the correct install location.
"""
if platfo... |
def addFile(self, path, msg=""):
"""Adds a file to the version"""
item = Item.from_path(repo=self.repo, path=path)
self.addItem(item) | def function[addFile, parameter[self, path, msg]]:
constant[Adds a file to the version]
variable[item] assign[=] call[name[Item].from_path, parameter[]]
call[name[self].addItem, parameter[name[item]]] | keyword[def] identifier[addFile] ( identifier[self] , identifier[path] , identifier[msg] = literal[string] ):
literal[string]
identifier[item] = identifier[Item] . identifier[from_path] ( identifier[repo] = identifier[self] . identifier[repo] , identifier[path] = identifier[path] )
identif... | def addFile(self, path, msg=''):
"""Adds a file to the version"""
item = Item.from_path(repo=self.repo, path=path)
self.addItem(item) |
def putch(self, char):
"""
Prints the specific character, which must be a valid printable ASCII
value in the range 32..127 only, or one of carriage return (\\r),
newline (\\n), backspace (\\b) or tab (\\t).
:param char: The character to print.
"""
if char == '\r'... | def function[putch, parameter[self, char]]:
constant[
Prints the specific character, which must be a valid printable ASCII
value in the range 32..127 only, or one of carriage return (\r),
newline (\n), backspace (\b) or tab (\t).
:param char: The character to print.
]
... | keyword[def] identifier[putch] ( identifier[self] , identifier[char] ):
literal[string]
keyword[if] identifier[char] == literal[string] :
identifier[self] . identifier[carriage_return] ()
keyword[elif] identifier[char] == literal[string] :
identifier[self] . id... | def putch(self, char):
"""
Prints the specific character, which must be a valid printable ASCII
value in the range 32..127 only, or one of carriage return (\\r),
newline (\\n), backspace (\\b) or tab (\\t).
:param char: The character to print.
"""
if char == '\r':
... |
def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None):
"""Generate raster mask for exposed bare ground from global bareground data
"""
print("Loading bareground")
b = bareground_ds.GetRasterBand(1)
l = b.ReadAsArray()
print("Masking pixels with <%0.1f%% bare ground" % baregro... | def function[get_bareground_mask, parameter[bareground_ds, bareground_thresh, out_fn]]:
constant[Generate raster mask for exposed bare ground from global bareground data
]
call[name[print], parameter[constant[Loading bareground]]]
variable[b] assign[=] call[name[bareground_ds].GetRasterBand,... | keyword[def] identifier[get_bareground_mask] ( identifier[bareground_ds] , identifier[bareground_thresh] = literal[int] , identifier[out_fn] = keyword[None] ):
literal[string]
identifier[print] ( literal[string] )
identifier[b] = identifier[bareground_ds] . identifier[GetRasterBand] ( literal[int] )
... | def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None):
"""Generate raster mask for exposed bare ground from global bareground data
"""
print('Loading bareground')
b = bareground_ds.GetRasterBand(1)
l = b.ReadAsArray()
print('Masking pixels with <%0.1f%% bare ground' % baregro... |
def wrap(cls, public_key, algorithm):
"""
Wraps a public key in a PublicKeyInfo structure
:param public_key:
A byte string or Asn1Value object of the public key
:param algorithm:
A unicode string of "rsa"
:return:
A PublicKeyInfo object
... | def function[wrap, parameter[cls, public_key, algorithm]]:
constant[
Wraps a public key in a PublicKeyInfo structure
:param public_key:
A byte string or Asn1Value object of the public key
:param algorithm:
A unicode string of "rsa"
:return:
... | keyword[def] identifier[wrap] ( identifier[cls] , identifier[public_key] , identifier[algorithm] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[public_key] , identifier[byte_cls] ) keyword[and] keyword[not] identifier[isinstance] ( identifier[public_key] , iden... | def wrap(cls, public_key, algorithm):
"""
Wraps a public key in a PublicKeyInfo structure
:param public_key:
A byte string or Asn1Value object of the public key
:param algorithm:
A unicode string of "rsa"
:return:
A PublicKeyInfo object
... |
def _channel_loop(detection, template, min_cc, detection_id, interpolate, i,
pre_lag_ccsum=None, detect_chans=0,
horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'],
debug=0):
"""
Inner loop for correlating and assigning picks.
Utility function ... | def function[_channel_loop, parameter[detection, template, min_cc, detection_id, interpolate, i, pre_lag_ccsum, detect_chans, horizontal_chans, vertical_chans, debug]]:
constant[
Inner loop for correlating and assigning picks.
Utility function to take a stream of data for the detected event and write
... | keyword[def] identifier[_channel_loop] ( identifier[detection] , identifier[template] , identifier[min_cc] , identifier[detection_id] , identifier[interpolate] , identifier[i] ,
identifier[pre_lag_ccsum] = keyword[None] , identifier[detect_chans] = literal[int] ,
identifier[horizontal_chans] =[ literal[string] , li... | def _channel_loop(detection, template, min_cc, detection_id, interpolate, i, pre_lag_ccsum=None, detect_chans=0, horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'], debug=0):
"""
Inner loop for correlating and assigning picks.
Utility function to take a stream of data for the detected event and wr... |
def _sanitize_values(arr):
"""
return an ndarray for our input,
in a platform independent manner
"""
if hasattr(arr, 'values'):
arr = arr.values
else:
# scalar
if is_scalar(arr):
arr = [arr]
# ndarray
if isinstance(arr, np.ndarray):
... | def function[_sanitize_values, parameter[arr]]:
constant[
return an ndarray for our input,
in a platform independent manner
]
if call[name[hasattr], parameter[name[arr], constant[values]]] begin[:]
variable[arr] assign[=] name[arr].values
return[name[arr]] | keyword[def] identifier[_sanitize_values] ( identifier[arr] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[arr] , literal[string] ):
identifier[arr] = identifier[arr] . identifier[values]
keyword[else] :
keyword[if] identifier[is_scalar] ( identifier[arr] )... | def _sanitize_values(arr):
"""
return an ndarray for our input,
in a platform independent manner
"""
if hasattr(arr, 'values'):
arr = arr.values # depends on [control=['if'], data=[]]
else:
# scalar
if is_scalar(arr):
arr = [arr] # depends on [control=['if']... |
def arrays(self):
"""Return an iterator over (name, value) pairs for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=1... | def function[arrays, parameter[self]]:
constant[Return an iterator over (name, value) pairs for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset... | keyword[def] identifier[arrays] ( identifier[self] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[sorted] ( identifier[listdir] ( identifier[self] . identifier[_store] , identifier[self] . identifier[_path] )):
identifier[path] = identifier[self] . identifier... | def arrays(self):
"""Return an iterator over (name, value) pairs for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
... |
def run(coro: 'Optional[Coroutine]' = None, *,
loop: Optional[AbstractEventLoop] = None,
shutdown_handler: Optional[Callable[[AbstractEventLoop], None]] = None,
executor_workers: int = 10,
executor: Optional[Executor] = None,
use_uvloop: bool = False) -> None:
"""
Start u... | def function[run, parameter[coro]]:
constant[
Start up the event loop, and wait for a signal to shut down.
:param coro: Optionally supply a coroutine. The loop will still
run if missing. The loop will continue to run after the supplied
coroutine finishes. The supplied coroutine is typic... | keyword[def] identifier[run] ( identifier[coro] : literal[string] = keyword[None] ,*,
identifier[loop] : identifier[Optional] [ identifier[AbstractEventLoop] ]= keyword[None] ,
identifier[shutdown_handler] : identifier[Optional] [ identifier[Callable] [[ identifier[AbstractEventLoop] ], keyword[None] ]]= keyword[No... | def run(coro: 'Optional[Coroutine]'=None, *, loop: Optional[AbstractEventLoop]=None, shutdown_handler: Optional[Callable[[AbstractEventLoop], None]]=None, executor_workers: int=10, executor: Optional[Executor]=None, use_uvloop: bool=False) -> None:
"""
Start up the event loop, and wait for a signal to shut down... |
def get_template(self, name=None, params=None):
"""
Retrieve an index template by its name.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_
:arg name: The name of the template
:arg flat_settings: Return settings in flat format (default:... | def function[get_template, parameter[self, name, params]]:
constant[
Retrieve an index template by its name.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_
:arg name: The name of the template
:arg flat_settings: Return settings in flat... | keyword[def] identifier[get_template] ( identifier[self] , identifier[name] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[transport] . identifier[perform_request] (
literal[string] , identifier[_make_path] ( literal[s... | def get_template(self, name=None, params=None):
"""
Retrieve an index template by its name.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_
:arg name: The name of the template
:arg flat_settings: Return settings in flat format (default: fal... |
def is_stopped(self, *args, **kwargs):
"""Return whether this container is stopped"""
kwargs["waiting"] = False
return self.wait_till_stopped(*args, **kwargs) | def function[is_stopped, parameter[self]]:
constant[Return whether this container is stopped]
call[name[kwargs]][constant[waiting]] assign[=] constant[False]
return[call[name[self].wait_till_stopped, parameter[<ast.Starred object at 0x7da20c6c7df0>]]] | keyword[def] identifier[is_stopped] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[False]
keyword[return] identifier[self] . identifier[wait_till_stopped] (* identifier[args] ,** identifier[kwargs] ) | def is_stopped(self, *args, **kwargs):
"""Return whether this container is stopped"""
kwargs['waiting'] = False
return self.wait_till_stopped(*args, **kwargs) |
def enter_eventloop(self):
"""enter eventloop"""
self.log.info("entering eventloop")
# restore default_int_handler
signal(SIGINT, default_int_handler)
while self.eventloop is not None:
try:
self.eventloop(self)
except KeyboardInterrupt:
... | def function[enter_eventloop, parameter[self]]:
constant[enter eventloop]
call[name[self].log.info, parameter[constant[entering eventloop]]]
call[name[signal], parameter[name[SIGINT], name[default_int_handler]]]
while compare[name[self].eventloop is_not constant[None]] begin[:]
<... | keyword[def] identifier[enter_eventloop] ( identifier[self] ):
literal[string]
identifier[self] . identifier[log] . identifier[info] ( literal[string] )
identifier[signal] ( identifier[SIGINT] , identifier[default_int_handler] )
keyword[while] identifier[self] . identifi... | def enter_eventloop(self):
"""enter eventloop"""
self.log.info('entering eventloop')
# restore default_int_handler
signal(SIGINT, default_int_handler)
while self.eventloop is not None:
try:
self.eventloop(self) # depends on [control=['try'], data=[]]
except KeyboardInter... |
def summary(args):
"""
%prog summary blastfile
Provide summary on id% and cov%, for both query and reference. Often used in
comparing genomes (based on NUCMER results).
"""
p = OptionParser(summary.__doc__)
p.add_option("--strict", default=False, action="store_true",
help="S... | def function[summary, parameter[args]]:
constant[
%prog summary blastfile
Provide summary on id% and cov%, for both query and reference. Often used in
comparing genomes (based on NUCMER results).
]
variable[p] assign[=] call[name[OptionParser], parameter[name[summary].__doc__]]
... | keyword[def] identifier[summary] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[summary] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = keyword[False] , identifier[action] = literal[string] ,
id... | def summary(args):
"""
%prog summary blastfile
Provide summary on id% and cov%, for both query and reference. Often used in
comparing genomes (based on NUCMER results).
"""
p = OptionParser(summary.__doc__)
p.add_option('--strict', default=False, action='store_true', help="Strict 'gapless' ... |
def smoothline(document, coords):
"smoothed polyline"
element = document.createElement('path')
path = []
points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)]
def pt(points):
x0, y0 = points[0]
x1, y1 = points[1]
p0 = (2*x0-x1, 2*y0-y1)
x0, y0 = points[-1]
x1, y1 = points[-2]
... | def function[smoothline, parameter[document, coords]]:
constant[smoothed polyline]
variable[element] assign[=] call[name[document].createElement, parameter[constant[path]]]
variable[path] assign[=] list[[]]
variable[points] assign[=] <ast.ListComp object at 0x7da1b0e2d0f0>
def fu... | keyword[def] identifier[smoothline] ( identifier[document] , identifier[coords] ):
literal[string]
identifier[element] = identifier[document] . identifier[createElement] ( literal[string] )
identifier[path] =[]
identifier[points] =[( identifier[coords] [ identifier[i] ], identifier[coords] [ identifier[i] +... | def smoothline(document, coords):
"""smoothed polyline"""
element = document.createElement('path')
path = []
points = [(coords[i], coords[i + 1]) for i in range(0, len(coords), 2)]
def pt(points):
(x0, y0) = points[0]
(x1, y1) = points[1]
p0 = (2 * x0 - x1, 2 * y0 - y1)
... |
def _from_binary_stdinfo(cls, binary_stream):
"""See base class."""
'''
TIMESTAMPS(32)
Creation time - 8
File altered time - 8
MFT/Metadata altered time - 8
Accessed time - 8
Flags - 4 (FileInfoFlags)
Maximum number of versions - 4
... | def function[_from_binary_stdinfo, parameter[cls, binary_stream]]:
constant[See base class.]
constant[
TIMESTAMPS(32)
Creation time - 8
File altered time - 8
MFT/Metadata altered time - 8
Accessed time - 8
Flags - 4 (FileInfoFlags)
... | keyword[def] identifier[_from_binary_stdinfo] ( identifier[cls] , identifier[binary_stream] ):
literal[string]
literal[string]
keyword[if] identifier[len] ( identifier[binary_stream] )== identifier[cls] . identifier[_REPR] . identifier[size] :
identifier[t_created] , identifier[t_changed] ... | def _from_binary_stdinfo(cls, binary_stream):
"""See base class."""
'\n TIMESTAMPS(32)\n Creation time - 8\n File altered time - 8\n MFT/Metadata altered time - 8\n Accessed time - 8\n Flags - 4 (FileInfoFlags)\n Maximum number of versions - 4\n ... |
def post(self, url, data):
"""Send a HTTP POST request to a URL and return the result.
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/json"
}
self.conn.request("POST", url, data, headers)
return self._process_r... | def function[post, parameter[self, url, data]]:
constant[Send a HTTP POST request to a URL and return the result.
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da204961450>, <ast.Constant object at 0x7da2049607f0>], [<ast.Constant object at 0x7da204962d40>, <ast.Constant o... | keyword[def] identifier[post] ( identifier[self] , identifier[url] , identifier[data] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] ,
literal[string] : literal[string]
}
identifier[self] . identifier[conn] . identifier[request] ( lit... | def post(self, url, data):
"""Send a HTTP POST request to a URL and return the result.
"""
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/json'}
self.conn.request('POST', url, data, headers)
return self._process_response() |
def execute(helper, config, args):
"""
Rebuilds an environment
"""
env_config = parse_env_config(config, args.environment)
helper.rebuild_environment(args.environment)
# wait
if not args.dont_wait:
helper.wait_for_environments(args.environment, health='Green', status='Ready') | def function[execute, parameter[helper, config, args]]:
constant[
Rebuilds an environment
]
variable[env_config] assign[=] call[name[parse_env_config], parameter[name[config], name[args].environment]]
call[name[helper].rebuild_environment, parameter[name[args].environment]]
if <a... | keyword[def] identifier[execute] ( identifier[helper] , identifier[config] , identifier[args] ):
literal[string]
identifier[env_config] = identifier[parse_env_config] ( identifier[config] , identifier[args] . identifier[environment] )
identifier[helper] . identifier[rebuild_environment] ( identifier[a... | def execute(helper, config, args):
"""
Rebuilds an environment
"""
env_config = parse_env_config(config, args.environment)
helper.rebuild_environment(args.environment)
# wait
if not args.dont_wait:
helper.wait_for_environments(args.environment, health='Green', status='Ready') # depe... |
def execute_callback(self, *args, **kwargs):
"""Executes a callback and returns the proper response.
Refer to :meth:`sijax.Sijax.execute_callback` for more details.
"""
response = self._sijax.execute_callback(*args, **kwargs)
return _make_response(response) | def function[execute_callback, parameter[self]]:
constant[Executes a callback and returns the proper response.
Refer to :meth:`sijax.Sijax.execute_callback` for more details.
]
variable[response] assign[=] call[name[self]._sijax.execute_callback, parameter[<ast.Starred object at 0x7da1b... | keyword[def] identifier[execute_callback] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[response] = identifier[self] . identifier[_sijax] . identifier[execute_callback] (* identifier[args] ,** identifier[kwargs] )
keyword[return] identifier[_m... | def execute_callback(self, *args, **kwargs):
"""Executes a callback and returns the proper response.
Refer to :meth:`sijax.Sijax.execute_callback` for more details.
"""
response = self._sijax.execute_callback(*args, **kwargs)
return _make_response(response) |
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs):
"""Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting
function ``fc_func``, optionally including the calculated seasonality.
This is an additive model, Y[t] = T[t] + S[t] + e[t]
Args:
... | def function[forecast, parameter[stl, fc_func, steps, seasonal]]:
constant[Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting
function ``fc_func``, optionally including the calculated seasonality.
This is an additive model, Y[t] = T[t] + S[t] + e[t]
Arg... | keyword[def] identifier[forecast] ( identifier[stl] , identifier[fc_func] , identifier[steps] = literal[int] , identifier[seasonal] = keyword[False] ,** identifier[fc_func_kwargs] ):
literal[string]
identifier[forecast_array] = identifier[np] . identifier[array] ([])
identifier[trend_a... | def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs):
"""Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting
function ``fc_func``, optionally including the calculated seasonality.
This is an additive model, Y[t] = T[t] + S[t] + e[t]
Args:
... |
def add_routes(fapp, routes, prefix=""):
"""Batch routes registering
Register routes to a blueprint/flask_app previously collected
with :func:`routes_collector`.
:param fapp: bluprint or flask_app to whom attach new routes.
:param routes: dict of routes collected by :func:`routes_collector`
:p... | def function[add_routes, parameter[fapp, routes, prefix]]:
constant[Batch routes registering
Register routes to a blueprint/flask_app previously collected
with :func:`routes_collector`.
:param fapp: bluprint or flask_app to whom attach new routes.
:param routes: dict of routes collected by :fu... | keyword[def] identifier[add_routes] ( identifier[fapp] , identifier[routes] , identifier[prefix] = literal[string] ):
literal[string]
keyword[for] identifier[r] keyword[in] identifier[routes] :
identifier[r] [ literal[string] ]= identifier[prefix] + identifier[r] [ literal[string] ]
id... | def add_routes(fapp, routes, prefix=''):
"""Batch routes registering
Register routes to a blueprint/flask_app previously collected
with :func:`routes_collector`.
:param fapp: bluprint or flask_app to whom attach new routes.
:param routes: dict of routes collected by :func:`routes_collector`
:p... |
def __setup(local_download_dir_warc, log_level):
"""
Setup
:return:
"""
if not os.path.exists(local_download_dir_warc):
os.makedirs(local_download_dir_warc)
# make loggers quite
configure_logging({"LOG_LEVEL": "ERROR"})
logging.getLogger('requests').setLevel(logging.CRITICAL)
... | def function[__setup, parameter[local_download_dir_warc, log_level]]:
constant[
Setup
:return:
]
if <ast.UnaryOp object at 0x7da18dc99e70> begin[:]
call[name[os].makedirs, parameter[name[local_download_dir_warc]]]
call[name[configure_logging], parameter[dictionary[[<a... | keyword[def] identifier[__setup] ( identifier[local_download_dir_warc] , identifier[log_level] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[local_download_dir_warc] ):
identifier[os] . identifier[makedirs] ( identifier[local_down... | def __setup(local_download_dir_warc, log_level):
"""
Setup
:return:
"""
if not os.path.exists(local_download_dir_warc):
os.makedirs(local_download_dir_warc) # depends on [control=['if'], data=[]]
# make loggers quite
configure_logging({'LOG_LEVEL': 'ERROR'})
logging.getLogger('r... |
def closeView(self, view=None):
"""
Closes the inputed view.
:param view | <int> || <XView> || None
"""
if type(view) == int:
view = self.widget(view)
elif view == None:
view = self.currentView()
index = self.indexOf(... | def function[closeView, parameter[self, view]]:
constant[
Closes the inputed view.
:param view | <int> || <XView> || None
]
if compare[call[name[type], parameter[name[view]]] equal[==] name[int]] begin[:]
variable[view] assign[=] call[name[self].widg... | keyword[def] identifier[closeView] ( identifier[self] , identifier[view] = keyword[None] ):
literal[string]
keyword[if] identifier[type] ( identifier[view] )== identifier[int] :
identifier[view] = identifier[self] . identifier[widget] ( identifier[view] )
keyword[elif] ident... | def closeView(self, view=None):
"""
Closes the inputed view.
:param view | <int> || <XView> || None
"""
if type(view) == int:
view = self.widget(view) # depends on [control=['if'], data=[]]
elif view == None:
view = self.currentView() # depends on [con... |
def add_nodes(self, nodes): # noqa: D302
r"""
Add nodes to tree.
:param nodes: Node(s) to add with associated data. If there are
several list items in the argument with the same node
name the resulting node data is a list with items
... | def function[add_nodes, parameter[self, nodes]]:
constant[
Add nodes to tree.
:param nodes: Node(s) to add with associated data. If there are
several list items in the argument with the same node
name the resulting node data is a list with items
... | keyword[def] identifier[add_nodes] ( identifier[self] , identifier[nodes] ):
literal[string]
identifier[self] . identifier[_validate_nodes_with_data] ( identifier[nodes] )
identifier[nodes] = identifier[nodes] keyword[if] identifier[isinstance] ( identifier[nodes] , identifier[list] ) ke... | def add_nodes(self, nodes): # noqa: D302
"\n Add nodes to tree.\n\n :param nodes: Node(s) to add with associated data. If there are\n several list items in the argument with the same node\n name the resulting node data is a list with items\n ... |
def _render(self, contexts, partials):
"""render inverted section"""
val = self._lookup(self.value, contexts)
if val:
return EMPTYSTRING
return self._render_children(contexts, partials) | def function[_render, parameter[self, contexts, partials]]:
constant[render inverted section]
variable[val] assign[=] call[name[self]._lookup, parameter[name[self].value, name[contexts]]]
if name[val] begin[:]
return[name[EMPTYSTRING]]
return[call[name[self]._render_children, paramet... | keyword[def] identifier[_render] ( identifier[self] , identifier[contexts] , identifier[partials] ):
literal[string]
identifier[val] = identifier[self] . identifier[_lookup] ( identifier[self] . identifier[value] , identifier[contexts] )
keyword[if] identifier[val] :
keyword[... | def _render(self, contexts, partials):
"""render inverted section"""
val = self._lookup(self.value, contexts)
if val:
return EMPTYSTRING # depends on [control=['if'], data=[]]
return self._render_children(contexts, partials) |
def set_nsxcontroller_ip(self, **kwargs):
"""
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
... | def function[set_nsxcontroller_ip, parameter[self]]:
constant[
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
R... | keyword[def] identifier[set_nsxcontroller_ip] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[name] = identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[ip_addr] = identifier[str] (( identifier[kwargs] . identifier[pop] ( literal[string] , keyword[N... | def set_nsxcontroller_ip(self, **kwargs):
"""
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
No... |
def remove_user_from_group(uid, gid):
""" Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.delete(acl_... | def function[remove_user_from_group, parameter[uid, gid]]:
constant[ Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
]
variable[acl_url] assign[=] call[name[urljoin], parameter[call[name[_acl_... | keyword[def] identifier[remove_user_from_group] ( identifier[uid] , identifier[gid] ):
literal[string]
identifier[acl_url] = identifier[urljoin] ( identifier[_acl_url] (), literal[string] . identifier[format] ( identifier[gid] , identifier[uid] ))
keyword[try] :
identifier[r] = identifier[htt... | def remove_user_from_group(uid, gid):
""" Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str
"""
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.delete(acl_... |
def restore_default_configuration():
"""
Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block
"""
def restore(target, default_valu... | def function[restore_default_configuration, parameter[]]:
constant[
Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block
]
... | keyword[def] identifier[restore_default_configuration] ():
literal[string]
keyword[def] identifier[restore] ( identifier[target] , identifier[default_value] ):
keyword[if] identifier[target] == identifier[default_value] :
keyword[return] identifier[default_value]
keywor... | def restore_default_configuration():
"""
Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block
"""
def restore(target, default_valu... |
def get_create_command(self):
"""Get the command to create the local repository."""
command = ['git', 'clone' if self.remote else 'init']
if self.bare:
command.append('--bare')
if self.remote:
command.append(self.remote)
command.append(self.local)
... | def function[get_create_command, parameter[self]]:
constant[Get the command to create the local repository.]
variable[command] assign[=] list[[<ast.Constant object at 0x7da1b0a36890>, <ast.IfExp object at 0x7da1b0a36980>]]
if name[self].bare begin[:]
call[name[command].append, pa... | keyword[def] identifier[get_create_command] ( identifier[self] ):
literal[string]
identifier[command] =[ literal[string] , literal[string] keyword[if] identifier[self] . identifier[remote] keyword[else] literal[string] ]
keyword[if] identifier[self] . identifier[bare] :
i... | def get_create_command(self):
"""Get the command to create the local repository."""
command = ['git', 'clone' if self.remote else 'init']
if self.bare:
command.append('--bare') # depends on [control=['if'], data=[]]
if self.remote:
command.append(self.remote) # depends on [control=['if... |
def find_exe(name, filepath=None):
"""Find an executable.
Args:
name: Name of the program, eg 'python'.
filepath: Path to executable, a search is performed if None.
Returns:
Path to the executable if found, otherwise an error is raised.
"""
if filepath:
if not os.pa... | def function[find_exe, parameter[name, filepath]]:
constant[Find an executable.
Args:
name: Name of the program, eg 'python'.
filepath: Path to executable, a search is performed if None.
Returns:
Path to the executable if found, otherwise an error is raised.
]
if na... | keyword[def] identifier[find_exe] ( identifier[name] , identifier[filepath] = keyword[None] ):
literal[string]
keyword[if] identifier[filepath] :
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[filepath] ):
identifier[open] ( identifier[... | def find_exe(name, filepath=None):
"""Find an executable.
Args:
name: Name of the program, eg 'python'.
filepath: Path to executable, a search is performed if None.
Returns:
Path to the executable if found, otherwise an error is raised.
"""
if filepath:
if not os.pa... |
def get_meta_graph_def(saved_model_dir, tag_set):
"""Utility function to read a meta_graph_def from disk.
From `saved_model_cli.py <https://github.com/tensorflow/tensorflow/blob/8e0e8d41a3a8f2d4a6100c2ea1dc9d6c6c4ad382/tensorflow/python/tools/saved_model_cli.py#L186>`_
Args:
:saved_model_dir: path to saved_... | def function[get_meta_graph_def, parameter[saved_model_dir, tag_set]]:
constant[Utility function to read a meta_graph_def from disk.
From `saved_model_cli.py <https://github.com/tensorflow/tensorflow/blob/8e0e8d41a3a8f2d4a6100c2ea1dc9d6c6c4ad382/tensorflow/python/tools/saved_model_cli.py#L186>`_
Args:
... | keyword[def] identifier[get_meta_graph_def] ( identifier[saved_model_dir] , identifier[tag_set] ):
literal[string]
identifier[saved_model] = identifier[reader] . identifier[read_saved_model] ( identifier[saved_model_dir] )
identifier[set_of_tags] = identifier[set] ( identifier[tag_set] . identifier[split] (... | def get_meta_graph_def(saved_model_dir, tag_set):
"""Utility function to read a meta_graph_def from disk.
From `saved_model_cli.py <https://github.com/tensorflow/tensorflow/blob/8e0e8d41a3a8f2d4a6100c2ea1dc9d6c6c4ad382/tensorflow/python/tools/saved_model_cli.py#L186>`_
Args:
:saved_model_dir: path to save... |
def _index_item(self, uri, num, batch_num):
""" queries the triplestore for an item sends it to elasticsearch """
data = RdfDataset(get_all_item_data(uri, self.namespace),
uri).base_class.es_json()
self.batch_data[batch_num].append(data)
self.count += 1 | def function[_index_item, parameter[self, uri, num, batch_num]]:
constant[ queries the triplestore for an item sends it to elasticsearch ]
variable[data] assign[=] call[call[name[RdfDataset], parameter[call[name[get_all_item_data], parameter[name[uri], name[self].namespace]], name[uri]]].base_class.es_j... | keyword[def] identifier[_index_item] ( identifier[self] , identifier[uri] , identifier[num] , identifier[batch_num] ):
literal[string]
identifier[data] = identifier[RdfDataset] ( identifier[get_all_item_data] ( identifier[uri] , identifier[self] . identifier[namespace] ),
identifier[uri] ... | def _index_item(self, uri, num, batch_num):
""" queries the triplestore for an item sends it to elasticsearch """
data = RdfDataset(get_all_item_data(uri, self.namespace), uri).base_class.es_json()
self.batch_data[batch_num].append(data)
self.count += 1 |
async def scalar(query, as_tuple=False):
"""Get single value from ``select()`` query, i.e. for aggregation.
:return: result is the same as after sync ``query.scalar()`` call
"""
cursor = await _execute_query_async(query)
try:
row = await cursor.fetchone()
finally:
await cursor.... | <ast.AsyncFunctionDef object at 0x7da20cabcdf0> | keyword[async] keyword[def] identifier[scalar] ( identifier[query] , identifier[as_tuple] = keyword[False] ):
literal[string]
identifier[cursor] = keyword[await] identifier[_execute_query_async] ( identifier[query] )
keyword[try] :
identifier[row] = keyword[await] identifier[cursor] . ide... | async def scalar(query, as_tuple=False):
"""Get single value from ``select()`` query, i.e. for aggregation.
:return: result is the same as after sync ``query.scalar()`` call
"""
cursor = await _execute_query_async(query)
try:
row = await cursor.fetchone() # depends on [control=['try'], dat... |
def post(self, endpoint, data):
"""
Executes the HTTP POST request
:param endpoint: string indicating the URL component to call
:param data: the data to submit
:return: the dumped JSON response content
"""
headers = {
"Content-Type": "application/json... | def function[post, parameter[self, endpoint, data]]:
constant[
Executes the HTTP POST request
:param endpoint: string indicating the URL component to call
:param data: the data to submit
:return: the dumped JSON response content
]
variable[headers] assign[=] dict... | keyword[def] identifier[post] ( identifier[self] , identifier[endpoint] , identifier[data] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] keyword[if] identifier[self] . ... | def post(self, endpoint, data):
"""
Executes the HTTP POST request
:param endpoint: string indicating the URL component to call
:param data: the data to submit
:return: the dumped JSON response content
"""
headers = {'Content-Type': 'application/json', 'Accept': 'applica... |
def bought_value(self):
"""
[已弃用]
"""
user_system_log.warn(_(u"[abandon] {} is no longer valid.").format('stock_position.bought_value'))
return self._quantity * self._avg_price | def function[bought_value, parameter[self]]:
constant[
[已弃用]
]
call[name[user_system_log].warn, parameter[call[call[name[_], parameter[constant[[abandon] {} is no longer valid.]]].format, parameter[constant[stock_position.bought_value]]]]]
return[binary_operation[name[self]._quantity... | keyword[def] identifier[bought_value] ( identifier[self] ):
literal[string]
identifier[user_system_log] . identifier[warn] ( identifier[_] ( literal[string] ). identifier[format] ( literal[string] ))
keyword[return] identifier[self] . identifier[_quantity] * identifier[self] . identifier[... | def bought_value(self):
"""
[已弃用]
"""
user_system_log.warn(_(u'[abandon] {} is no longer valid.').format('stock_position.bought_value'))
return self._quantity * self._avg_price |
def memoize(function):
"""A very simple memoize decorator to optimize pure-ish functions
Don't use this unless you've examined the code and see the
potential risks.
"""
cache = {}
@functools.wraps(function)
def _memoize(*args):
if args in cache:
return cache[args]
... | def function[memoize, parameter[function]]:
constant[A very simple memoize decorator to optimize pure-ish functions
Don't use this unless you've examined the code and see the
potential risks.
]
variable[cache] assign[=] dictionary[[], []]
def function[_memoize, parameter[]]:
... | keyword[def] identifier[memoize] ( identifier[function] ):
literal[string]
identifier[cache] ={}
@ identifier[functools] . identifier[wraps] ( identifier[function] )
keyword[def] identifier[_memoize] (* identifier[args] ):
keyword[if] identifier[args] keyword[in] identifier[cache] :
... | def memoize(function):
"""A very simple memoize decorator to optimize pure-ish functions
Don't use this unless you've examined the code and see the
potential risks.
"""
cache = {}
@functools.wraps(function)
def _memoize(*args):
if args in cache:
return cache[args] # de... |
def frames(self):
"""Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj... | def function[frames, parameter[self]]:
constant[Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
... | keyword[def] identifier[frames] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_running] :
keyword[raise] identifier[RuntimeError] ( literal[string] %( identifier[self] . identifier[_path_to_images] ))
keyword[if] identifier[s... | def frames(self):
"""Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tu... |
def dpcnn(embedding_matrix, embedding_size, trainable_embedding, maxlen, max_features,
filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation,
max_pooling, mean_pooling, weighted_average_attention, concat_mode,
dropout_embedding, conv_dropout, dense_... | def function[dpcnn, parameter[embedding_matrix, embedding_size, trainable_embedding, maxlen, max_features, filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation, max_pooling, mean_pooling, weighted_average_attention, concat_mode, dropout_embedding, conv_dropout, dense_dropout, d... | keyword[def] identifier[dpcnn] ( identifier[embedding_matrix] , identifier[embedding_size] , identifier[trainable_embedding] , identifier[maxlen] , identifier[max_features] ,
identifier[filter_nr] , identifier[kernel_size] , identifier[repeat_block] , identifier[dense_size] , identifier[repeat_dense] , identifier[ou... | def dpcnn(embedding_matrix, embedding_size, trainable_embedding, maxlen, max_features, filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation, max_pooling, mean_pooling, weighted_average_attention, concat_mode, dropout_embedding, conv_dropout, dense_dropout, dropout_mode, conv_ke... |
def _is_reference(arg):
'''
Return True, if arg is a reference to a previously defined statement.
'''
return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types) | def function[_is_reference, parameter[arg]]:
constant[
Return True, if arg is a reference to a previously defined statement.
]
return[<ast.BoolOp object at 0x7da1b1c36e30>] | keyword[def] identifier[_is_reference] ( identifier[arg] ):
literal[string]
keyword[return] identifier[isinstance] ( identifier[arg] , identifier[dict] ) keyword[and] identifier[len] ( identifier[arg] )== literal[int] keyword[and] identifier[isinstance] ( identifier[next] ( identifier[six] . identifier... | def _is_reference(arg):
"""
Return True, if arg is a reference to a previously defined statement.
"""
return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types) |
def gen_opt_str(ser_rec: pd.Series)->str:
'''generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
'''
name = ser_rec.name
indent = r' '
str_opt = f'.. option:: {name}'+'\n\n'
fo... | def function[gen_opt_str, parameter[ser_rec]]:
constant[generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
]
variable[name] assign[=] name[ser_rec].name
variable[indent] assig... | keyword[def] identifier[gen_opt_str] ( identifier[ser_rec] : identifier[pd] . identifier[Series] )-> identifier[str] :
literal[string]
identifier[name] = identifier[ser_rec] . identifier[name]
identifier[indent] = literal[string]
identifier[str_opt] = literal[string] + literal[string]
ke... | def gen_opt_str(ser_rec: pd.Series) -> str:
"""generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
"""
name = ser_rec.name
indent = ' '
str_opt = f'.. option:: {name}' + '\n\n'
... |
def open_for_io(self, writable, password):
"""Open the medium for I/O.
in writable of type bool
Set this to open the medium for both reading and writing. When
not set the medium is opened readonly.
in password of type str
Password for accessing an encrypted... | def function[open_for_io, parameter[self, writable, password]]:
constant[Open the medium for I/O.
in writable of type bool
Set this to open the medium for both reading and writing. When
not set the medium is opened readonly.
in password of type str
Password... | keyword[def] identifier[open_for_io] ( identifier[self] , identifier[writable] , identifier[password] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[writable] , identifier[bool] ):
keyword[raise] identifier[TypeError] ( literal[string] )
key... | def open_for_io(self, writable, password):
"""Open the medium for I/O.
in writable of type bool
Set this to open the medium for both reading and writing. When
not set the medium is opened readonly.
in password of type str
Password for accessing an encrypted med... |
def confirm_value(self, widget):
"""event called pressing on OK button.
propagates the string content of the input field
"""
self.hide()
params = (self.fileFolderNavigator.get_selection_list(),)
return params | def function[confirm_value, parameter[self, widget]]:
constant[event called pressing on OK button.
propagates the string content of the input field
]
call[name[self].hide, parameter[]]
variable[params] assign[=] tuple[[<ast.Call object at 0x7da20c993820>]]
return[name[para... | keyword[def] identifier[confirm_value] ( identifier[self] , identifier[widget] ):
literal[string]
identifier[self] . identifier[hide] ()
identifier[params] =( identifier[self] . identifier[fileFolderNavigator] . identifier[get_selection_list] (),)
keyword[return] identifier[param... | def confirm_value(self, widget):
"""event called pressing on OK button.
propagates the string content of the input field
"""
self.hide()
params = (self.fileFolderNavigator.get_selection_list(),)
return params |
def StartingAgeEnum(ctx):
"""Starting Age Enumeration."""
return Enum(
ctx,
what=-2,
unset=-1,
dark=0,
feudal=1,
castle=2,
imperial=3,
postimperial=4,
dmpostimperial=6
) | def function[StartingAgeEnum, parameter[ctx]]:
constant[Starting Age Enumeration.]
return[call[name[Enum], parameter[name[ctx]]]] | keyword[def] identifier[StartingAgeEnum] ( identifier[ctx] ):
literal[string]
keyword[return] identifier[Enum] (
identifier[ctx] ,
identifier[what] =- literal[int] ,
identifier[unset] =- literal[int] ,
identifier[dark] = literal[int] ,
identifier[feudal] = literal[int] ,
iden... | def StartingAgeEnum(ctx):
"""Starting Age Enumeration."""
return Enum(ctx, what=-2, unset=-1, dark=0, feudal=1, castle=2, imperial=3, postimperial=4, dmpostimperial=6) |
def render_string(self, template_name, **kwargs):
"""This method was rewritten to support multiple template engine
(Determine by `TEMPLATE_ENGINE` setting, could be `tornado` and `jinja2`),
it will only affect on template rendering process, ui modules feature,
which is mostly exposed in ... | def function[render_string, parameter[self, template_name]]:
constant[This method was rewritten to support multiple template engine
(Determine by `TEMPLATE_ENGINE` setting, could be `tornado` and `jinja2`),
it will only affect on template rendering process, ui modules feature,
which is m... | keyword[def] identifier[render_string] ( identifier[self] , identifier[template_name] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] == identifier[settings] [ literal[string] ]:
keyword[return] identifier[super] ( identifier[BaseHandler] , identifier[self] ). i... | def render_string(self, template_name, **kwargs):
"""This method was rewritten to support multiple template engine
(Determine by `TEMPLATE_ENGINE` setting, could be `tornado` and `jinja2`),
it will only affect on template rendering process, ui modules feature,
which is mostly exposed in `ren... |
def check(self, query):
"""
:param query:
"""
if query.get_type() != Keyword.DELETE:
return Ok(True)
return Err("Delete queries are forbidden.") | def function[check, parameter[self, query]]:
constant[
:param query:
]
if compare[call[name[query].get_type, parameter[]] not_equal[!=] name[Keyword].DELETE] begin[:]
return[call[name[Ok], parameter[constant[True]]]]
return[call[name[Err], parameter[constant[Delete queries ar... | keyword[def] identifier[check] ( identifier[self] , identifier[query] ):
literal[string]
keyword[if] identifier[query] . identifier[get_type] ()!= identifier[Keyword] . identifier[DELETE] :
keyword[return] identifier[Ok] ( keyword[True] )
keyword[return] identifier[Err] ( ... | def check(self, query):
"""
:param query:
"""
if query.get_type() != Keyword.DELETE:
return Ok(True) # depends on [control=['if'], data=[]]
return Err('Delete queries are forbidden.') |
def add_step(self, value_map):
""" Add the values in value_map to the end of the trace. """
if len(self.trace) == 0:
raise PyrtlError('error, simulation trace needs at least 1 signal to track '
'(by default, unnamed signals are not traced -- try either passing '
... | def function[add_step, parameter[self, value_map]]:
constant[ Add the values in value_map to the end of the trace. ]
if compare[call[name[len], parameter[name[self].trace]] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da20c796260>
for taget[name[wire]] in starred[name[self].tr... | keyword[def] identifier[add_step] ( identifier[self] , identifier[value_map] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[trace] )== literal[int] :
keyword[raise] identifier[PyrtlError] ( literal[string]
literal[string]
li... | def add_step(self, value_map):
""" Add the values in value_map to the end of the trace. """
if len(self.trace) == 0:
raise PyrtlError('error, simulation trace needs at least 1 signal to track (by default, unnamed signals are not traced -- try either passing a name to a WireVector or setting a "wirevecto... |
def get_catalogs(self):
"""Pass through to provider CatalogLookupSession.get_catalogs"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs()
cat_list = []
... | def function[get_catalogs, parameter[self]]:
constant[Pass through to provider CatalogLookupSession.get_catalogs]
variable[catalogs] assign[=] call[call[name[self]._get_provider_session, parameter[constant[catalog_lookup_session]]].get_catalogs, parameter[]]
variable[cat_list] assign[=] list[[]]... | keyword[def] identifier[get_catalogs] ( identifier[self] ):
literal[string]
identifier[catalogs] = identifier[self] . identifier[_get_provider_session] ( literal[string] ). identifier[get_catalogs] ()
identifier[cat_list] =[]
keyword[for] identifier[cat] keywor... | def get_catalogs(self):
"""Pass through to provider CatalogLookupSession.get_catalogs"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs()
cat_list = []
for cat in catalogs:
... |
def registerViewType(self, cls, window=None):
"""
Registers the inputed widget class as a potential view class. If the \
optional window argument is supplied, then the registerToWindow method \
will be called for the class.
:param cls | <subclass of XView>
... | def function[registerViewType, parameter[self, cls, window]]:
constant[
Registers the inputed widget class as a potential view class. If the optional window argument is supplied, then the registerToWindow method will be called for the class.
:param cls | <s... | keyword[def] identifier[registerViewType] ( identifier[self] , identifier[cls] , identifier[window] = keyword[None] ):
literal[string]
keyword[if] ( keyword[not] identifier[cls] keyword[in] identifier[self] . identifier[_viewTypes] ):
identifier[self] . identifier[_viewTypes] . iden... | def registerViewType(self, cls, window=None):
"""
Registers the inputed widget class as a potential view class. If the optional window argument is supplied, then the registerToWindow method will be called for the class.
:param cls | <subclass of XView>
... |
def exec_all_endpoints(self, *args, **kwargs):
"""Execute each passed endpoint and collect the results. If a result
is anoter `MultipleResults` it will extend the results with those
contained therein. If the result is `NoResult`, skip the addition."""
results = []
for handler in ... | def function[exec_all_endpoints, parameter[self]]:
constant[Execute each passed endpoint and collect the results. If a result
is anoter `MultipleResults` it will extend the results with those
contained therein. If the result is `NoResult`, skip the addition.]
variable[results] assign[=] ... | keyword[def] identifier[exec_all_endpoints] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[handler] keyword[in] identifier[self] . identifier[endpoints] :
keyword[if] identifier[isinstance] (... | def exec_all_endpoints(self, *args, **kwargs):
"""Execute each passed endpoint and collect the results. If a result
is anoter `MultipleResults` it will extend the results with those
contained therein. If the result is `NoResult`, skip the addition."""
results = []
for handler in self.endpoin... |
def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__inv... | def function[_collapse_invariants, parameter[bases, namespace]]:
constant[Collect invariants from the bases and merge them with the invariants in the namespace.]
variable[invariants] assign[=] list[[]]
for taget[name[base]] in starred[name[bases]] begin[:]
if call[name[hasattr], ... | keyword[def] identifier[_collapse_invariants] ( identifier[bases] : identifier[List] [ identifier[type] ], identifier[namespace] : identifier[MutableMapping] [ identifier[str] , identifier[Any] ])-> keyword[None] :
literal[string]
identifier[invariants] =[]
keyword[for] identifier[base] keywor... | def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, '__inva... |
def astype(self, dtype):
"""Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a strin... | def function[astype, parameter[self, dtype]]:
constant[Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as ... | keyword[def] identifier[astype] ( identifier[self] , identifier[dtype] ):
literal[string]
keyword[if] identifier[dtype] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[dtype] = identifier[np] . identifier[dtype] ( ... | def astype(self, dtype):
"""Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a string. D... |
def integer(_object):
"""
Validates a given input is of type int..
Example usage::
data = {'a' : 21}
schema = ('a', integer)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argu... | def function[integer, parameter[_object]]:
constant[
Validates a given input is of type int..
Example usage::
data = {'a' : 21}
schema = ('a', integer)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
... | keyword[def] identifier[integer] ( identifier[_object] ):
literal[string]
keyword[if] identifier[is_callable] ( identifier[_object] ):
identifier[_validator] = identifier[_object]
@ identifier[wraps] ( identifier[_validator] )
keyword[def] identifier[decorated] ( identifier[va... | def integer(_object):
"""
Validates a given input is of type int..
Example usage::
data = {'a' : 21}
schema = ('a', integer)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argu... |
def put_name(self, type_, id_, name):
"""
Write a cached name to disk.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: None
"""
cachefile = self.filename(type_, id_)
dirname = os.path.dirname(cachefile)
try:
os... | def function[put_name, parameter[self, type_, id_, name]]:
constant[
Write a cached name to disk.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: None
]
variable[cachefile] assign[=] call[name[self].filename, parameter[name[type_], name[i... | keyword[def] identifier[put_name] ( identifier[self] , identifier[type_] , identifier[id_] , identifier[name] ):
literal[string]
identifier[cachefile] = identifier[self] . identifier[filename] ( identifier[type_] , identifier[id_] )
identifier[dirname] = identifier[os] . identifier[path] .... | def put_name(self, type_, id_, name):
"""
Write a cached name to disk.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: None
"""
cachefile = self.filename(type_, id_)
dirname = os.path.dirname(cachefile)
try:
os.makedirs(dirname) ... |
def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):
"""Plot a grid of points over the array of data on the figure.
Parameters
-----------.
grid_arcsec : ndarray or data.array.grids.RegularGrid
A grid of (y,x) coordinates in arc-seconds which may be plott... | def function[plot_grid, parameter[grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec]]:
constant[Plot a grid of points over the array of data on the figure.
Parameters
-----------.
grid_arcsec : ndarray or data.array.grids.RegularGrid
A grid of (y,x) coordinates in... | keyword[def] identifier[plot_grid] ( identifier[grid_arcsec] , identifier[array] , identifier[units] , identifier[kpc_per_arcsec] , identifier[pointsize] , identifier[zoom_offset_arcsec] ):
literal[string]
keyword[if] identifier[grid_arcsec] keyword[is] keyword[not] keyword[None] :
keyword[if... | def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):
"""Plot a grid of points over the array of data on the figure.
Parameters
-----------.
grid_arcsec : ndarray or data.array.grids.RegularGrid
A grid of (y,x) coordinates in arc-seconds which may be plott... |
def convert_data_to_dtype(data, data_type, mot_float_type='float'):
"""Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the dat... | def function[convert_data_to_dtype, parameter[data, data_type, mot_float_type]]:
constant[Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_fl... | keyword[def] identifier[convert_data_to_dtype] ( identifier[data] , identifier[data_type] , identifier[mot_float_type] = literal[string] ):
literal[string]
identifier[scalar_dtype] = identifier[ctype_to_dtype] ( identifier[data_type] , identifier[mot_float_type] )
keyword[if] identifier[isinstance] ... | def convert_data_to_dtype(data, data_type, mot_float_type='float'):
"""Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the dat... |
def bytes2NativeString(x, encoding='utf-8'):
"""
Convert C{bytes} to a native C{str}.
On Python 3 and higher, str and bytes
are not equivalent. In this case, decode
the bytes, and return a native string.
On Python 2 and lower, str and bytes
are equivalent. In this case, just
just ret... | def function[bytes2NativeString, parameter[x, encoding]]:
constant[
Convert C{bytes} to a native C{str}.
On Python 3 and higher, str and bytes
are not equivalent. In this case, decode
the bytes, and return a native string.
On Python 2 and lower, str and bytes
are equivalent. In this ... | keyword[def] identifier[bytes2NativeString] ( identifier[x] , identifier[encoding] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[x] , identifier[bytes] ) keyword[and] identifier[str] != identifier[bytes] :
keyword[return] identifier[x] . identifier[decode]... | def bytes2NativeString(x, encoding='utf-8'):
"""
Convert C{bytes} to a native C{str}.
On Python 3 and higher, str and bytes
are not equivalent. In this case, decode
the bytes, and return a native string.
On Python 2 and lower, str and bytes
are equivalent. In this case, just
just ret... |
def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
"""Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x
"""
return PrintOperation(x, data, message, **kwa... | def function[Print, parameter[x, data, message]]:
constant[Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x
]
return[call[call[name[PrintOperation], parameter[name[... | keyword[def] identifier[Print] ( identifier[x] , identifier[data] , identifier[message] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[PrintOperation] ( identifier[x] , identifier[data] , identifier[message] ,** identifier[kwargs] ). identifier[outputs] [ literal[int] ] | def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
'Call tf.Print.\n\n Args:\n x: a Tensor.\n data: a list of Tensor\n message: a string\n **kwargs: keyword arguments to tf.Print\n Returns:\n a Tensor which is identical in value to x\n '
return PrintOperation(x, data, messa... |
def get_activities(self, before=None, after=None, limit=None):
"""
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date... | def function[get_activities, parameter[self, before, after, limit]]:
constant[
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before sp... | keyword[def] identifier[get_activities] ( identifier[self] , identifier[before] = keyword[None] , identifier[after] = keyword[None] , identifier[limit] = keyword[None] ):
literal[string]
keyword[if] identifier[before] :
identifier[before] = identifier[self] . identifier[_utc_datetime... | def get_activities(self, before=None, after=None, limit=None):
"""
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date. (U... |
def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip):
"""This function will take in a port spec as specified by the port_spec compiler and
will output an nginx web proxy config string. This string can then be written to a file
and used running nginx """
nginx_http_config, nginx_stream_conf... | def function[get_nginx_configuration_spec, parameter[port_spec_dict, docker_bridge_ip]]:
constant[This function will take in a port spec as specified by the port_spec compiler and
will output an nginx web proxy config string. This string can then be written to a file
and used running nginx ]
<as... | keyword[def] identifier[get_nginx_configuration_spec] ( identifier[port_spec_dict] , identifier[docker_bridge_ip] ):
literal[string]
identifier[nginx_http_config] , identifier[nginx_stream_config] = literal[string] , literal[string]
keyword[for] identifier[port_spec] keyword[in] identifier[port_sp... | def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip):
"""This function will take in a port spec as specified by the port_spec compiler and
will output an nginx web proxy config string. This string can then be written to a file
and used running nginx """
(nginx_http_config, nginx_stream_con... |
async def get_connections(self, data=True):
"""Return connections for all the agents in the slave environments.
This is a managing function for
:meth:`~creamas.mp.MultiEnvironment.get_connections`.
"""
return await self.menv.get_connections(data=data, as_coro=True) | <ast.AsyncFunctionDef object at 0x7da2044c1150> | keyword[async] keyword[def] identifier[get_connections] ( identifier[self] , identifier[data] = keyword[True] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[menv] . identifier[get_connections] ( identifier[data] = identifier[data] , identifier[as_coro] = keyword[... | async def get_connections(self, data=True):
"""Return connections for all the agents in the slave environments.
This is a managing function for
:meth:`~creamas.mp.MultiEnvironment.get_connections`.
"""
return await self.menv.get_connections(data=data, as_coro=True) |
def search_id(id, medium, credentials):
"""Grabs the [medium] with the given id from MyAnimeList as a [medium]
object.
:param id The id of the [medium].
:param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA).
:return The [medium] object with id requested, or None if no such [m... | def function[search_id, parameter[id, medium, credentials]]:
constant[Grabs the [medium] with the given id from MyAnimeList as a [medium]
object.
:param id The id of the [medium].
:param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA).
:return The [medium] object with id r... | keyword[def] identifier[search_id] ( identifier[id] , identifier[medium] , identifier[credentials] ):
literal[string]
identifier[helpers] . identifier[check_creds] ( identifier[credentials] , identifier[header] )
keyword[if] identifier[id] <= literal[int] keyword[or] keyword[not] identifier[float]... | def search_id(id, medium, credentials):
"""Grabs the [medium] with the given id from MyAnimeList as a [medium]
object.
:param id The id of the [medium].
:param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA).
:return The [medium] object with id requested, or None if no such [m... |
def cli(env, volume_id, capacity, tier, upgrade):
"""Order snapshot space for a file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier)
try:
order = file_manager.order_snapshot_space(
volume_id,
cap... | def function[cli, parameter[env, volume_id, capacity, tier, upgrade]]:
constant[Order snapshot space for a file storage volume.]
variable[file_manager] assign[=] call[name[SoftLayer].FileStorageManager, parameter[name[env].client]]
if compare[name[tier] is_not constant[None]] begin[:]
... | keyword[def] identifier[cli] ( identifier[env] , identifier[volume_id] , identifier[capacity] , identifier[tier] , identifier[upgrade] ):
literal[string]
identifier[file_manager] = identifier[SoftLayer] . identifier[FileStorageManager] ( identifier[env] . identifier[client] )
keyword[if] identifier[... | def cli(env, volume_id, capacity, tier, upgrade):
"""Order snapshot space for a file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier) # depends on [control=['if'], data=['tier']]
try:
order = file_manager.order_snapshot_s... |
def run(self, positionals=None):
'''run the entire helper procedure, including:
- start: initialize the helper, collection preferences
- record: record any relevant features for the environment / session
- interact: interact with the user for additional informatoin
... | def function[run, parameter[self, positionals]]:
constant[run the entire helper procedure, including:
- start: initialize the helper, collection preferences
- record: record any relevant features for the environment / session
- interact: interact with the user for additio... | keyword[def] identifier[run] ( identifier[self] , identifier[positionals] = keyword[None] ):
literal[string]
identifier[self] . identifier[run_id] = identifier[RobotNamer] (). identifier[generate] ()
identifier[steps] = identifier[self] . identifier[config] . identifier[... | def run(self, positionals=None):
"""run the entire helper procedure, including:
- start: initialize the helper, collection preferences
- record: record any relevant features for the environment / session
- interact: interact with the user for additional informatoin
... |
def get_measurements(region, core_info, data, extra_offset=0):
"""
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Return... | def function[get_measurements, parameter[region, core_info, data, extra_offset]]:
constant[
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (... | keyword[def] identifier[get_measurements] ( identifier[region] , identifier[core_info] , identifier[data] , identifier[extra_offset] = literal[int] ):
literal[string]
identifier[measurements] =[]
identifier[clean_core_info] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[core_in... | def get_measurements(region, core_info, data, extra_offset=0):
"""
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Return... |
def lonlat2xyz(lon, lat):
"""
Convert lon / lat (radians) for the spherical triangulation into x,y,z
on the unit sphere
"""
lons = np.array(lon)
lats = np.array(lat)
xs = np.cos(lats) * np.cos(lons)
ys = np.cos(lats) * np.sin(lons)
zs = np.sin(lats)
return xs, ys, zs | def function[lonlat2xyz, parameter[lon, lat]]:
constant[
Convert lon / lat (radians) for the spherical triangulation into x,y,z
on the unit sphere
]
variable[lons] assign[=] call[name[np].array, parameter[name[lon]]]
variable[lats] assign[=] call[name[np].array, parameter[name[lat]]]... | keyword[def] identifier[lonlat2xyz] ( identifier[lon] , identifier[lat] ):
literal[string]
identifier[lons] = identifier[np] . identifier[array] ( identifier[lon] )
identifier[lats] = identifier[np] . identifier[array] ( identifier[lat] )
identifier[xs] = identifier[np] . identifier[cos] ( iden... | def lonlat2xyz(lon, lat):
"""
Convert lon / lat (radians) for the spherical triangulation into x,y,z
on the unit sphere
"""
lons = np.array(lon)
lats = np.array(lat)
xs = np.cos(lats) * np.cos(lons)
ys = np.cos(lats) * np.sin(lons)
zs = np.sin(lats)
return (xs, ys, zs) |
def TableArgsMeta(table_args):
'''Declarative metaclass automatically adding (merging) __table_args__ to
mapped classes. Example:
Meta = TableArgsMeta({
'mysql_engine': 'InnoDB',
'mysql_default charset': 'utf8',
}
Base = declarative_base(name='Base', metaclass=M... | def function[TableArgsMeta, parameter[table_args]]:
constant[Declarative metaclass automatically adding (merging) __table_args__ to
mapped classes. Example:
Meta = TableArgsMeta({
'mysql_engine': 'InnoDB',
'mysql_default charset': 'utf8',
}
Base = declarativ... | keyword[def] identifier[TableArgsMeta] ( identifier[table_args] ):
literal[string]
keyword[class] identifier[_TableArgsMeta] ( identifier[declarative] . identifier[DeclarativeMeta] ):
keyword[def] identifier[__init__] ( identifier[cls] , identifier[name] , identifier[bases] , identifier[dict_]... | def TableArgsMeta(table_args):
"""Declarative metaclass automatically adding (merging) __table_args__ to
mapped classes. Example:
Meta = TableArgsMeta({
'mysql_engine': 'InnoDB',
'mysql_default charset': 'utf8',
}
Base = declarative_base(name='Base', metaclass=M... |
def create(message: str, pubkey: Optional[str] = None, signing_keys: Optional[List[SigningKey]] = None,
message_comment: Optional[str] = None, signatures_comment: Optional[str] = None) -> str:
"""
Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-... | def function[create, parameter[message, pubkey, signing_keys, message_comment, signatures_comment]]:
constant[
Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-8 message
:param pubkey: Public key of recipient for encryption
:param signing_keys: ... | keyword[def] identifier[create] ( identifier[message] : identifier[str] , identifier[pubkey] : identifier[Optional] [ identifier[str] ]= keyword[None] , identifier[signing_keys] : identifier[Optional] [ identifier[List] [ identifier[SigningKey] ]]= keyword[None] ,
identifier[message_comment] : identifier[Optional] [... | def create(message: str, pubkey: Optional[str]=None, signing_keys: Optional[List[SigningKey]]=None, message_comment: Optional[str]=None, signatures_comment: Optional[str]=None) -> str:
"""
Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-8 message
:param pu... |
def Nu_Swenson(Re, Pr, rho_w=None, rho_b=None):
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_w = 0.00459 Re_w^{0.923} Pr_w^{0.613}
\left(\frac{\rho_w}{\rho_b}\right)^{0.2... | def function[Nu_Swenson, parameter[Re, Pr, rho_w, rho_b]]:
constant[Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_w = 0.00459 Re_w^{0.923} Pr_w^{0.613}
\left(\frac{\rho_w}... | keyword[def] identifier[Nu_Swenson] ( identifier[Re] , identifier[Pr] , identifier[rho_w] = keyword[None] , identifier[rho_b] = keyword[None] ):
literal[string]
identifier[Nu] = literal[int] * identifier[Re] ** literal[int] * identifier[Pr] ** literal[int]
keyword[if] identifier[rho_w] keyword[and]... | def Nu_Swenson(Re, Pr, rho_w=None, rho_b=None):
"""Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_w = 0.00459 Re_w^{0.923} Pr_w^{0.613}
\\left(\\frac{\\rho_w}{\\rho_b}\\right)^... |
def resolve_image(input, resolvers=None, fmt='png', width=300, height=300, frame=False, crop=None, bgcolor=None,
atomcolor=None, hcolor=None, bondcolor=None, framecolor=None, symbolfontsize=11, linewidth=2,
hsymbol='special', csymbol='special', stereolabels=False, stereowedges=True, ... | def function[resolve_image, parameter[input, resolvers, fmt, width, height, frame, crop, bgcolor, atomcolor, hcolor, bondcolor, framecolor, symbolfontsize, linewidth, hsymbol, csymbol, stereolabels, stereowedges, header, footer]]:
constant[Resolve input to a 2D image depiction.
:param string input: Chemica... | keyword[def] identifier[resolve_image] ( identifier[input] , identifier[resolvers] = keyword[None] , identifier[fmt] = literal[string] , identifier[width] = literal[int] , identifier[height] = literal[int] , identifier[frame] = keyword[False] , identifier[crop] = keyword[None] , identifier[bgcolor] = keyword[None] ,
... | def resolve_image(input, resolvers=None, fmt='png', width=300, height=300, frame=False, crop=None, bgcolor=None, atomcolor=None, hcolor=None, bondcolor=None, framecolor=None, symbolfontsize=11, linewidth=2, hsymbol='special', csymbol='special', stereolabels=False, stereowedges=True, header=None, footer=None, **kwargs):... |
def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored ... | def function[get_travis_branch, parameter[]]:
constant[Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the na... | keyword[def] identifier[get_travis_branch] ():
literal[string]
keyword[try] :
identifier[travis_pull_request] = identifier[get_travis_env_or_fail] ( literal[string] )
keyword[if] identifier[truthy] ( identifier[travis_pull_request] ):
identifier[travis_pull_request_branch] =... | def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored ... |
def create_ssl_context():
"""Create and return SSL Context."""
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context | def function[create_ssl_context, parameter[]]:
constant[Create and return SSL Context.]
variable[ssl_context] assign[=] call[name[ssl].create_default_context, parameter[name[ssl].Purpose.SERVER_AUTH]]
name[ssl_context].check_hostname assign[=] constant[False]
name[ssl_context].verify_mod... | keyword[def] identifier[create_ssl_context] ():
literal[string]
identifier[ssl_context] = identifier[ssl] . identifier[create_default_context] ( identifier[ssl] . identifier[Purpose] . identifier[SERVER_AUTH] )
identifier[ssl_context] . identifier[check_hostname] = keyword[False]
... | def create_ssl_context():
"""Create and return SSL Context."""
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context |
def init_cursor(self):
"""Position the cursor appropriately.
The cursor is set to either the beginning of the oplog, or
wherever it was last left off.
Returns the cursor and True if the cursor is empty.
"""
timestamp = self.read_last_checkpoint()
if timestamp i... | def function[init_cursor, parameter[self]]:
constant[Position the cursor appropriately.
The cursor is set to either the beginning of the oplog, or
wherever it was last left off.
Returns the cursor and True if the cursor is empty.
]
variable[timestamp] assign[=] call[nam... | keyword[def] identifier[init_cursor] ( identifier[self] ):
literal[string]
identifier[timestamp] = identifier[self] . identifier[read_last_checkpoint] ()
keyword[if] identifier[timestamp] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[only_dump] :
ke... | def init_cursor(self):
"""Position the cursor appropriately.
The cursor is set to either the beginning of the oplog, or
wherever it was last left off.
Returns the cursor and True if the cursor is empty.
"""
timestamp = self.read_last_checkpoint()
if timestamp is None or sel... |
def Build_ConfigPanel(self):
"""config panel for left-hand-side of frame: RGB Maps"""
panel = self.config_panel
sizer = wx.BoxSizer(wx.VERTICAL)
lsty = wx.ALIGN_LEFT|wx.LEFT|wx.TOP|wx.EXPAND
if self.config_mode == 'rgb':
for icol, col in enumerate(RGB_COLORS):
... | def function[Build_ConfigPanel, parameter[self]]:
constant[config panel for left-hand-side of frame: RGB Maps]
variable[panel] assign[=] name[self].config_panel
variable[sizer] assign[=] call[name[wx].BoxSizer, parameter[name[wx].VERTICAL]]
variable[lsty] assign[=] binary_operation[binar... | keyword[def] identifier[Build_ConfigPanel] ( identifier[self] ):
literal[string]
identifier[panel] = identifier[self] . identifier[config_panel]
identifier[sizer] = identifier[wx] . identifier[BoxSizer] ( identifier[wx] . identifier[VERTICAL] )
identifier[lsty] = identifier[wx] ... | def Build_ConfigPanel(self):
"""config panel for left-hand-side of frame: RGB Maps"""
panel = self.config_panel
sizer = wx.BoxSizer(wx.VERTICAL)
lsty = wx.ALIGN_LEFT | wx.LEFT | wx.TOP | wx.EXPAND
if self.config_mode == 'rgb':
for (icol, col) in enumerate(RGB_COLORS):
self.cmap_p... |
def gen_bash_vars(job_input_file, job_homedir=None, check_name_collision=True):
"""
:param job_input_file: path to a JSON file describing the job inputs
:param job_homedir: path to home directory, used for testing purposes
:param check_name_collision: should we check for name collisions?
:return: li... | def function[gen_bash_vars, parameter[job_input_file, job_homedir, check_name_collision]]:
constant[
:param job_input_file: path to a JSON file describing the job inputs
:param job_homedir: path to home directory, used for testing purposes
:param check_name_collision: should we check for name collis... | keyword[def] identifier[gen_bash_vars] ( identifier[job_input_file] , identifier[job_homedir] = keyword[None] , identifier[check_name_collision] = keyword[True] ):
literal[string]
identifier[file_key_descs] , identifier[rest_hash] = identifier[analyze_bash_vars] ( identifier[job_input_file] , identifier[jo... | def gen_bash_vars(job_input_file, job_homedir=None, check_name_collision=True):
"""
:param job_input_file: path to a JSON file describing the job inputs
:param job_homedir: path to home directory, used for testing purposes
:param check_name_collision: should we check for name collisions?
:return: li... |
def _download_file(url, local_filename):
'''
Utility function that downloads a chunked response from the specified url to a local path.
This method is suitable for larger downloads.
'''
response = requests.get(url, stream=True)
with open(local_filename, 'wb') as outfile:
for chunk in res... | def function[_download_file, parameter[url, local_filename]]:
constant[
Utility function that downloads a chunked response from the specified url to a local path.
This method is suitable for larger downloads.
]
variable[response] assign[=] call[name[requests].get, parameter[name[url]]]
... | keyword[def] identifier[_download_file] ( identifier[url] , identifier[local_filename] ):
literal[string]
identifier[response] = identifier[requests] . identifier[get] ( identifier[url] , identifier[stream] = keyword[True] )
keyword[with] identifier[open] ( identifier[local_filename] , literal[string... | def _download_file(url, local_filename):
"""
Utility function that downloads a chunked response from the specified url to a local path.
This method is suitable for larger downloads.
"""
response = requests.get(url, stream=True)
with open(local_filename, 'wb') as outfile:
for chunk in res... |
def rename(self, new_name):
"""
Rename the container.
On success, returns the new Container object.
On failure, returns False.
"""
if _lxc.Container.rename(self, new_name):
return Container(new_name)
return False | def function[rename, parameter[self, new_name]]:
constant[
Rename the container.
On success, returns the new Container object.
On failure, returns False.
]
if call[name[_lxc].Container.rename, parameter[name[self], name[new_name]]] begin[:]
return[call... | keyword[def] identifier[rename] ( identifier[self] , identifier[new_name] ):
literal[string]
keyword[if] identifier[_lxc] . identifier[Container] . identifier[rename] ( identifier[self] , identifier[new_name] ):
keyword[return] identifier[Container] ( identifier[new_name] )
... | def rename(self, new_name):
"""
Rename the container.
On success, returns the new Container object.
On failure, returns False.
"""
if _lxc.Container.rename(self, new_name):
return Container(new_name) # depends on [control=['if'], data=[]]
return False |
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
... | def function[_recv_robust, parameter[self, sock, size]]:
constant[
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
]
while constant[True] begin[:]
<ast.Try object at 0x7da1b22e9240> | keyword[def] identifier[_recv_robust] ( identifier[self] , identifier[sock] , identifier[size] ):
literal[string]
keyword[while] keyword[True] :
keyword[try] :
keyword[return] identifier[sock] . identifier[recv] ( identifier[size] )
keyword[except] iden... | def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size) # depends on [control=['try'], data=[]]
except socket.e... |
def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough):
"""Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows.
"""
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range(... | def function[headloss_fric, parameter[FlowRate, Diam, Length, Nu, PipeRough]]:
constant[Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows.
]
call[name[ut].check_range, parameter[list[[<ast.Name object at 0x7da1b06ce0b0>, <ast.Con... | keyword[def] identifier[headloss_fric] ( identifier[FlowRate] , identifier[Diam] , identifier[Length] , identifier[Nu] , identifier[PipeRough] ):
literal[string]
identifier[ut] . identifier[check_range] ([ identifier[Length] , literal[string] , literal[string] ])
keyword[return] ( identifier... | def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough):
"""Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows.
"""
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range(... |
async def find(self, seq_set: SequenceSet, selected: SelectedMailbox,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> AsyncIterable[Tuple[int, MessageT]]:
"""Find the active message UID and message pairs in the mailbox that
are contained in the given sequen... | <ast.AsyncFunctionDef object at 0x7da18f58c7f0> | keyword[async] keyword[def] identifier[find] ( identifier[self] , identifier[seq_set] : identifier[SequenceSet] , identifier[selected] : identifier[SelectedMailbox] ,
identifier[requirement] : identifier[FetchRequirement] = identifier[FetchRequirement] . identifier[METADATA] )-> identifier[AsyncIterable] [ identifi... | async def find(self, seq_set: SequenceSet, selected: SelectedMailbox, requirement: FetchRequirement=FetchRequirement.METADATA) -> AsyncIterable[Tuple[int, MessageT]]:
"""Find the active message UID and message pairs in the mailbox that
are contained in the given sequences set. Message sequence numbers
... |
def importer(name, extensions=None, sniff=None):
'''
@importer(name) is a decorator that declares that the following function is an file loading
function that should be registered with the neuropythy load function. See also the
forget_importer function.
Any importer function must take, as its f... | def function[importer, parameter[name, extensions, sniff]]:
constant[
@importer(name) is a decorator that declares that the following function is an file loading
function that should be registered with the neuropythy load function. See also the
forget_importer function.
Any importer functio... | keyword[def] identifier[importer] ( identifier[name] , identifier[extensions] = keyword[None] , identifier[sniff] = keyword[None] ):
literal[string]
identifier[name] = identifier[name] . identifier[lower] ()
keyword[if] identifier[name] keyword[in] identifier[importers] :
keyword[raise] i... | def importer(name, extensions=None, sniff=None):
"""
@importer(name) is a decorator that declares that the following function is an file loading
function that should be registered with the neuropythy load function. See also the
forget_importer function.
Any importer function must take, as its f... |
def auth_user_process_url(self, url):
'Process tokens and errors from redirect_uri.'
url = urlparse.urlparse(url)
url_qs = dict(it.chain.from_iterable(
urlparse.parse_qsl(v) for v in [url.query, url.fragment] ))
if url_qs.get('error'):
raise APIAuthError(
'{} :: {}'.format(url_qs['error'], url_qs.get(... | def function[auth_user_process_url, parameter[self, url]]:
constant[Process tokens and errors from redirect_uri.]
variable[url] assign[=] call[name[urlparse].urlparse, parameter[name[url]]]
variable[url_qs] assign[=] call[name[dict], parameter[call[name[it].chain.from_iterable, parameter[<ast.Ge... | keyword[def] identifier[auth_user_process_url] ( identifier[self] , identifier[url] ):
literal[string]
identifier[url] = identifier[urlparse] . identifier[urlparse] ( identifier[url] )
identifier[url_qs] = identifier[dict] ( identifier[it] . identifier[chain] . identifier[from_iterable] (
identifier[urlp... | def auth_user_process_url(self, url):
"""Process tokens and errors from redirect_uri."""
url = urlparse.urlparse(url)
url_qs = dict(it.chain.from_iterable((urlparse.parse_qsl(v) for v in [url.query, url.fragment])))
if url_qs.get('error'):
raise APIAuthError('{} :: {}'.format(url_qs['error'], ur... |
def get_datawrapper(self, file_format='BlockNeuronBuilder', data_wrapper=DataWrapper):
'''returns a DataWrapper'''
self._check_consistency()
datablock, sections = self._make_datablock()
return data_wrapper(datablock, file_format, sections) | def function[get_datawrapper, parameter[self, file_format, data_wrapper]]:
constant[returns a DataWrapper]
call[name[self]._check_consistency, parameter[]]
<ast.Tuple object at 0x7da18bc726b0> assign[=] call[name[self]._make_datablock, parameter[]]
return[call[name[data_wrapper], parameter[n... | keyword[def] identifier[get_datawrapper] ( identifier[self] , identifier[file_format] = literal[string] , identifier[data_wrapper] = identifier[DataWrapper] ):
literal[string]
identifier[self] . identifier[_check_consistency] ()
identifier[datablock] , identifier[sections] = identifier[sel... | def get_datawrapper(self, file_format='BlockNeuronBuilder', data_wrapper=DataWrapper):
"""returns a DataWrapper"""
self._check_consistency()
(datablock, sections) = self._make_datablock()
return data_wrapper(datablock, file_format, sections) |
def _create_gcl_resource(self):
"""Create a configured Resource object.
The logging.resource.Resource object enables GCL to filter and
bucket incoming logs according to which resource (host) they're
coming from.
Returns:
(obj): Instance of `google.cloud.logging.reso... | def function[_create_gcl_resource, parameter[self]]:
constant[Create a configured Resource object.
The logging.resource.Resource object enables GCL to filter and
bucket incoming logs according to which resource (host) they're
coming from.
Returns:
(obj): Instance of... | keyword[def] identifier[_create_gcl_resource] ( identifier[self] ):
literal[string]
keyword[return] identifier[gcl_resource] . identifier[Resource] ( literal[string] ,{
literal[string] : identifier[self] . identifier[project_id] ,
literal[string] : identifier[self] . identifier[... | def _create_gcl_resource(self):
"""Create a configured Resource object.
The logging.resource.Resource object enables GCL to filter and
bucket incoming logs according to which resource (host) they're
coming from.
Returns:
(obj): Instance of `google.cloud.logging.resource... |
def parse(cls, credentials) -> typing.Optional["Credentials"]:
"""Parse/interpret some given credentials.
These may take the form of:
* An empty string.
* An empty sequence.
* A string, containing three parts (consumer key, token key, and token
secret) separated by ... | def function[parse, parameter[cls, credentials]]:
constant[Parse/interpret some given credentials.
These may take the form of:
* An empty string.
* An empty sequence.
* A string, containing three parts (consumer key, token key, and token
secret) separated by colons.... | keyword[def] identifier[parse] ( identifier[cls] , identifier[credentials] )-> identifier[typing] . identifier[Optional] [ literal[string] ]:
literal[string]
keyword[if] identifier[credentials] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] ident... | def parse(cls, credentials) -> typing.Optional['Credentials']:
"""Parse/interpret some given credentials.
These may take the form of:
* An empty string.
* An empty sequence.
* A string, containing three parts (consumer key, token key, and token
secret) separated by colo... |
def do_view(self):
"""
Authenticate user with given credentials.
Connects user's queue and exchange
"""
self.current.output['login_process'] = True
self.current.task_data['login_successful'] = False
if self.current.is_auth:
self._do_upgrade()
e... | def function[do_view, parameter[self]]:
constant[
Authenticate user with given credentials.
Connects user's queue and exchange
]
call[name[self].current.output][constant[login_process]] assign[=] constant[True]
call[name[self].current.task_data][constant[login_successful]... | keyword[def] identifier[do_view] ( identifier[self] ):
literal[string]
identifier[self] . identifier[current] . identifier[output] [ literal[string] ]= keyword[True]
identifier[self] . identifier[current] . identifier[task_data] [ literal[string] ]= keyword[False]
keyword[if] i... | def do_view(self):
"""
Authenticate user with given credentials.
Connects user's queue and exchange
"""
self.current.output['login_process'] = True
self.current.task_data['login_successful'] = False
if self.current.is_auth:
self._do_upgrade() # depends on [control=['if']... |
def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... | def function[read, parameter[self, size]]:
constant[Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, wher... | keyword[def] identifier[read] ( identifier[self] , identifier[size] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_open] :
keyword[raise] identifier[IOError] ( literal[string] )
keyword[if] identifier[self] . identifier[_current_offset] < lite... | def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... |
def show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_member_entry_entry_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration")
config = show_zoni... | def function[show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_member_entry_entry_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_zoning_enabled_configuration] as... | keyword[def] identifier[show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_member_entry_entry_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_zoning_ena... | def show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_member_entry_entry_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_zoning_enabled_configuration = ET.Element('show_zoning_enabled_configuration')
config = show_zoning_enabled_confi... |
def _autocorr_func3(mags, lag, maglen, magmed, magstd):
'''
This is yet another alternative to calculate the autocorrelation.
Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/maste... | def function[_autocorr_func3, parameter[mags, lag, maglen, magmed, magstd]]:
constant[
This is yet another alternative to calculate the autocorrelation.
Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian... | keyword[def] identifier[_autocorr_func3] ( identifier[mags] , identifier[lag] , identifier[maglen] , identifier[magmed] , identifier[magstd] ):
literal[string]
identifier[result] = identifier[npcorrelate] ( identifier[mags] , identifier[mags] , identifier[mode] = literal[string] )
identifier[res... | def _autocorr_func3(mags, lag, maglen, magmed, magstd):
"""
This is yet another alternative to calculate the autocorrelation.
Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/maste... |
def _compute_edges_cells(self):
"""This creates interior edge->cells relations. While it's not
necessary for many applications, it sometimes does come in handy.
"""
if self.edges is None:
self.create_edges()
num_edges = len(self.edges["nodes"])
counts = nump... | def function[_compute_edges_cells, parameter[self]]:
constant[This creates interior edge->cells relations. While it's not
necessary for many applications, it sometimes does come in handy.
]
if compare[name[self].edges is constant[None]] begin[:]
call[name[self].create_edg... | keyword[def] identifier[_compute_edges_cells] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[edges] keyword[is] keyword[None] :
identifier[self] . identifier[create_edges] ()
identifier[num_edges] = identifier[len] ( identifier[self] . iden... | def _compute_edges_cells(self):
"""This creates interior edge->cells relations. While it's not
necessary for many applications, it sometimes does come in handy.
"""
if self.edges is None:
self.create_edges() # depends on [control=['if'], data=[]]
num_edges = len(self.edges['nodes'])... |
def repr2(data, **kwargs):
"""
Makes a pretty and easy-to-doctest string representation!
This is an alternative to repr, and `pprint.pformat` that attempts to be
both more configurable and generate output that is consistent between
python versions.
Notes:
This function has many keyword... | def function[repr2, parameter[data]]:
constant[
Makes a pretty and easy-to-doctest string representation!
This is an alternative to repr, and `pprint.pformat` that attempts to be
both more configurable and generate output that is consistent between
python versions.
Notes:
This func... | keyword[def] identifier[repr2] ( identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[custom_extensions] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
identifier[_return_info] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] )
... | def repr2(data, **kwargs):
"""
Makes a pretty and easy-to-doctest string representation!
This is an alternative to repr, and `pprint.pformat` that attempts to be
both more configurable and generate output that is consistent between
python versions.
Notes:
This function has many keyword... |
def gt(self, key, value, includeMissing=False):
'''Return entries where the key's value is greater (>).
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},... | def function[gt, parameter[self, key, value, includeMissing]]:
constant[Return entries where the key's value is greater (>).
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, ... | keyword[def] identifier[gt] ( identifier[self] , identifier[key] , identifier[value] , identifier[includeMissing] = keyword[False] ):
literal[string]
( identifier[self] . identifier[table] , identifier[self] . identifier[index_track] )= identifier[internal] . identifier[select] ( identifier[self] . ... | def gt(self, key, value, includeMissing=False):
"""Return entries where the key's value is greater (>).
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},
... |
def _get_relative_reference(self, cursor, ref_key):
"""Returns absolute reference code for key.
Parameters
----------
cursor: 3-tuple of Integer
\tCurrent cursor position
ref_key: 3-tuple of Integer
\tAbsolute reference key
"""
magics = ["X", "... | def function[_get_relative_reference, parameter[self, cursor, ref_key]]:
constant[Returns absolute reference code for key.
Parameters
----------
cursor: 3-tuple of Integer
Current cursor position
ref_key: 3-tuple of Integer
Absolute reference key
]
... | keyword[def] identifier[_get_relative_reference] ( identifier[self] , identifier[cursor] , identifier[ref_key] ):
literal[string]
identifier[magics] =[ literal[string] , literal[string] , literal[string] ]
keyword[def] identifier[get_rel_key_ele] ( identifier[cursor_ele] , iden... | def _get_relative_reference(self, cursor, ref_key):
"""Returns absolute reference code for key.
Parameters
----------
cursor: 3-tuple of Integer
Current cursor position
ref_key: 3-tuple of Integer
Absolute reference key
"""
magics = ['X', 'Y', 'Z']
... |
def from_rfc3339_nanos(value):
"""Convert a nanosecond-precision timestamp to a native datetime.
.. note::
Python datetimes do not support nanosecond precision; this function
therefore truncates such values to microseconds.
Args:
value (str): The RFC3339 string to convert.
Ret... | def function[from_rfc3339_nanos, parameter[value]]:
constant[Convert a nanosecond-precision timestamp to a native datetime.
.. note::
Python datetimes do not support nanosecond precision; this function
therefore truncates such values to microseconds.
Args:
value (str): The RFC3... | keyword[def] identifier[from_rfc3339_nanos] ( identifier[value] ):
literal[string]
identifier[with_nanos] = identifier[_RFC3339_NANOS] . identifier[match] ( identifier[value] )
keyword[if] identifier[with_nanos] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] (
... | def from_rfc3339_nanos(value):
"""Convert a nanosecond-precision timestamp to a native datetime.
.. note::
Python datetimes do not support nanosecond precision; this function
therefore truncates such values to microseconds.
Args:
value (str): The RFC3339 string to convert.
Ret... |
def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None):
"""Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
... | def function[read_cache, parameter[cachefile, coltype, sort, segment]]:
constant[Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS t... | keyword[def] identifier[read_cache] ( identifier[cachefile] , identifier[coltype] = identifier[LIGOTimeGPS] , identifier[sort] = keyword[None] , identifier[segment] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[cachefile] , identifier[FILE_LIKE] ):
... | def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None):
"""Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
... |
def _memory_usage(func, gallery_conf):
"""Get memory usage of a function call."""
if gallery_conf['show_memory']:
from memory_profiler import memory_usage
assert callable(func)
mem, out = memory_usage(func, max_usage=True, retval=True,
multiprocess=True)
... | def function[_memory_usage, parameter[func, gallery_conf]]:
constant[Get memory usage of a function call.]
if call[name[gallery_conf]][constant[show_memory]] begin[:]
from relative_module[memory_profiler] import module[memory_usage]
assert[call[name[callable], parameter[name[func]]]]
... | keyword[def] identifier[_memory_usage] ( identifier[func] , identifier[gallery_conf] ):
literal[string]
keyword[if] identifier[gallery_conf] [ literal[string] ]:
keyword[from] identifier[memory_profiler] keyword[import] identifier[memory_usage]
keyword[assert] identifier[callable] (... | def _memory_usage(func, gallery_conf):
"""Get memory usage of a function call."""
if gallery_conf['show_memory']:
from memory_profiler import memory_usage
assert callable(func)
(mem, out) = memory_usage(func, max_usage=True, retval=True, multiprocess=True)
mem = mem[0] # depends... |
def get_deadletter_receiver(
self, transfer_deadletter=False, prefetch=0,
mode=ReceiveSettleMode.PeekLock, idle_timeout=0, **kwargs):
"""Get a Receiver for the deadletter endpoint of the entity.
A Receiver represents a single open connection with which multiple receive operation... | def function[get_deadletter_receiver, parameter[self, transfer_deadletter, prefetch, mode, idle_timeout]]:
constant[Get a Receiver for the deadletter endpoint of the entity.
A Receiver represents a single open connection with which multiple receive operations can be made.
:param transfer_deadl... | keyword[def] identifier[get_deadletter_receiver] (
identifier[self] , identifier[transfer_deadletter] = keyword[False] , identifier[prefetch] = literal[int] ,
identifier[mode] = identifier[ReceiveSettleMode] . identifier[PeekLock] , identifier[idle_timeout] = literal[int] ,** identifier[kwargs] ):
literal[... | def get_deadletter_receiver(self, transfer_deadletter=False, prefetch=0, mode=ReceiveSettleMode.PeekLock, idle_timeout=0, **kwargs):
"""Get a Receiver for the deadletter endpoint of the entity.
A Receiver represents a single open connection with which multiple receive operations can be made.
:para... |
def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... | def function[randkey, parameter[bits, keyspace, rng]]:
constant[ Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
@... | keyword[def] identifier[randkey] ( identifier[bits] , identifier[keyspace] = identifier[string] . identifier[ascii_letters] + identifier[string] . identifier[digits] + literal[string] ,
identifier[rng] = keyword[None] ):
literal[string]
keyword[return] literal[string] . identifier[join] ( identifier[char... | def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.', rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed out... |
def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a ... | def function[prepare_method_call, parameter[self, method, args]]:
constant[
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the f... | keyword[def] identifier[prepare_method_call] ( identifier[self] , identifier[method] , identifier[args] ):
literal[string]
keyword[if] identifier[self] . identifier[_method_requires_handler_ref] ( identifier[method] ):
keyword[if] identifier[isinstance] ( identifier[args] , identifie... | def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'pat... |
def WriteOutput(title, locations, limit, f):
"""Write html to f for up to limit trips between locations.
Args:
title: String used in html title
locations: list of (lat, lng) tuples
limit: maximum number of queries in the html
f: a file object
"""
output_prefix = """
<html>
<head>
<meta http-equ... | def function[WriteOutput, parameter[title, locations, limit, f]]:
constant[Write html to f for up to limit trips between locations.
Args:
title: String used in html title
locations: list of (lat, lng) tuples
limit: maximum number of queries in the html
f: a file object
]
variable[ou... | keyword[def] identifier[WriteOutput] ( identifier[title] , identifier[locations] , identifier[limit] , identifier[f] ):
literal[string]
identifier[output_prefix] = literal[string] % identifier[locals] ()
identifier[output_suffix] = literal[string] % identifier[locals] ()
identifier[f] . identifier[writ... | def WriteOutput(title, locations, limit, f):
"""Write html to f for up to limit trips between locations.
Args:
title: String used in html title
locations: list of (lat, lng) tuples
limit: maximum number of queries in the html
f: a file object
"""
output_prefix = '\n<html>\n<head>\n<meta htt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.