text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create(cls, **kwargs):
"""Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="vicky@h.com")
>>> user.id... | [
"def",
"create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"cls",
".",
"add",
"(",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
")",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | 24.052632 | 22.526316 |
def active_days(records):
"""
The number of days during which the user was active. A user is considered
active if he sends a text, receives a text, initiates a call, receives a
call, or has a mobility point.
"""
days = set(r.datetime.date() for r in records)
return len(days) | [
"def",
"active_days",
"(",
"records",
")",
":",
"days",
"=",
"set",
"(",
"r",
".",
"datetime",
".",
"date",
"(",
")",
"for",
"r",
"in",
"records",
")",
"return",
"len",
"(",
"days",
")"
] | 37 | 15.5 |
def dump(self, o_name=None, details=False, raw=False):
"""Dump an host (all hosts) from the arbiter.
The arbiter will get the host (all hosts) information from all its schedulers.
This gets the main host information from the scheduler. If details is set, then some
more information are ... | [
"def",
"dump",
"(",
"self",
",",
"o_name",
"=",
"None",
",",
"details",
"=",
"False",
",",
"raw",
"=",
"False",
")",
":",
"if",
"details",
"is",
"not",
"False",
":",
"details",
"=",
"bool",
"(",
"details",
")",
"if",
"raw",
"is",
"not",
"False",
... | 52.809091 | 27.809091 |
def internal_reset(self):
"""
internal state reset.
used e.g. in unittests
"""
log.critical("PIA internal_reset()")
self.empty_key_toggle = True
self.current_input_char = None
self.input_repead = 0 | [
"def",
"internal_reset",
"(",
"self",
")",
":",
"log",
".",
"critical",
"(",
"\"PIA internal_reset()\"",
")",
"self",
".",
"empty_key_toggle",
"=",
"True",
"self",
".",
"current_input_char",
"=",
"None",
"self",
".",
"input_repead",
"=",
"0"
] | 28.111111 | 6.333333 |
def initQApplication():
""" Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist.
Sets Argos specific attributes, such as the OrganizationName, so that the application
persistent settings are read/written to the correct settings file/winreg. It is therefore
impor... | [
"def",
"initQApplication",
"(",
")",
":",
"# PyQtGraph recommends raster graphics system for OS-X.",
"if",
"'darwin'",
"in",
"sys",
".",
"platform",
":",
"graphicsSystem",
"=",
"\"raster\"",
"# raster, native or opengl",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'Q... | 45.777778 | 25.111111 |
def packet_xml(url_encoded_ivorn=None):
"""
Returns the XML packet contents stored for a given IVORN.
The required IVORN should be appended to the URL after ``/xml/``
in :ref:`URL-encoded <url-encoding>` form.
"""
# Handle Apache / Debug server difference...
# Apache conf must include the s... | [
"def",
"packet_xml",
"(",
"url_encoded_ivorn",
"=",
"None",
")",
":",
"# Handle Apache / Debug server difference...",
"# Apache conf must include the setting::",
"# AllowEncodedSlashes NoDecode",
"# otherwise urlencoded paths have",
"# double-slashes ('//') replaced with single-slashes ('/... | 36.454545 | 15.727273 |
def getEffort(self, edgeID, time):
"""getEffort(string, double) -> double
Returns the effort value used for (re-)routing
which is valid on the edge at the given time.
"""
self._connection._beginMessage(tc.CMD_GET_EDGE_VARIABLE, tc.VAR_EDGE_EFFORT,
... | [
"def",
"getEffort",
"(",
"self",
",",
"edgeID",
",",
"time",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_GET_EDGE_VARIABLE",
",",
"tc",
".",
"VAR_EDGE_EFFORT",
",",
"edgeID",
",",
"1",
"+",
"4",
")",
"self",
".",
"_... | 48.25 | 17.833333 |
def before_after_apply(self, before_fn, after_fn, leaf_fn=None):
"""Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant
"""
stack = [self]
while stack:
... | [
"def",
"before_after_apply",
"(",
"self",
",",
"before_fn",
",",
"after_fn",
",",
"leaf_fn",
"=",
"None",
")",
":",
"stack",
"=",
"[",
"self",
"]",
"while",
"stack",
":",
"node",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"node",
".",
"is_leaf",
":",
... | 37.75 | 12.9 |
def sample(self, num_samples=1000, hmc_iters=20):
"""
Sample the (unfixed) model parameters.
:param num_samples: the number of samples to draw (1000 by default)
:type num_samples: int
:param hmc_iters: the number of leap-frog iterations (20 by default)
:type hmc_... | [
"def",
"sample",
"(",
"self",
",",
"num_samples",
"=",
"1000",
",",
"hmc_iters",
"=",
"20",
")",
":",
"params",
"=",
"np",
".",
"empty",
"(",
"(",
"num_samples",
",",
"self",
".",
"p",
".",
"size",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num_s... | 40 | 18.066667 |
def QWidget_factory(ui_file=None, *args, **kwargs):
"""
Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes
using given ui file.
:param ui_file: Ui file.
:type ui_file: unicode
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords ... | [
"def",
"QWidget_factory",
"(",
"ui_file",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"ui_file",
"or",
"DEFAULT_UI_FILE",
"if",
"not",
"foundations",
".",
"common",
".",
"path_exists",
"(",
"file",
")",
":",
"raise",
... | 27.834783 | 20.026087 |
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 _module_name_from_previous_frame(num_frames_back):
"""
Returns the module name associated with a frame `num_frames_back` in the
call stack. This function adds 1 to account for itself, so `num_frames_back`
should be given relative to the caller.
"""
frm = inspect.stack()[num_frames_back + 1]
... | [
"def",
"_module_name_from_previous_frame",
"(",
"num_frames_back",
")",
":",
"frm",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"num_frames_back",
"+",
"1",
"]",
"return",
"inspect",
".",
"getmodule",
"(",
"frm",
"[",
"0",
"]",
")",
".",
"__name__"
] | 44.75 | 13 |
def load_rho(name, column):
'''Load a datafile with rho structure like mag and phase
'''
try:
content = np.loadtxt(name, skiprows=1, usecols=([column]))
except:
raise ValueError('Given column to open does not exist.')
return content | [
"def",
"load_rho",
"(",
"name",
",",
"column",
")",
":",
"try",
":",
"content",
"=",
"np",
".",
"loadtxt",
"(",
"name",
",",
"skiprows",
"=",
"1",
",",
"usecols",
"=",
"(",
"[",
"column",
"]",
")",
")",
"except",
":",
"raise",
"ValueError",
"(",
... | 29 | 26.555556 |
def choose_ancestral_states_map(tree, feature, states):
"""
Chooses node ancestral states based on their marginal probabilities using MAP method.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the ancestral states are to be chosen
:param states: numpy.array of... | [
"def",
"choose_ancestral_states_map",
"(",
"tree",
",",
"feature",
",",
"states",
")",
":",
"lh_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"LH",
")",
"allowed_state_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"ALLOWED... | 54.588235 | 28.823529 |
def single_queue_send(
transport: 'UDPTransport',
recipient: Address,
queue: Queue_T,
queue_identifier: QueueIdentifier,
event_stop: Event,
event_healthy: Event,
event_unhealthy: Event,
message_retries: int,
message_retry_timeout: int,
mess... | [
"def",
"single_queue_send",
"(",
"transport",
":",
"'UDPTransport'",
",",
"recipient",
":",
"Address",
",",
"queue",
":",
"Queue_T",
",",
"queue_identifier",
":",
"QueueIdentifier",
",",
"event_stop",
":",
"Event",
",",
"event_healthy",
":",
"Event",
",",
"event... | 29.831776 | 19.682243 |
def search(self, query, _or=False, ignores=[]):
"""Search word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<list>SEARCH_RESULT(<int> document_id,
<list <int> > counts
... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"_or",
"=",
"False",
",",
"ignores",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"str",
")",
":",
"dids",
"=",
"MapIntInt",
"(",
"{",
"}",
")",
"self",
".",
"fm",
".",
"search... | 37.861111 | 13.611111 |
def write_amendment(self, amendment_id, file_content, branch, author):
"""Given an amendment_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_amendment_')[0]
msg = "Update Amendm... | [
"def",
"write_amendment",
"(",
"self",
",",
"amendment_id",
",",
"file_content",
",",
"branch",
",",
"author",
")",
":",
"gh_user",
"=",
"branch",
".",
"split",
"(",
"'_amendment_'",
")",
"[",
"0",
"]",
"msg",
"=",
"\"Update Amendment '%s' via OpenTree API\"",
... | 45.615385 | 16.692308 |
def is_transition_metal(self):
"""
True if element is a transition metal.
"""
ns = list(range(21, 31))
ns.extend(list(range(39, 49)))
ns.append(57)
ns.extend(list(range(72, 81)))
ns.append(89)
ns.extend(list(range(104, 113)))
return self.Z ... | [
"def",
"is_transition_metal",
"(",
"self",
")",
":",
"ns",
"=",
"list",
"(",
"range",
"(",
"21",
",",
"31",
")",
")",
"ns",
".",
"extend",
"(",
"list",
"(",
"range",
"(",
"39",
",",
"49",
")",
")",
")",
"ns",
".",
"append",
"(",
"57",
")",
"n... | 28.636364 | 7.181818 |
def _report_volume_count(self):
"""Report volume count per state (dangling or not)"""
m_func = FUNC_MAP[GAUGE][self.use_histogram]
attached_volumes = self.docker_util.client.volumes(filters={'dangling': False})
dangling_volumes = self.docker_util.client.volumes(filters={'dangling': True... | [
"def",
"_report_volume_count",
"(",
"self",
")",
":",
"m_func",
"=",
"FUNC_MAP",
"[",
"GAUGE",
"]",
"[",
"self",
".",
"use_histogram",
"]",
"attached_volumes",
"=",
"self",
".",
"docker_util",
".",
"client",
".",
"volumes",
"(",
"filters",
"=",
"{",
"'dang... | 64.1 | 31.8 |
def cleanup(self):
"""
Clean up the saved state.
"""
if os.path.exists(self.path):
os.remove(self.path) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"path",
")"
] | 23.666667 | 6.666667 |
def split_model_idx(model:nn.Module, idxs:Collection[int])->ModuleList:
"Split `model` according to the indexes in `idxs`."
layers = flatten_model(model)
if idxs[0] != 0: idxs = [0] + idxs
if idxs[-1] != len(layers): idxs.append(len(layers))
return [nn.Sequential(*layers[i:j]) for i,j in zip(idxs[:-... | [
"def",
"split_model_idx",
"(",
"model",
":",
"nn",
".",
"Module",
",",
"idxs",
":",
"Collection",
"[",
"int",
"]",
")",
"->",
"ModuleList",
":",
"layers",
"=",
"flatten_model",
"(",
"model",
")",
"if",
"idxs",
"[",
"0",
"]",
"!=",
"0",
":",
"idxs",
... | 54.666667 | 17.666667 |
def append(self, row=None):
"""append(row=None)
:param row: a list of values to apply to the newly append row or :obj:`None`
:type row: [:obj:`object`] or :obj:`None`
:returns: :obj:`Gtk.TreeIter` of the appended row
:rtype: :obj:`Gtk.TreeIter`
If `row` is :obj:`None` ... | [
"def",
"append",
"(",
"self",
",",
"row",
"=",
"None",
")",
":",
"if",
"row",
":",
"return",
"self",
".",
"_do_insert",
"(",
"-",
"1",
",",
"row",
")",
"# gtk_list_store_insert() does not know about the \"position == -1\"",
"# case, so use append() here",
"else",
... | 35.086957 | 21.608696 |
def df_drop_duplicates(df, ignore_key_pattern="time"):
"""
Drop duplicates from dataframe ignore columns with keys containing defined pattern.
:param df:
:param noinfo_key_pattern:
:return:
"""
keys_to_remove = list_contains(df.keys(), ignore_key_pattern)
#key_tf = [key.find(noinfo_key... | [
"def",
"df_drop_duplicates",
"(",
"df",
",",
"ignore_key_pattern",
"=",
"\"time\"",
")",
":",
"keys_to_remove",
"=",
"list_contains",
"(",
"df",
".",
"keys",
"(",
")",
",",
"ignore_key_pattern",
")",
"#key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()]",
... | 27.421053 | 21.421053 |
def upper_bollinger_band(data, period, std_mult=2.0):
"""
Upper Bollinger Band.
Formula:
u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
simple_ma = sma(data, period)[period-1:]
upper_bb = []
for idx in rang... | [
"def",
"upper_bollinger_band",
"(",
"data",
",",
"period",
",",
"std_mult",
"=",
"2.0",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"simple_ma",
"=",
"sma",
"(",
"data"... | 27.789474 | 17.894737 |
def do_video(self, args):
"""Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever subcommand function was selected
func(self, args)
else:
... | [
"def",
"do_video",
"(",
"self",
",",
"args",
")",
":",
"func",
"=",
"getattr",
"(",
"args",
",",
"'func'",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# Call whatever subcommand function was selected",
"func",
"(",
"self",
",",
"args",
")",
... | 44.111111 | 12.111111 |
def _port_action_vxlan(self, port, segment, func):
"""Verify configuration and then process event."""
# If the segment is None, just log a warning message and return.
if segment is None:
self._log_missing_segment()
return
device_id = port.get('device_id')
... | [
"def",
"_port_action_vxlan",
"(",
"self",
",",
"port",
",",
"segment",
",",
"func",
")",
":",
"# If the segment is None, just log a warning message and return.",
"if",
"segment",
"is",
"None",
":",
"self",
".",
"_log_missing_segment",
"(",
")",
"return",
"device_id",
... | 40.454545 | 17.909091 |
def policy_exists(policyName,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name, check to see if the given policy exists.
Returns True if the given policy exists and returns False if the given
policy does not exist.
CLI Example:
.. code-block:: bash
... | [
"def",
"policy_exists",
"(",
"policyName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"... | 29.76 | 24.88 |
def btc_tx_serialize(_txobj):
"""
Given a transaction dict returned by btc_tx_deserialize, convert it back into a
hex-encoded byte string.
Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools)
"""
# output buffer
o = []
txobj = ... | [
"def",
"btc_tx_serialize",
"(",
"_txobj",
")",
":",
"# output buffer",
"o",
"=",
"[",
"]",
"txobj",
"=",
"None",
"if",
"encoding",
".",
"json_is_base",
"(",
"_txobj",
",",
"16",
")",
":",
"# txobj is built from hex strings already. deserialize them ",
"txobj",
"=... | 28.4125 | 23.8875 |
def srun_nodes(self):
"""Get list of nodes where to execute the command
"""
count = self.execution.get('srun_nodes', 0)
if isinstance(count, six.string_types):
tag = count
count = 0
elif isinstance(count, SEQUENCES):
return count
else:
... | [
"def",
"srun_nodes",
"(",
"self",
")",
":",
"count",
"=",
"self",
".",
"execution",
".",
"get",
"(",
"'srun_nodes'",
",",
"0",
")",
"if",
"isinstance",
"(",
"count",
",",
"six",
".",
"string_types",
")",
":",
"tag",
"=",
"count",
"count",
"=",
"0",
... | 34.705882 | 10.941176 |
def get_language_data(self, qid, lang, lang_data_type):
"""
get language data for specified qid
:param qid:
:param lang: language code
:param lang_data_type: 'label', 'description' or 'aliases'
:return: list of strings
If nothing is found:
If lang_data... | [
"def",
"get_language_data",
"(",
"self",
",",
"qid",
",",
"lang",
",",
"lang_data_type",
")",
":",
"self",
".",
"init_language_data",
"(",
"lang",
",",
"lang_data_type",
")",
"current_lang_data",
"=",
"self",
".",
"loaded_langs",
"[",
"lang",
"]",
"[",
"lang... | 41.210526 | 14.894737 |
def load_graphs():
'''load graphs from mavgraphs.xml'''
mestate.graphs = []
gfiles = ['mavgraphs.xml']
if 'HOME' in os.environ:
for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
for filename in filenames:
if filename.lower().e... | [
"def",
"load_graphs",
"(",
")",
":",
"mestate",
".",
"graphs",
"=",
"[",
"]",
"gfiles",
"=",
"[",
"'mavgraphs.xml'",
"]",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"for",
"dirname",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"... | 44.95122 | 19.439024 |
def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, f... | [
"def",
"initialize_fields",
"(",
"self",
")",
":",
"# # Pull all the \"normal\" fields off the model instance meta.",
"for",
"name",
",",
"field",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"fie... | 41.666667 | 20.809524 |
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials):
"""
Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features.
"""
#######################################################################... | [
"def",
"plotConvergenceByColumnTopology",
"(",
"results",
",",
"columnRange",
",",
"featureRange",
",",
"networkType",
",",
"numTrials",
")",
":",
"########################################################################",
"#",
"# Accumulate all the results per column in a convergenc... | 34.738462 | 22.676923 |
def parse_line(self, line):
"""Parses a single line of a GPI.
Return a tuple `(processed_line, entities)`. Typically
there will be a single entity, but in some cases there
may be none (invalid line) or multiple (disjunctive clause in
annotation extensions)
Note: most ap... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"vals",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"len",
"(",
"vals",
")",
"<",
"7",
":",
"self",
".",
"report",
".",
"error",
"(",
"line",
",",
"assocparser",
".",
"Report",
".... | 29.243902 | 21.170732 |
def get_physical_port(self):
"""Returns the link aggregation object or the ethernet port object."""
obj = None
if self.is_link_aggregation():
obj = UnityLinkAggregation.get(self._cli, self.get_id())
else:
obj = UnityEthernetPort.get(self._cli, self.get_id())
... | [
"def",
"get_physical_port",
"(",
"self",
")",
":",
"obj",
"=",
"None",
"if",
"self",
".",
"is_link_aggregation",
"(",
")",
":",
"obj",
"=",
"UnityLinkAggregation",
".",
"get",
"(",
"self",
".",
"_cli",
",",
"self",
".",
"get_id",
"(",
")",
")",
"else",... | 40.75 | 17.25 |
def create_module(clear_target, target):
"""Creates a new template HFOS plugin module"""
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter='MANAGE')
sys.exit(2... | [
"def",
"create_module",
"(",
"clear_target",
",",
"target",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"if",
"clear_target",
":",
"shutil",
".",
"rmtree",
"(",
"target",
")",
"else",
":",
"log",
"(",
"\"Target exists! Use ... | 27.347826 | 19.826087 |
def get_stack_frames(error_stack: bool = True) -> list:
"""
Returns a list of the current stack frames, which are pruned focus on the
Cauldron code where the relevant information resides.
"""
cauldron_path = environ.paths.package()
resources_path = environ.paths.resources()
frames = (
... | [
"def",
"get_stack_frames",
"(",
"error_stack",
":",
"bool",
"=",
"True",
")",
"->",
"list",
":",
"cauldron_path",
"=",
"environ",
".",
"paths",
".",
"package",
"(",
")",
"resources_path",
"=",
"environ",
".",
"paths",
".",
"resources",
"(",
")",
"frames",
... | 29.074074 | 21.814815 |
def analog_sensor_power(cls, bus, operation):
""" Method that turns on all of the analog sensor modules
Includes all attached soil moisture sensors
Note that all of the SensorCluster object should be attached
in parallel and only 1 GPIO pin is available
... | [
"def",
"analog_sensor_power",
"(",
"cls",
",",
"bus",
",",
"operation",
")",
":",
"# Set appropriate analog sensor power bit in GPIO mask\r",
"# using the ControlCluster bank_mask to avoid overwriting any data\r",
"reg_data",
"=",
"get_IO_reg",
"(",
"bus",
",",
"0x20",
",",
"... | 53.52 | 20.88 |
def is_valid(self, wordid) -> bool:
"""
Ensures </s> is only generated when the hypothesis is completed.
:param wordid: The wordid to validate.
:return: True if all constraints are already met or the word ID is not the EOS id.
"""
return self.finished() or wordid != self... | [
"def",
"is_valid",
"(",
"self",
",",
"wordid",
")",
"->",
"bool",
":",
"return",
"self",
".",
"finished",
"(",
")",
"or",
"wordid",
"!=",
"self",
".",
"eos_id",
"or",
"(",
"self",
".",
"num_needed",
"(",
")",
"==",
"1",
"and",
"self",
".",
"eos_id"... | 47.75 | 26.25 |
def broadcast_variables(*variables):
"""Given any number of variables, return variables with matching dimensions
and broadcast data.
The data on the returned variables will be a view of the data on the
corresponding original arrays, but dimensions will be reordered and
inserted so that both broadca... | [
"def",
"broadcast_variables",
"(",
"*",
"variables",
")",
":",
"dims_map",
"=",
"_unified_dims",
"(",
"variables",
")",
"dims_tuple",
"=",
"tuple",
"(",
"dims_map",
")",
"return",
"tuple",
"(",
"var",
".",
"set_dims",
"(",
"dims_map",
")",
"if",
"var",
"."... | 48.5 | 18.357143 |
def read_property_to_any(obj, propertyIdentifier, propertyArrayIndex=None):
"""Read the specified property of the object, with the optional array index,
and cast the result into an Any object."""
if _debug: read_property_to_any._debug("read_property_to_any %s %r %r", obj, propertyIdentifier, propertyArrayIn... | [
"def",
"read_property_to_any",
"(",
"obj",
",",
"propertyIdentifier",
",",
"propertyArrayIndex",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"read_property_to_any",
".",
"_debug",
"(",
"\"read_property_to_any %s %r %r\"",
",",
"obj",
",",
"propertyIdentifier",
",",
... | 45.425 | 23.875 |
def _parse_sequences(ilines, expect_qlen):
"""Parse the sequences in the current block.
Sequence looks like:
$3=227(209):
>gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamma subunit [Aquifex ... | [
"def",
"_parse_sequences",
"(",
"ilines",
",",
"expect_qlen",
")",
":",
"while",
"True",
":",
"first",
"=",
"next",
"(",
"ilines",
")",
"if",
"first",
".",
"startswith",
"(",
"'_'",
")",
"and",
"first",
".",
"endswith",
"(",
"'].'",
")",
":",
"# End of... | 39.8125 | 21.921875 |
def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
"""
Config the logging.
"""
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
lo... | [
"def",
"logging_config",
"(",
"logpath",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"console_level",
"=",
"logging",
".",
"INFO",
",",
"no_console",
"=",
"False",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'nli'",
")",... | 32.4 | 11.133333 |
def restore(self):
"""Restore the saved value for the attribute of the object."""
if self.proxy_object is None:
if self.getter:
setattr(self.getter_class, self.attr_name, self.getter)
elif self.is_local:
setattr(self.orig_object, self.attr_name, se... | [
"def",
"restore",
"(",
"self",
")",
":",
"if",
"self",
".",
"proxy_object",
"is",
"None",
":",
"if",
"self",
".",
"getter",
":",
"setattr",
"(",
"self",
".",
"getter_class",
",",
"self",
".",
"attr_name",
",",
"self",
".",
"getter",
")",
"elif",
"sel... | 43.5 | 15.642857 |
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2):
u"""
Generate an ASCII name slug. If a checkused filter is provided, it will
be called with the candidate. If it returns True, make_name will add
counter numbers starting from 2 until a suitable candidate is found.
:param str... | [
"def",
"make_name",
"(",
"text",
",",
"delim",
"=",
"u'-'",
",",
"maxlength",
"=",
"50",
",",
"checkused",
"=",
"None",
",",
"counter",
"=",
"2",
")",
":",
"name",
"=",
"text",
".",
"replace",
"(",
"'@'",
",",
"delim",
")",
"name",
"=",
"unidecode"... | 39.625 | 20.795455 |
def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True):
"""Validate the keyword arguments to 'fillna'.
This checks that exactly one of 'value' and 'method' is specified.
If 'method' is specified, this validates that it's a valid method.
Parameters
----------
value, method :... | [
"def",
"validate_fillna_kwargs",
"(",
"value",
",",
"method",
",",
"validate_scalar_dict_value",
"=",
"True",
")",
":",
"from",
"pandas",
".",
"core",
".",
"missing",
"import",
"clean_fill_method",
"if",
"value",
"is",
"None",
"and",
"method",
"is",
"None",
":... | 37.676471 | 23.882353 |
def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request obje... | [
"def",
"check",
"(",
"self",
",",
"request",
",",
"secret",
")",
":",
"if",
"request",
".",
"get_header",
"(",
"\"Authorization\"",
")",
"==",
"\"\"",
":",
"return",
"False",
"ah",
"=",
"self",
".",
"parse_auth_headers",
"(",
"request",
".",
"get_header",
... | 47.4375 | 20.125 |
def setup_observations(self):
""" main entry point for setting up observations
"""
obs_methods = [self.setup_water_budget_obs,self.setup_hyd,
self.setup_smp,self.setup_hob,self.setup_hds,
self.setup_sfr_obs]
obs_types = ["mflist water budget... | [
"def",
"setup_observations",
"(",
"self",
")",
":",
"obs_methods",
"=",
"[",
"self",
".",
"setup_water_budget_obs",
",",
"self",
".",
"setup_hyd",
",",
"self",
".",
"setup_smp",
",",
"self",
".",
"setup_hob",
",",
"self",
".",
"setup_hds",
",",
"self",
"."... | 45.571429 | 18.214286 |
def element_neighbors(self):
"""Return a list with element numbers (zero indexed) of neighboring
elements. Note that the elements are not sorted. No spacial orientation
can be inferred from the order of neighbors.
WARNING: This function is slow due to a nested loop. This would be a
... | [
"def",
"element_neighbors",
"(",
"self",
")",
":",
"if",
"self",
".",
"element_neighbors_data",
"is",
"not",
"None",
":",
"return",
"self",
".",
"element_neighbors_data",
"max_nr_edges",
"=",
"self",
".",
"header",
"[",
"'element_infos'",
"]",
"[",
"0",
",",
... | 40 | 21.428571 |
def generate_url(query, first, recent, country_code):
"""(str, str) -> str
A url in the required format is generated.
"""
query = '+'.join(query.split())
url = 'http://www.bing.com/search?q=' + query + '&first=' + first
if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be enough. This... | [
"def",
"generate_url",
"(",
"query",
",",
"first",
",",
"recent",
",",
"country_code",
")",
":",
"query",
"=",
"'+'",
".",
"join",
"(",
"query",
".",
"split",
"(",
")",
")",
"url",
"=",
"'http://www.bing.com/search?q='",
"+",
"query",
"+",
"'&first='",
"... | 44.272727 | 16.545455 |
def create_table(group, name, dtype, **attributes):
"""Create a new array dataset under group with compound datatype and maxshape=(None,)"""
dset = group.create_dataset(
name, shape=(0,), dtype=dtype, maxshape=(None,))
set_attributes(dset, **attributes)
return dset | [
"def",
"create_table",
"(",
"group",
",",
"name",
",",
"dtype",
",",
"*",
"*",
"attributes",
")",
":",
"dset",
"=",
"group",
".",
"create_dataset",
"(",
"name",
",",
"shape",
"=",
"(",
"0",
",",
")",
",",
"dtype",
"=",
"dtype",
",",
"maxshape",
"="... | 47.333333 | 10.333333 |
def decode_varint(f, max_bytes=4):
"""Decode variable integer using algorithm similar to that described
in MQTT Version 3.1.1 line 297.
Parameters
----------
f: file
Object with a read method.
max_bytes: int or None
If a varint cannot be constructed using `max_bytes` or fewer
... | [
"def",
"decode_varint",
"(",
"f",
",",
"max_bytes",
"=",
"4",
")",
":",
"num_bytes_consumed",
"=",
"0",
"value",
"=",
"0",
"m",
"=",
"1",
"while",
"True",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"1",
")",
"if",
"len",
"(",
"buf",
")",
"==",
"0"... | 24.784314 | 22.72549 |
def log_request(self, handler: RequestHandler) -> None:
"""Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary a... | [
"def",
"log_request",
"(",
"self",
",",
"handler",
":",
"RequestHandler",
")",
"->",
"None",
":",
"if",
"\"log_function\"",
"in",
"self",
".",
"settings",
":",
"self",
".",
"settings",
"[",
"\"log_function\"",
"]",
"(",
"handler",
")",
"return",
"if",
"han... | 37.166667 | 13.916667 |
def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
"""Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sen... | [
"def",
"decode",
"(",
"model",
",",
"tokens",
",",
"start_token",
",",
"end_token",
",",
"pad_token",
",",
"max_len",
"=",
"10000",
",",
"max_repeat",
"=",
"10",
",",
"max_repeat_block",
"=",
"10",
")",
":",
"is_single",
"=",
"not",
"isinstance",
"(",
"t... | 47.272727 | 19.022727 |
def find_python():
"""Search for Python automatically"""
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), N... | [
"def",
"find_python",
"(",
")",
":",
"python",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pythonExecutable\"",
")",
"or",
"# Support for multiple executables.",
"next",
"(",
"(",
"exe",
"for",
"exe",
"in",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYTHON_EXECUTABLE\... | 26.047619 | 20.857143 |
def parse_bewit(bewit):
"""
Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str
"""
decoded_bewit = b64decode(bewit).decode(... | [
"def",
"parse_bewit",
"(",
"bewit",
")",
":",
"decoded_bewit",
"=",
"b64decode",
"(",
"bewit",
")",
".",
"decode",
"(",
"'ascii'",
")",
"bewit_parts",
"=",
"decoded_bewit",
".",
"split",
"(",
"\"\\\\\"",
")",
"if",
"len",
"(",
"bewit_parts",
")",
"!=",
"... | 33.333333 | 14.4 |
def _HasOOOWrite(self, path):
"""Returns whether the path has had an out-of-order write."""
# Check the sizes of each path before the current one.
size = tf.io.gfile.stat(path).length
old_size = self._finalized_sizes.get(path, None)
if size != old_size:
if old_size is None:
logger.erro... | [
"def",
"_HasOOOWrite",
"(",
"self",
",",
"path",
")",
":",
"# Check the sizes of each path before the current one.",
"size",
"=",
"tf",
".",
"io",
".",
"gfile",
".",
"stat",
"(",
"path",
")",
".",
"length",
"old_size",
"=",
"self",
".",
"_finalized_sizes",
"."... | 40.466667 | 18.266667 |
def create_config(config_path="scriptworker.yaml"):
"""Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tuple: (config ... | [
"def",
"create_config",
"(",
"config_path",
"=",
"\"scriptworker.yaml\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print",
"(",
"\"{} doesn't exist! Exiting...\"",
".",
"format",
"(",
"config_path",
")",
",",
"fil... | 32.457143 | 17.428571 |
def _generate_examples(self, images_dir_path, labels_path, setid_path,
split_name):
"""Yields examples."""
with tf.io.gfile.GFile(labels_path, "rb") as f:
labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0]
with tf.io.gfile.GFile(setid_path, "rb") as f:
exam... | [
"def",
"_generate_examples",
"(",
"self",
",",
"images_dir_path",
",",
"labels_path",
",",
"setid_path",
",",
"split_name",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"labels_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"labels",
"... | 40.6 | 17.666667 |
def write_out(self, message, verbosity_level=1):
"""
Convenient method for outputing.
"""
if self.verbosity and self.verbosity >= verbosity_level:
sys.stdout.write(smart_str(message))
sys.stdout.flush() | [
"def",
"write_out",
"(",
"self",
",",
"message",
",",
"verbosity_level",
"=",
"1",
")",
":",
"if",
"self",
".",
"verbosity",
"and",
"self",
".",
"verbosity",
">=",
"verbosity_level",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"smart_str",
"(",
"messag... | 36 | 7.142857 |
def _html(self, text):
'''Parse a Tweet and generate HTML.'''
html = URL_REGEX.sub(self._parse_urls, text)
html = USERNAME_REGEX.sub(self._parse_users, html)
html = LIST_REGEX.sub(self._parse_lists, html)
return HASHTAG_REGEX.sub(self._parse_tags, html) | [
"def",
"_html",
"(",
"self",
",",
"text",
")",
":",
"html",
"=",
"URL_REGEX",
".",
"sub",
"(",
"self",
".",
"_parse_urls",
",",
"text",
")",
"html",
"=",
"USERNAME_REGEX",
".",
"sub",
"(",
"self",
".",
"_parse_users",
",",
"html",
")",
"html",
"=",
... | 48 | 14 |
def is_subclass(ch, ns, super_class, sub):
"""Determine if one class is a subclass of another class.
Parameters:
ch:
A CIMOMHandle. Either a pycimmb.CIMOMHandle or a
:class:`~pywbem.WBEMConnection` object.
ns (:term:`string`):
Namespace (case independent).
super_cl... | [
"def",
"is_subclass",
"(",
"ch",
",",
"ns",
",",
"super_class",
",",
"sub",
")",
":",
"lsuper",
"=",
"super_class",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"sub",
",",
"CIMClass",
")",
":",
"subname",
"=",
"sub",
".",
"classname",
"subclass",
... | 31.826923 | 17.134615 |
def _rotations_to_disentangle(local_param):
"""
Static internal method to work out Ry and Rz rotation angles used
to disentangle the LSB qubit.
These rotations make up the block diagonal matrix U (i.e. multiplexor)
that disentangles the LSB.
[[Ry(theta_1).Rz(phi_1) 0 ... | [
"def",
"_rotations_to_disentangle",
"(",
"local_param",
")",
":",
"remaining_vector",
"=",
"[",
"]",
"thetas",
"=",
"[",
"]",
"phis",
"=",
"[",
"]",
"param_len",
"=",
"len",
"(",
"local_param",
")",
"for",
"i",
"in",
"range",
"(",
"param_len",
"//",
"2",... | 36.945946 | 19 |
def readNamelist(namFilename, unique_glyphs=False, cache=None):
"""
Args:
namFilename: The path to the Namelist file.
unique_glyphs: Optional, whether to only include glyphs unique to subset.
cache: Optional, a dict used to cache loaded Namelist files
Returns:
A dict with following keys:
"fileNa... | [
"def",
"readNamelist",
"(",
"namFilename",
",",
"unique_glyphs",
"=",
"False",
",",
"cache",
"=",
"None",
")",
":",
"currentlyIncluding",
"=",
"set",
"(",
")",
"if",
"not",
"cache",
":",
"cache",
"=",
"{",
"}",
"return",
"_readNamelist",
"(",
"currentlyInc... | 40.233333 | 21.5 |
def get_seqstr(config, metadata):
"""
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding directions, and task names.... | [
"def",
"get_seqstr",
"(",
"config",
",",
"metadata",
")",
":",
"seq_abbrs",
"=",
"metadata",
".",
"get",
"(",
"'ScanningSequence'",
",",
"''",
")",
".",
"split",
"(",
"'_'",
")",
"seqs",
"=",
"[",
"config",
"[",
"'seq'",
"]",
".",
"get",
"(",
"seq",
... | 31.551724 | 19.482759 |
def impute(self, vars: dict, replace: bool = False, prefix: str = 'imp_', out: 'SASdata' = None) -> 'SASdata':
"""
Imputes missing values for a SASdata object.
:param vars: a dictionary in the form of {'varname':'impute type'} or {'impute type':'[var1, var2]'}
:param replace:
:p... | [
"def",
"impute",
"(",
"self",
",",
"vars",
":",
"dict",
",",
"replace",
":",
"bool",
"=",
"False",
",",
"prefix",
":",
"str",
"=",
"'imp_'",
",",
"out",
":",
"'SASdata'",
"=",
"None",
")",
"->",
"'SASdata'",
":",
"outstr",
"=",
"''",
"if",
"out",
... | 44.26087 | 21.617391 |
def compute_K_L_alpha_ll(self):
r"""Compute `K`, `L`, `alpha` and log-likelihood according to the first part of Algorithm 2.1 in R&W.
Computes `K` and the noise portion of `K` using :py:meth:`compute_Kij`,
computes `L` using :py:func:`scipy.linalg.cholesky`, then computes
`alpha... | [
"def",
"compute_K_L_alpha_ll",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"K_up_to_date",
":",
"y",
"=",
"self",
".",
"y",
"err_y",
"=",
"self",
".",
"err_y",
"self",
".",
"K",
"=",
"self",
".",
"compute_Kij",
"(",
"self",
".",
"X",
",",
"Non... | 50.371429 | 22.314286 |
def rcts(self, command, *args, **kwargs):
'''General function for applying a rolling R function to a timeserie'''
cls = self.__class__
name = kwargs.pop('name','')
date = kwargs.pop('date',None)
data = kwargs.pop('data',None)
kwargs.pop('bycolumn',None)
ts ... | [
"def",
"rcts",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"''",
")",
"date",
"=",
"kwargs",
".",
"pop",
"(",
"'d... | 41.9 | 10.5 |
def update(self):
"""Once you open a dataset, it activates all the widgets.
"""
self.info.display_dataset()
self.overview.update()
self.labels.update(labels=self.info.dataset.header['chan_name'])
self.channels.update()
try:
self.info.markers = self.in... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"info",
".",
"display_dataset",
"(",
")",
"self",
".",
"overview",
".",
"update",
"(",
")",
"self",
".",
"labels",
".",
"update",
"(",
"labels",
"=",
"self",
".",
"info",
".",
"dataset",
".",
"he... | 35.785714 | 17.5 |
def image_size(self, pnmfile):
"""Get width and height of pnm file.
simeon@homebox src>pnmfile /tmp/214-2.png
/tmp/214-2.png:PPM raw, 100 by 100 maxval 255
"""
pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r')
pnmfileout = pout.read(200)
pout.... | [
"def",
"image_size",
"(",
"self",
",",
"pnmfile",
")",
":",
"pout",
"=",
"os",
".",
"popen",
"(",
"self",
".",
"shellsetup",
"+",
"self",
".",
"pnmfile",
"+",
"' '",
"+",
"pnmfile",
",",
"'r'",
")",
"pnmfileout",
"=",
"pout",
".",
"read",
"(",
"200... | 37 | 15.055556 |
def register_lazy_provider_method(self, cls, method):
"""
Register a class method lazily as a provider.
"""
if 'provides' not in getattr(method, '__di__', {}):
raise DiayException('method %r is not a provider' % method)
@functools.wraps(method)
def wrapper(*a... | [
"def",
"register_lazy_provider_method",
"(",
"self",
",",
"cls",
",",
"method",
")",
":",
"if",
"'provides'",
"not",
"in",
"getattr",
"(",
"method",
",",
"'__di__'",
",",
"{",
"}",
")",
":",
"raise",
"DiayException",
"(",
"'method %r is not a provider'",
"%",
... | 38.416667 | 18.416667 |
def pip_upgrade_all_user(line):
"""Attempt to upgrade all packages installed with --user"""
import pip
for dist in pip.get_installed_distributions(user_only=True):
do_pip(["install", "--upgrade", "--user", dist.project_name]) | [
"def",
"pip_upgrade_all_user",
"(",
"line",
")",
":",
"import",
"pip",
"for",
"dist",
"in",
"pip",
".",
"get_installed_distributions",
"(",
"user_only",
"=",
"True",
")",
":",
"do_pip",
"(",
"[",
"\"install\"",
",",
"\"--upgrade\"",
",",
"\"--user\"",
",",
"... | 48.2 | 17.6 |
def register_regex_entity(self, regex_str):
"""
A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
regex_str(str): a string representing a regular expression as defined above
"""
if regex_str and regex_str not in self._regex_strin... | [
"def",
"register_regex_entity",
"(",
"self",
",",
"regex_str",
")",
":",
"if",
"regex_str",
"and",
"regex_str",
"not",
"in",
"self",
".",
"_regex_strings",
":",
"self",
".",
"_regex_strings",
".",
"add",
"(",
"regex_str",
")",
"self",
".",
"regular_expressions... | 41 | 22.454545 |
def get_full_description(self, s, base=None):
"""Get the full description from a docstring
This here and the line above is the full description (i.e. the
combination of the :meth:`get_summary` and the
:meth:`get_extended_summary`) output
Parameters
----------
s:... | [
"def",
"get_full_description",
"(",
"self",
",",
"s",
",",
"base",
"=",
"None",
")",
":",
"summary",
"=",
"self",
".",
"get_summary",
"(",
"s",
")",
"extended_summary",
"=",
"self",
".",
"get_extended_summary",
"(",
"s",
")",
"ret",
"=",
"(",
"summary",
... | 34.814815 | 20.185185 |
def build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):
"""
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with
some properties so it is more testable
"""
doctype = ElifeDocumentType(qualifiedName)
doctype._identified_mixin_init(publicId, syste... | [
"def",
"build_doctype",
"(",
"qualifiedName",
",",
"publicId",
"=",
"None",
",",
"systemId",
"=",
"None",
",",
"internalSubset",
"=",
"None",
")",
":",
"doctype",
"=",
"ElifeDocumentType",
"(",
"qualifiedName",
")",
"doctype",
".",
"_identified_mixin_init",
"(",... | 40.5 | 15.1 |
def register_service(service):
"""
Register the ryu application specified by 'service' as
a provider of events defined in the calling module.
If an application being loaded consumes events (in the sense of
set_ev_cls) provided by the 'service' application, the latter
application will be automat... | [
"def",
"register_service",
"(",
"service",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"m_name",
"=",
"frame",
".",
"f_back",
".",
"f_globals",
"[",
"'__name__'",
"]",
"m",
"=",
"sys",
".",
"modules",
"[",
"m_name",
"]",
"m",
".",... | 36.75 | 15.875 |
def getInferenceTypeFromLabel(cls, label):
"""
Extracts the PredictionKind (temporal vs. nontemporal) from the given
metric label.
:param label: (string) for a metric spec generated by
:meth:`getMetricLabel`
:returns: (:class:`~nupic.frameworks.opf.opf_utils.InferenceType`)
"""
... | [
"def",
"getInferenceTypeFromLabel",
"(",
"cls",
",",
"label",
")",
":",
"infType",
",",
"_",
",",
"_",
"=",
"label",
".",
"partition",
"(",
"cls",
".",
"_LABEL_SEPARATOR",
")",
"if",
"not",
"InferenceType",
".",
"validate",
"(",
"infType",
")",
":",
"ret... | 27.625 | 21.0625 |
def annotate_and_optimize_ast(
parsed_ast: ast.Module,
source_code: str,
class_types: Optional[ClassTypes] = None,
) -> None:
"""
Performs annotation and optimization on a parsed python AST by doing the
following:
* Annotating all AST nodes with the originating source code of the AST
* ... | [
"def",
"annotate_and_optimize_ast",
"(",
"parsed_ast",
":",
"ast",
".",
"Module",
",",
"source_code",
":",
"str",
",",
"class_types",
":",
"Optional",
"[",
"ClassTypes",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"AnnotatingVisitor",
"(",
"source_code",
... | 39.409091 | 19.5 |
def execute_commands(self, mapping, *args, **kwargs):
"""Concurrently executes a sequence of commands on a Redis cluster that
are associated with a routing key, returning a new mapping where
values are a list of results that correspond to the command in the same
position. For example::
... | [
"def",
"execute_commands",
"(",
"self",
",",
"mapping",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"is_script_command",
"(",
"command",
")",
":",
"return",
"isinstance",
"(",
"command",
"[",
"0",
"]",
",",
"Script",
")",
"def",
"check_... | 45.104167 | 21.770833 |
def is_rdemo(file_name):
"""
Return True if file_name matches a regexp for an R demo. False otherwise.
:param file_name: file to test
"""
packaged_demos = ["h2o.anomaly.R", "h2o.deeplearning.R", "h2o.gbm.R", "h2o.glm.R", "h2o.glrm.R", "h2o.kmeans.R",
"h2o.naiveBayes.R", "h2o.p... | [
"def",
"is_rdemo",
"(",
"file_name",
")",
":",
"packaged_demos",
"=",
"[",
"\"h2o.anomaly.R\"",
",",
"\"h2o.deeplearning.R\"",
",",
"\"h2o.gbm.R\"",
",",
"\"h2o.glm.R\"",
",",
"\"h2o.glrm.R\"",
",",
"\"h2o.kmeans.R\"",
",",
"\"h2o.naiveBayes.R\"",
",",
"\"h2o.prcomp.R\"... | 47.3 | 23.1 |
def readAt(self, offset, size):
"""
Reads as many bytes indicated in the size parameter at the specific offset.
@type offset: int
@param offset: Offset of the value to be read.
@type size: int
@param size: This parameter indicates how many bytes are going to be read fro... | [
"def",
"readAt",
"(",
"self",
",",
"offset",
",",
"size",
")",
":",
"if",
"offset",
">",
"self",
".",
"length",
":",
"if",
"self",
".",
"log",
":",
"print",
"\"Warning: Trying to read: %d bytes - only %d bytes left\"",
"%",
"(",
"nroBytes",
",",
"self",
".",... | 34.954545 | 22.590909 |
def is_contradictory(self, other):
"""
Can these two strings coexist ?
"""
other = StringCell.coerce(other)
if self.value is None or other.value is None:
# None = empty, and won't contradict anything
return False
def sequence_in(s1, s2):
... | [
"def",
"is_contradictory",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"StringCell",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"value",
"is",
"None",
"or",
"other",
".",
"value",
"is",
"None",
":",
"# None = empty, and won't contradict anyt... | 32.625 | 14.1875 |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
ZipFileEntry: a file entry or None.
"""
if not self.FileEntryExistsByPathSpec(path_spec):
return None
l... | [
"def",
"GetFileEntryByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"if",
"not",
"self",
".",
"FileEntryExistsByPathSpec",
"(",
"path_spec",
")",
":",
"return",
"None",
"location",
"=",
"getattr",
"(",
"path_spec",
",",
"'location'",
",",
"None",
")",
... | 27.666667 | 20.555556 |
def _decode_exp(self, access_token=None):
"""Extract exp field from access token.
Args:
access_token (str): Access token to decode. Defaults to ``None``.
Returns:
int: JWT expiration in epoch seconds.
"""
c = self.get_credentials()
jwt = access_... | [
"def",
"_decode_exp",
"(",
"self",
",",
"access_token",
"=",
"None",
")",
":",
"c",
"=",
"self",
".",
"get_credentials",
"(",
")",
"jwt",
"=",
"access_token",
"or",
"c",
".",
"access_token",
"x",
"=",
"self",
".",
"decode_jwt_payload",
"(",
"jwt",
")",
... | 29.12 | 17.84 |
def copy_pkg(self, filename, id_=-1):
"""Copy a pkg, dmg, or zip to all repositories.
Args:
filename: String path to the local file to copy.
id_: Integer ID you wish to associate package with for a JDS
or CDP only. Default is -1, which is used for creating
... | [
"def",
"copy_pkg",
"(",
"self",
",",
"filename",
",",
"id_",
"=",
"-",
"1",
")",
":",
"for",
"repo",
"in",
"self",
".",
"_children",
":",
"repo",
".",
"copy_pkg",
"(",
"filename",
",",
"id_",
")"
] | 40.545455 | 15.454545 |
def get_bundle_imported_services(self, bundle):
"""
Returns this bundle's ServiceReference list for all services it is
using or returns None if this bundle is not using any services.
A bundle is considered to be using a service if its use count for that
service is greater than ze... | [
"def",
"get_bundle_imported_services",
"(",
"self",
",",
"bundle",
")",
":",
"with",
"self",
".",
"__svc_lock",
":",
"return",
"sorted",
"(",
"self",
".",
"__bundle_imports",
".",
"get",
"(",
"bundle",
",",
"[",
"]",
")",
")"
] | 45.3125 | 21.1875 |
def _cache_ops_associate(protocol, msgtype):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L111.
Positional arguments:
protocol -- Netlink protocol (integer).
msgtype -- Netlink message type (integer).
Returns:
nl_cache_ops instance with matching protocol containing mat... | [
"def",
"_cache_ops_associate",
"(",
"protocol",
",",
"msgtype",
")",
":",
"ops",
"=",
"cache_ops",
"while",
"ops",
":",
"# Loop until `ops` is None.",
"if",
"ops",
".",
"co_protocol",
"==",
"protocol",
":",
"for",
"co_msgtype",
"in",
"ops",
".",
"co_msgtypes",
... | 33.611111 | 14.944444 |
def parse_config(f):
"""
Load an yml-formatted configuration from file stream |f|
:param file f: Where to read the config.
"""
try:
c = yaml.safe_load(f)
for section_name, section in c.items():
group = get_group(section_name)
for key, val in section.items()... | [
"def",
"parse_config",
"(",
"f",
")",
":",
"try",
":",
"c",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"for",
"section_name",
",",
"section",
"in",
"c",
".",
"items",
"(",
")",
":",
"group",
"=",
"get_group",
"(",
"section_name",
")",
"for",
"ke... | 33.052632 | 18.526316 |
def p_retry_option(p):
"""
retry_option : LIMIT COLON NUMBER
| DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET
"""
if len(p) == 4:
p[0] = {"limit": int(p[3]) }
elif len(p) == 7:
p[0] = {"delay": Delay(int(p[5]), p[3])}
else:
raise RuntimeError("I... | [
"def",
"p_retry_option",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"{",
"\"limit\"",
":",
"int",
"(",
"p",
"[",
"3",
"]",
")",
"}",
"elif",
"len",
"(",
"p",
")",
"==",
"7",
":",
"p",
"[",
"... | 31.545455 | 15 |
def components(self):
'''The period string'''
p = ''
neg = self.totaldays < 0
y = self.years
m = self.months
w = self.weeks
d = self.days
if y:
p = '%sY' % abs(y)
if m:
p = '%s%sM' % (p, abs(m))
if w:
p =... | [
"def",
"components",
"(",
"self",
")",
":",
"p",
"=",
"''",
"neg",
"=",
"self",
".",
"totaldays",
"<",
"0",
"y",
"=",
"self",
".",
"years",
"m",
"=",
"self",
".",
"months",
"w",
"=",
"self",
".",
"weeks",
"d",
"=",
"self",
".",
"days",
"if",
... | 24.294118 | 15.705882 |
def _validate_jp2h(self, boxes):
"""Validate the JP2 Header box."""
self._check_jp2h_child_boxes(boxes, 'top-level')
jp2h_lst = [box for box in boxes if box.box_id == 'jp2h']
jp2h = jp2h_lst[0]
# 1st jp2 header box cannot be empty.
if len(jp2h.box) == 0:
msg... | [
"def",
"_validate_jp2h",
"(",
"self",
",",
"boxes",
")",
":",
"self",
".",
"_check_jp2h_child_boxes",
"(",
"boxes",
",",
"'top-level'",
")",
"jp2h_lst",
"=",
"[",
"box",
"for",
"box",
"in",
"boxes",
"if",
"box",
".",
"box_id",
"==",
"'jp2h'",
"]",
"jp2h"... | 36.259259 | 17.148148 |
def show_search_results(
log_rec,
code_view=True,
json_view=False,
show_message_details=False):
"""show_search_results
Show search results like rsyslog or as pretty-printed
JSON dictionaries per log for debugging drill-down fields
:param log_rec: log record from splunk
... | [
"def",
"show_search_results",
"(",
"log_rec",
",",
"code_view",
"=",
"True",
",",
"json_view",
"=",
"False",
",",
"show_message_details",
"=",
"False",
")",
":",
"log_dict",
"=",
"None",
"try",
":",
"log_dict",
"=",
"json",
".",
"loads",
"(",
"log_rec",
")... | 27.513158 | 15.138158 |
def initialise_modified_data(self):
"""
Initialise the modified_data if necessary
"""
if self.__modified_data__ is None:
if self.__original_data__:
self.__modified_data__ = list(self.__original_data__)
else:
self.__modified_data__ =... | [
"def",
"initialise_modified_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"__modified_data__",
"is",
"None",
":",
"if",
"self",
".",
"__original_data__",
":",
"self",
".",
"__modified_data__",
"=",
"list",
"(",
"self",
".",
"__original_data__",
")",
"else",... | 35 | 8.111111 |
def ReadAllClientLabels(self, cursor=None):
"""Reads the user labels for a list of clients."""
cursor.execute("SELECT DISTINCT owner_username, label FROM client_labels")
result = []
for owner, label in cursor.fetchall():
result.append(rdf_objects.ClientLabel(name=label, owner=owner))
result... | [
"def",
"ReadAllClientLabels",
"(",
"self",
",",
"cursor",
"=",
"None",
")",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT DISTINCT owner_username, label FROM client_labels\"",
")",
"result",
"=",
"[",
"]",
"for",
"owner",
",",
"label",
"in",
"cursor",
".",
"fetc... | 34.363636 | 23.636364 |
def Emulation_setEmulatedMedia(self, media):
"""
Function path: Emulation.setEmulatedMedia
Domain: Emulation
Method name: setEmulatedMedia
Parameters:
Required arguments:
'media' (type: string) -> Media type to emulate. Empty string disables the override.
No return value.
Description: ... | [
"def",
"Emulation_setEmulatedMedia",
"(",
"self",
",",
"media",
")",
":",
"assert",
"isinstance",
"(",
"media",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'media' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"media",
")",
"subdom_funcs"... | 31.473684 | 20.842105 |
def _new(self, dx_hash, **kwargs):
'''
:param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.
:type dx_hash: dict
:param runSpec: Run specification
:type runSpec: dict
:param dxapi: API ... | [
"def",
"_new",
"(",
"self",
",",
"dx_hash",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"field",
"in",
"'runSpec'",
",",
"'dxapi'",
":",
"if",
"field",
"not",
"in",
"kwargs",
":",
"raise",
"DXError",
"(",
"\"%s: Keyword argument %s is required\"",
"%",
"(",
... | 44.422222 | 21.444444 |
def extract_date(cls, date_str):
"""
Tries to extract a `datetime` object from the given string, expecting
date information only.
Raises `DateTimeFormatterException` if the extraction fails.
"""
if not date_str:
raise DateTimeFormatterException('date_str must... | [
"def",
"extract_date",
"(",
"cls",
",",
"date_str",
")",
":",
"if",
"not",
"date_str",
":",
"raise",
"DateTimeFormatterException",
"(",
"'date_str must a valid string {}.'",
".",
"format",
"(",
"date_str",
")",
")",
"try",
":",
"return",
"cls",
".",
"_extract_ti... | 39.785714 | 24.357143 |
def generate_docs(self, clspath, more_content):
"""Generate documentation for this configman class"""
obj = import_class(clspath)
sourcename = 'docstring of %s' % clspath
all_options = []
indent = ' '
config = obj.get_required_config()
if config.options:
... | [
"def",
"generate_docs",
"(",
"self",
",",
"clspath",
",",
"more_content",
")",
":",
"obj",
"=",
"import_class",
"(",
"clspath",
")",
"sourcename",
"=",
"'docstring of %s'",
"%",
"clspath",
"all_options",
"=",
"[",
"]",
"indent",
"=",
"' '",
"config",
"=",... | 41.22619 | 18.309524 |
def mark_deactivated(self,request,queryset):
"""An admin action for marking several cages as inactive.
This action sets the selected cages as Active=False and Death=today.
This admin action also shows as the output the number of mice sacrificed."""
rows_updated = queryset.update(Activ... | [
"def",
"mark_deactivated",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"rows_updated",
"=",
"queryset",
".",
"update",
"(",
"Active",
"=",
"False",
",",
"End",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"if",
"rows_updated",
... | 52.454545 | 20.363636 |
def limit(self, maximum):
"""
Return a new query, limited to a certain number of results.
Unlike core reporting queries, you cannot specify a starting
point for live queries, just the maximum results returned.
```python
# first 50
query.limit(50)
```
... | [
"def",
"limit",
"(",
"self",
",",
"maximum",
")",
":",
"self",
".",
"meta",
"[",
"'limit'",
"]",
"=",
"maximum",
"self",
".",
"raw",
".",
"update",
"(",
"{",
"'max_results'",
":",
"maximum",
",",
"}",
")",
"return",
"self"
] | 24.555556 | 21.222222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.