text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def send_message(self, user=None, message=None, channel=None):
""" Todo """
self.logger.info("sending message to %s: %s", user, message)
cid=channel
if not cid:
for cid in self.channels:
if str(self.channels[cid]) == str(user):
channel=cid
self.logger.debug(cid)
if ... | [
"def",
"send_message",
"(",
"self",
",",
"user",
"=",
"None",
",",
"message",
"=",
"None",
",",
"channel",
"=",
"None",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"sending message to %s: %s\"",
",",
"user",
",",
"message",
")",
"cid",
"=",
"c... | 35.733333 | 16 |
def param_query(name: str) -> PAParams:
'''Find the PAParams for a network by its long or short name. Raises
UnsupportedNetwork if no PAParams is found.
'''
for pa_params in params:
if name in (pa_params.network_name, pa_params.network_shortname,):
return pa_params
raise Unsupp... | [
"def",
"param_query",
"(",
"name",
":",
"str",
")",
"->",
"PAParams",
":",
"for",
"pa_params",
"in",
"params",
":",
"if",
"name",
"in",
"(",
"pa_params",
".",
"network_name",
",",
"pa_params",
".",
"network_shortname",
",",
")",
":",
"return",
"pa_params",... | 32.3 | 22.3 |
def debug_dump(message, file_prefix="dump"):
"""
Utility while developing to dump message data to play with in the
interpreter
"""
global index
index += 1
with open("%s_%s.dump" % (file_prefix, index), 'w') as f:
f.write(message.SerializeToString())
f.close() | [
"def",
"debug_dump",
"(",
"message",
",",
"file_prefix",
"=",
"\"dump\"",
")",
":",
"global",
"index",
"index",
"+=",
"1",
"with",
"open",
"(",
"\"%s_%s.dump\"",
"%",
"(",
"file_prefix",
",",
"index",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"... | 24.5 | 19.666667 |
def rest(o) -> Optional[ISeq]:
"""If o is a ISeq, return the elements after the first in o. If o is None,
returns an empty seq. Otherwise, coerces o to a seq and returns the rest."""
if o is None:
return None
if isinstance(o, ISeq):
s = o.rest
if s is None:
return lse... | [
"def",
"rest",
"(",
"o",
")",
"->",
"Optional",
"[",
"ISeq",
"]",
":",
"if",
"o",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"o",
",",
"ISeq",
")",
":",
"s",
"=",
"o",
".",
"rest",
"if",
"s",
"is",
"None",
":",
"return",
"l... | 29.357143 | 16.214286 |
def p_expression_lessthan(self, p):
'expression : expression LT expression'
p[0] = LessThan(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_lessthan",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"LessThan",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
... | 43.25 | 7.75 |
def commitVCS(self, tag=None):
''' Commit the current working directory state (or do nothing if the
working directory is not version controlled)
'''
if not self.vcs:
return
self.vcs.commit(message='version %s' % tag, tag=tag) | [
"def",
"commitVCS",
"(",
"self",
",",
"tag",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"vcs",
":",
"return",
"self",
".",
"vcs",
".",
"commit",
"(",
"message",
"=",
"'version %s'",
"%",
"tag",
",",
"tag",
"=",
"tag",
")"
] | 39.285714 | 21.285714 |
def type_list(self, index_name):
'''
List the types available in an index
'''
request = self.session
url = 'http://%s:%s/%s/_mapping' % (self.host, self.port, index_name)
response = request.get(url)
if request.status_code == 200:
return response[index_... | [
"def",
"type_list",
"(",
"self",
",",
"index_name",
")",
":",
"request",
"=",
"self",
".",
"session",
"url",
"=",
"'http://%s:%s/%s/_mapping'",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"index_name",
")",
"response",
"=",
"request",
"... | 33.090909 | 15.454545 |
def process_casperjs_stdout(stdout):
"""Parse and digest capture script output.
"""
for line in stdout.splitlines():
bits = line.split(':', 1)
if len(bits) < 2:
bits = ('INFO', bits)
level, msg = bits
if level == 'FATAL':
logger.fatal(msg)
... | [
"def",
"process_casperjs_stdout",
"(",
"stdout",
")",
":",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"bits",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"bits",
"=",
"... | 27.0625 | 11.25 |
def formfield(self, **kwargs):
"""Gets the form field associated with this field."""
defaults = {
'form_class': LocalizedTextFieldForm
}
defaults.update(kwargs)
return super().formfield(**defaults) | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'form_class'",
":",
"LocalizedTextFieldForm",
"}",
"defaults",
".",
"update",
"(",
"kwargs",
")",
"return",
"super",
"(",
")",
".",
"formfield",
"(",
"*",
"*",
"... | 27 | 18 |
def first_rec(ofile, Rec, file_type):
"""
opens the file ofile as a magic template file with headers as the keys to Rec
"""
keylist = []
opened = False
# sometimes Windows needs a little extra time to open a file
# or else it throws an error
while not opened:
try:
pma... | [
"def",
"first_rec",
"(",
"ofile",
",",
"Rec",
",",
"file_type",
")",
":",
"keylist",
"=",
"[",
"]",
"opened",
"=",
"False",
"# sometimes Windows needs a little extra time to open a file",
"# or else it throws an error",
"while",
"not",
"opened",
":",
"try",
":",
"pm... | 29.541667 | 14.208333 |
def distribution_compatible(dist, supported_tags=None):
"""Is this distribution compatible with the given interpreter/platform combination?
:param supported_tags: A list of tag tuples specifying which tags are supported
by the platform in question.
:returns: True if the distribution is compatible, False if i... | [
"def",
"distribution_compatible",
"(",
"dist",
",",
"supported_tags",
"=",
"None",
")",
":",
"if",
"supported_tags",
"is",
"None",
":",
"supported_tags",
"=",
"get_supported",
"(",
")",
"package",
"=",
"Package",
".",
"from_href",
"(",
"dist",
".",
"location",... | 41.384615 | 17.692308 |
def authorize(context, action, target, do_raise=True):
"""Verify that the action is valid on the target in this context.
:param context: monasca project context
:param action: String representing the action to be checked. This
should be colon separated for clarity.
:param target: Dic... | [
"def",
"authorize",
"(",
"context",
",",
"action",
",",
"target",
",",
"do_raise",
"=",
"True",
")",
":",
"init",
"(",
")",
"credentials",
"=",
"context",
".",
"to_policy_values",
"(",
")",
"try",
":",
"result",
"=",
"_ENFORCER",
".",
"authorize",
"(",
... | 42.8 | 20.514286 |
def export_cmd_options(self, options_override=None, standalone=False):
"""
Override!
:return:
"""
cmd_options = super(MongosServer, self).export_cmd_options(
options_override=options_override)
# Add configServers arg
cluster = self.get_validate_cl... | [
"def",
"export_cmd_options",
"(",
"self",
",",
"options_override",
"=",
"None",
",",
"standalone",
"=",
"False",
")",
":",
"cmd_options",
"=",
"super",
"(",
"MongosServer",
",",
"self",
")",
".",
"export_cmd_options",
"(",
"options_override",
"=",
"options_overr... | 29.214286 | 19.928571 |
def copy_file(self, from_path, to_path):
""" Copy file. """
if not op.exists(op.dirname(to_path)):
self.make_directory(op.dirname(to_path))
shutil.copy(from_path, to_path)
logging.debug('File copied: {0}'.format(to_path)) | [
"def",
"copy_file",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"op",
".",
"dirname",
"(",
"to_path",
")",
")",
":",
"self",
".",
"make_directory",
"(",
"op",
".",
"dirname",
"(",
"to_path",
")",
... | 37.142857 | 10.857143 |
def get_content_commit_date(extensions, acceptance_callback=None,
root_dir='.'):
"""Get the datetime for the most recent commit to a project that
affected certain types of content.
Parameters
----------
extensions : sequence of 'str'
Extensions of files to consid... | [
"def",
"get_content_commit_date",
"(",
"extensions",
",",
"acceptance_callback",
"=",
"None",
",",
"root_dir",
"=",
"'.'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"def",
"_null_callback",
"(",
"_",
")",
":",
"return",
"Tru... | 39.576923 | 21.769231 |
def _set_meter(self, v, load=False):
"""
Setter method for meter, mapped from YANG variable /openflow_state/meter (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_meter is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_meter",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 69.291667 | 33.875 |
def find_guests(names, path=None):
'''
Return a dict of hosts and named guests
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
names = names.split(',')
for data in _list_iter(path=path):
host,... | [
"def",
"find_guests",
"(",
"names",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"names",
"=",
"names",
".",
"split",
"(",
"','",
")",
"for",
"data",
"in",
"_list_iter",
"(",
"path",
"=",
"path",
")",
":",
"host",
",",
"stat",
"=",
... | 25.913043 | 16.086957 |
def get_assignable_repository_ids(self, repository_id):
"""Gets a list of repositories including and under the given repository node in which any asset can be assigned.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (osid.id.IdList) - list of assign... | [
"def",
"get_assignable_repository_ids",
"(",
"self",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids",
"# This will likely be overridden by an authorization adapter",
"mgr",
"=",
"self",
".",
"_get_... | 50.142857 | 19.333333 |
def _build_youtube_dl(worker, destdir, site):
'''
Builds a `youtube_dl.YoutubeDL` for brozzling `site` with `worker`.
The `YoutubeDL` instance does a few special brozzler-specific things:
- keeps track of urls fetched using a `YoutubeDLSpy`
- periodically updates `site.last_claimed` in rethinkdb
... | [
"def",
"_build_youtube_dl",
"(",
"worker",
",",
"destdir",
",",
"site",
")",
":",
"class",
"_YoutubeDL",
"(",
"youtube_dl",
".",
"YoutubeDL",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__module__",
"+",
"\".\"",
"+",
"__qualname__",
")",
"... | 44.109677 | 21.490323 |
def generateRecords(self, records):
"""Generate multiple records. Refer to definition for generateRecord"""
if self.verbosity>0: print 'Generating', len(records), 'records...'
for record in records:
self.generateRecord(record) | [
"def",
"generateRecords",
"(",
"self",
",",
"records",
")",
":",
"if",
"self",
".",
"verbosity",
">",
"0",
":",
"print",
"'Generating'",
",",
"len",
"(",
"records",
")",
",",
"'records...'",
"for",
"record",
"in",
"records",
":",
"self",
".",
"generateRe... | 40 | 16.166667 |
def start_adc_comparator(self, channel, high_threshold, low_threshold,
gain=1, data_rate=None, active_low=True,
traditional=True, latching=False, num_readings=1):
"""Start continuous ADC conversions on the specified channel (0-3) with
the compara... | [
"def",
"start_adc_comparator",
"(",
"self",
",",
"channel",
",",
"high_threshold",
",",
"low_threshold",
",",
"gain",
"=",
"1",
",",
"data_rate",
"=",
"None",
",",
"active_low",
"=",
"True",
",",
"traditional",
"=",
"True",
",",
"latching",
"=",
"False",
"... | 71.8 | 31.533333 |
def compare_mim_panels(self, existing_panel, new_panel):
"""Check if the latest version of OMIM differs from the most recent in database
Return all genes that where not in the previous version.
Args:
existing_panel(dict)
new_panel(dict)
Returns:
n... | [
"def",
"compare_mim_panels",
"(",
"self",
",",
"existing_panel",
",",
"new_panel",
")",
":",
"existing_genes",
"=",
"set",
"(",
"[",
"gene",
"[",
"'hgnc_id'",
"]",
"for",
"gene",
"in",
"existing_panel",
"[",
"'genes'",
"]",
"]",
")",
"new_genes",
"=",
"set... | 36.466667 | 22.066667 |
def lookup(self, req, parent, name):
"""Look up a directory entry by name and get its attributes.
Valid replies:
reply_entry
reply_err
"""
self.reply_err(req, errno.ENOENT) | [
"def",
"lookup",
"(",
"self",
",",
"req",
",",
"parent",
",",
"name",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"ENOENT",
")"
] | 27.75 | 12.375 |
def get_server_capabilities(self):
"""Returns the server capabilities
raises: IloError on an error from iLO.
"""
capabilities = {}
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)
try:
... | [
"def",
"get_server_capabilities",
"(",
"self",
")",
":",
"capabilities",
"=",
"{",
"}",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"sushy_manager",
"=",
"self",
".",
"_get_sushy_manager",
"(",
"PROLIANT_MANAGER_ID",
")",
... | 42.911392 | 18.21519 |
def _download_py2(link, path, __hdr__):
"""Download a file from a link in Python 2."""
try:
req = urllib2.Request(link, headers=__hdr__)
u = urllib2.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as out... | [
"def",
"_download_py2",
"(",
"link",
",",
"path",
",",
"__hdr__",
")",
":",
"try",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"link",
",",
"headers",
"=",
"__hdr__",
")",
"u",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
"except",
"Exceptio... | 30.916667 | 17.416667 |
def compute(a, b, axis):
"""
Finds optimal displacements localized along an axis
"""
delta = []
for aa, bb in zip(rollaxis(a, axis, 0), rollaxis(b, axis, 0)):
delta.append(Displacement.compute(aa, bb).delta)
return LocalDisplacement(delta, axis=axis) | [
"def",
"compute",
"(",
"a",
",",
"b",
",",
"axis",
")",
":",
"delta",
"=",
"[",
"]",
"for",
"aa",
",",
"bb",
"in",
"zip",
"(",
"rollaxis",
"(",
"a",
",",
"axis",
",",
"0",
")",
",",
"rollaxis",
"(",
"b",
",",
"axis",
",",
"0",
")",
")",
"... | 37.875 | 14.625 |
def get_symbols(self, site='Pro'):
"""
获取支持的交易对
:param site:
:return:
"""
assert site in ['Pro', 'HADAX']
params = {}
path = f'/v1{"/" if site == "Pro" else "/hadax/"}common/symbols'
def _wrapper(_func):
@wraps(_func)
def h... | [
"def",
"get_symbols",
"(",
"self",
",",
"site",
"=",
"'Pro'",
")",
":",
"assert",
"site",
"in",
"[",
"'Pro'",
",",
"'HADAX'",
"]",
"params",
"=",
"{",
"}",
"path",
"=",
"f'/v1{\"/\" if site == \"Pro\" else \"/hadax/\"}common/symbols'",
"def",
"_wrapper",
"(",
... | 22.888889 | 18.333333 |
def kde_plot_df(df, xlims=None, **kwargs):
"""Plots kde estimates of distributions of samples in each cell of the
input pandas DataFrame.
There is one subplot for each dataframe column, and on each subplot there
is one kde line.
Parameters
----------
df: pandas data frame
Each cell... | [
"def",
"kde_plot_df",
"(",
"df",
",",
"xlims",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"xlims",
"is",
"None",
"or",
"isinstance",
"(",
"xlims",
",",
"dict",
")",
"figsize",
"=",
"kwargs",
".",
"pop",
"(",
"'figsize'",
",",
"(",
"6... | 35.421053 | 15.907895 |
def plot_sediment_memory(self, ax=None):
"""Plot sediment memory prior and posterior distributions"""
if ax is None:
ax = plt.gca()
y_prior, x_prior = self.prior_sediment_memory()
ax.plot(x_prior, y_prior, label='Prior')
y_posterior = self.mcmcfit.sediment_memory
... | [
"def",
"plot_sediment_memory",
"(",
"self",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"y_prior",
",",
"x_prior",
"=",
"self",
".",
"prior_sediment_memory",
"(",
")",
"ax",
".",
"plot",
... | 42.08 | 20.64 |
def append_instances(cls, inst1, inst2):
"""
Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible.
:param inst1: the first dataset
:type inst1: Instances
:param inst2: the first dataset
:type inst2: Instances
:retur... | [
"def",
"append_instances",
"(",
"cls",
",",
"inst1",
",",
"inst2",
")",
":",
"msg",
"=",
"inst1",
".",
"equal_headers",
"(",
"inst2",
")",
"if",
"msg",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"Cannot appent instances: \"",
"+",
"msg",
")",
... | 36.777778 | 12.444444 |
def uint16_gt(a: int, b: int) -> bool:
"""
Return a > b.
"""
half_mod = 0x8000
return (((a < b) and ((b - a) > half_mod)) or
((a > b) and ((a - b) < half_mod))) | [
"def",
"uint16_gt",
"(",
"a",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"bool",
":",
"half_mod",
"=",
"0x8000",
"return",
"(",
"(",
"(",
"a",
"<",
"b",
")",
"and",
"(",
"(",
"b",
"-",
"a",
")",
">",
"half_mod",
")",
")",
"or",
"(",
"(",
... | 26.571429 | 8.571429 |
def continent(self, code: bool = False) -> str:
"""Get a random continent name or continent code.
:param code: Return code of continent.
:return: Continent name.
"""
codes = CONTINENT_CODES if \
code else self._data['continent']
return self.random.choice(cod... | [
"def",
"continent",
"(",
"self",
",",
"code",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"codes",
"=",
"CONTINENT_CODES",
"if",
"code",
"else",
"self",
".",
"_data",
"[",
"'continent'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
... | 31.4 | 11 |
def transpose_mat44(src_mat, transpose_mat=None):
"""Create a transpose of a matrix."""
if not transpose_mat:
transpose_mat = Matrix44()
for i in range(4):
for j in range(4):
transpose_mat.data[i][j] = src_mat.data[j][i]
return transpose_mat | [
"def",
"transpose_mat44",
"(",
"src_mat",
",",
"transpose_mat",
"=",
"None",
")",
":",
"if",
"not",
"transpose_mat",
":",
"transpose_mat",
"=",
"Matrix44",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"for",
"j",
"in",
"range",
"(",
"4",
... | 25.272727 | 19.545455 |
def update(self, table_name, primary_key, instance):
""" replaces document identified by the primary_key or creates one if a matching document does not exist"""
assert isinstance(primary_key, dict)
assert isinstance(instance, BaseDocument)
collection = self._db[table_name]
# wor... | [
"def",
"update",
"(",
"self",
",",
"table_name",
",",
"primary_key",
",",
"instance",
")",
":",
"assert",
"isinstance",
"(",
"primary_key",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"instance",
",",
"BaseDocument",
")",
"collection",
"=",
"self",
".",
... | 50.1875 | 17.75 |
def sync_list_items(self):
"""
Access the sync_list_items
:returns: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemList
"""
if self._sync_list_items is None:
self.... | [
"def",
"sync_list_items",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sync_list_items",
"is",
"None",
":",
"self",
".",
"_sync_list_items",
"=",
"SyncListItemList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'servi... | 38 | 16.571429 |
def _get_block_data(self, mat, block):
"""Retrieve a block from a 3D or 4D volume
Parameters
----------
mat: a 3D or 4D volume
block: a tuple containing block information:
- a triple containing the lowest-coordinate voxel in the block
- a triple containing ... | [
"def",
"_get_block_data",
"(",
"self",
",",
"mat",
",",
"block",
")",
":",
"(",
"pt",
",",
"sz",
")",
"=",
"block",
"if",
"len",
"(",
"mat",
".",
"shape",
")",
"==",
"3",
":",
"return",
"mat",
"[",
"pt",
"[",
"0",
"]",
":",
"pt",
"[",
"0",
... | 31.4 | 17.766667 |
def new(cls, func, args, mon, count=0):
"""
:returns: a new Result instance
"""
try:
with mon:
val = func(*args)
except StopIteration:
res = Result(None, mon, msg='TASK_ENDED')
except Exception:
_etype, exc, tb = sys.exc... | [
"def",
"new",
"(",
"cls",
",",
"func",
",",
"args",
",",
"mon",
",",
"count",
"=",
"0",
")",
":",
"try",
":",
"with",
"mon",
":",
"val",
"=",
"func",
"(",
"*",
"args",
")",
"except",
"StopIteration",
":",
"res",
"=",
"Result",
"(",
"None",
",",... | 31.25 | 11.625 |
def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
... | [
"def",
"expected_related_units",
"(",
"reltype",
"=",
"None",
")",
":",
"if",
"not",
"has_juju_version",
"(",
"\"2.4.4\"",
")",
":",
"# goal-state existed in 2.4.0, but did not list individual units to",
"# join a relation in 2.4.1 through 2.4.3. (LP: #1794739)",
"raise",
"NotImp... | 41.625 | 20.84375 |
def WriteEventBody(self, event):
"""Writes the body of an event object to the spreadsheet.
Args:
event (EventObject): event.
"""
for field_name in self._fields:
if field_name == 'datetime':
output_value = self._FormatDateTime(event)
else:
output_value = self._dynamic_f... | [
"def",
"WriteEventBody",
"(",
"self",
",",
"event",
")",
":",
"for",
"field_name",
"in",
"self",
".",
"_fields",
":",
"if",
"field_name",
"==",
"'datetime'",
":",
"output_value",
"=",
"self",
".",
"_FormatDateTime",
"(",
"event",
")",
"else",
":",
"output_... | 35 | 21.25641 |
def touch(fname):
"""
Mimics the `touch` command
Busy loops until the mtime has actually been changed, use for tests only
"""
orig_mtime = get_mtime(fname)
while get_mtime(fname) == orig_mtime:
pathlib.Path(fname).touch() | [
"def",
"touch",
"(",
"fname",
")",
":",
"orig_mtime",
"=",
"get_mtime",
"(",
"fname",
")",
"while",
"get_mtime",
"(",
"fname",
")",
"==",
"orig_mtime",
":",
"pathlib",
".",
"Path",
"(",
"fname",
")",
".",
"touch",
"(",
")"
] | 27.333333 | 13.555556 |
def pruned_c2cifft(invec, outvec, indices, pretransposed=False):
"""
Perform a pruned iFFT, only valid for power of 2 iffts as the
decomposition is easier to choose. This is not a strict requirement of the
functions, but it is unlikely to the optimal to use anything but power
of 2. (Alex to provide ... | [
"def",
"pruned_c2cifft",
"(",
"invec",
",",
"outvec",
",",
"indices",
",",
"pretransposed",
"=",
"False",
")",
":",
"N1",
",",
"N2",
"=",
"splay",
"(",
"invec",
")",
"if",
"not",
"pretransposed",
":",
"invec",
"=",
"fft_transpose",
"(",
"invec",
")",
"... | 36.6875 | 21.875 |
def acquire(lock, blocking=True):
"""Acquire a lock, possibly in a non-blocking fashion.
Includes backwards compatibility hacks for old versions of Python, dask
and dask-distributed.
"""
if blocking:
# no arguments needed
return lock.acquire()
elif DistributedLock is not None an... | [
"def",
"acquire",
"(",
"lock",
",",
"blocking",
"=",
"True",
")",
":",
"if",
"blocking",
":",
"# no arguments needed",
"return",
"lock",
".",
"acquire",
"(",
")",
"elif",
"DistributedLock",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"lock",
",",
"Distr... | 41.052632 | 17.105263 |
def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
rais... | [
"def",
"get_tc_device",
"(",
"self",
")",
":",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"OUTGOING",
":",
"return",
"self",
".",
"device",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"INCOMING",
":",
"return",
"self",
... | 30 | 21.857143 |
def get_offset(self):
"""
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
"""
resp = requests.head(self.url, headers=self.headers)
offset = resp.hea... | [
"def",
"get_offset",
"(",
"self",
")",
":",
"resp",
"=",
"requests",
".",
"head",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"offset",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'upload-offset'",
")",
"if",
"offset... | 42.846154 | 21 |
def analyze_fa(fa):
"""
analyze fa (names, insertions) and convert fasta to prodigal/cmscan safe file
- find insertions (masked sequence)
- make upper case
- assign names to id number
"""
if fa.name == '<stdin>':
safe = 'temp.id'
else:
safe = '%s.id' % (fa.name)
safe ... | [
"def",
"analyze_fa",
"(",
"fa",
")",
":",
"if",
"fa",
".",
"name",
"==",
"'<stdin>'",
":",
"safe",
"=",
"'temp.id'",
"else",
":",
"safe",
"=",
"'%s.id'",
"%",
"(",
"fa",
".",
"name",
")",
"safe",
"=",
"open",
"(",
"safe",
",",
"'w'",
")",
"sequen... | 31.848485 | 15.30303 |
def ruamelindex(self, strictindex):
"""
Get the ruamel equivalent of a strict parsed index.
E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify
"""
return (
self.key_association.get(strictindex, strictindex)
if self.is_mapping()
else... | [
"def",
"ruamelindex",
"(",
"self",
",",
"strictindex",
")",
":",
"return",
"(",
"self",
".",
"key_association",
".",
"get",
"(",
"strictindex",
",",
"strictindex",
")",
"if",
"self",
".",
"is_mapping",
"(",
")",
"else",
"strictindex",
")"
] | 30.181818 | 17.272727 |
def kw_map(**kws):
"""
Decorator for renamed keyword arguments, given a keyword argument
mapping "actual_name: kwarg_rename" for each keyword parameter to
be renamed.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for actual_name, kwarg_... | [
"def",
"kw_map",
"(",
"*",
"*",
"kws",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"actual_name",
",",
"kwarg... | 35.1875 | 13.5625 |
def _chien_search_faster(self, sigma):
'''Faster chien search, processing only useful coefficients (the ones in the messages) instead of the whole 2^8 range.
Besides the speed boost, this also allows to fix a number of issue: correctly decoding when the last ecc byte is corrupted, and accepting messages... | [
"def",
"_chien_search_faster",
"(",
"self",
",",
"sigma",
")",
":",
"n",
"=",
"self",
".",
"n",
"X",
"=",
"[",
"]",
"j",
"=",
"[",
"]",
"p",
"=",
"GF2int",
"(",
"self",
".",
"generator",
")",
"# Normally we should try all 2^8 possible values, but here we opt... | 107.814815 | 85.518519 |
def add_node_set_configuration(self, param_name, node_to_value):
"""
Set Nodes parameter
:param param_name: parameter identifier (as specified by the chosen model)
:param node_to_value: dictionary mapping each node a parameter value
"""
for nid, val in future.utils.iteri... | [
"def",
"add_node_set_configuration",
"(",
"self",
",",
"param_name",
",",
"node_to_value",
")",
":",
"for",
"nid",
",",
"val",
"in",
"future",
".",
"utils",
".",
"iteritems",
"(",
"node_to_value",
")",
":",
"self",
".",
"add_node_configuration",
"(",
"param_na... | 43.777778 | 22 |
def post_event_unpublish(self, id, **data):
"""
POST /events/:id/unpublish/
Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders,
even if the event is in the past. In order for a paid event to be unpublished, it must not have... | [
"def",
"post_event_unpublish",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"post",
"(",
"\"/events/{0}/unpublish/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | 57 | 34.6 |
def _checkAllAdmxPolicies(policy_class,
adml_language='en-US',
return_full_policy_names=False,
hierarchical_return=False,
return_not_configured=False):
'''
rewrite of _getAllAdminTemplateSettingsFromRegPolFil... | [
"def",
"_checkAllAdmxPolicies",
"(",
"policy_class",
",",
"adml_language",
"=",
"'en-US'",
",",
"return_full_policy_names",
"=",
"False",
",",
"hierarchical_return",
"=",
"False",
",",
"return_not_configured",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'PO... | 73.227074 | 36.615721 |
def get_formatted_path(self, **kwargs):
"""
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
"""
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.pat... | [
"def",
"get_formatted_path",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_validate_path_placeholders",
"(",
"self",
".",
"path_placeholders",
",",
"kwargs",
")",
"return",
"self",
".",
"path",
".",
"format",
"(",
"*",
"*",
"kwargs",
")"
] | 27.25 | 18.583333 |
def HernquistX(s):
"""
Computes X function from equations (33) & (34) of Hernquist (1990)
"""
if(s<0.):
raise ValueError("s must be positive in Hernquist X function")
elif(s<1.):
return numpy.log((1+numpy.sqrt(1-s*s))/s)/numpy.sqrt(1-s*s)
elif(s==1.):
return 1.
else... | [
"def",
"HernquistX",
"(",
"s",
")",
":",
"if",
"(",
"s",
"<",
"0.",
")",
":",
"raise",
"ValueError",
"(",
"\"s must be positive in Hernquist X function\"",
")",
"elif",
"(",
"s",
"<",
"1.",
")",
":",
"return",
"numpy",
".",
"log",
"(",
"(",
"1",
"+",
... | 30.166667 | 21 |
def encode_nibbles(nibbles):
"""
The Hex Prefix function
"""
if is_nibbles_terminated(nibbles):
flag = HP_FLAG_2
else:
flag = HP_FLAG_0
raw_nibbles = remove_nibbles_terminator(nibbles)
is_odd = len(raw_nibbles) % 2
if is_odd:
flagged_nibbles = tuple(itertools.c... | [
"def",
"encode_nibbles",
"(",
"nibbles",
")",
":",
"if",
"is_nibbles_terminated",
"(",
"nibbles",
")",
":",
"flag",
"=",
"HP_FLAG_2",
"else",
":",
"flag",
"=",
"HP_FLAG_0",
"raw_nibbles",
"=",
"remove_nibbles_terminator",
"(",
"nibbles",
")",
"is_odd",
"=",
"l... | 20.777778 | 19.888889 |
def measures(self):
"""Iterate over all measures"""
from ambry.valuetype.core import ROLE
return [c for c in self.columns if c.role == ROLE.MEASURE] | [
"def",
"measures",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"columns",
"if",
"c",
".",
"role",
"==",
"ROLE",
".",
"MEASURE",
"]"
] | 33.8 | 18.4 |
def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError("Unable to download file")
with open(filename, "wb") as f:
f.write(r.content) | [
"def",
"download_file",
"(",
"url",
",",
"filename",
")",
":",
"r",
"=",
"_get_requests_session",
"(",
")",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"if",
"not",
"r",
".",
"ok",
":",
"raise",
"IOError",
"(",
"\"Unable to download file\"",... | 33.5 | 13.875 |
def iterate(self, image, feature_extractor, feature_vector):
"""iterate(image, feature_extractor, feature_vector) -> bounding_box
Scales the given image, and extracts features from all possible bounding boxes.
For each of the sampled bounding boxes, this function fills the given pre-allocated feature vect... | [
"def",
"iterate",
"(",
"self",
",",
"image",
",",
"feature_extractor",
",",
"feature_vector",
")",
":",
"for",
"scale",
",",
"scaled_image_shape",
"in",
"self",
".",
"scales",
"(",
"image",
")",
":",
"# prepare the feature extractor to extract features from the given ... | 43.066667 | 29.366667 |
def air_absorption_coefficient(medium, wavelength):
"""
The function returns linear absorbtion coefficient of selected medium at
given x-ray wavelength [mm^-1]
Mass attenuation coefficients are taken from NIST "Tables of X-Ray Mass
Attenuation Coefficients and Mass Energy-Absorption Coefficien... | [
"def",
"air_absorption_coefficient",
"(",
"medium",
",",
"wavelength",
")",
":",
"if",
"medium",
"==",
"'Helium'",
":",
"density",
"=",
"1.663e-04",
"# the table contains photon energy [Mev] and mass attenuation coefficient",
"# mu/sigma [cm^2/g]",
"mass_attenuation_coefficient",... | 61.783784 | 30.657658 |
def on(self, *args):
"""
If no arguments are specified, turn all the LEDs on. If arguments are
specified, they must be the indexes of the LEDs you wish to turn on.
For example::
from gpiozero import LEDBoard
leds = LEDBoard(2, 3, 4, 5)
leds.on(0) ... | [
"def",
"on",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_stop_blink",
"(",
")",
"if",
"args",
":",
"for",
"index",
"in",
"args",
":",
"self",
"[",
"index",
"]",
".",
"on",
"(",
")",
"else",
":",
"super",
"(",
"LEDBoard",
",",
"self"... | 34.148148 | 19.407407 |
def transcript_to_gpd_line(tx,transcript_name=None,gene_name=None,direction=None):
"""Get the genpred format string representation of the mapping
:param transcript_name:
:param gene_name:
:param strand:
:type transcript_name: string
:type gene_name: string
:type strand: string
:return: ... | [
"def",
"transcript_to_gpd_line",
"(",
"tx",
",",
"transcript_name",
"=",
"None",
",",
"gene_name",
"=",
"None",
",",
"direction",
"=",
"None",
")",
":",
"tname",
"=",
"tx",
".",
"_options",
".",
"name",
"if",
"transcript_name",
":",
"tname",
"=",
"transcri... | 32.285714 | 13.8 |
def write_file(path, data):
"""Writes data to specified path."""
with open(path, 'w') as f:
log.debug('setting %s contents:\n%s', path, data)
f.write(data)
return f | [
"def",
"write_file",
"(",
"path",
",",
"data",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"log",
".",
"debug",
"(",
"'setting %s contents:\\n%s'",
",",
"path",
",",
"data",
")",
"f",
".",
"write",
"(",
"data",
")",
"ret... | 31.166667 | 14.5 |
def read_hatlc(hatlc):
'''
This reads a consolidated HAT LC written by the functions above.
Returns a dict.
'''
lcfname = os.path.basename(hatlc)
# unzip the files first
if '.gz' in lcfname:
lcf = gzip.open(hatlc,'rb')
elif '.bz2' in lcfname:
lcf = bz2.BZ2File(hatlc, ... | [
"def",
"read_hatlc",
"(",
"hatlc",
")",
":",
"lcfname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"hatlc",
")",
"# unzip the files first",
"if",
"'.gz'",
"in",
"lcfname",
":",
"lcf",
"=",
"gzip",
".",
"open",
"(",
"hatlc",
",",
"'rb'",
")",
"elif",... | 31.580645 | 20.419355 |
def remove_term(self, t):
"""Only removes top-level terms. Child terms can be removed at the parent. """
try:
self.terms.remove(t)
except ValueError:
pass
if t.section and t.parent_term_lc == 'root':
t.section = self.add_section(t.section)
... | [
"def",
"remove_term",
"(",
"self",
",",
"t",
")",
":",
"try",
":",
"self",
".",
"terms",
".",
"remove",
"(",
"t",
")",
"except",
"ValueError",
":",
"pass",
"if",
"t",
".",
"section",
"and",
"t",
".",
"parent_term_lc",
"==",
"'root'",
":",
"t",
".",... | 26.944444 | 20.277778 |
def within_history(rev, windowdict):
"""Return whether the windowdict has history at the revision."""
if not windowdict:
return False
begin = windowdict._past[0][0] if windowdict._past else \
windowdict._future[-1][0]
end = windowdict._future[0][0] if windowdict._future else \
... | [
"def",
"within_history",
"(",
"rev",
",",
"windowdict",
")",
":",
"if",
"not",
"windowdict",
":",
"return",
"False",
"begin",
"=",
"windowdict",
".",
"_past",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"windowdict",
".",
"_past",
"else",
"windowdict",
".",
"_... | 41.111111 | 11.777778 |
def _normalize(self, string):
''' Returns a sanitized string. '''
string = super(VerbixDe, self)._normalize(string)
string = string.replace('sie; Sie', 'sie')
string = string.strip()
return string | [
"def",
"_normalize",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"super",
"(",
"VerbixDe",
",",
"self",
")",
".",
"_normalize",
"(",
"string",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'sie; Sie'",
",",
"'sie'",
")",
"string",
"=",
... | 28.714286 | 15.571429 |
def _normalize(self):
""" Make the quaternion unit length.
"""
# Get length
L = self.norm()
if not L:
raise ValueError('Quaternion cannot have 0-length.')
# Correct
self.w /= L
self.x /= L
self.y /= L
self.z /= L | [
"def",
"_normalize",
"(",
"self",
")",
":",
"# Get length",
"L",
"=",
"self",
".",
"norm",
"(",
")",
"if",
"not",
"L",
":",
"raise",
"ValueError",
"(",
"'Quaternion cannot have 0-length.'",
")",
"# Correct",
"self",
".",
"w",
"/=",
"L",
"self",
".",
"x",... | 24.416667 | 17.5 |
def fill_kwargs(self, input_layer, kwargs):
"""Applies name_suffix and defaults to kwargs and returns the result."""
return input_layer._replace_args_with_defaults(_args=self._assign_defaults,
**kwargs) | [
"def",
"fill_kwargs",
"(",
"self",
",",
"input_layer",
",",
"kwargs",
")",
":",
"return",
"input_layer",
".",
"_replace_args_with_defaults",
"(",
"_args",
"=",
"self",
".",
"_assign_defaults",
",",
"*",
"*",
"kwargs",
")"
] | 64.5 | 15.5 |
def on_timer(self, _signum, _unused_frame):
"""Invoked by the Poll timer signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted
"""
if self.is_shutting_down:
LOGGER.debug('Polling timer fired while shutting... | [
"def",
"on_timer",
"(",
"self",
",",
"_signum",
",",
"_unused_frame",
")",
":",
"if",
"self",
".",
"is_shutting_down",
":",
"LOGGER",
".",
"debug",
"(",
"'Polling timer fired while shutting down'",
")",
"return",
"if",
"not",
"self",
".",
"polled",
":",
"self"... | 37.322581 | 18.645161 |
def get_policy_config(platform,
filters=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
... | [
"def",
"get_policy_config",
"(",
"platform",
",",
"filters",
"=",
"None",
",",
"prepend",
"=",
"True",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"only_lower_merge",
"... | 34.059172 | 20.508876 |
def add(self, iterable):
""" Insert an iterable (pattern) item into the markov chain.
The order of the pattern will define more of the chain.
"""
item1 = item2 = MarkovChain.START
for item3 in iterable:
self[(item1, item2)].add_side(item3)
item1 = item... | [
"def",
"add",
"(",
"self",
",",
"iterable",
")",
":",
"item1",
"=",
"item2",
"=",
"MarkovChain",
".",
"START",
"for",
"item3",
"in",
"iterable",
":",
"self",
"[",
"(",
"item1",
",",
"item2",
")",
"]",
".",
"add_side",
"(",
"item3",
")",
"item1",
"=... | 39.3 | 10.6 |
def to_numpy_matrix(self, variable_order=None):
"""Convert a binary quadratic model to NumPy 2D array.
Args:
variable_order (list, optional):
If provided, indexes the rows/columns of the NumPy array. If `variable_order` includes
any variables not in the binar... | [
"def",
"to_numpy_matrix",
"(",
"self",
",",
"variable_order",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"variable_order",
"is",
"None",
":",
"# just use the existing variable labels, assuming that they are [0, N)",
"num_variables",
"=",
"len",
"(",
"... | 38.45 | 25.3375 |
def resolve_loader(self, meta: ProgramDescription):
"""
Resolve program loader
"""
if not meta.loader:
meta.loader = 'single' if meta.path else 'separate'
for loader_cls in self._loaders:
if loader_cls.name == meta.loader:
meta.loader_cls ... | [
"def",
"resolve_loader",
"(",
"self",
",",
"meta",
":",
"ProgramDescription",
")",
":",
"if",
"not",
"meta",
".",
"loader",
":",
"meta",
".",
"loader",
"=",
"'single'",
"if",
"meta",
".",
"path",
"else",
"'separate'",
"for",
"loader_cls",
"in",
"self",
"... | 32.444444 | 14 |
def member_command(self, member_id, command):
"""apply command (start/stop/restart) to member instance of replica set
Args:
member_id - member index
command - string command (start/stop/restart)
return True if operation success otherwise False
"""
server_... | [
"def",
"member_command",
"(",
"self",
",",
"member_id",
",",
"command",
")",
":",
"server_id",
"=",
"self",
".",
"_servers",
".",
"host_to_server_id",
"(",
"self",
".",
"member_id_to_host",
"(",
"member_id",
")",
")",
"return",
"self",
".",
"_servers",
".",
... | 41 | 13 |
def __merge_json_values(current, previous):
"""Merges the values between the current and previous run of the script."""
for value in current:
name = value['name']
# Find the previous value
previous_value = __find_and_remove_value(previous, value)
if previous_value is not None:
... | [
"def",
"__merge_json_values",
"(",
"current",
",",
"previous",
")",
":",
"for",
"value",
"in",
"current",
":",
"name",
"=",
"value",
"[",
"'name'",
"]",
"# Find the previous value",
"previous_value",
"=",
"__find_and_remove_value",
"(",
"previous",
",",
"value",
... | 32.576923 | 19.615385 |
def sample_discrete_from_log(p_log,return_lognorms=False,axis=0,dtype=np.int32):
'samples log probability array along specified axis'
lognorms = logsumexp(p_log,axis=axis)
cumvals = np.exp(p_log - np.expand_dims(lognorms,axis)).cumsum(axis)
thesize = np.array(p_log.shape)
thesize[axis] = 1
randv... | [
"def",
"sample_discrete_from_log",
"(",
"p_log",
",",
"return_lognorms",
"=",
"False",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
":",
"lognorms",
"=",
"logsumexp",
"(",
"p_log",
",",
"axis",
"=",
"axis",
")",
"cumvals",
"=",
"n... | 43.785714 | 17.928571 |
def append(self, *other):
"""
Append self with other stream(s). Chaining this way has the behaviour:
``self = Stream(self, *others)``
"""
self._data = it.chain(self._data, Stream(*other)._data)
return self | [
"def",
"append",
"(",
"self",
",",
"*",
"other",
")",
":",
"self",
".",
"_data",
"=",
"it",
".",
"chain",
"(",
"self",
".",
"_data",
",",
"Stream",
"(",
"*",
"other",
")",
".",
"_data",
")",
"return",
"self"
] | 25 | 19.444444 |
def create_role_config_groups(resource_root, service_name, apigroup_list,
cluster_name="default"):
"""
Create role config groups.
@param resource_root: The root Resource object.
@param service_name: Service name.
@param apigroup_list: List of role config groups to create.
@param cluster_name: Cluster na... | [
"def",
"create_role_config_groups",
"(",
"resource_root",
",",
"service_name",
",",
"apigroup_list",
",",
"cluster_name",
"=",
"\"default\"",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"post",
",",
"_get_role_config_groups_path",
"(",
"cluster_name",
",",
... | 38.571429 | 12.571429 |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reaso... | [
"def",
"verify",
"(",
"self",
",",
"obj",
")",
":",
"out_obj",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"ValidationError",
"(",
"\"Invalid dictionary\"",
",",
"reason",
"=",
"\"object is not a dictionary\"",
")",
... | 42.046154 | 28 |
def room_reserve(self):
"""
This method create a new record for hotel.reservation
-----------------------------------------------------
@param self: The object pointer
@return: new record set for hotel reservation.
"""
hotel_res_obj = self.env['hotel.reservation']... | [
"def",
"room_reserve",
"(",
"self",
")",
":",
"hotel_res_obj",
"=",
"self",
".",
"env",
"[",
"'hotel.reservation'",
"]",
"for",
"res",
"in",
"self",
":",
"rec",
"=",
"(",
"hotel_res_obj",
".",
"create",
"(",
"{",
"'partner_id'",
":",
"res",
".",
"partner... | 48.185185 | 15.740741 |
def install(force=False, lazy=False):
"""
Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar
is already available, unless ``lazy`` is ``True``.)
:param bool force: Force download even if local jar already exists.
:param bool lazy: Don't report an error if local jar already exists a... | [
"def",
"install",
"(",
"force",
"=",
"False",
",",
"lazy",
"=",
"False",
")",
":",
"if",
"exists",
"(",
"antlr_jar_path",
")",
":",
"if",
"lazy",
":",
"return",
"if",
"not",
"force",
":",
"raise",
"OSError",
"(",
"errno",
".",
"EEXIST",
",",
"'file a... | 35.384615 | 20.846154 |
def _field_sort_name(cls, name):
"""Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `dat... | [
"def",
"_field_sort_name",
"(",
"cls",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"cls",
".",
"__dict__",
"[",
"name",
"]",
",",
"DateItemField",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"'year'",
",",
"'date0'",
",",
"name",
")",
"name",
... | 44.357143 | 15 |
def _build_put_headers(self, robj, if_none_match=False):
"""Build the headers for a POST/PUT request."""
# Construct the headers...
if robj.charset is not None:
content_type = ('%s; charset="%s"' %
(robj.content_type, robj.charset))
else:
... | [
"def",
"_build_put_headers",
"(",
"self",
",",
"robj",
",",
"if_none_match",
"=",
"False",
")",
":",
"# Construct the headers...",
"if",
"robj",
".",
"charset",
"is",
"not",
"None",
":",
"content_type",
"=",
"(",
"'%s; charset=\"%s\"'",
"%",
"(",
"robj",
".",
... | 33 | 17.735294 |
def background_color(self):
"""Background color."""
if self._has_real():
return self._data.real_background_color
return self._data.background_color | [
"def",
"background_color",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_background_color",
"return",
"self",
".",
"_data",
".",
"background_color"
] | 35.8 | 7.6 |
def _get_addresses(self, address_data, retain_name=False):
"""
Takes RFC-compliant email addresses in both terse (email only)
and verbose (name + email) forms and returns a list of
email address strings
(TODO: breaking change that returns a tuple of (name, email) per string)
... | [
"def",
"_get_addresses",
"(",
"self",
",",
"address_data",
",",
"retain_name",
"=",
"False",
")",
":",
"if",
"retain_name",
":",
"raise",
"NotImplementedError",
"(",
"\"Not yet implemented, but will need client-code changes too\"",
")",
"# We trust than an email address conta... | 41.807692 | 22.269231 |
async def channel_cmd(self, ctx, *, channel : discord.Channel = None):
"""Ignores a specific channel from being processed.
If no channel is specified, the current channel is ignored.
If a channel is ignored then the bot does not process commands in that
channel until it is unignored.
... | [
"async",
"def",
"channel_cmd",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"channel",
":",
"discord",
".",
"Channel",
"=",
"None",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"ctx",
".",
"message",
".",
"channel",
"ignored",
"=",
"self"... | 40.105263 | 22.736842 |
def to_escpos(self):
""" converts the current style to an escpos command string """
cmd = ''
ordered_cmds = self.cmds.keys()
ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order']))
for style in ordered_cmds:
cmd += self.cmds[style][self.get(... | [
"def",
"to_escpos",
"(",
"self",
")",
":",
"cmd",
"=",
"''",
"ordered_cmds",
"=",
"self",
".",
"cmds",
".",
"keys",
"(",
")",
"ordered_cmds",
".",
"sort",
"(",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"self",
".",
"cmds",
"[",
"x",
"]",
"[",
"... | 42.375 | 16.875 |
def attributes(self, filter=Filter()):
"""
Get only the attribute content.
@param filter: A filter to constrain the result.
@type filter: L{Filter}
@return: A list of tuples (attr, ancestry)
@rtype: [(L{SchemaObject}, [L{SchemaObject},..]),..]
"""
result =... | [
"def",
"attributes",
"(",
"self",
",",
"filter",
"=",
"Filter",
"(",
")",
")",
":",
"result",
"=",
"[",
"]",
"for",
"child",
",",
"ancestry",
"in",
"self",
":",
"if",
"child",
".",
"isattr",
"(",
")",
"and",
"child",
"in",
"filter",
":",
"result",
... | 36.153846 | 9.230769 |
def connect_tcp(self, address, port):
"""Connect to tcp/ip `address`:`port`. Delegated to `_connect_tcp`."""
info('Connecting to TCP address: %s:%d', address, port)
self._connect_tcp(address, port) | [
"def",
"connect_tcp",
"(",
"self",
",",
"address",
",",
"port",
")",
":",
"info",
"(",
"'Connecting to TCP address: %s:%d'",
",",
"address",
",",
"port",
")",
"self",
".",
"_connect_tcp",
"(",
"address",
",",
"port",
")"
] | 54.5 | 6.5 |
def lemmatize(ambiguous_word: str, pos: str = None, neverstem=False,
lemmatizer=wnl, stemmer=porter) -> str:
"""
Tries to convert a surface word into lemma, and if lemmatize word is not in
wordnet then try and convert surface word into its stem.
This is to handle the case where users inpu... | [
"def",
"lemmatize",
"(",
"ambiguous_word",
":",
"str",
",",
"pos",
":",
"str",
"=",
"None",
",",
"neverstem",
"=",
"False",
",",
"lemmatizer",
"=",
"wnl",
",",
"stemmer",
"=",
"porter",
")",
"->",
"str",
":",
"# Try to be a little smarter and use most frequent... | 37.6 | 18.48 |
def expected_inheritance(variant_obj):
"""Gather information from common gene information."""
manual_models = set()
for gene in variant_obj.get('genes', []):
manual_models.update(gene.get('manual_inheritance', []))
return list(manual_models) | [
"def",
"expected_inheritance",
"(",
"variant_obj",
")",
":",
"manual_models",
"=",
"set",
"(",
")",
"for",
"gene",
"in",
"variant_obj",
".",
"get",
"(",
"'genes'",
",",
"[",
"]",
")",
":",
"manual_models",
".",
"update",
"(",
"gene",
".",
"get",
"(",
"... | 43.333333 | 9.333333 |
def iter_search_nodes(self, **conditions):
"""
Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees.
"""
for n in self... | [
"def",
"iter_search_nodes",
"(",
"self",
",",
"*",
"*",
"conditions",
")",
":",
"for",
"n",
"in",
"self",
".",
"traverse",
"(",
")",
":",
"conditions_passed",
"=",
"0",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"conditions",
")",
... | 42.428571 | 12.142857 |
def _create_cfgnode(self, sim_successors, call_stack, func_addr, block_id=None, depth=None, exception_info=None):
"""
Create a context-sensitive CFGNode instance for a specific block.
:param SimSuccessors sim_successors: The SimSuccessors object.
:param CallStack call_stack_suff... | [
"def",
"_create_cfgnode",
"(",
"self",
",",
"sim_successors",
",",
"call_stack",
",",
"func_addr",
",",
"block_id",
"=",
"None",
",",
"depth",
"=",
"None",
",",
"exception_info",
"=",
"None",
")",
":",
"sa",
"=",
"sim_successors",
".",
"artifacts",
"# shorth... | 47.38806 | 23.059701 |
def _handle_input_request(self, msg):
"""Save history and add a %plot magic."""
if self._hidden:
raise RuntimeError('Request for raw input during hidden execution.')
# Make sure that all output from the SUB channel has been processed
# before entering readline mode.
... | [
"def",
"_handle_input_request",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"_hidden",
":",
"raise",
"RuntimeError",
"(",
"'Request for raw input during hidden execution.'",
")",
"# Make sure that all output from the SUB channel has been processed",
"# before entering... | 42.5 | 15.733333 |
def _generate_route_helper(self, namespace, route, download_to_file=False):
"""Generate a Python method that corresponds to a route.
:param namespace: Namespace that the route belongs to.
:param stone.ir.ApiRoute route: IR node for the route.
:param bool download_to_file: Whether a spec... | [
"def",
"_generate_route_helper",
"(",
"self",
",",
"namespace",
",",
"route",
",",
"download_to_file",
"=",
"False",
")",
":",
"arg_data_type",
"=",
"route",
".",
"arg_data_type",
"result_data_type",
"=",
"route",
".",
"result_data_type",
"request_binary_body",
"=",... | 42.5 | 18.078431 |
def all(self):
""" Returns list with vids of all indexed partitions. """
partitions = []
query = text("""
SELECT dataset_vid, vid
FROM partition_index;""")
for result in self.execute(query):
dataset_vid, vid = result
partitions.append(Par... | [
"def",
"all",
"(",
"self",
")",
":",
"partitions",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT dataset_vid, vid\n FROM partition_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"execute",
"(",
"query",
")",
":",
"datase... | 33.083333 | 16.916667 |
def install_var(instance, clear_target, clear_all):
"""Install required folders in /var"""
_check_root()
log("Checking frontend library and cache directories",
emitter='MANAGE')
uid = pwd.getpwnam("hfos").pw_uid
gid = grp.getgrnam("hfos").gr_gid
join = os.path.join
# If these nee... | [
"def",
"install_var",
"(",
"instance",
",",
"clear_target",
",",
"clear_all",
")",
":",
"_check_root",
"(",
")",
"log",
"(",
"\"Checking frontend library and cache directories\"",
",",
"emitter",
"=",
"'MANAGE'",
")",
"uid",
"=",
"pwd",
".",
"getpwnam",
"(",
"\"... | 32.767442 | 17.55814 |
def add_widget(self, widget, column=0):
"""
Add a widget to this Layout.
If you are adding this Widget to the Layout dynamically after starting to play the Scene,
don't forget to ensure that the value is explicitly set before the next update.
:param widget: The widget to be add... | [
"def",
"add_widget",
"(",
"self",
",",
"widget",
",",
"column",
"=",
"0",
")",
":",
"# Make sure that the Layout is fully initialised before we try to add any widgets.",
"if",
"self",
".",
"_frame",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"You must add the La... | 42.6 | 23.6 |
def run_sorters(sorter_list, recording_dict_or_list, working_folder, grouping_property=None,
shared_binary_copy=False, engine=None, engine_kargs={}, debug=False, write_log=True):
"""
This run several sorter on several recording.
Simple implementation will nested loops.
Need... | [
"def",
"run_sorters",
"(",
"sorter_list",
",",
"recording_dict_or_list",
",",
"working_folder",
",",
"grouping_property",
"=",
"None",
",",
"shared_binary_copy",
"=",
"False",
",",
"engine",
"=",
"None",
",",
"engine_kargs",
"=",
"{",
"}",
",",
"debug",
"=",
"... | 38.062937 | 23.657343 |
def make_uniq_for_step(ctx, ukeys, step, stage, full_data, clean_missing_after_seconds, to_uniq):
"""initially just a copy from UNIQ_PULL"""
# TODO:
# this still seems to work ok for Storage types json/bubble,
# for DS we need to reload de dumped step to uniqify
if not ukeys:
return to_uni... | [
"def",
"make_uniq_for_step",
"(",
"ctx",
",",
"ukeys",
",",
"step",
",",
"stage",
",",
"full_data",
",",
"clean_missing_after_seconds",
",",
"to_uniq",
")",
":",
"# TODO:",
"# this still seems to work ok for Storage types json/bubble,",
"# for DS we need to reload de dumped s... | 41.625 | 21.25 |
def load_corpus(*data_file_paths):
"""
Return the data contained within a specified corpus.
"""
for file_path in data_file_paths:
corpus = []
corpus_data = read_corpus(file_path)
conversations = corpus_data.get('conversations', [])
corpus.extend(conversations)
c... | [
"def",
"load_corpus",
"(",
"*",
"data_file_paths",
")",
":",
"for",
"file_path",
"in",
"data_file_paths",
":",
"corpus",
"=",
"[",
"]",
"corpus_data",
"=",
"read_corpus",
"(",
"file_path",
")",
"conversations",
"=",
"corpus_data",
".",
"get",
"(",
"'conversati... | 28.357143 | 15.071429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.