text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def fetch(self, category=CATEGORY_MESSAGE, offset=DEFAULT_OFFSET, chats=None):
"""Fetch the messages the bot can read from the server.
The method retrieves, from the Telegram server, the messages
sent with an offset equal or greater than the given.
A list of chats, groups and channels ... | [
"def",
"fetch",
"(",
"self",
",",
"category",
"=",
"CATEGORY_MESSAGE",
",",
"offset",
"=",
"DEFAULT_OFFSET",
",",
"chats",
"=",
"None",
")",
":",
"if",
"not",
"offset",
":",
"offset",
"=",
"DEFAULT_OFFSET",
"kwargs",
"=",
"{",
"\"offset\"",
":",
"offset",
... | 36.923077 | 0.00203 |
def add_hba_entry(self, *, type='host', database, user, address=None,
auth_method, auth_options=None):
"""Add a record to pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: c... | [
"def",
"add_hba_entry",
"(",
"self",
",",
"*",
",",
"type",
"=",
"'host'",
",",
"database",
",",
"user",
",",
"address",
"=",
"None",
",",
"auth_method",
",",
"auth_options",
"=",
"None",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
... | 35.676471 | 0.002408 |
def init_region_config(self, region):
"""
Initialize the region's configuration
:param region: Name of the region
"""
self.regions[region] = self.region_config_class(region_name = region, resource_types = self.resource_types) | [
"def",
"init_region_config",
"(",
"self",
",",
"region",
")",
":",
"self",
".",
"regions",
"[",
"region",
"]",
"=",
"self",
".",
"region_config_class",
"(",
"region_name",
"=",
"region",
",",
"resource_types",
"=",
"self",
".",
"resource_types",
")"
] | 39.571429 | 0.024735 |
def upload_status(self, upload_id):
"""The method is checking status of uploaded dataset"""
path = '/api/1.0/upload/status'
query = 'id={}'.format(upload_id)
return self._api_get(definition.DatasetUploadStatusResponse, path, query) | [
"def",
"upload_status",
"(",
"self",
",",
"upload_id",
")",
":",
"path",
"=",
"'/api/1.0/upload/status'",
"query",
"=",
"'id={}'",
".",
"format",
"(",
"upload_id",
")",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"DatasetUploadStatusResponse",
","... | 44 | 0.011152 |
def generate_probmodelxml(model, encoding='utf-8', prettyprint=True):
"""
Generate ProbModelXML lines for model.
Parameters
----------
model : Graph
The Bayesian or Markov Model
encoding : string (optional)
Encoding for text data
prettyprint: bool (optional)
If True ... | [
"def",
"generate_probmodelxml",
"(",
"model",
",",
"encoding",
"=",
"'utf-8'",
",",
"prettyprint",
"=",
"True",
")",
":",
"writer",
"=",
"ProbModelXMLWriter",
"(",
"G",
",",
"encoding",
"=",
"encoding",
",",
"prettyprint",
"=",
"prettyprint",
")",
"for",
"li... | 31.304348 | 0.001348 |
def save(self, trial, storage=Checkpoint.DISK):
"""Saves the trial's state to a checkpoint."""
trial._checkpoint.storage = storage
trial._checkpoint.last_result = trial.last_result
if storage == Checkpoint.MEMORY:
trial._checkpoint.value = trial.runner.save_to_object.remote()... | [
"def",
"save",
"(",
"self",
",",
"trial",
",",
"storage",
"=",
"Checkpoint",
".",
"DISK",
")",
":",
"trial",
".",
"_checkpoint",
".",
"storage",
"=",
"storage",
"trial",
".",
"_checkpoint",
".",
"last_result",
"=",
"trial",
".",
"last_result",
"if",
"sto... | 47.37037 | 0.001533 |
def setupEnvironment(self=None):
"""Set the environment (argv, sys.path and module import) of
scoop.MAIN_MODULE.
"""
# get the module path in the Python path
sys.path.append(os.path.dirname(os.path.abspath(scoop.MAIN_MODULE)))
# Add the user arguments to argv
sys... | [
"def",
"setupEnvironment",
"(",
"self",
"=",
"None",
")",
":",
"# get the module path in the Python path",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"scoop",
".",
"MAIN_MODULE",
... | 29.6 | 0.001453 |
def recv_msg(sock):
"""Receives a method and message from the socket. This function blocks the
current thread.
"""
data = recv(sock, struct.calcsize(METHOD_STRUCT_FORMAT))
method, = struct.unpack(METHOD_STRUCT_FORMAT, data)
data = recv(sock, struct.calcsize(SIZE_STRUCT_FORMAT))
size, = stru... | [
"def",
"recv_msg",
"(",
"sock",
")",
":",
"data",
"=",
"recv",
"(",
"sock",
",",
"struct",
".",
"calcsize",
"(",
"METHOD_STRUCT_FORMAT",
")",
")",
"method",
",",
"=",
"struct",
".",
"unpack",
"(",
"METHOD_STRUCT_FORMAT",
",",
"data",
")",
"data",
"=",
... | 38.636364 | 0.002299 |
def open_data_source(source):
"""Open a GWF file source into a `lalframe.XLALFrStream` object
Parameters
----------
source : `str`, `file`, `list`
Data source to read.
Returns
-------
stream : `lalframe.FrStream`
An open `FrStream`.
Raises
------
ValueError
... | [
"def",
"open_data_source",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"FILE_LIKE",
")",
":",
"source",
"=",
"source",
".",
"name",
"if",
"isinstance",
"(",
"source",
",",
"CacheEntry",
")",
":",
"source",
"=",
"source",
".",
"path",... | 28.688889 | 0.000749 |
def assertSingleClass(self,P):
"""
Check whether the rate/probability matrix consists of a single connected class.
If this is not the case, the steady state distribution is not well defined.
"""
components, _ = csgraph.connected_components(P, directed=True, connection='weak') ... | [
"def",
"assertSingleClass",
"(",
"self",
",",
"P",
")",
":",
"components",
",",
"_",
"=",
"csgraph",
".",
"connected_components",
"(",
"P",
",",
"directed",
"=",
"True",
",",
"connection",
"=",
"'weak'",
")",
"assert",
"components",
"==",
"1",
",",
"\"Th... | 64.857143 | 0.023913 |
def zlist(columns, items, print_columns=None,
text="", title="", width=DEFAULT_WIDTH,
height=ZLIST_HEIGHT, timeout=None):
"""
Display a list of values
:param columns: a list of columns name
:type columns: list of strings
:param items: a list of values
:type items: list of st... | [
"def",
"zlist",
"(",
"columns",
",",
"items",
",",
"print_columns",
"=",
"None",
",",
"text",
"=",
"\"\"",
",",
"title",
"=",
"\"\"",
",",
"width",
"=",
"DEFAULT_WIDTH",
",",
"height",
"=",
"ZLIST_HEIGHT",
",",
"timeout",
"=",
"None",
")",
":",
"dialog... | 33.068966 | 0.002026 |
def loopUntil(
self, condition=None, timeout: float = 0) -> Iterator[object]:
"""
Iterate until condition is met, with optional timeout in seconds.
The yielded value is that of the condition or False when timed out.
Args:
condition: Predicate function that is tes... | [
"def",
"loopUntil",
"(",
"self",
",",
"condition",
"=",
"None",
",",
"timeout",
":",
"float",
"=",
"0",
")",
"->",
"Iterator",
"[",
"object",
"]",
":",
"endTime",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"True",
":",
"test",
"="... | 35.291667 | 0.002299 |
def stop(self):
"""
Releases the db mutex lock. Throws an error if the lock was released before the function finished.
"""
if not DBMutex.objects.filter(id=self.lock.id).exists():
raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id))
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"DBMutex",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"self",
".",
"lock",
".",
"id",
")",
".",
"exists",
"(",
")",
":",
"raise",
"DBMutexTimeoutError",
"(",
"'Lock {0} expired before function complete... | 44.25 | 0.01108 |
def getMaintenanceTypes(self):
""" Return the current list of maintenance types
"""
types = [('Preventive',safe_unicode(_('Preventive')).encode('utf-8')),
('Repair', safe_unicode(_('Repair')).encode('utf-8')),
('Enhancement', safe_unicode(_('Enhancement')).encod... | [
"def",
"getMaintenanceTypes",
"(",
"self",
")",
":",
"types",
"=",
"[",
"(",
"'Preventive'",
",",
"safe_unicode",
"(",
"_",
"(",
"'Preventive'",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"(",
"'Repair'",
",",
"safe_unicode",
"(",
"_",
"("... | 51.428571 | 0.010929 |
async def register(self, request):
"""Registers the user."""
session = await get_session(request)
user_id = session.get('user_id')
if user_id:
return redirect(request, 'timeline')
error = None
form = None
if request.method == 'POST':
form ... | [
"async",
"def",
"register",
"(",
"self",
",",
"request",
")",
":",
"session",
"=",
"await",
"get_session",
"(",
"request",
")",
"user_id",
"=",
"session",
".",
"get",
"(",
"'user_id'",
")",
"if",
"user_id",
":",
"return",
"redirect",
"(",
"request",
",",... | 41.533333 | 0.001569 |
def rpc(self, address, rpc_id, *args, **kwargs):
"""Immediately dispatch an RPC inside this EmulatedDevice.
This function is meant to be used for testing purposes as well as by
tiles inside a complex EmulatedDevice subclass that need to
communicate with each other. It should only be ca... | [
"def",
"rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"rpc_id",
",",
"RPCDeclaration",
")",
":",
"arg_format",
"=",
"rpc_id",
".",
"arg_format",
"resp_format",
"=",
"rpc_... | 39.395349 | 0.002304 |
def addSlider3D(
sliderfunc,
pos1,
pos2,
xmin,
xmax,
value=None,
s=0.03,
title="",
rotation=0,
c=None,
showValue=True,
):
"""Add a 3D slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param ... | [
"def",
"addSlider3D",
"(",
"sliderfunc",
",",
"pos1",
",",
"pos2",
",",
"xmin",
",",
"xmax",
",",
"value",
"=",
"None",
",",
"s",
"=",
"0.03",
",",
"title",
"=",
"\"\"",
",",
"rotation",
"=",
"0",
",",
"c",
"=",
"None",
",",
"showValue",
"=",
"Tr... | 30.275 | 0.0004 |
def activate_state_tab(self, state_m):
"""Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state)
"""
# The current shown state differs from the desired one
... | [
"def",
"activate_state_tab",
"(",
"self",
",",
"state_m",
")",
":",
"# The current shown state differs from the desired one",
"current_state_m",
"=",
"self",
".",
"get_current_state_m",
"(",
")",
"if",
"current_state_m",
"is",
"not",
"state_m",
":",
"state_identifier",
... | 42.625 | 0.001912 |
def export(self, nidm_version, export_dir):
"""
Create prov graph.
"""
attributes = [(PROV['type'], NIDM_STATISTIC_MAP),
(DCT['format'], self.fmt)]
if not self.isderfrommap:
attributes.insert(0, (
NIDM_IN_COORDINATE_SPACE, self.... | [
"def",
"export",
"(",
"self",
",",
"nidm_version",
",",
"export_dir",
")",
":",
"attributes",
"=",
"[",
"(",
"PROV",
"[",
"'type'",
"]",
",",
"NIDM_STATISTIC_MAP",
")",
",",
"(",
"DCT",
"[",
"'format'",
"]",
",",
"self",
".",
"fmt",
")",
"]",
"if",
... | 40.965517 | 0.001645 |
def copy(self):
"""Return a copy of this list with each element copied to new memory
"""
out = type(self)()
for series in self:
out.append(series.copy())
return out | [
"def",
"copy",
"(",
"self",
")",
":",
"out",
"=",
"type",
"(",
"self",
")",
"(",
")",
"for",
"series",
"in",
"self",
":",
"out",
".",
"append",
"(",
"series",
".",
"copy",
"(",
")",
")",
"return",
"out"
] | 30 | 0.009259 |
def convert_ipynbs(directory):
"""Recursively converts all ipynb files in a directory into rst files in
the same directory."""
# The ipython_examples dir has to be in the same dir as this script
for root, subfolders, files in os.walk(os.path.abspath(directory)):
for f in files:
if ".... | [
"def",
"convert_ipynbs",
"(",
"directory",
")",
":",
"# The ipython_examples dir has to be in the same dir as this script",
"for",
"root",
",",
"subfolders",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
")",... | 47.222222 | 0.002309 |
def _multiply(self, f1, f2, out):
"""Pointwise multiplication of ``f1`` and ``f2``.
Notes
-----
The multiplication is implemented with a simple Python
function, so the non-vectorized versions are slow.
"""
# Avoid infinite recursions by making a copy of the funct... | [
"def",
"_multiply",
"(",
"self",
",",
"f1",
",",
"f2",
",",
"out",
")",
":",
"# Avoid infinite recursions by making a copy of the functions",
"f1_copy",
"=",
"f1",
".",
"copy",
"(",
")",
"f2_copy",
"=",
"f2",
".",
"copy",
"(",
")",
"def",
"product_oop",
"(",... | 37.681818 | 0.002353 |
def encode_memo(priv, pub, nonce, message):
""" Encode a message with a shared secret between Alice and Bob
:param PrivateKey priv: Private Key (of Alice)
:param PublicKey pub: Public Key (of Bob)
:param int nonce: Random nonce
:param str message: Memo message
:return: Encry... | [
"def",
"encode_memo",
"(",
"priv",
",",
"pub",
",",
"nonce",
",",
"message",
")",
":",
"shared_secret",
"=",
"get_shared_secret",
"(",
"priv",
",",
"pub",
")",
"aes",
"=",
"init_aes",
"(",
"shared_secret",
",",
"nonce",
")",
"\" Checksum \"",
"raw",
"=",
... | 31.761905 | 0.001456 |
def columns(self, *args) -> List[List[Well]]:
"""
Accessor function used to navigate through a labware by column.
With indexing one can treat it as a typical python nested list.
To access row A for example,
simply write: labware.columns()[0]
This will output ['A1', 'B1',... | [
"def",
"columns",
"(",
"self",
",",
"*",
"args",
")",
"->",
"List",
"[",
"List",
"[",
"Well",
"]",
"]",
":",
"col_dict",
"=",
"self",
".",
"_create_indexed_dictionary",
"(",
"group",
"=",
"2",
")",
"keys",
"=",
"sorted",
"(",
"col_dict",
",",
"key",
... | 39.068966 | 0.001723 |
def _handle_universal(self, X):
"""
Scan through the corpus to compute counts of each Universal
Dependencies part-of-speech.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of... | [
"def",
"_handle_universal",
"(",
"self",
",",
"X",
")",
":",
"jump",
"=",
"{",
"# combine proper and regular nouns",
"\"NOUN\"",
":",
"\"noun\"",
",",
"\"PROPN\"",
":",
"\"noun\"",
",",
"\"ADJ\"",
":",
"\"adjective\"",
",",
"\"VERB\"",
":",
"\"verb\"",
",",
"#... | 33.685714 | 0.001649 |
def _get_pga_on_rock(self, rup, dists, _C):
"""
Compute and return PGA on rock conditions (that is vs30 = 760.0 m/s).
This is needed to compute non-linear site amplification term
"""
# Median PGA in g for Vref = 760.0, without site amplification,
# that is equation (1) pa... | [
"def",
"_get_pga_on_rock",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"_C",
")",
":",
"# Median PGA in g for Vref = 760.0, without site amplification,",
"# that is equation (1) pag 106, without the third and fourth terms",
"# Mref and Rref values are given in the caption to table 6, pag... | 54.8 | 0.001794 |
def Vizier_xmatch(self, viz_cat, cat_name, ra_col='_RAJ2000', dec_col='_DEJ2000', radius='', group=True):
"""
Use astroquery to pull in and cross match a catalog with sources in self.catalog
Parameters
----------
viz_cat: str
The catalog string from Vizier (e... | [
"def",
"Vizier_xmatch",
"(",
"self",
",",
"viz_cat",
",",
"cat_name",
",",
"ra_col",
"=",
"'_RAJ2000'",
",",
"dec_col",
"=",
"'_DEJ2000'",
",",
"radius",
"=",
"''",
",",
"group",
"=",
"True",
")",
":",
"# Make sure sources have been grouped",
"if",
"self",
"... | 41.5 | 0.009156 |
def one(src, default=None, key=None):
"""Along the same lines as builtins, :func:`all` and :func:`any`, and
similar to :func:`first`, ``one()`` returns the single object in
the given iterable *src* that evaluates to ``True``, as determined
by callable *key*. If unset, *key* defaults to :class:`bool`. If... | [
"def",
"one",
"(",
"src",
",",
"default",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"ones",
"=",
"list",
"(",
"itertools",
".",
"islice",
"(",
"filter",
"(",
"key",
",",
"src",
")",
",",
"2",
")",
")",
"return",
"ones",
"[",
"0",
"]",
"... | 35.575758 | 0.000829 |
def _get_repr(obj, pretty=False, indent=1):
"""
Get string representation of an object
:param obj: object
:type obj: object
:param pretty: use pretty formatting
:type pretty: bool
:param indent: indentation for pretty formatting
:type indent: int
... | [
"def",
"_get_repr",
"(",
"obj",
",",
"pretty",
"=",
"False",
",",
"indent",
"=",
"1",
")",
":",
"if",
"pretty",
":",
"repr_value",
"=",
"pformat",
"(",
"obj",
",",
"indent",
")",
"else",
":",
"repr_value",
"=",
"repr",
"(",
"obj",
")",
"if",
"sys",... | 32.875 | 0.002463 |
def compare_mean_curves(calc_ref, calc, nsigma=3):
"""
Compare the hazard curves coming from two different calculations.
"""
dstore_ref = datastore.read(calc_ref)
dstore = datastore.read(calc)
imtls = dstore_ref['oqparam'].imtls
if dstore['oqparam'].imtls != imtls:
raise RuntimeError... | [
"def",
"compare_mean_curves",
"(",
"calc_ref",
",",
"calc",
",",
"nsigma",
"=",
"3",
")",
":",
"dstore_ref",
"=",
"datastore",
".",
"read",
"(",
"calc_ref",
")",
"dstore",
"=",
"datastore",
".",
"read",
"(",
"calc",
")",
"imtls",
"=",
"dstore_ref",
"[",
... | 49.953488 | 0.000457 |
def get_power(self):
"""Returns the Power in Watt"""
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict | [
"def",
"get_power",
"(",
"self",
")",
":",
"power_dict",
"=",
"self",
".",
"get_power_all",
"(",
")",
"for",
"device",
"in",
"power_dict",
".",
"keys",
"(",
")",
":",
"power_dict",
"[",
"device",
"]",
"=",
"float",
"(",
"power_dict",
"[",
"device",
"]"... | 38.666667 | 0.008439 |
def check_db_for_missing_notifications():
"""Check the database for missing notifications."""
aws_access_key_id = os.environ['aws_access_key_id']
aws_secret_access_key = os.environ['aws_secret_access_key']
if config.getboolean('Shell Parameters', 'launch_in_sandbox_mode'):
conn = MTurkConnection... | [
"def",
"check_db_for_missing_notifications",
"(",
")",
":",
"aws_access_key_id",
"=",
"os",
".",
"environ",
"[",
"'aws_access_key_id'",
"]",
"aws_secret_access_key",
"=",
"os",
".",
"environ",
"[",
"'aws_secret_access_key'",
"]",
"if",
"config",
".",
"getboolean",
"... | 51.824074 | 0.002191 |
def has_alias(self, header):
"""Return the alias name for the relative header or None if nonexist."""
try:
# Force to lower case (issue #1126)
return self._limits[self.plugin_name + '_' + header.lower() + '_' + 'alias'][0]
except (KeyError, IndexError):
# logg... | [
"def",
"has_alias",
"(",
"self",
",",
"header",
")",
":",
"try",
":",
"# Force to lower case (issue #1126)",
"return",
"self",
".",
"_limits",
"[",
"self",
".",
"plugin_name",
"+",
"'_'",
"+",
"header",
".",
"lower",
"(",
")",
"+",
"'_'",
"+",
"'alias'",
... | 48.125 | 0.010204 |
def users_profile_set(self, **kwargs) -> SlackResponse:
"""Set the profile information for a user."""
self._validate_xoxp_token()
return self.api_call("users.profile.set", json=kwargs) | [
"def",
"users_profile_set",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"self",
".",
"_validate_xoxp_token",
"(",
")",
"return",
"self",
".",
"api_call",
"(",
"\"users.profile.set\"",
",",
"json",
"=",
"kwargs",
")"
] | 51.25 | 0.009615 |
def add_step(step_name, func):
"""
Add a step function to Orca.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argument name "iter_var" may be used to have the current
iteration variable ... | [
"def",
"add_step",
"(",
"step_name",
",",
"func",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"Callable",
")",
":",
"logger",
".",
"debug",
"(",
"'registering step {!r}'",
".",
"format",
"(",
"step_name",
")",
")",
"_STEPS",
"[",
"step_name",
"]",
"=... | 29.095238 | 0.001585 |
def get_all_resource_attributes(ref_key, network_id, template_id=None, **kwargs):
"""
Get all the resource attributes for a given resource type in the network.
That includes all the resource attributes for a given type within the network.
For example, if the ref_key is 'NODE', then it will r... | [
"def",
"get_all_resource_attributes",
"(",
"ref_key",
",",
"network_id",
",",
"template_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"resource_attr_qry",
"=",
"db",
".",
"DBSession",
".",
... | 44.266667 | 0.015226 |
def install_app(app, target='/Applications/'):
'''
Install an app file by moving it into the specified Applications directory
Args:
app (str): The location of the .app file
target (str): The target in which to install the package to
Default is ''/Applications/''
R... | [
"def",
"install_app",
"(",
"app",
",",
"target",
"=",
"'/Applications/'",
")",
":",
"if",
"target",
"[",
"-",
"4",
":",
"]",
"!=",
"'.app'",
":",
"if",
"app",
"[",
"-",
"1",
":",
"]",
"==",
"'/'",
":",
"base_app",
"=",
"os",
".",
"path",
".",
"... | 25.8125 | 0.001167 |
def list_users(order_by='id'):
'''
Show all users for this company.
CLI Example:
salt myminion bamboohr.list_users
By default, the return data will be keyed by ID. However, it can be ordered
by any other field. Keep in mind that if the field that is chosen contains
duplicate values (i... | [
"def",
"list_users",
"(",
"order_by",
"=",
"'id'",
")",
":",
"ret",
"=",
"{",
"}",
"status",
",",
"result",
"=",
"_query",
"(",
"action",
"=",
"'meta'",
",",
"command",
"=",
"'users'",
")",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"result",
")",
... | 32.457143 | 0.000855 |
def _format_list(list_, **kwargs):
"""
Makes a pretty printable / human-readable string representation of a
sequence. In most cases this string could be evaled.
Args:
list_ (list): input list
**kwargs: nl, newlines, packed, nobr, nobraces, itemsep, trailing_sep,
strvals inde... | [
"def",
"_format_list",
"(",
"list_",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_root_info'",
"]",
"=",
"_rectify_root_info",
"(",
"kwargs",
".",
"get",
"(",
"'_root_info'",
",",
"None",
")",
")",
"kwargs",
"[",
"'_root_info'",
"]",
"[",
"'depth... | 32.507692 | 0.002297 |
def sys_rt_sigprocmask(self, cpu, how, newset, oldset):
"""Wrapper for sys_sigprocmask"""
return self.sys_sigprocmask(cpu, how, newset, oldset) | [
"def",
"sys_rt_sigprocmask",
"(",
"self",
",",
"cpu",
",",
"how",
",",
"newset",
",",
"oldset",
")",
":",
"return",
"self",
".",
"sys_sigprocmask",
"(",
"cpu",
",",
"how",
",",
"newset",
",",
"oldset",
")"
] | 52.333333 | 0.012579 |
def Group(self):
"""Return group object for group containing this server.
>>> clc.v2.Server("CA3BTDICNTRLM01").Group()
<clc.APIv2.group.Group object at 0x10b07b7d0>
>>> print _
Ansible Managed Servers
"""
return(clc.v2.Group(id=self.groupId,alias=self.alias,session=self.session)) | [
"def",
"Group",
"(",
"self",
")",
":",
"return",
"(",
"clc",
".",
"v2",
".",
"Group",
"(",
"id",
"=",
"self",
".",
"groupId",
",",
"alias",
"=",
"self",
".",
"alias",
",",
"session",
"=",
"self",
".",
"session",
")",
")"
] | 26.090909 | 0.037037 |
def parse_address(text: str) -> Tuple[str, int]:
'''Parse PASV address.'''
match = re.search(
r'\('
r'(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*'
r'\)',
text)
if mat... | [
"def",
"parse_address",
"(",
"text",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\('",
"r'(\\d{1,3})\\s*,'",
"r'\\s*(\\d{1,3})\\s*,'",
"r'\\s*(\\d{1,3})\\s*,'",
"r'\\s*(\\d{1,3})\\s*,'",
"r'\\s*(\\d... | 29.833333 | 0.001353 |
def register_preset(cls, name, preset):
"""
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to
automatically register themselves with a preset by using a classmethod of their own with only the name of the
preset to register wi... | [
"def",
"register_preset",
"(",
"cls",
",",
"name",
",",
"preset",
")",
":",
"if",
"cls",
".",
"_presets",
"is",
"None",
":",
"cls",
".",
"_presets",
"=",
"{",
"}",
"cls",
".",
"_presets",
"[",
"name",
"]",
"=",
"preset"
] | 47.333333 | 0.009217 |
def configure_logger(logger, filename, folder, log_level):
'''Configure logging behvior for the simulations.
'''
fmt = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
if folder is not None:
log_file = os.path.join(folder, filename)
hdl = logging.FileHandler(log_file)
... | [
"def",
"configure_logger",
"(",
"logger",
",",
"filename",
",",
"folder",
",",
"log_level",
")",
":",
"fmt",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)s: %(message)s'",
")",
"if",
"folder",
"is",
"not",
"None",
":",
"log_file",
"=",
"os"... | 36 | 0.001805 |
def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_chang... | [
"def",
"change_parameters",
"(",
"self",
",",
"params",
")",
":",
"no_of_params",
"=",
"0",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_... | 43.222222 | 0.010076 |
def cli(ctx, amount, index, stage):
"""Pull, Transform, Push,streaming inside a pipe(experimental)."""
ctx.obj.say_green('Starting Streaming Pipe')
res_pull = ctx.invoke(pull, amount=amount, index=index, stage=stage)
res_tra = False
if res_pull:
# amount to transform can be less (or more)
... | [
"def",
"cli",
"(",
"ctx",
",",
"amount",
",",
"index",
",",
"stage",
")",
":",
"ctx",
".",
"obj",
".",
"say_green",
"(",
"'Starting Streaming Pipe'",
")",
"res_pull",
"=",
"ctx",
".",
"invoke",
"(",
"pull",
",",
"amount",
"=",
"amount",
",",
"index",
... | 41.8125 | 0.001462 |
def _generateTabularData(res, oldTabularData = {}, isTerminal=False, canUnicode=True):
"""
Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
... | [
"def",
"_generateTabularData",
"(",
"res",
",",
"oldTabularData",
"=",
"{",
"}",
",",
"isTerminal",
"=",
"False",
",",
"canUnicode",
"=",
"True",
")",
":",
"def",
"_grabbingNewHeader",
"(",
"h",
")",
":",
"\"\"\"\n Updates the headers to be general.\n\n ... | 31.25641 | 0.001749 |
def header(*msg, level='h1', separator=" ", print_out=print):
''' Print header block in text mode
'''
out_string = separator.join(str(x) for x in msg)
if level == 'h0':
# box_len = 80 if len(msg) < 80 else len(msg)
box_len = 80
print_out('+' + '-' * (box_len + 2))
print_o... | [
"def",
"header",
"(",
"*",
"msg",
",",
"level",
"=",
"'h1'",
",",
"separator",
"=",
"\" \"",
",",
"print_out",
"=",
"print",
")",
":",
"out_string",
"=",
"separator",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"msg",
")",
"if",
"le... | 33.15 | 0.001466 |
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any ... | [
"def",
"show",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"refresh",
"=",
"kwargs",
".",
"pop",
"(",
"'refresh'",
",",
"False",
")",
"... | 30.792683 | 0.001151 |
def remove(self, values):
"""
Remove DNS entries from this ranked DNS list. A DNS entry can be either
a raw IP Address, or an element of type :class:`smc.elements.network.Host`
or :class:`smc.elements.servers.DNSServer`.
:param list values: list of IP addresses, Host and... | [
"def",
"remove",
"(",
"self",
",",
"values",
")",
":",
"removables",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
":",
"if",
"value",
"in",
"self",
":",
"removables",
".",
"append",
"(",
"value",
")",
"if",
"removables",
":",
"self",
".",
"entries"... | 40.35 | 0.010896 |
def stdout(prev, endl='\n', thru=False):
"""This pipe read data from previous iterator and write it to stdout.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param endl: The end-of-line symbol for each output.
:type endl: str
:param thru: If true, data will passed to next generat... | [
"def",
"stdout",
"(",
"prev",
",",
"endl",
"=",
"'\\n'",
",",
"thru",
"=",
"False",
")",
":",
"for",
"i",
"in",
"prev",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"i",
")",
"+",
"endl",
")",
"if",
"thru",
":",
"yield",
"i"
] | 31.625 | 0.001919 |
def setCurrentMode(self, mode):
"""
Sets the current color mode for this console to the inputed value.
:param mode | <unicode>
"""
if type(mode) == int:
mode = self.LoggingMap.get(mode, ('standard', ''))[0]
if mode == self._... | [
"def",
"setCurrentMode",
"(",
"self",
",",
"mode",
")",
":",
"if",
"type",
"(",
"mode",
")",
"==",
"int",
":",
"mode",
"=",
"self",
".",
"LoggingMap",
".",
"get",
"(",
"mode",
",",
"(",
"'standard'",
",",
"''",
")",
")",
"[",
"0",
"]",
"if",
"m... | 30.2 | 0.009631 |
def get_feature_permission(request, feature, operation=None):
"""Check if a feature-specific field can be displayed.
This method check a permission for a feature-specific field.
Such field is usually provided through Neutron extension.
:param request: Request Object
:param feature: feature name de... | [
"def",
"get_feature_permission",
"(",
"request",
",",
"feature",
",",
"operation",
"=",
"None",
")",
":",
"network_config",
"=",
"getattr",
"(",
"settings",
",",
"'OPENSTACK_NEUTRON_NETWORK'",
",",
"{",
"}",
")",
"feature_info",
"=",
"FEATURE_MAP",
".",
"get",
... | 41.673077 | 0.000451 |
def resize(self, size, interp='nearest'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`... | [
"def",
"resize",
"(",
"self",
",",
"size",
",",
"interp",
"=",
"'nearest'",
")",
":",
"resized_data_0",
"=",
"sm",
".",
"imresize",
"(",
"self",
".",
"_data",
"[",
":",
",",
":",
",",
"0",
"]",
",",
"size",
",",
"interp",
"=",
"interp",
",",
"mod... | 39.482759 | 0.015345 |
def reverse(
self,
query,
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
kind=None,
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-reada... | [
"def",
"reverse",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"DEFAULT_SENTINEL",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
"kind",
"=",
"None",
",",
")",
":",
"if",
"exactly_one",
"is",
"DEFAULT_SENTINEL",
":",
"warnings",
".",
"warn",
"(",
"'... | 39.892308 | 0.002258 |
def search(self, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \
br_coord = (None, None), name = None, country = None, locality = None, \
region = None, postal_code = None, street_address = None,\
website_url = ... | [
"def",
"search",
"(",
"self",
",",
"category",
"=",
"None",
",",
"cuisine",
"=",
"None",
",",
"location",
"=",
"(",
"None",
",",
"None",
")",
",",
"radius",
"=",
"None",
",",
"tl_coord",
"=",
"(",
"None",
",",
"None",
")",
",",
"br_coord",
"=",
"... | 51.45283 | 0.032026 |
def make_list(item_or_items):
"""
Makes a list out of the given items.
Examples:
>>> make_list(1)
[1]
>>> make_list('str')
['str']
>>> make_list(('i', 'am', 'a', 'tuple'))
['i', 'am', 'a', 'tuple']
>>> print(make_list(None))
None
>>> # ... | [
"def",
"make_list",
"(",
"item_or_items",
")",
":",
"if",
"item_or_items",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"item_or_items",
",",
"list",
")",
":",
"return",
"item_or_items",
"if",
"hasattr",
"(",
"item_or_items",
",",
"'__iter__'"... | 27.46875 | 0.002198 |
def getLogger(name):
"""Create logger with custom exception() method
"""
def exception(self, msg, *args, **kwargs):
extra = kwargs.setdefault('extra', {})
extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG)
kwargs['exc_info'] = True
self.log(logging.ERROR, msg, *args, *... | [
"def",
"getLogger",
"(",
"name",
")",
":",
"def",
"exception",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"extra",
"=",
"kwargs",
".",
"setdefault",
"(",
"'extra'",
",",
"{",
"}",
")",
"extra",
"[",
"'exc_fullstac... | 36.583333 | 0.002222 |
def start_rest_api(host, port, connection, timeout, registry,
client_max_size=None):
"""Builds the web app, adds route handlers, and finally starts the app.
"""
loop = asyncio.get_event_loop()
connection.open()
app = web.Application(loop=loop, client_max_size=client_max_size)
... | [
"def",
"start_rest_api",
"(",
"host",
",",
"port",
",",
"connection",
",",
"timeout",
",",
"registry",
",",
"client_max_size",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"connection",
".",
"open",
"(",
")",
"app",
"="... | 37.215686 | 0.000513 |
def url(self) -> str:
"""Returns the full url requested."""
return urlunparse(
ParseResult(
self.scheme, self.host, self.path, '', self.query_string.decode('ascii'), '',
),
) | [
"def",
"url",
"(",
"self",
")",
"->",
"str",
":",
"return",
"urlunparse",
"(",
"ParseResult",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"path",
",",
"''",
",",
"self",
".",
"query_string",
".",
"decode",
"(",
"'ascii'",
... | 33.142857 | 0.012605 |
def dePeriod(arr):
"""make an array of periodic angles increase linearly"""
diff= arr-nu.roll(arr,1,axis=1)
w= diff < -6.
addto= nu.cumsum(w.astype(int),axis=1)
return arr+_TWOPI*addto | [
"def",
"dePeriod",
"(",
"arr",
")",
":",
"diff",
"=",
"arr",
"-",
"nu",
".",
"roll",
"(",
"arr",
",",
"1",
",",
"axis",
"=",
"1",
")",
"w",
"=",
"diff",
"<",
"-",
"6.",
"addto",
"=",
"nu",
".",
"cumsum",
"(",
"w",
".",
"astype",
"(",
"int",... | 33.166667 | 0.034314 |
def get_config(variable, default=None):
""" Get configuration variable for strudel.* packages
Args:
variable (str): name of the config variable
default: value to use of config variable not set
Returns:
variable value
Order of search:
1. stutils.CONFIG
2. settin... | [
"def",
"get_config",
"(",
"variable",
",",
"default",
"=",
"None",
")",
":",
"if",
"variable",
"in",
"CONFIG",
":",
"return",
"CONFIG",
"[",
"variable",
"]",
"if",
"hasattr",
"(",
"settings",
",",
"variable",
")",
":",
"return",
"getattr",
"(",
"settings... | 27.815789 | 0.000914 |
def parse(response):
"""Parse a postdata-style response format from the API into usable data"""
"""Split a a=1b=2c=3 string into a dictionary of pairs"""
tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]}
# The odd dummy parameter is of no use to us
if '... | [
"def",
"parse",
"(",
"response",
")",
":",
"\"\"\"Split a a=1b=2c=3 string into a dictionary of pairs\"\"\"",
"tokens",
"=",
"{",
"r",
"[",
"0",
"]",
":",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"[",
"r",
".",
"split",
"(",
"'='",
")",
"for",
"r",
"in",
... | 41.419355 | 0.008371 |
def centerize(src, dst_shape, margin_color=None):
"""Centerize image for specified image size
@param src: image to centerize
@param dst_shape: image shape (height, width) or (height, width, channel)
"""
if src.shape[:2] == dst_shape[:2]:
return src
centerized = np.zeros(dst_shape, dtype... | [
"def",
"centerize",
"(",
"src",
",",
"dst_shape",
",",
"margin_color",
"=",
"None",
")",
":",
"if",
"src",
".",
"shape",
"[",
":",
"2",
"]",
"==",
"dst_shape",
"[",
":",
"2",
"]",
":",
"return",
"src",
"centerized",
"=",
"np",
".",
"zeros",
"(",
... | 33.904762 | 0.001366 |
def targetpop(upper_density, coul, target_cf, slsp, n_tot):
"""restriction on finding the right populations that leave the crystal
field same"""
if upper_density < 0.503: return 0.
trypops=population_distri(upper_density, n_tot)
slsp.set_filling(trypops)
slsp.selfconsistency(coul,0)
efm_free... | [
"def",
"targetpop",
"(",
"upper_density",
",",
"coul",
",",
"target_cf",
",",
"slsp",
",",
"n_tot",
")",
":",
"if",
"upper_density",
"<",
"0.503",
":",
"return",
"0.",
"trypops",
"=",
"population_distri",
"(",
"upper_density",
",",
"n_tot",
")",
"slsp",
".... | 47.727273 | 0.009346 |
def version(**kwargs):
"""
Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True.
"""
retry = kwargs.get("retry")
if retry:
click.echo('Retrying publication of the same version...')
else:
click.ec... | [
"def",
"version",
"(",
"*",
"*",
"kwargs",
")",
":",
"retry",
"=",
"kwargs",
".",
"get",
"(",
"\"retry\"",
")",
"if",
"retry",
":",
"click",
".",
"echo",
"(",
"'Retrying publication of the same version...'",
")",
"else",
":",
"click",
".",
"echo",
"(",
"... | 36.666667 | 0.002083 |
def format_span_json(span):
"""Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span.
"""
span_json = {
'displayName': utils.get_truncatable_str(span.name)... | [
"def",
"format_span_json",
"(",
"span",
")",
":",
"span_json",
"=",
"{",
"'displayName'",
":",
"utils",
".",
"get_truncatable_str",
"(",
"span",
".",
"name",
")",
",",
"'spanId'",
":",
"span",
".",
"span_id",
",",
"'startTime'",
":",
"span",
".",
"start_ti... | 28.673077 | 0.000649 |
def upload_object(bucket_path, bucket, content='',
metadata=None, acl=None, cache_control=None,
content_type=None):
"""Upload an arbitrary object to an S3 bucket.
Parameters
----------
bucket_path : `str`
Destination path (also known as the key name) of the f... | [
"def",
"upload_object",
"(",
"bucket_path",
",",
"bucket",
",",
"content",
"=",
"''",
",",
"metadata",
"=",
"None",
",",
"acl",
"=",
"None",
",",
"cache_control",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"obj",
"=",
"bucket",
".",
"Obje... | 37.833333 | 0.000613 |
def depsignal(class_, signal_name, *, defer=False):
"""
Connect the decorated method or coroutine method to the addressed signal on
a class on which the service depends.
:param class_: A service class which is listed in the
:attr:`~.Meta.ORDER_AFTER` relationship.
:type class_: :... | [
"def",
"depsignal",
"(",
"class_",
",",
"signal_name",
",",
"*",
",",
"defer",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"add_handler_spec",
"(",
"f",
",",
"_depsignal_spec",
"(",
"class_",
",",
"signal_name",
",",
"f",
",",
"defe... | 40.52 | 0.000482 |
def join(self, formatted_texts):
""":type formatted_texts: list[FormattedText]"""
formatted_texts = list(formatted_texts) # so that after the first iteration elements are not lost if generator
for formatted_text in formatted_texts:
assert self._is_compatible(formatted_text), "Cannot... | [
"def",
"join",
"(",
"self",
",",
"formatted_texts",
")",
":",
"formatted_texts",
"=",
"list",
"(",
"formatted_texts",
")",
"# so that after the first iteration elements are not lost if generator",
"for",
"formatted_text",
"in",
"formatted_texts",
":",
"assert",
"self",
".... | 66 | 0.010684 |
def from_flag(cls, flag):
"""
Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` p... | [
"def",
"from_flag",
"(",
"cls",
",",
"flag",
")",
":",
"if",
"not",
"is_flag_set",
"(",
"flag",
")",
"or",
"'.'",
"not",
"in",
"flag",
":",
"return",
"None",
"parts",
"=",
"flag",
".",
"split",
"(",
"'.'",
")",
"if",
"parts",
"[",
"0",
"]",
"==",... | 43.428571 | 0.002146 |
def loads(
s,
record_store=None,
schema=None,
loader=from_json_compatible,
record_class=None # deprecated in favor of schema
):
""" Create a Record instance from a json serialized dictionary
:param s:
String with a json-serialized dictionary
:param record_s... | [
"def",
"loads",
"(",
"s",
",",
"record_store",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"loader",
"=",
"from_json_compatible",
",",
"record_class",
"=",
"None",
"# deprecated in favor of schema",
")",
":",
"if",
"record_class",
"is",
"not",
"None",
":",
... | 29.85 | 0.001622 |
def as_string(self, forsigning=False):
"""
>>> len(OmapiMessage().as_string(True)) >= 24
True
@type forsigning: bool
@rtype: bytes
@raises OmapiSizeLimitError:
"""
ret = OutBuffer()
self.serialize(ret, forsigning)
return ret.getvalue() | [
"def",
"as_string",
"(",
"self",
",",
"forsigning",
"=",
"False",
")",
":",
"ret",
"=",
"OutBuffer",
"(",
")",
"self",
".",
"serialize",
"(",
"ret",
",",
"forsigning",
")",
"return",
"ret",
".",
"getvalue",
"(",
")"
] | 20.416667 | 0.046875 |
def fw_version(self):
"""
Returns the firmware version of the sensor if available. Currently only
I2C/NXT sensors support this.
"""
(self._fw_version, value) = self.get_cached_attr_string(self._fw_version, 'fw_version')
return value | [
"def",
"fw_version",
"(",
"self",
")",
":",
"(",
"self",
".",
"_fw_version",
",",
"value",
")",
"=",
"self",
".",
"get_cached_attr_string",
"(",
"self",
".",
"_fw_version",
",",
"'fw_version'",
")",
"return",
"value"
] | 39.142857 | 0.010714 |
def update_coordinates(self, filename, update_port_locations=True):
"""Update the coordinates of this Compound from a file.
Parameters
----------
filename : str
Name of file from which to load coordinates. Supported file types
are the same as those supported by l... | [
"def",
"update_coordinates",
"(",
"self",
",",
"filename",
",",
"update_port_locations",
"=",
"True",
")",
":",
"if",
"update_port_locations",
":",
"xyz_init",
"=",
"self",
".",
"xyz",
"self",
"=",
"load",
"(",
"filename",
",",
"compound",
"=",
"self",
",",
... | 41 | 0.001907 |
def get_brand_by_id(cls, brand_id, **kwargs):
"""Find Brand
Return single instance of Brand by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_brand_by_id(brand_id, async=True)
... | [
"def",
"get_brand_by_id",
"(",
"cls",
",",
"brand_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_brand_by_id_with_http_inf... | 39.333333 | 0.002364 |
def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... | [
"def",
"factory",
"(",
"self",
",",
"data",
",",
"manager",
"=",
"None",
")",
":",
"# Make the syntax a little nicer for common cases.",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"and",
"len",
"(",
"data",
")",
"==",
"1",
"and",
"'type'",
"not",
"... | 36.545455 | 0.001616 |
def set_default_org(self, name):
""" set the default org for tasks by name key """
org = self.get_org(name)
self.unset_default_org()
org.config["default"] = True
self.set_org(org) | [
"def",
"set_default_org",
"(",
"self",
",",
"name",
")",
":",
"org",
"=",
"self",
".",
"get_org",
"(",
"name",
")",
"self",
".",
"unset_default_org",
"(",
")",
"org",
".",
"config",
"[",
"\"default\"",
"]",
"=",
"True",
"self",
".",
"set_org",
"(",
"... | 35.666667 | 0.009132 |
def interpolate2dStructuredCrossAvg(grid, mask, kernel=15, power=2):
'''
#######
usefull if large empty areas need to be filled
'''
vals = np.empty(shape=4, dtype=grid.dtype)
dist = np.empty(shape=4, dtype=np.uint16)
weights = np.empty(shape=4, dtype=np.float32)
valid = np.em... | [
"def",
"interpolate2dStructuredCrossAvg",
"(",
"grid",
",",
"mask",
",",
"kernel",
"=",
"15",
",",
"power",
"=",
"2",
")",
":",
"vals",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"4",
",",
"dtype",
"=",
"grid",
".",
"dtype",
")",
"dist",
"=",
"np"... | 31.307692 | 0.002387 |
def set_ifo_tag(self,ifo_tag,pass_to_command_line=True):
"""
Set the ifo tag that is passed to the analysis code.
@param ifo_tag: a string to identify one or more IFOs
@bool pass_to_command_line: add ifo-tag as a variable option.
"""
self.__ifo_tag = ifo_tag
if pass_to_command_line:
se... | [
"def",
"set_ifo_tag",
"(",
"self",
",",
"ifo_tag",
",",
"pass_to_command_line",
"=",
"True",
")",
":",
"self",
".",
"__ifo_tag",
"=",
"ifo_tag",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'ifo-tag'",
",",
"ifo_tag",
")"
] | 38.444444 | 0.011299 |
def unique(self, drop_dups=False):
''' Make this index unique, optionally dropping duplicate entries.
:param drop_dups: Drop duplicate objects while creating the unique \
index? Default to ``False``
'''
self.__unique = True
if drop_dups and pymongo.version_t... | [
"def",
"unique",
"(",
"self",
",",
"drop_dups",
"=",
"False",
")",
":",
"self",
".",
"__unique",
"=",
"True",
"if",
"drop_dups",
"and",
"pymongo",
".",
"version_tuple",
">=",
"(",
"2",
",",
"7",
",",
"5",
")",
":",
"# pragma: nocover",
"raise",
"BadInd... | 44.454545 | 0.01002 |
def handle(self, line_info):
"""Execute magic functions."""
ifun = line_info.ifun
the_rest = line_info.the_rest
cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
(ifun + " " + the_rest))
return cmd | [
"def",
"handle",
"(",
"self",
",",
"line_info",
")",
":",
"ifun",
"=",
"line_info",
".",
"ifun",
"the_rest",
"=",
"line_info",
".",
"the_rest",
"cmd",
"=",
"'%sget_ipython().magic(%r)'",
"%",
"(",
"line_info",
".",
"pre_whitespace",
",",
"(",
"ifun",
"+",
... | 42.714286 | 0.013115 |
def list(context, resource, **kwargs):
"""List all resources"""
data = utils.sanitize_kwargs(**kwargs)
id = data.pop('id', None)
subresource = data.pop('subresource', None)
if subresource:
uri = '%s/%s/%s/%s' % (context.dci_cs_api, resource, id, subresource)
else:
uri = '%s/%s' ... | [
"def",
"list",
"(",
"context",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"utils",
".",
"sanitize_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"id",
"=",
"data",
".",
"pop",
"(",
"'id'",
",",
"None",
")",
"subresource",
"=",
"data",... | 34.416667 | 0.002358 |
def handleFailure(self, test, err):
"""
Baseclass override. Called when a test fails.
If the test isn't going to be rerun again, then report the failure
to the nose test result.
:param test:
The test that has raised an error
:type test:
:class:`n... | [
"def",
"handleFailure",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"# pylint:disable=invalid-name",
"want_failure",
"=",
"self",
".",
"_handle_test_error_or_failure",
"(",
"test",
",",
"err",
")",
"if",
"not",
"want_failure",
"and",
"id",
"(",
"test",
")"... | 35.48 | 0.002195 |
def hacking_todo_format(physical_line, tokens):
"""Check for 'TODO()'.
OpenStack HACKING guide recommendation for TODO:
Include your name with TODOs as in "# TODO(termie)"
Okay: # TODO(sdague)
H101: # TODO fail
H101: # TODO
H101: # TODO (jogo) fail
Okay: TODO = 5
"""
# TODO(jog... | [
"def",
"hacking_todo_format",
"(",
"physical_line",
",",
"tokens",
")",
":",
"# TODO(jogo): make the following doctests pass:",
"# H101: #TODO(jogo fail",
"# H101: #TODO(jogo",
"# TODO(jogo): make this check docstrings as well (don't have to be at top",
"# of function)"... | 33.695652 | 0.001255 |
def SETPE(cpu, dest):
"""
Sets byte if parity even.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0)) | [
"def",
"SETPE",
"(",
"cpu",
",",
"dest",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"ITEBV",
"(",
"dest",
".",
"size",
",",
"cpu",
".",
"PF",
",",
"1",
",",
"0",
")",
")"
] | 26.125 | 0.009259 |
def close(self):
"""close conn"""
if not self._s or not hasattr(self._s, "close"):
return
try:
self._s.close()
except BaseException:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_s",
"or",
"not",
"hasattr",
"(",
"self",
".",
"_s",
",",
"\"close\"",
")",
":",
"return",
"try",
":",
"self",
".",
"_s",
".",
"close",
"(",
")",
"except",
"BaseException",
":",
"p... | 24.75 | 0.009756 |
def V_horiz_ellipsoidal(D, L, a, h, headonly=False):
r'''Calculates volume of a tank with ellipsoidal ends, according to [1]_.
.. math::
V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----------
D... | [
"def",
"V_horiz_ellipsoidal",
"(",
"D",
",",
"L",
",",
"a",
",",
"h",
",",
"headonly",
"=",
"False",
")",
":",
"R",
"=",
"0.5",
"*",
"D",
"Af",
"=",
"R",
"*",
"R",
"*",
"acos",
"(",
"(",
"R",
"-",
"h",
")",
"/",
"R",
")",
"-",
"(",
"R",
... | 27.23913 | 0.001541 |
def stop(self):
'''
Shutdown zmq listener.
'''
log.info('Stopping the zmq listener class')
self.sub.close()
self.ctx.term() | [
"def",
"stop",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Stopping the zmq listener class'",
")",
"self",
".",
"sub",
".",
"close",
"(",
")",
"self",
".",
"ctx",
".",
"term",
"(",
")"
] | 23.571429 | 0.011696 |
def _divide_and_round(a, b):
"""divide a by b and round result to the nearest integer
When the ratio is exactly half-way between two integers,
the even integer is returned.
"""
# Based on the reference implementation for divmod_near
# in Objects/longobject.c.
q, r = divmod(a, b)
# round... | [
"def",
"_divide_and_round",
"(",
"a",
",",
"b",
")",
":",
"# Based on the reference implementation for divmod_near",
"# in Objects/longobject.c.",
"q",
",",
"r",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"# round up if either r / b > 0.5, or r / b == 0.5 and q is odd.",
"# Th... | 33.833333 | 0.001597 |
def listBlocksParents(self):
"""
API to list block parents of multiple blocks. To be called by blockparents url with post call.
:param block_names: list of block names [block_name1, block_name2, ...] (Required). Mwx length 1000.
:type block_names: list
"""
try :
... | [
"def",
"listBlocksParents",
"(",
"self",
")",
":",
"try",
":",
"body",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
"data",
"=",
"cjson",
".",
"decode",
"(",
"body",
")",
"data",
"=",
"validateJSONInputNoCopy",
"(",
"\"block\"",
",",
"data",
","... | 57.454545 | 0.010373 |
def complementTab(seq=[]):
"""returns a list of complementary sequence without inversing it"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M',
'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't',
'c': 'g... | [
"def",
"complementTab",
"(",
"seq",
"=",
"[",
"]",
")",
":",
"complement",
"=",
"{",
"'A'",
":",
"'T'",
",",
"'C'",
":",
"'G'",
",",
"'G'",
":",
"'C'",
",",
"'T'",
":",
"'A'",
",",
"'R'",
":",
"'Y'",
",",
"'Y'",
":",
"'R'",
",",
"'M'",
":",
... | 44.772727 | 0.019881 |
def export_hcurves_by_imt_csv(
key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum):
"""
Export the curves of the given realization into CSV.
:param key: output_type and export_type
:param kind: a string with the kind of output (realization or statistics)
:param rlzs_assoc: a :class:... | [
"def",
"export_hcurves_by_imt_csv",
"(",
"key",
",",
"kind",
",",
"rlzs_assoc",
",",
"fname",
",",
"sitecol",
",",
"array",
",",
"oq",
",",
"checksum",
")",
":",
"nsites",
"=",
"len",
"(",
"sitecol",
")",
"fnames",
"=",
"[",
"]",
"for",
"imt",
",",
"... | 42.933333 | 0.000759 |
def _preloop_hook(self) -> None:
""" Start the alerter thread """
# This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears.
# Therefore this is the best place to start the alerter thread since there is no risk of it alerting
# before the prom... | [
"def",
"_preloop_hook",
"(",
"self",
")",
"->",
"None",
":",
"# This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears.",
"# Therefore this is the best place to start the alerter thread since there is no risk of it alerting",
"# before the prompt is ... | 64.1 | 0.009231 |
def _initialize_components(self, kwargs):
"""initialize the various components using the supplied \*\*kwargs
Parameters
----------
kwargs: dict
\*\*kwargs dict as received by __init__()
"""
tomodir = None
# load/assign grid
if 'tomodir' in k... | [
"def",
"_initialize_components",
"(",
"self",
",",
"kwargs",
")",
":",
"tomodir",
"=",
"None",
"# load/assign grid",
"if",
"'tomodir'",
"in",
"kwargs",
":",
"# load grid",
"tomodir",
"=",
"kwargs",
".",
"get",
"(",
"'tomodir'",
")",
"print",
"(",
"'importing t... | 33.777778 | 0.002131 |
def assign_texts(node, words, next_idx=0):
"""
Recursively assign the words to nodes by finding and
assigning strings to the leaves of a tree in left
to right order.
"""
if len(node.children) == 0:
node.text = words[next_idx]
return next_idx + 1
else:
for child in nod... | [
"def",
"assign_texts",
"(",
"node",
",",
"words",
",",
"next_idx",
"=",
"0",
")",
":",
"if",
"len",
"(",
"node",
".",
"children",
")",
"==",
"0",
":",
"node",
".",
"text",
"=",
"words",
"[",
"next_idx",
"]",
"return",
"next_idx",
"+",
"1",
"else",
... | 31 | 0.00241 |
def await_result(obj, timeout=None):
"""
Return the result of a `Future` object.
:param obj:
Value object.
:type obj: concurrent.futures.Future | object
:param timeout:
The number of seconds to wait for the result if the future isn't done.
If None, then there is no limit on... | [
"def",
"await_result",
"(",
"obj",
",",
"timeout",
"=",
"None",
")",
":",
"from",
"concurrent",
".",
"futures",
"import",
"Future",
"return",
"obj",
".",
"result",
"(",
"timeout",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Future",
")",
"else",
"obj"
] | 25.296296 | 0.00141 |
def getQwordAtOffset(self, offset):
"""
Returns a C{QWORD} from a given offset.
@type offset: int
@param offset: The offset to get the C{QWORD} from.
@rtype: L{QWORD}
@return: The L{QWORD} obtained at the given offset.
"""
return datatyp... | [
"def",
"getQwordAtOffset",
"(",
"self",
",",
"offset",
")",
":",
"return",
"datatypes",
".",
"QWORD",
".",
"parse",
"(",
"utils",
".",
"ReadData",
"(",
"self",
".",
"getDataAtOffset",
"(",
"offset",
",",
"8",
")",
")",
")"
] | 34 | 0.015625 |
def parse_class(self, tup_tree):
"""
Parse CLASS element returning a CIMClass if the parse was successful.
::
<!ELEMENT CLASS (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY |
PROPERTY.REFERENCE)*, METHOD*)>
<!ATTLIST CLASS
... | [
"def",
"parse_class",
"(",
"self",
",",
"tup_tree",
")",
":",
"# Doesn't check ordering of elements, but it's not very important",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'CLASS'",
",",
"(",
"'NAME'",
",",
")",
",",
"(",
"'SUPERCLASS'",
",",
")",
",",
... | 39.09375 | 0.00156 |
def toggle_codecompletion(self, checked):
"""Toggle automatic code completion"""
self.shell.set_codecompletion_auto(checked)
self.set_option('codecompletion/auto', checked) | [
"def",
"toggle_codecompletion",
"(",
"self",
",",
"checked",
")",
":",
"self",
".",
"shell",
".",
"set_codecompletion_auto",
"(",
"checked",
")",
"self",
".",
"set_option",
"(",
"'codecompletion/auto'",
",",
"checked",
")"
] | 49 | 0.01005 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.