text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def live_chat_banner(context):
""" Display any available live chats as advertisements.
"""
context = copy(context)
# Find any upcoming or current live chat. The Chat date must be less than 5
# days away, or currently in progress.
oldchat = LiveChat.chat_finder.get_last_live_chat()
if oldc... | [
"def",
"live_chat_banner",
"(",
"context",
")",
":",
"context",
"=",
"copy",
"(",
"context",
")",
"# Find any upcoming or current live chat. The Chat date must be less than 5",
"# days away, or currently in progress.",
"oldchat",
"=",
"LiveChat",
".",
"chat_finder",
".",
"get... | 32.560976 | 15.780488 |
def send_cons3rt_agent_logs(self):
"""Sends a Slack message with an attachment for each cons3rt agent log
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log... | [
"def",
"send_cons3rt_agent_logs",
"(",
"self",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.send_cons3rt_agent_logs'",
")",
"log",
".",
"debug",
"(",
"'Searching for log files in directory: {d}'",
".",
"format",
"(",
"... | 48.75 | 25.291667 |
def _prepare_statement(sql_statement, parameters):
"""
Prepare the specified SQL statement, replacing the placeholders by the
value of the given parameters
@param sql_statement: the string expression of a SQL statement.
@param parameters: a dictionary of parameters where the ke... | [
"def",
"_prepare_statement",
"(",
"sql_statement",
",",
"parameters",
")",
":",
"placehoolders",
"=",
"RdbmsConnection",
".",
"_get_placeholders",
"(",
"sql_statement",
",",
"parameters",
")",
"for",
"(",
"variable_name",
",",
"(",
"variable_type",
",",
"variable_va... | 46.517241 | 29.827586 |
def path(self, filename=None, ext='tsv', digest=False, shard=False, encoding='utf-8'):
"""
Return the path for this class with a certain set of parameters.
`ext` sets the extension of the file.
If `hash` is true, the filename (w/o extenstion) will be hashed.
If `shard` is true, t... | [
"def",
"path",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"ext",
"=",
"'tsv'",
",",
"digest",
"=",
"False",
",",
"shard",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"self",
".",
"BASE",
"is",
"NotImplemented",
":",
"raise",
... | 41.44 | 20.64 |
def parse_template(template_str):
"""
Parse the SAM template.
:param template_str: A packaged YAML or json CloudFormation template
:type template_str: str
:return: Dictionary with keys defined in the template
:rtype: dict
"""
try:
# PyYAML doesn't support json as well as it shou... | [
"def",
"parse_template",
"(",
"template_str",
")",
":",
"try",
":",
"# PyYAML doesn't support json as well as it should, so if the input",
"# is actually just json it is better to parse it with the standard",
"# json parser.",
"return",
"json",
".",
"loads",
"(",
"template_str",
",... | 41.444444 | 23.444444 |
def patch(save=True, tensorboardX=tensorboardX_loaded):
"""Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb.
We save the tfevents files and graphs to wandb by default.
Arguments:
save, default: True - Passing False will skip sending events.
... | [
"def",
"patch",
"(",
"save",
"=",
"True",
",",
"tensorboardX",
"=",
"tensorboardX_loaded",
")",
":",
"global",
"Summary",
",",
"Event",
"if",
"tensorboardX",
":",
"tensorboard_module",
"=",
"\"tensorboardX.writer\"",
"if",
"tensorflow_loaded",
":",
"wandb",
".",
... | 50.054545 | 22.6 |
def create_spot(self,
price,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False,
timeout=No... | [
"def",
"create_spot",
"(",
"self",
",",
"price",
",",
"instance_type",
"=",
"'default'",
",",
"tags",
"=",
"None",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False"... | 38.819672 | 17.311475 |
def get_local_references(tb, max_string_length=1000):
"""
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
if 'self' in tb.tb_frame.f_locals:
_locals = [('self', repr(tb.tb_frame.f_local... | [
"def",
"get_local_references",
"(",
"tb",
",",
"max_string_length",
"=",
"1000",
")",
":",
"if",
"'self'",
"in",
"tb",
".",
"tb_frame",
".",
"f_locals",
":",
"_locals",
"=",
"[",
"(",
"'self'",
",",
"repr",
"(",
"tb",
".",
"tb_frame",
".",
"f_locals",
... | 31.4 | 18.5 |
def load_csr(pem_path):
"""Load CSR from PEM encoded file"""
with open(pem_path, "rb") as f:
return cryptography.x509.load_pem_x509_csr(
data=f.read(), backend=cryptography.hazmat.backends.default_backend()
) | [
"def",
"load_csr",
"(",
"pem_path",
")",
":",
"with",
"open",
"(",
"pem_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"cryptography",
".",
"x509",
".",
"load_pem_x509_csr",
"(",
"data",
"=",
"f",
".",
"read",
"(",
")",
",",
"backend",
"=",
"cr... | 39.833333 | 17.5 |
def send_results(self, result):
"""
Upload a result object to server.
If resultConverter has been provided, use it to convert result object to format accepted
by the server.
If needed, use testcase_converter to convert tc metadata in result to suitable format.
returns ne... | [
"def",
"send_results",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"result_converter",
":",
"print",
"(",
"self",
".",
"result_converter",
"(",
"result",
")",
")",
"else",
":",
"print",
"(",
"result",
")"
] | 37.076923 | 19.384615 |
def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall("[@format]")[0]
raw_format = ds.attrib['format']
try:
self.documentFormatVersion = int(raw_format)
except ValueError:
#... | [
"def",
"readVersion",
"(",
"self",
")",
":",
"ds",
"=",
"self",
".",
"root",
".",
"findall",
"(",
"\"[@format]\"",
")",
"[",
"0",
"]",
"raw_format",
"=",
"ds",
".",
"attrib",
"[",
"'format'",
"]",
"try",
":",
"self",
".",
"documentFormatVersion",
"=",
... | 35.916667 | 14.166667 |
def cli(obj, roles):
"""List users."""
client = obj['client']
query = [('roles', r) for r in roles]
if obj['output'] == 'json':
r = client.http.get('/users', query)
click.echo(json.dumps(r['users'], sort_keys=True, indent=4, ensure_ascii=False))
else:
timezone = obj['timezon... | [
"def",
"cli",
"(",
"obj",
",",
"roles",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"query",
"=",
"[",
"(",
"'roles'",
",",
"r",
")",
"for",
"r",
"in",
"roles",
"]",
"if",
"obj",
"[",
"'output'",
"]",
"==",
"'json'",
":",
"r",
"=",
... | 47.133333 | 31.333333 |
def create_product (self, name, location='GLO', unit='kg', **kwargs):
"""
Create a new product in the model database
"""
new_product = item_factory(name=name, location=location, unit=unit, type='product', **kwargs)
if not self.exists_in_database(new_product['code']):
... | [
"def",
"create_product",
"(",
"self",
",",
"name",
",",
"location",
"=",
"'GLO'",
",",
"unit",
"=",
"'kg'",
",",
"*",
"*",
"kwargs",
")",
":",
"new_product",
"=",
"item_factory",
"(",
"name",
"=",
"name",
",",
"location",
"=",
"location",
",",
"unit",
... | 36.733333 | 22.333333 |
def _jdn(self):
"""Return the Julian date number for the given date."""
if self._last_updated == "gdate":
return conv.gdate_to_jdn(self.gdate)
return conv.hdate_to_jdn(self.hdate) | [
"def",
"_jdn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_updated",
"==",
"\"gdate\"",
":",
"return",
"conv",
".",
"gdate_to_jdn",
"(",
"self",
".",
"gdate",
")",
"return",
"conv",
".",
"hdate_to_jdn",
"(",
"self",
".",
"hdate",
")"
] | 42.2 | 7.6 |
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
... | [
"def",
"get_api_ruler",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_ruler",
"is",
"None",
":",
"try",
":",
"self",
".",
"api_ruler",
"=",
"autoclass",
"(",
"'org.clulab.reach.export.apis.ApiRuler'",
")",
"except",
"JavaException",
"as",
"e",
":",
"raise",
... | 34.8 | 15.333333 |
def _stdout_level(self):
"""Returns the level that stdout runs at"""
for level, consumer in self.consumers:
if consumer is sys.stdout:
return level
return self.FATAL | [
"def",
"_stdout_level",
"(",
"self",
")",
":",
"for",
"level",
",",
"consumer",
"in",
"self",
".",
"consumers",
":",
"if",
"consumer",
"is",
"sys",
".",
"stdout",
":",
"return",
"level",
"return",
"self",
".",
"FATAL"
] | 35.333333 | 8.5 |
def model_results(self) -> str:
"""
Reads the model.results file
"""
with open(os.path.join(self.directory, "model.results")) as f:
return f.read() | [
"def",
"model_results",
"(",
"self",
")",
"->",
"str",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"\"model.results\"",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | 31 | 9.333333 |
def dates_to_delete(dates,
years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY,
now=None):
"""
Return a set of date that should be deleted, out of ``dates``.
See ``to_keep`` for a description of arguments.
"""
dates = set(dates)
return dates - dates... | [
"def",
"dates_to_delete",
"(",
"dates",
",",
"years",
"=",
"0",
",",
"months",
"=",
"0",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"firstweekday",
"=",
"SATURDAY",
",",
"now",
"=",
"None",
")",
":",
"dates",
"=",
"set",
"(",
"dates",
")... | 39.230769 | 17.076923 |
def simple_est_prec(data, freq_min=0.0, freq_max=1.0, n_particles=6000, return_all=False):
"""
Estimates a simple precession (cos²) from experimental data.
Note that this model is mainly for testing purposes, as it does not
consider the phase or amplitude of precession, leaving only the frequency.
... | [
"def",
"simple_est_prec",
"(",
"data",
",",
"freq_min",
"=",
"0.0",
",",
"freq_max",
"=",
"1.0",
",",
"n_particles",
"=",
"6000",
",",
"return_all",
"=",
"False",
")",
":",
"model",
"=",
"BinomialModel",
"(",
"SimplePrecessionModel",
"(",
"freq_min",
")",
... | 37.333333 | 22.708333 |
def _update_remote_children(remote_parent, children):
"""
Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children
"""
nam... | [
"def",
"_update_remote_children",
"(",
"remote_parent",
",",
"children",
")",
":",
"name_to_child",
"=",
"_name_to_child_map",
"(",
"children",
")",
"for",
"remote_child",
"in",
"remote_parent",
".",
"children",
":",
"local_child",
"=",
"name_to_child",
".",
"get",
... | 48.909091 | 18 |
def who_likes(obj):
"""
Usage:
{% who_likes obj as var %}
"""
return Like.objects.filter(
receiver_content_type=ContentType.objects.get_for_model(obj),
receiver_object_id=obj.pk
) | [
"def",
"who_likes",
"(",
"obj",
")",
":",
"return",
"Like",
".",
"objects",
".",
"filter",
"(",
"receiver_content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
",",
"receiver_object_id",
"=",
"obj",
".",
"pk",
")"
] | 23.888889 | 15.222222 |
def _language_in_list(language, targets, min_score=80):
"""
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iter... | [
"def",
"_language_in_list",
"(",
"language",
",",
"targets",
",",
"min_score",
"=",
"80",
")",
":",
"matched",
"=",
"best_match",
"(",
"language",
",",
"targets",
",",
"min_score",
"=",
"min_score",
")",
"return",
"matched",
"[",
"1",
"]",
">",
"0"
] | 43.3 | 20.9 |
def comments_2(self, value=None):
"""Corresponds to IDD Field `comments_2`
Args:
value (str): value for IDD Field `comments_2`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
... | [
"def",
"comments_2",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type str '... | 34.826087 | 20.956522 |
def _step7func(self, samples, force, ipyclient):
""" Step 7: Filter and write output files """
## Get sample objects from list of strings
samples = _get_samples(self, samples)
if self._headers:
print("\n Step 7: Filter and write output files for {} Samples".\
... | [
"def",
"_step7func",
"(",
"self",
",",
"samples",
",",
"force",
",",
"ipyclient",
")",
":",
"## Get sample objects from list of strings",
"samples",
"=",
"_get_samples",
"(",
"self",
",",
"samples",
")",
"if",
"self",
".",
"_headers",
":",
"print",
"(",
"\"\\n... | 43.977273 | 23.045455 |
def _run(self, url_path, headers=None, **kwargs):
"""
Requests API
"""
url = self._construct_url(url_path)
payload = kwargs
payload.update({'api_token': self.api_token})
return self._make_request(url, payload, headers) | [
"def",
"_run",
"(",
"self",
",",
"url_path",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"_construct_url",
"(",
"url_path",
")",
"payload",
"=",
"kwargs",
"payload",
".",
"update",
"(",
"{",
"'api_token'",
... | 26.7 | 15.7 |
def get(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True,
encoding='utf-8', params=None, stream=False):
"""
模拟http get请求
:param url: 访问Url
:param headers: 请求头
:param cookies: 请求cookies
:param timeout: 超时时间
... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"timeout",
"=",
"60",
",",
"verify",
"=",
"False",
",",
"proxies",
"=",
"None",
",",
"allow_redirects",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'"... | 43.684211 | 19.578947 |
def read(filename, mmap=False):
"""
Return the sample rate (in samples/sec) and data from a WAV file
Parameters
----------
filename : string or open file handle
Input wav file.
mmap : bool, optional
Whether to read data as memory mapped.
Only to be used on real files (De... | [
"def",
"read",
"(",
"filename",
",",
"mmap",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"filename",
",",
"'read'",
")",
":",
"fid",
"=",
"filename",
"mmap",
"=",
"False",
"else",
":",
"fid",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"try",... | 29.880597 | 18.686567 |
def reset_status(self):
"""Set all scenarios' status to empty in the table."""
for row in range(self.table.rowCount()):
status_item = self.table.item(row, 1)
status_item.setText(self.tr('')) | [
"def",
"reset_status",
"(",
"self",
")",
":",
"for",
"row",
"in",
"range",
"(",
"self",
".",
"table",
".",
"rowCount",
"(",
")",
")",
":",
"status_item",
"=",
"self",
".",
"table",
".",
"item",
"(",
"row",
",",
"1",
")",
"status_item",
".",
"setTex... | 45.2 | 7.6 |
def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""... | [
"def",
"get_account",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"'status'",
"return",
"self",
".",
"account",
".",
"getObject",
"(",
"id",
"=",
"a... | 37.083333 | 19.75 |
def _query_systemstate(self):
"""Query the maximum number of connections supported by this adapter
"""
def status_filter_func(event):
if event.command_class == 3 and event.command == 0:
return True
return False
try:
response = self._... | [
"def",
"_query_systemstate",
"(",
"self",
")",
":",
"def",
"status_filter_func",
"(",
"event",
")",
":",
"if",
"event",
".",
"command_class",
"==",
"3",
"and",
"event",
".",
"command",
"==",
"0",
":",
"return",
"True",
"return",
"False",
"try",
":",
"res... | 33.692308 | 24.653846 |
def tcc_pos(text: str) -> Set[int]:
"""
TCC positions
:param str text: text to be tokenized to character clusters
:return: list of the end of subwords
"""
if not text or not isinstance(text, str):
return set()
p_set = set()
p = 0
for w in tcc(text):
p += len(w)
... | [
"def",
"tcc_pos",
"(",
"text",
":",
"str",
")",
"->",
"Set",
"[",
"int",
"]",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"set",
"(",
")",
"p_set",
"=",
"set",
"(",
")",
"p",
"=",
"0",
"fo... | 21.125 | 18.25 |
def wr_xlsx(self, fout_xlsx):
"""Print grouped GOEA results into an xlsx file."""
objwr = WrXlsxSortedGos("GOEA", self.sortobj)
#### fld2fmt['ratio_in_study'] = '{:>8}'
#### fld2fmt['ratio_in_pop'] = '{:>12}'
#### ntfld2wbfmtdict = {
# ntfld_wbfmt = {
# 'ratio... | [
"def",
"wr_xlsx",
"(",
"self",
",",
"fout_xlsx",
")",
":",
"objwr",
"=",
"WrXlsxSortedGos",
"(",
"\"GOEA\"",
",",
"self",
".",
"sortobj",
")",
"#### fld2fmt['ratio_in_study'] = '{:>8}'",
"#### fld2fmt['ratio_in_pop'] = '{:>12}'",
"#### ntfld2wbfmtdict = {",
"# ntfld_wbfmt =... | 43.470588 | 11.411765 |
def _rewrite_error_path(self, error, offset=0):
"""
Recursively rewrites the error path to correctly represent logic errors
"""
if error.is_logic_error:
self._rewrite_logic_error_path(error, offset)
elif error.is_group_error:
self._rewrite_group_error_path... | [
"def",
"_rewrite_error_path",
"(",
"self",
",",
"error",
",",
"offset",
"=",
"0",
")",
":",
"if",
"error",
".",
"is_logic_error",
":",
"self",
".",
"_rewrite_logic_error_path",
"(",
"error",
",",
"offset",
")",
"elif",
"error",
".",
"is_group_error",
":",
... | 41 | 11.75 |
def get_dict(self):
"""
Convert all rules to dict and return them.
"""
out = {
property_name: getattr(self, property_name)
for property_name in self._property_names
}
if "frequency" in out:
out["frequency"] = int(out["frequency"])
... | [
"def",
"get_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"property_name",
":",
"getattr",
"(",
"self",
",",
"property_name",
")",
"for",
"property_name",
"in",
"self",
".",
"_property_names",
"}",
"if",
"\"frequency\"",
"in",
"out",
":",
"out",
"[",
"\... | 24.846154 | 18.384615 |
def getPartition(self, seq, p, q):
"""Returns the pth partition of q partitions of seq."""
# Test for error conditions here
if p<0 or p>=q:
print "No partition exists."
return
remainder = len(seq)%q
basesize = len(seq)//q
hi = []
... | [
"def",
"getPartition",
"(",
"self",
",",
"seq",
",",
"p",
",",
"q",
")",
":",
"# Test for error conditions here",
"if",
"p",
"<",
"0",
"or",
"p",
">=",
"q",
":",
"print",
"\"No partition exists.\"",
"return",
"remainder",
"=",
"len",
"(",
"seq",
")",
"%"... | 29.535714 | 15.071429 |
def _compute_counts(event, time, order=None):
"""Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order ... | [
"def",
"_compute_counts",
"(",
"event",
",",
"time",
",",
"order",
"=",
"None",
")",
":",
"n_samples",
"=",
"event",
".",
"shape",
"[",
"0",
"]",
"if",
"order",
"is",
"None",
":",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"="... | 24.641791 | 20.940299 |
def url_value_preprocessor(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a url value preprocessor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.url_value_preprocessor
def value_preprocessor(endpoint... | [
"def",
"url_value_preprocessor",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"self",
".",
"url_value_preprocessors",
"[",
"name",
"]",
".",
"append",
"(",
"func",
")",
"return",
... | 33 | 21.846154 |
def update_credentials(self, aws_access_key_id, aws_secret_access_key):
''' Update credentials '''
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key | [
"def",
"update_credentials",
"(",
"self",
",",
"aws_access_key_id",
",",
"aws_secret_access_key",
")",
":",
"self",
".",
"aws_access_key_id",
"=",
"aws_access_key_id",
"self",
".",
"aws_secret_access_key",
"=",
"aws_secret_access_key"
] | 53.25 | 16.25 |
def add_to_category(self, category, name, action):
"""
Adds given action to given category.
:param category: Category to store the action.
:type category: unicode
:param name: Action name.
:type name: unicode
:param action: Action object.
:type action: QA... | [
"def",
"add_to_category",
"(",
"self",
",",
"category",
",",
"name",
",",
"action",
")",
":",
"category",
"=",
"self",
".",
"get_category",
"(",
"category",
",",
"vivify",
"=",
"True",
")",
"if",
"not",
"isinstance",
"(",
"category",
",",
"dict",
")",
... | 30.47619 | 15.809524 |
def when(obj, strict=None):
"""Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_... | [
"def",
"when",
"(",
"obj",
",",
"strict",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"get_obj",
"(",
"obj",
")",
"if",
"strict",
"is",
"None",
":",
"strict",
"=",
"True",
"theMock",
"=",
"_get_mock",
... | 35.571429 | 25.467532 |
def walk(self) -> Iterable['MessageContent']:
"""Iterate through the message and all its nested sub-parts in the
order they occur.
"""
if self.body.has_nested:
return chain([self], *(part.walk() for part in self.body.nested))
else:
return [self] | [
"def",
"walk",
"(",
"self",
")",
"->",
"Iterable",
"[",
"'MessageContent'",
"]",
":",
"if",
"self",
".",
"body",
".",
"has_nested",
":",
"return",
"chain",
"(",
"[",
"self",
"]",
",",
"*",
"(",
"part",
".",
"walk",
"(",
")",
"for",
"part",
"in",
... | 33.555556 | 16.333333 |
def exception(self, timeout=None):
"""Return a exception raised by the call that the future
represents.
:param timeout: The number of seconds to wait for the exception
if the future has not been completed. None, the default,
sets no limit.
:returns: The exception ... | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# with self.__condition:",
"if",
"self",
".",
"__state",
"==",
"FINISHED",
":",
"return",
"self",
".",
"__exception",
"self",
".",
"__condition",
".",
"wait",
"(",
"timeout",
")",
"if... | 38.761905 | 16.333333 |
def partitions(collection):
"""Generate all set partitions of a collection.
Example:
>>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE
[[[0, 1, 2]],
[[0], [1, 2]],
[[0, 1], [2]],
[[1], [0, 2]],
[[0], [1], [2]]]
"""
collection = list(col... | [
"def",
"partitions",
"(",
"collection",
")",
":",
"collection",
"=",
"list",
"(",
"collection",
")",
"# Special cases",
"if",
"not",
"collection",
":",
"return",
"if",
"len",
"(",
"collection",
")",
"==",
"1",
":",
"yield",
"[",
"collection",
"]",
"return"... | 25.153846 | 19.230769 |
def som_train(som_pointer, data, epochs, autostop):
"""!
@brief Trains self-organized feature map (SOM) using CCORE pyclustering library.
@param[in] data (list): Input data - list of points where each point is represented by list of features, for example coordinates.
@param[in] epochs (uint): Numb... | [
"def",
"som_train",
"(",
"som_pointer",
",",
"data",
",",
"epochs",
",",
"autostop",
")",
":",
"pointer_data",
"=",
"package_builder",
"(",
"data",
",",
"c_double",
")",
".",
"create",
"(",
")",
"ccore",
"=",
"ccore_library",
".",
"get",
"(",
")",
"ccore... | 44 | 29.764706 |
def receive_message(queue, region, num=1, opts=None, user=None):
'''
Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : N... | [
"def",
"receive_message",
"(",
"queue",
",",
"region",
",",
"num",
"=",
"1",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'Messages'",
":",
"None",
",",
"}",
"queues",
"=",
"list_queues",
"(",
"region",
",",
"opts... | 24.619048 | 24.809524 |
def error(errors):
"""Create error element."""
e_tree, e_oaipmh = envelope()
for code, message in errors:
e_error = SubElement(e_oaipmh, etree.QName(NS_OAIPMH, 'error'))
e_error.set('code', code)
e_error.text = message
return e_tree | [
"def",
"error",
"(",
"errors",
")",
":",
"e_tree",
",",
"e_oaipmh",
"=",
"envelope",
"(",
")",
"for",
"code",
",",
"message",
"in",
"errors",
":",
"e_error",
"=",
"SubElement",
"(",
"e_oaipmh",
",",
"etree",
".",
"QName",
"(",
"NS_OAIPMH",
",",
"'error... | 33.125 | 13.5 |
def run(self, timeout = 0):
"""
Run a proactor loop and return new socket events. Timeout is a timedelta
object, 0 if active coros or None.
epoll timeout param is a integer number of seconds.
"""
ptimeout = float(
timeout.microseconds/1000000+timeout.... | [
"def",
"run",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"ptimeout",
"=",
"float",
"(",
"timeout",
".",
"microseconds",
"/",
"1000000",
"+",
"timeout",
".",
"seconds",
"if",
"timeout",
"else",
"(",
"self",
".",
"resolution",
"if",
"timeout",
"is"... | 40.162162 | 16.864865 |
def parse_rpm_output(output, tags=None, separator=';'):
"""
Parse output of the rpm query.
:param output: list, decoded output (str) from the rpm subprocess
:param tags: list, str fields used for query output
:return: list, dicts describing each rpm package
"""
if tags is None:
tag... | [
"def",
"parse_rpm_output",
"(",
"output",
",",
"tags",
"=",
"None",
",",
"separator",
"=",
"';'",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"image_component_rpm_tags",
"def",
"field",
"(",
"tag",
")",
":",
"\"\"\"\n Get a field value by na... | 25.9 | 17.466667 |
def _create_optimizer(self, X, y, status):
"""Samples are ordered by relevance"""
if self.optimizer is None:
self.optimizer = 'avltree'
times, ranks = y
if self.optimizer == 'simple':
optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=sel... | [
"def",
"_create_optimizer",
"(",
"self",
",",
"X",
",",
"y",
",",
"status",
")",
":",
"if",
"self",
".",
"optimizer",
"is",
"None",
":",
"self",
".",
"optimizer",
"=",
"'avltree'",
"times",
",",
"ranks",
"=",
"y",
"if",
"self",
".",
"optimizer",
"=="... | 55.423077 | 29.807692 |
def gen(self, init_state=None):
"""
Starting either with a naive BEGIN state, or the provided `init_state`
(as a tuple), return a generator that will yield successive items
until the chain reaches the END state.
"""
state = init_state or (BEGIN,) * self.state_size
... | [
"def",
"gen",
"(",
"self",
",",
"init_state",
"=",
"None",
")",
":",
"state",
"=",
"init_state",
"or",
"(",
"BEGIN",
",",
")",
"*",
"self",
".",
"state_size",
"while",
"True",
":",
"next_word",
"=",
"self",
".",
"move",
"(",
"state",
")",
"if",
"ne... | 40.083333 | 12.416667 |
def get_deployment_by_name(self, service_name, deployment_name):
'''
Returns configuration information, status, and system properties for a
deployment.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
'''
... | [
"def",
"get_deployment_by_name",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
")",
":",
"_validate_not_none",
"(",
"'service_name'",
",",
"service_name",
")",
"_validate_not_none",
"(",
"'deployment_name'",
",",
"deployment_name",
")",
"return",
"self",
"... | 36 | 18.5 |
def lowpass_cheby2(samples, freq, sr, maxorder=12):
# type: (np.ndarray, float, int, int) -> np.ndarray
"""
Cheby2-Lowpass Filter
Filter data by passing data only below a certain frequency.
The main purpose of this cheby2 filter is downsampling.
This method will iteratively design a filter... | [
"def",
"lowpass_cheby2",
"(",
"samples",
",",
"freq",
",",
"sr",
",",
"maxorder",
"=",
"12",
")",
":",
"# type: (np.ndarray, float, int, int) -> np.ndarray",
"if",
"freq",
">",
"sr",
"*",
"0.5",
":",
"raise",
"ValueError",
"(",
"\"Can't filter freq. above nyquist\""... | 39.363636 | 18 |
def stem(self, words):
"""
Use the porter stemmer to generate consistent forms of
words, e.g.::
from walrus.search.utils import PorterStemmer
stemmer = PorterStemmer()
for word in ['faith', 'faiths', 'faithful']:
print s.stem(word, 0, len(word... | [
"def",
"stem",
"(",
"self",
",",
"words",
")",
":",
"stemmer",
"=",
"PorterStemmer",
"(",
")",
"_stem",
"=",
"stemmer",
".",
"stem",
"for",
"word",
"in",
"words",
":",
"yield",
"_stem",
"(",
"word",
",",
"0",
",",
"len",
"(",
"word",
")",
"-",
"1... | 28.473684 | 16.263158 |
def section(self, section):
""" Returns a list of tuples of (option, value) for the section """
# check if the named section exists
if self.config.has_section(section):
return (True, self.config.items(section))
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"section",
"(",
"self",
",",
"section",
")",
":",
"# check if the named section exists",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"return",
"(",
"True",
",",
"self",
".",
"config",
".",
"items",
"(",
"section",
")",... | 51.166667 | 9.666667 |
def perform_content_negotiation(self, request, force=False):
"""
Determine which renderer and media type to use render the response.
"""
renderers = self.get_renderers()
conneg = self.get_content_negotiator()
try:
return conneg.select_renderer(request, render... | [
"def",
"perform_content_negotiation",
"(",
"self",
",",
"request",
",",
"force",
"=",
"False",
")",
":",
"renderers",
"=",
"self",
".",
"get_renderers",
"(",
")",
"conneg",
"=",
"self",
".",
"get_content_negotiator",
"(",
")",
"try",
":",
"return",
"conneg",... | 35.384615 | 19.076923 |
def inp(i):
"""
Input: {
text - text to print
}
Output: {
return - return code = 0
string - input string
}
"""
t=i['text']
if con_encoding=='':
x=sys.stdin.encoding
if x==None:
b=t.encode... | [
"def",
"inp",
"(",
"i",
")",
":",
"t",
"=",
"i",
"[",
"'text'",
"]",
"if",
"con_encoding",
"==",
"''",
":",
"x",
"=",
"sys",
".",
"stdin",
".",
"encoding",
"if",
"x",
"==",
"None",
":",
"b",
"=",
"t",
".",
"encode",
"(",
")",
"else",
":",
"... | 20.179487 | 19.923077 |
def cmd_usercheck(username, no_cache, verbose, wopen):
"""Check if the given username exists on various social networks and other popular sites.
\b
$ habu.usercheck portantier
{
"aboutme": "https://about.me/portantier",
"disqus": "https://disqus.com/by/portantier/",
"github": "h... | [
"def",
"cmd_usercheck",
"(",
"username",
",",
"no_cache",
",",
"verbose",
",",
"wopen",
")",
":",
"habucfg",
"=",
"loadcfg",
"(",
")",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"... | 35.489362 | 21.617021 |
def _prompt(pre_prompt, items, post_prompt, default, indexed, stream):
'''
Prompt once.
If you want the default displayed, put a format {} into the
post_prompt string (like 'select one [{}]: ')
'''
# try to sub in the default if provided
if default is not None:
if '{}' in pre_prompt:... | [
"def",
"_prompt",
"(",
"pre_prompt",
",",
"items",
",",
"post_prompt",
",",
"default",
",",
"indexed",
",",
"stream",
")",
":",
"# try to sub in the default if provided",
"if",
"default",
"is",
"not",
"None",
":",
"if",
"'{}'",
"in",
"pre_prompt",
":",
"pre_pr... | 29.930233 | 15.604651 |
def handle_cdata(pos, window, charpat, stopchars):
'''
Return (result, new_position) tuple.
Result is cdata string if possible and None if more input is needed
Or of course bad syntax can raise a RuntimeError
'''
cdata = ''
cursor = start = pos
try:
while True:
while... | [
"def",
"handle_cdata",
"(",
"pos",
",",
"window",
",",
"charpat",
",",
"stopchars",
")",
":",
"cdata",
"=",
"''",
"cursor",
"=",
"start",
"=",
"pos",
"try",
":",
"while",
"True",
":",
"while",
"charpat",
".",
"match",
"(",
"window",
"[",
"cursor",
"]... | 45.22807 | 19.052632 |
def convertNeutral2Xml(infile, outfile=None):
"""Convert Neutral file format to Dolfin XML."""
f = open(infile, "r")
lines = f.readlines()
f.close()
ncoords = int(lines[0])
fdolf_coords = []
for i in range(1, ncoords + 1):
x, y, z = lines[i].split()
fdolf_coords.append([flo... | [
"def",
"convertNeutral2Xml",
"(",
"infile",
",",
"outfile",
"=",
"None",
")",
":",
"f",
"=",
"open",
"(",
"infile",
",",
"\"r\"",
")",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"f",
".",
"close",
"(",
")",
"ncoords",
"=",
"int",
"(",
"lines",
... | 37.159091 | 19.25 |
def subscribe(self, callable=None, block=False, port=1883):
'''
a method to establish a mosquitto socket with server to receive position updates
:param callable: [optional] callable to process the received positions
:param block: [optional] boolean to block the main thr... | [
"def",
"subscribe",
"(",
"self",
",",
"callable",
"=",
"None",
",",
"block",
"=",
"False",
",",
"port",
"=",
"1883",
")",
":",
"title",
"=",
"'%s.subscribe'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
... | 34.0625 | 22.2125 |
def main(argv):
"""Main."""
del argv # Unused.
if flags.FLAGS.version:
print("GRR frontend {}".format(config_server.VERSION["packageversion"]))
return
config.CONFIG.AddContext("HTTPServer Context")
server_startup.Init()
httpd = CreateServer()
server_startup.DropPrivileges()
try:
httpd... | [
"def",
"main",
"(",
"argv",
")",
":",
"del",
"argv",
"# Unused.",
"if",
"flags",
".",
"FLAGS",
".",
"version",
":",
"print",
"(",
"\"GRR frontend {}\"",
".",
"format",
"(",
"config_server",
".",
"VERSION",
"[",
"\"packageversion\"",
"]",
")",
")",
"return"... | 19.7 | 24.15 |
def tls_session_update(self, msg_str):
"""
Either for parsing or building, we store the server_random along with
the raw string representing this handshake message. We also store the
cipher suite (if recognized), and finally we instantiate the write and
read connection states.
... | [
"def",
"tls_session_update",
"(",
"self",
",",
"msg_str",
")",
":",
"super",
"(",
"TLSClientHello",
",",
"self",
")",
".",
"tls_session_update",
"(",
"msg_str",
")",
"s",
"=",
"self",
".",
"tls_session",
"s",
".",
"tls_version",
"=",
"self",
".",
"version"... | 43.243243 | 18.756757 |
def _compute_mjd(self, kw, val):
"""
Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value.
@param kw: a list of keywords
@param val: a list of matching values
@return: the MJD-OBS-CENTER as a julian date.
"""
try:
... | [
"def",
"_compute_mjd",
"(",
"self",
",",
"kw",
",",
"val",
")",
":",
"try",
":",
"idx",
"=",
"kw",
".",
"index",
"(",
"'MJD-OBS-CENTER'",
")",
"except",
"ValueError",
":",
"return",
"if",
"len",
"(",
"val",
")",
"==",
"len",
"(",
"kw",
")",
":",
... | 42.684211 | 17.421053 |
def create_basic_app(cls, bundles=None, _config_overrides=None):
"""
Creates a "fake" app for use while developing
"""
bundles = bundles or []
name = bundles[-1].module_name if bundles else 'basic_app'
app = FlaskUnchained(name, template_folder=os.path.join(
o... | [
"def",
"create_basic_app",
"(",
"cls",
",",
"bundles",
"=",
"None",
",",
"_config_overrides",
"=",
"None",
")",
":",
"bundles",
"=",
"bundles",
"or",
"[",
"]",
"name",
"=",
"bundles",
"[",
"-",
"1",
"]",
".",
"module_name",
"if",
"bundles",
"else",
"'b... | 32.722222 | 19.722222 |
def main():
"""parse commandline arguments and print result"""
#
# setup command line parsing a la argpase
#
parser = argparse.ArgumentParser()
# positional args
parser.add_argument('uri', metavar='URI', nargs='?', default='/',
help='[owserver:]//server:port/entity'... | [
"def",
"main",
"(",
")",
":",
"#",
"# setup command line parsing a la argpase",
"#",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# positional args",
"parser",
".",
"add_argument",
"(",
"'uri'",
",",
"metavar",
"=",
"'URI'",
",",
"nargs",
"=",
... | 37.54023 | 20 |
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self... | [
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self"... | 33.636364 | 16.090909 |
def initializeProfile(self):
"""
Initializes the Component Profile.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Building '{0}' profile.".format(self.__file))
sections_file_parser = SectionsFileParser(self.__file)
sections_file_parser.parse... | [
"def",
"initializeProfile",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Building '{0}' profile.\"",
".",
"format",
"(",
"self",
".",
"__file",
")",
")",
"sections_file_parser",
"=",
"SectionsFileParser",
"(",
"self",
".",
"__file",
")",
"sections_fi... | 45.563636 | 32.109091 |
def df64bitto32bit(tbl):
"""
Convert a Pandas dataframe from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
tbl : The dataframe to convert
Returns
-------
The converted dataframe
"""
newtbl = pd.DataFrame(index=tbl.index)
for colname in... | [
"def",
"df64bitto32bit",
"(",
"tbl",
")",
":",
"newtbl",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"tbl",
".",
"index",
")",
"for",
"colname",
"in",
"tbl",
".",
"columns",
":",
"newtbl",
"[",
"colname",
"]",
"=",
"series64bitto32bit",
"(",
"tbl",... | 23.176471 | 19.058824 |
def list_records(self, limit=None, offset=None):
"""
Returns a list of all records configured for this domain.
"""
return self.manager.list_records(self, limit=limit, offset=offset) | [
"def",
"list_records",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"return",
"self",
".",
"manager",
".",
"list_records",
"(",
"self",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")"
] | 41.8 | 13.4 |
def dispatch(self, event: Event) -> Iterator[Any]:
"""
Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler
"""
LOG.debug('Dispatching event "%s"', event.get("t... | [
"def",
"dispatch",
"(",
"self",
",",
"event",
":",
"Event",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"LOG",
".",
"debug",
"(",
"'Dispatching event \"%s\"'",
",",
"event",
".",
"get",
"(",
"\"type\"",
")",
")",
"if",
"event",
"[",
"\"type\"",
"]",
... | 32.736842 | 19.684211 |
def p_default_option(self, p):
"""default_option : EQ primitive
| EQ tag_ref
| empty"""
if p[1]:
if isinstance(p[2], AstTagRef):
p[0] = p[2]
else:
p[0] = p[2] | [
"def",
"p_default_option",
"(",
"self",
",",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
":",
"if",
"isinstance",
"(",
"p",
"[",
"2",
"]",
",",
"AstTagRef",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"2",
"]",
"else",
":",
"p",
"[",
"0",
"... | 30.444444 | 9.777778 |
def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
"""Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
T... | [
"def",
"find_profile_dir_by_name",
"(",
"cls",
",",
"ipython_dir",
",",
"name",
"=",
"u'default'",
",",
"config",
"=",
"None",
")",
":",
"dirname",
"=",
"u'profile_'",
"+",
"name",
"paths",
"=",
"[",
"os",
".",
"getcwdu",
"(",
")",
",",
"ipython_dir",
"]... | 39.076923 | 18.461538 |
def find_best_sequence(hits_found, specie_path, gene, silent_N_flag):
"""
This function takes the list hits_found as argument. This contains all
hits found for the blast search of one gene. A hit includes the subjct
sequence, the query, and the start and stop position of the allignment
correspond... | [
"def",
"find_best_sequence",
"(",
"hits_found",
",",
"specie_path",
",",
"gene",
",",
"silent_N_flag",
")",
":",
"# Get information from the fisrt hit found\t",
"all_start",
"=",
"hits_found",
"[",
"0",
"]",
"[",
"0",
"]",
"current_end",
"=",
"hits_found",
"[",
"0... | 39.043103 | 18.612069 |
def insert(self, index, p_object):
"""
Insert an element to a list
"""
validated_value = self.get_validated_object(p_object)
if validated_value is not None:
self.__modified_data__.insert(index, validated_value) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"p_object",
")",
":",
"validated_value",
"=",
"self",
".",
"get_validated_object",
"(",
"p_object",
")",
"if",
"validated_value",
"is",
"not",
"None",
":",
"self",
".",
"__modified_data__",
".",
"insert",
"(",... | 36.571429 | 8.285714 |
def square_sum(list_vector):
"""!
@brief Calculates square sum of vector that is represented by list, each element can be represented by list - multidimensional elements.
@param[in] list_vector (list): Input vector.
@return (double) Square sum of vector.
"""
square_... | [
"def",
"square_sum",
"(",
"list_vector",
")",
":",
"square_sum",
"=",
"0.0",
"list_representation",
"=",
"(",
"type",
"(",
"list_vector",
"[",
"0",
"]",
")",
"==",
"list",
")",
"for",
"index_element",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"list_vecto... | 36.25 | 26.8 |
def stage_pywbem_args(self, method, **kwargs):
"""
Log request method and all args.
Normally called before the cmd is executed to record request
parameters.
This method does not support the summary detail_level because
that seems to add little info to the log that is not ... | [
"def",
"stage_pywbem_args",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"_pywbem_method",
"=",
"method",
"if",
"self",
".",
"enabled",
"and",
"self",
".",
"api_detail_level",
"is",... | 46.151515 | 22.272727 |
def set_continue(self, name, action, seqno, value=None, default=False,
disable=False):
"""Configures the routemap continue value
Args:
name (string): The full name of the routemap.
action (string): The action to take for this routemap clause.
seq... | [
"def",
"set_continue",
"(",
"self",
",",
"name",
",",
"action",
",",
"seqno",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"commands",
"=",
"[",
"'route-map %s %s %s'",
"%",
"(",
"name",
",",
"action"... | 43.962963 | 22.703704 |
def bind_to_environ(self, environ, server_name=None, subdomain=None):
"""Like :meth:`bind` but you can pass it an WSGI environment and it
will fetch the information from that dictionary. Note that because of
limitations in the protocol there is no way to get the current
subdomain and re... | [
"def",
"bind_to_environ",
"(",
"self",
",",
"environ",
",",
"server_name",
"=",
"None",
",",
"subdomain",
"=",
"None",
")",
":",
"environ",
"=",
"_get_environ",
"(",
"environ",
")",
"wsgi_server_name",
"=",
"get_host",
"(",
"environ",
")",
".",
"lower",
"(... | 43.306667 | 22.346667 |
def lpc(blk, order=None):
"""
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the covariance
method, assuming a zero-mean stochastic process, using numpy.linalg.pinv
as a linear system solver.
"""
from numpy import matrix
... | [
"def",
"lpc",
"(",
"blk",
",",
"order",
"=",
"None",
")",
":",
"from",
"numpy",
"import",
"matrix",
"from",
"numpy",
".",
"linalg",
"import",
"pinv",
"lagm",
"=",
"lag_matrix",
"(",
"blk",
",",
"order",
")",
"phi",
"=",
"matrix",
"(",
"lagm",
")",
... | 33.105263 | 20.157895 |
def find_linux_venv_py_version():
"""Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4``
"""
available_python_version = [
"python2.6",
"python2.7",
"python3.3",
"python3.4",
"python3.5",
"python3.6",
]
dir_p... | [
"def",
"find_linux_venv_py_version",
"(",
")",
":",
"available_python_version",
"=",
"[",
"\"python2.6\"",
",",
"\"python2.7\"",
",",
"\"python3.3\"",
",",
"\"python3.4\"",
",",
"\"python3.5\"",
",",
"\"python3.6\"",
",",
"]",
"dir_path",
"=",
"os",
".",
"path",
"... | 31.315789 | 15.157895 |
def getClassPath():
""" Get the full java class path.
Includes user added paths and the environment CLASSPATH.
"""
global _CLASSPATHS
global _SEP
out=[]
for path in _CLASSPATHS:
if path=='':
continue
if path.endswith('*'):
paths=_glob.glob(path+".jar"... | [
"def",
"getClassPath",
"(",
")",
":",
"global",
"_CLASSPATHS",
"global",
"_SEP",
"out",
"=",
"[",
"]",
"for",
"path",
"in",
"_CLASSPATHS",
":",
"if",
"path",
"==",
"''",
":",
"continue",
"if",
"path",
".",
"endswith",
"(",
"'*'",
")",
":",
"paths",
"... | 24.052632 | 16.263158 |
def draw(self):
"""
Draw guide
Returns
-------
out : matplotlib.offsetbox.Offsetbox
A drawing of this legend
"""
obverse = slice(0, None)
reverse = slice(None, None, -1)
nbreak = len(self.key)
themeable = self.theme.figure._the... | [
"def",
"draw",
"(",
"self",
")",
":",
"obverse",
"=",
"slice",
"(",
"0",
",",
"None",
")",
"reverse",
"=",
"slice",
"(",
"None",
",",
"None",
",",
"-",
"1",
")",
"nbreak",
"=",
"len",
"(",
"self",
".",
"key",
")",
"themeable",
"=",
"self",
".",... | 34.899083 | 14.275229 |
def highlight_matching_symbols_pairs(editor):
"""
Highlights given editor matching pairs.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool
"""
format = editor.language.theme.get("accelerator.pair")
if not format:
return False
... | [
"def",
"highlight_matching_symbols_pairs",
"(",
"editor",
")",
":",
"format",
"=",
"editor",
".",
"language",
".",
"theme",
".",
"get",
"(",
"\"accelerator.pair\"",
")",
"if",
"not",
"format",
":",
"return",
"False",
"extra_selections",
"=",
"editor",
".",
"ex... | 41.916667 | 23.875 |
def authenticate_device(self, api_token, device_token, email=None,
user_url=None, override=False, fetch=True):
"""Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
... | [
"def",
"authenticate_device",
"(",
"self",
",",
"api_token",
",",
"device_token",
",",
"email",
"=",
"None",
",",
"user_url",
"=",
"None",
",",
"override",
"=",
"False",
",",
"fetch",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"context",
".",
"has_... | 42.861111 | 21.694444 |
def set_remote(self, key=None, value=None, data=None, **kwdata):
"""
Set data for the remote end(s) of this conversation.
Data can be passed in either as a single dict, or as key-word args.
Note that, in Juju, setting relation data is inherently service scoped.
That is, if the ... | [
"def",
"set_remote",
"(",
"self",
",",
"key",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwdata",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"key",
"is",
"not",
"None",
":",
... | 39.962963 | 22.407407 |
def denormalize(data):
'''
denormalize(data) yield a denormalized version of the given JSON-friendly normalized data. This
is the inverse of the normalize(obj) function.
The normalize and denormalize functions use the reserved keyword '__type__' along with the
<obj>.normalize() and <class>.denorm... | [
"def",
"denormalize",
"(",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"elif",
"pimms",
".",
"is_scalar",
"(",
"data",
",",
"(",
"'number'",
",",
"'bool'",
",",
"'string'",
",",
"'unicode'",
")",
")",
":",
"return",
"data",
"... | 54.277778 | 26.666667 |
def stop(self, signum=None, _unused=None):
"""Stop the consumer from consuming by calling BasicCancel and setting
our state.
:param int signum: The signal received
:param frame _unused: The stack frame from when the signal was called
"""
LOGGER.debug('Stop called in sta... | [
"def",
"stop",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"_unused",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Stop called in state: %s'",
",",
"self",
".",
"state_description",
")",
"if",
"self",
".",
"is_stopped",
":",
"LOGGER",
".",
"wa... | 39.827586 | 20.413793 |
def round_to(self, dt, hour, minute, second, mode="floor"):
"""Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
mode = mode.lower()
new_dt = datetime(dt.year, dt.month,... | [
"def",
"round_to",
"(",
"self",
",",
"dt",
",",
"hour",
",",
"minute",
",",
"second",
",",
"mode",
"=",
"\"floor\"",
")",
":",
"mode",
"=",
"mode",
".",
"lower",
"(",
")",
"new_dt",
"=",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month"... | 30.208333 | 18.375 |
def accumulate_nested_doc(nested_path, expr=IDENTITY):
"""
:param nested_path: THE PATH USED TO EXTRACT THE NESTED RECORDS
:param expr: FUNCTION USED ON THE NESTED OBJECT TO GET SPECIFIC VALUE
:return: THE DE_TYPED NESTED OBJECT ARRAY
"""
name = literal_field(nested_path)
def output(doc):
... | [
"def",
"accumulate_nested_doc",
"(",
"nested_path",
",",
"expr",
"=",
"IDENTITY",
")",
":",
"name",
"=",
"literal_field",
"(",
"nested_path",
")",
"def",
"output",
"(",
"doc",
")",
":",
"acc",
"=",
"[",
"]",
"for",
"h",
"in",
"doc",
".",
"inner_hits",
... | 37.285714 | 13.190476 |
def private_ips_absent(name, network_interface_name=None, network_interface_id=None,
private_ip_addresses=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure an ENI does not have secondary private ip addresses associated with it
name
(String) - State definitio... | [
"def",
"private_ips_absent",
"(",
"name",
",",
"network_interface_name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"private_ip_addresses",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"pr... | 40.80916 | 24.549618 |
def plot_joint_sfs(s, ax=None, imshow_kwargs=None):
"""Plot a joint site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes_pop1, n_chromosomes_pop2)
Joint site frequency spectrum.
ax : axes, optional
Axes on which to draw. If not provided, a new fig... | [
"def",
"plot_joint_sfs",
"(",
"s",
",",
"ax",
"=",
"None",
",",
"imshow_kwargs",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"matplotlib",
".",
"colors",
"import",
"LogNorm",
"# check inputs",
"s",
"=",
"asarray_ndim",
... | 26.425532 | 20.829787 |
def generate(self, api):
"""Generates a module for each namespace."""
for namespace in api.namespaces.values():
# One module per namespace is created. The module takes the name
# of the namespace.
with self.output_to_relative_path('{}.py'.format(namespace.name)):
... | [
"def",
"generate",
"(",
"self",
",",
"api",
")",
":",
"for",
"namespace",
"in",
"api",
".",
"namespaces",
".",
"values",
"(",
")",
":",
"# One module per namespace is created. The module takes the name",
"# of the namespace.",
"with",
"self",
".",
"output_to_relative_... | 52.571429 | 18 |
def replace_refs_factory(references, use_cleveref_default, use_eqref,
plusname, starname, target):
"""Returns replace_refs(key, value, fmt, meta) action that replaces
references with format-specific content. The content is determined using
the 'references' dict, which associates re... | [
"def",
"replace_refs_factory",
"(",
"references",
",",
"use_cleveref_default",
",",
"use_eqref",
",",
"plusname",
",",
"starname",
",",
"target",
")",
":",
"global",
"_cleveref_tex_flag",
"# pylint: disable=global-statement",
"# Update global if clever referencing is required b... | 42.297297 | 23.27027 |
def places(client, query, location=None, radius=None, language=None,
min_price=None, max_price=None, open_now=False, type=None, region=None,
page_token=None):
"""
Places search.
:param query: The text string on which to search, for example: "restaurant".
:type query: string
:... | [
"def",
"places",
"(",
"client",
",",
"query",
",",
"location",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"language",
"=",
"None",
",",
"min_price",
"=",
"None",
",",
"max_price",
"=",
"None",
",",
"open_now",
"=",
"False",
",",
"type",
"=",
"None... | 40.672727 | 25.218182 |
def group_list(auth=None, **kwargs):
'''
List groups
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_list
salt '*' keystoneng.group_list domain_id=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return ... | [
"def",
"group_list",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"list_groups",
"(",
"*",
"*",
... | 23.857143 | 22 |
def iter_extensions(extension):
""" Depth-first iterator over sub-extensions on `extension`.
"""
for _, ext in inspect.getmembers(extension, is_extension):
for item in iter_extensions(ext):
yield item
yield ext | [
"def",
"iter_extensions",
"(",
"extension",
")",
":",
"for",
"_",
",",
"ext",
"in",
"inspect",
".",
"getmembers",
"(",
"extension",
",",
"is_extension",
")",
":",
"for",
"item",
"in",
"iter_extensions",
"(",
"ext",
")",
":",
"yield",
"item",
"yield",
"ex... | 34.857143 | 10.428571 |
def _save_env(env):
"""Saves one environment.
Args:
env (dict): the env dict to save.
"""
env_path = os.path.join(env["resultdir"], "env")
if os.path.isdir(env["resultdir"]):
with open(env_path, "w") as f:
yaml.dump(env, f) | [
"def",
"_save_env",
"(",
"env",
")",
":",
"env_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env",
"[",
"\"resultdir\"",
"]",
",",
"\"env\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"env",
"[",
"\"resultdir\"",
"]",
")",
":",
"with",
... | 23.909091 | 14.454545 |
def external_program_check(
to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])):
"""
Validates the existence and basic working-ness of other programs
Implemented because it is easy to get confusing error output when
one does not install a dependency because of the fork-worker model
that is both n... | [
"def",
"external_program_check",
"(",
"to_check",
"=",
"frozenset",
"(",
"[",
"PSQL_BIN",
",",
"LZOP_BIN",
",",
"PV_BIN",
"]",
")",
")",
":",
"could_not_run",
"=",
"[",
"]",
"error_msgs",
"=",
"[",
"]",
"def",
"psql_err_handler",
"(",
"popen",
")",
":",
... | 36.786885 | 20.42623 |
def init_weights(self, m):
""" Initialize the weights.
"""
classname = m.__class__.__name__
if classname.find('Linear') != -1:
if hasattr(m, 'weight') and m.weight is not None:
self.init_weight(m.weight)
if hasattr(m, 'bias') and m.bias is not None... | [
"def",
"init_weights",
"(",
"self",
",",
"m",
")",
":",
"classname",
"=",
"m",
".",
"__class__",
".",
"__name__",
"if",
"classname",
".",
"find",
"(",
"'Linear'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'weight'",
")",
"and",
"m"... | 47.65 | 10.55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.