text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _parse_parallel_sentences(f1, f2):
"""Returns examples from parallel SGML or text files, which may be gzipped."""
def _parse_text(path):
"""Returns the sentences from a single text file, which may be gzipped."""
split_path = path.split(".")
if split_path[-1] == "gz":
lang = split_path[-2]
... | [
"def",
"_parse_parallel_sentences",
"(",
"f1",
",",
"f2",
")",
":",
"def",
"_parse_text",
"(",
"path",
")",
":",
"\"\"\"Returns the sentences from a single text file, which may be gzipped.\"\"\"",
"split_path",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
"if",
"spli... | 35.016667 | 18.316667 |
def query_base_timer(self):
"""
gets the value from the device's base timer
"""
(_, _, time) = unpack('<ccI', self.con.send_xid_command("e3", 6))
return time | [
"def",
"query_base_timer",
"(",
"self",
")",
":",
"(",
"_",
",",
"_",
",",
"time",
")",
"=",
"unpack",
"(",
"'<ccI'",
",",
"self",
".",
"con",
".",
"send_xid_command",
"(",
"\"e3\"",
",",
"6",
")",
")",
"return",
"time"
] | 32 | 13 |
def to_repo_relative_path(self, path, split=False):
"""
Given a path, return relative path to diretory
:Parameters:
#. path (str): Path as a string
#. split (boolean): Whether to split path to its components
:Returns:
#. relativePath (str, list): Rel... | [
"def",
"to_repo_relative_path",
"(",
"self",
",",
"path",
",",
"split",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"if",
"path",
"==",
"'.'",
":",
"path",
"=",
"''",
"path",
"=",
"path",
".",
"split",... | 31.45 | 17.55 |
def _insert_post_complete_tasks(context):
"""Insert the event's asyncs and cleanup tasks."""
logging.debug("Context %s is complete.", context.id)
# Async event handlers
context.exec_event_handler('complete', transactional=True)
# Insert cleanup tasks
try:
# TODO: If tracking results w... | [
"def",
"_insert_post_complete_tasks",
"(",
"context",
")",
":",
"logging",
".",
"debug",
"(",
"\"Context %s is complete.\"",
",",
"context",
".",
"id",
")",
"# Async event handlers",
"context",
".",
"exec_event_handler",
"(",
"'complete'",
",",
"transactional",
"=",
... | 34.722222 | 20.388889 |
def _special_dates(self, calendars, ad_hoc_dates, start_date, end_date):
"""
Compute a Series of times associated with special dates.
Parameters
----------
holiday_calendars : list[(datetime.time, HolidayCalendar)]
Pairs of time and calendar describing when that time... | [
"def",
"_special_dates",
"(",
"self",
",",
"calendars",
",",
"ad_hoc_dates",
",",
"start_date",
",",
"end_date",
")",
":",
"# List of Series for regularly-scheduled times.",
"regular",
"=",
"[",
"scheduled_special_times",
"(",
"calendar",
",",
"start_date",
",",
"end_... | 36.509434 | 21.339623 |
def handle_cluster_request(self, tsn, command_id, args):
"""Handle the cluster command."""
if command_id == 0:
if self._timer_handle:
self._timer_handle.cancel()
loop = asyncio.get_event_loop()
self._timer_handle = loop.call_later(30, self._turn_off) | [
"def",
"handle_cluster_request",
"(",
"self",
",",
"tsn",
",",
"command_id",
",",
"args",
")",
":",
"if",
"command_id",
"==",
"0",
":",
"if",
"self",
".",
"_timer_handle",
":",
"self",
".",
"_timer_handle",
".",
"cancel",
"(",
")",
"loop",
"=",
"asyncio"... | 44.571429 | 9.857143 |
def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args):
'''
Ensure that the endpoint for a service doesn't exist in Keystone catalog
name
The name of the service whose endpoints should not exist
region (optional)
The region of the endpoint. Defaults to... | [
"def",
"endpoint_absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"interface",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
... | 42.073171 | 26.853659 |
def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None):
'''
Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id
'''
cli... | [
"def",
"delete_pipeline",
"(",
"pipeline_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
... | 32.666667 | 29.666667 |
def signal_transmit(self, fd):
""" Awake one process waiting to transmit data on fd """
connection = self.connections(fd)
if connection is None or connection >= len(self.rwait):
return
procs = self.rwait[connection]
if procs:
procid = random.sample(procs,... | [
"def",
"signal_transmit",
"(",
"self",
",",
"fd",
")",
":",
"connection",
"=",
"self",
".",
"connections",
"(",
"fd",
")",
"if",
"connection",
"is",
"None",
"or",
"connection",
">=",
"len",
"(",
"self",
".",
"rwait",
")",
":",
"return",
"procs",
"=",
... | 34.8 | 13.8 |
def react(self, **kwargs):
"""
The time of recation is ignored hereTime is ignored here
and should be handled by whatever called this function.
"""
react_type = kwargs.get("type", self._type)
if react_type == 'hover':
return self.__hover(**kwargs)
... | [
"def",
"react",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"react_type",
"=",
"kwargs",
".",
"get",
"(",
"\"type\"",
",",
"self",
".",
"_type",
")",
"if",
"react_type",
"==",
"'hover'",
":",
"return",
"self",
".",
"__hover",
"(",
"*",
"*",
"kw... | 35 | 14.866667 |
def account_balance(self, base="btc", quote="usd"):
"""
Returns dictionary::
{u'btc_reserved': u'0',
u'fee': u'0.5000',
u'btc_available': u'2.30856098',
u'usd_reserved': u'0',
u'btc_balance': u'2.30856098',
u'usd_balance': u'1... | [
"def",
"account_balance",
"(",
"self",
",",
"base",
"=",
"\"btc\"",
",",
"quote",
"=",
"\"usd\"",
")",
":",
"url",
"=",
"self",
".",
"_construct_url",
"(",
"\"balance/\"",
",",
"base",
",",
"quote",
")",
"return",
"self",
".",
"_post",
"(",
"url",
",",... | 40.333333 | 13.166667 |
def addPos(self, dp_x=None, dy=None, dz=None):
"""Add vector to current actor position."""
p = np.array(self.GetPosition())
if dz is None: # assume dp_x is of the form (x,y,z)
self.SetPosition(p + dp_x)
else:
self.SetPosition(p + [dp_x, dy, dz])
if self.t... | [
"def",
"addPos",
"(",
"self",
",",
"dp_x",
"=",
"None",
",",
"dy",
"=",
"None",
",",
"dz",
"=",
"None",
")",
":",
"p",
"=",
"np",
".",
"array",
"(",
"self",
".",
"GetPosition",
"(",
")",
")",
"if",
"dz",
"is",
"None",
":",
"# assume dp_x is of th... | 36.7 | 11.2 |
def connection_lost(self, reason):
"""Stops all timers and notifies peer that connection is lost.
"""
if self._peer:
state = self._peer.state.bgp_state
if self._is_bound or state == BGP_FSM_OPEN_SENT:
self._peer.connection_lost(reason)
self._... | [
"def",
"connection_lost",
"(",
"self",
",",
"reason",
")",
":",
"if",
"self",
".",
"_peer",
":",
"state",
"=",
"self",
".",
"_peer",
".",
"state",
".",
"bgp_state",
"if",
"self",
".",
"_is_bound",
"or",
"state",
"==",
"BGP_FSM_OPEN_SENT",
":",
"self",
... | 30.066667 | 18.8 |
def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | [
"def",
"get_random_name",
"(",
"sep",
":",
"str",
"=",
"'-'",
")",
":",
"r",
"=",
"random",
".",
"SystemRandom",
"(",
")",
"return",
"'{}{}{}'",
".",
"format",
"(",
"r",
".",
"choice",
"(",
"_left",
")",
",",
"sep",
",",
"r",
".",
"choice",
"(",
... | 32 | 12.888889 |
def model_at_lower_sigma_limit(self, sigma_limit):
"""Setup 1D vectors of the upper and lower limits of the multinest nlo.
These are generated at an input limfrac, which gives the percentage of 1d posterior weighted samples within \
each parameter estimate
Parameters
----------... | [
"def",
"model_at_lower_sigma_limit",
"(",
"self",
",",
"sigma_limit",
")",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"param",
":",
"param",
"[",
"0",
"]",
",",
"self",
".",
"model_at_sigma_limit",
"(",
"sigma_limit",
")",
")",
")"
] | 44.384615 | 29.461538 |
def float_unpack(Q, size, le):
"""Convert a 32-bit or 64-bit integer created
by float_pack into a Python float."""
if size == 8:
MIN_EXP = -1021 # = sys.float_info.min_exp
MAX_EXP = 1024 # = sys.float_info.max_exp
MANT_DIG = 53 # = sys.float_info.mant_dig
BITS = 64
elif size == 4:
MIN... | [
"def",
"float_unpack",
"(",
"Q",
",",
"size",
",",
"le",
")",
":",
"if",
"size",
"==",
"8",
":",
"MIN_EXP",
"=",
"-",
"1021",
"# = sys.float_info.min_exp",
"MAX_EXP",
"=",
"1024",
"# = sys.float_info.max_exp",
"MANT_DIG",
"=",
"53",
"# = sys.float_info.mant_dig"... | 28.527778 | 17.638889 |
def command(self, *args, **kwargs):
"""Usage::
@cli.command(aliases=['ci'])
def commit():
...
"""
aliases = kwargs.pop('aliases', None)
decorator = super(ProfilingCLI, self).command(*args, **kwargs)
if aliases is None:
return dec... | [
"def",
"command",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"aliases",
"=",
"kwargs",
".",
"pop",
"(",
"'aliases'",
",",
"None",
")",
"decorator",
"=",
"super",
"(",
"ProfilingCLI",
",",
"self",
")",
".",
"command",
"(",
"*"... | 28.333333 | 14.833333 |
def delete_service_key(self, service_name, key_name):
"""
Delete a service key for the given service.
"""
key = self.get_service_key(service_name, key_name)
logging.info("Deleting service key %s for service %s" % (key, service_name))
return self.api.delete(key['metadata']... | [
"def",
"delete_service_key",
"(",
"self",
",",
"service_name",
",",
"key_name",
")",
":",
"key",
"=",
"self",
".",
"get_service_key",
"(",
"service_name",
",",
"key_name",
")",
"logging",
".",
"info",
"(",
"\"Deleting service key %s for service %s\"",
"%",
"(",
... | 46 | 14.285714 |
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
... | [
"def",
"migrated",
"(",
"name",
",",
"remote_addr",
",",
"cert",
",",
"key",
",",
"verify_cert",
",",
"src_remote_addr",
",",
"stop_and_start",
"=",
"False",
",",
"src_cert",
"=",
"None",
",",
"src_key",
"=",
"None",
",",
"src_verify_cert",
"=",
"None",
")... | 26.89781 | 20.416058 |
def list_containers(self):
"""
List all available podman containers.
:return: collection of instances of :class:`conu.PodmanContainer`
"""
containers = []
for container in self._list_podman_containers():
identifier = container["ID"]
name = contain... | [
"def",
"list_containers",
"(",
"self",
")",
":",
"containers",
"=",
"[",
"]",
"for",
"container",
"in",
"self",
".",
"_list_podman_containers",
"(",
")",
":",
"identifier",
"=",
"container",
"[",
"\"ID\"",
"]",
"name",
"=",
"container",
"[",
"\"Names\"",
"... | 34.090909 | 17.909091 |
def report_files(self, report_fn, morfs, directory=None):
"""Run a reporting function on a number of morfs.
`report_fn` is called for each relative morf in `morfs`. It is called
as::
report_fn(code_unit, analysis)
where `code_unit` is the `CodeUnit` for the morf, and `ana... | [
"def",
"report_files",
"(",
"self",
",",
"report_fn",
",",
"morfs",
",",
"directory",
"=",
"None",
")",
":",
"self",
".",
"find_code_units",
"(",
"morfs",
")",
"if",
"not",
"self",
".",
"code_units",
":",
"raise",
"CoverageException",
"(",
"\"No data to repo... | 34.09375 | 20.46875 |
def convert_coco_stuff_mat(data_dir, out_dir):
"""Convert to png and save json with path. This currently only contains
the segmentation labels for objects+stuff in cocostuff - if we need to
combine with other labels from original COCO that will be a TODO."""
sets = ['train', 'val']
categories = []
... | [
"def",
"convert_coco_stuff_mat",
"(",
"data_dir",
",",
"out_dir",
")",
":",
"sets",
"=",
"[",
"'train'",
",",
"'val'",
"]",
"categories",
"=",
"[",
"]",
"json_name",
"=",
"'coco_stuff_%s.json'",
"ann_dict",
"=",
"{",
"}",
"for",
"data_set",
"in",
"sets",
"... | 46.894737 | 11.973684 |
def quotation(self, origin, target):
"""Return quotation between two currencies (origin, target)"""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.quotation(origin, target) | [
"def",
"quotation",
"(",
"self",
",",
"origin",
",",
"target",
")",
":",
"if",
"not",
"self",
".",
"_backend",
":",
"raise",
"ExchangeBackendNotInstalled",
"(",
")",
"return",
"self",
".",
"_backend",
".",
"quotation",
"(",
"origin",
",",
"target",
")"
] | 47.2 | 7.2 |
def validate_member_type(self, value):
"""Validate each member of the list, if member_type exists"""
if self.member_type:
for item in value:
self.member_type.validate(item) | [
"def",
"validate_member_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"member_type",
":",
"for",
"item",
"in",
"value",
":",
"self",
".",
"member_type",
".",
"validate",
"(",
"item",
")"
] | 42.4 | 6.2 |
def invert(d):
"""
Invert a dictionary into a dictionary of sets.
>>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP
{1: {'a', 'c'}, 2: {'b'}}
"""
out = {}
for k, v in iteritems(d):
try:
out[v].add(k)
except KeyError:
out[v] = {k}
return out | [
"def",
"invert",
"(",
"d",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"d",
")",
":",
"try",
":",
"out",
"[",
"v",
"]",
".",
"add",
"(",
"k",
")",
"except",
"KeyError",
":",
"out",
"[",
"v",
"]",
"=",
"{"... | 21.785714 | 17.5 |
def iodp_samples(samp_file, output_samp_file=None, output_dir_path='.',
input_dir_path='', data_model_num=3):
"""
Convert IODP samples data file into MagIC samples file.
Default is to overwrite samples.txt in your working directory.
Parameters
----------
samp_file : str
... | [
"def",
"iodp_samples",
"(",
"samp_file",
",",
"output_samp_file",
"=",
"None",
",",
"output_dir_path",
"=",
"'.'",
",",
"input_dir_path",
"=",
"''",
",",
"data_model_num",
"=",
"3",
")",
":",
"samp_file_name",
"=",
"\"samples.txt\"",
"sample_alternatives",
"=",
... | 40.508197 | 13.612022 |
def upload_custom_metric(func, func_file="metrics.py", func_name=None, class_name=None, source_provider=None):
"""
Upload given metrics function into H2O cluster.
The metrics can have different representation:
- class: needs to implement map(pred, act, weight, offset, model), reduce(l, r) and metric(... | [
"def",
"upload_custom_metric",
"(",
"func",
",",
"func_file",
"=",
"\"metrics.py\"",
",",
"func_name",
"=",
"None",
",",
"class_name",
"=",
"None",
",",
"source_provider",
"=",
"None",
")",
":",
"import",
"tempfile",
"import",
"inspect",
"# Use default source prov... | 41.852941 | 24.529412 |
def _prepare_for_submission(self, tempfolder, inputdict):
"""
Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be r... | [
"def",
"_prepare_for_submission",
"(",
"self",
",",
"tempfolder",
",",
"inputdict",
")",
":",
"parameters",
",",
"code",
",",
"distance_matrix",
",",
"symlink",
"=",
"self",
".",
"_validate_inputs",
"(",
"inputdict",
")",
"# Prepare CalcInfo to be returned to aiida",
... | 35.131579 | 17.868421 |
def learn(self, numEpochs, batchsize):
"""Train the classifier for a given number of epochs, with a given batchsize"""
for epoch in range(numEpochs):
print('epoch %d' % epoch)
indexes = np.random.permutation(self.trainsize)
for i in range(0, self.trainsize, batchsize)... | [
"def",
"learn",
"(",
"self",
",",
"numEpochs",
",",
"batchsize",
")",
":",
"for",
"epoch",
"in",
"range",
"(",
"numEpochs",
")",
":",
"print",
"(",
"'epoch %d'",
"%",
"epoch",
")",
"indexes",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"self",
... | 56.555556 | 12.888889 |
def internal_auth_client(requires_instance=False, force_new_client=False):
"""
Looks up the values for this CLI's Instance Client in config
If none exists and requires_instance is True or force_new_client is True,
registers a new Instance Client with GLobus Auth
If none exists and requires_instanc... | [
"def",
"internal_auth_client",
"(",
"requires_instance",
"=",
"False",
",",
"force_new_client",
"=",
"False",
")",
":",
"client_id",
"=",
"lookup_option",
"(",
"CLIENT_ID_OPTNAME",
")",
"client_secret",
"=",
"lookup_option",
"(",
"CLIENT_SECRET_OPTNAME",
")",
"templat... | 39.839286 | 22.053571 |
def upi(self):
"""A dict of CLBs with UPI as key"""
parameter = 'UPI'
if parameter not in self._by:
self._populate(by=parameter)
return self._by[parameter] | [
"def",
"upi",
"(",
"self",
")",
":",
"parameter",
"=",
"'UPI'",
"if",
"parameter",
"not",
"in",
"self",
".",
"_by",
":",
"self",
".",
"_populate",
"(",
"by",
"=",
"parameter",
")",
"return",
"self",
".",
"_by",
"[",
"parameter",
"]"
] | 32.333333 | 8.333333 |
def set_offset( self, offset ):
"""Set the current read offset (in bytes) for the instance."""
assert offset in range( len( self.buffer ) )
self.pos = offset
self._fill_buffer() | [
"def",
"set_offset",
"(",
"self",
",",
"offset",
")",
":",
"assert",
"offset",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"buffer",
")",
")",
"self",
".",
"pos",
"=",
"offset",
"self",
".",
"_fill_buffer",
"(",
")"
] | 41 | 9.8 |
def get_context(self):
"""
Context sent to templates for rendering include the form's cleaned
data and also the current Request object.
"""
if not self.is_valid():
raise ValueError("Cannot generate Context when form is invalid.")
return dict(request=self.reque... | [
"def",
"get_context",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot generate Context when form is invalid.\"",
")",
"return",
"dict",
"(",
"request",
"=",
"self",
".",
"request",
",",
"*",
"... | 42.125 | 16.125 |
def get_formatted(self, key):
"""Return formatted value for context[key].
If context[key] is a type string, will just format and return the
string.
If context[key] is a special literal type, like a py string or sic
string, will run the formatting implemented by the custom tag
... | [
"def",
"get_formatted",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"try",
":",
"return",
"self",
".",
"get_processed_string",
"(",
"val",
")",
"except",
"KeyNotInContext... | 37.75 | 24.291667 |
def loads(self, src):
""" Compile css from scss string.
"""
assert isinstance(src, (unicode_, bytes_))
nodes = self.scan(src.strip())
self.parse(nodes)
return ''.join(map(str, nodes)) | [
"def",
"loads",
"(",
"self",
",",
"src",
")",
":",
"assert",
"isinstance",
"(",
"src",
",",
"(",
"unicode_",
",",
"bytes_",
")",
")",
"nodes",
"=",
"self",
".",
"scan",
"(",
"src",
".",
"strip",
"(",
")",
")",
"self",
".",
"parse",
"(",
"nodes",
... | 32.142857 | 6.714286 |
def get_checks_paths(checks_paths=None):
"""
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
"""
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abs... | [
"def",
"get_checks_paths",
"(",
"checks_paths",
"=",
"None",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"\"checks\"",
")",
"p",
"=",
"os",
... | 35.538462 | 18.615385 |
def mod_sys_path(paths):
"""
A context manager that will append the specified paths to Python's
``sys.path`` during the execution of the block.
:param paths: the paths to append
:type paths: list(str)
"""
old_path = sys.path
sys.path = paths + sys.path
try:
yield
finall... | [
"def",
"mod_sys_path",
"(",
"paths",
")",
":",
"old_path",
"=",
"sys",
".",
"path",
"sys",
".",
"path",
"=",
"paths",
"+",
"sys",
".",
"path",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"path",
"=",
"old_path"
] | 22.4 | 18.666667 |
def draw_commands(self, surf):
"""Draw the list of available commands."""
past_abilities = {act.ability for act in self._past_actions if act.ability}
for y, cmd in enumerate(sorted(self._abilities(
lambda c: c.name != "Smart"), key=lambda c: c.name), start=2):
if self._queued_action and cmd ==... | [
"def",
"draw_commands",
"(",
"self",
",",
"surf",
")",
":",
"past_abilities",
"=",
"{",
"act",
".",
"ability",
"for",
"act",
"in",
"self",
".",
"_past_actions",
"if",
"act",
".",
"ability",
"}",
"for",
"y",
",",
"cmd",
"in",
"enumerate",
"(",
"sorted",... | 48.6875 | 18.4375 |
def addCorpusId(self, value):
'''Adds SourceId to External_Info
'''
if isinstance(value, Corpus_Id):
self.corpus_ids.append(value)
else:
raise (TypeError,
'source_id Type should be Source_Id, not %s' % type(source_id)) | [
"def",
"addCorpusId",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Corpus_Id",
")",
":",
"self",
".",
"corpus_ids",
".",
"append",
"(",
"value",
")",
"else",
":",
"raise",
"(",
"TypeError",
",",
"'source_id Type should be So... | 35.75 | 15.25 |
def command_setup(self, *args):
"""Defines a new sftp file system configuration or edits an old one with the same id.
Usage: sftpman setup {options}
Available {options}:
--id={unique system identifier}
You use this to recognize and manage this sftp system.
... | [
"def",
"command_setup",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"usage",
"(",
")",
":",
"print",
"(",
"self",
".",
"command_setup",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"... | 43.362319 | 18.956522 |
def makedirs(path):
"""
Create directories if they do not exist, otherwise do nothing.
Return path for convenience
"""
if not os.path.isdir(path):
os.makedirs(path)
return path | [
"def",
"makedirs",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"path"
] | 22.333333 | 16.111111 |
def CheckClientAccess(self, username, client_id):
"""Checks whether a given user can access given client."""
self._CheckAccess(
username, str(client_id),
rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CLIENT) | [
"def",
"CheckClientAccess",
"(",
"self",
",",
"username",
",",
"client_id",
")",
":",
"self",
".",
"_CheckAccess",
"(",
"username",
",",
"str",
"(",
"client_id",
")",
",",
"rdf_objects",
".",
"ApprovalRequest",
".",
"ApprovalType",
".",
"APPROVAL_TYPE_CLIENT",
... | 47.2 | 12.8 |
def create_pull_request_reviewer(self, reviewer, repository_id, pull_request_id, reviewer_id, project=None):
"""CreatePullRequestReviewer.
[Preview API] Add a reviewer to a pull request or cast a vote.
:param :class:`<IdentityRefWithVote> <azure.devops.v5_1.git.models.IdentityRefWithVote>` revie... | [
"def",
"create_pull_request_reviewer",
"(",
"self",
",",
"reviewer",
",",
"repository_id",
",",
"pull_request_id",
",",
"reviewer_id",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_value... | 71.846154 | 35.615385 |
def list_downloads():
'''
Return a list of all updates that have been downloaded locally.
:return: A list of updates that have been downloaded
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_downloads
'''
outfiles = []
for root, subFolder, files... | [
"def",
"list_downloads",
"(",
")",
":",
"outfiles",
"=",
"[",
"]",
"for",
"root",
",",
"subFolder",
",",
"files",
"in",
"salt",
".",
"utils",
".",
"path",
".",
"os_walk",
"(",
"'/Library/Updates'",
")",
":",
"for",
"f",
"in",
"files",
":",
"outfiles",
... | 25.83871 | 24.419355 |
def _make_request(self, url, parameters, result_key):
"""Make http/https request to Google API.
Method prepares url parameters, drops None values, and gets default
values. Finally makes request using protocol assigned to client and
returns data.
:param url: url part - specifies... | [
"def",
"_make_request",
"(",
"self",
",",
"url",
",",
"parameters",
",",
"result_key",
")",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"base",
",",
"url",
")",
",",
"\"json\"",
")",
"# drop all None va... | 39.714286 | 18 |
def add_hash_memo(self, memo_hash):
"""Set the memo for the transaction to a new :class:`HashMemo
<stellar_base.memo.HashMemo>`.
:param memo_hash: A 32 byte hash or hex encoded string to use as the memo.
:type memo_hash: bytes, str
:return: This builder instance.
"""
... | [
"def",
"add_hash_memo",
"(",
"self",
",",
"memo_hash",
")",
":",
"memo_hash",
"=",
"memo",
".",
"HashMemo",
"(",
"memo_hash",
")",
"return",
"self",
".",
"add_memo",
"(",
"memo_hash",
")"
] | 35.636364 | 12.727273 |
def competition_submit_cli(self,
file_name,
message,
competition,
competition_opt=None,
quiet=False):
""" submit a competition using the client. Arguments ar... | [
"def",
"competition_submit_cli",
"(",
"self",
",",
"file_name",
",",
"message",
",",
"competition",
",",
"competition_opt",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"competition",
"=",
"competition",
"or",
"competition_opt",
"try",
":",
"submit_result"... | 44.6 | 16.56 |
def new(ruletype, **kwargs):
"""Instantiate a new build rule based on kwargs.
Appropriate args list varies with rule type.
Minimum args required:
[... fill this in ...]
"""
try:
ruleclass = TYPE_MAP[ruletype]
except KeyError:
raise error.InvalidRule('Unrecognized rule type... | [
"def",
"new",
"(",
"ruletype",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"ruleclass",
"=",
"TYPE_MAP",
"[",
"ruletype",
"]",
"except",
"KeyError",
":",
"raise",
"error",
".",
"InvalidRule",
"(",
"'Unrecognized rule type: %s'",
"%",
"ruletype",
")",
"t... | 27.823529 | 19.176471 |
def set_syslog_config(host,
username,
password,
syslog_config,
config_value,
protocol=None,
port=None,
firewall=True,
reset_service=True,
... | [
"def",
"set_syslog_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"syslog_config",
",",
"config_value",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"firewall",
"=",
"True",
",",
"reset_service",
"=",
"True",
",",
"esxi_hosts",
... | 43.096296 | 28.148148 |
def _split_input_from_namespace(cls, app, namespace, entity_kind,
shard_count):
"""Helper for _split_input_from_params.
If there are not enough Entities to make all of the given shards, the
returned list of KeyRanges will include Nones. The returned list will
contain K... | [
"def",
"_split_input_from_namespace",
"(",
"cls",
",",
"app",
",",
"namespace",
",",
"entity_kind",
",",
"shard_count",
")",
":",
"raw_entity_kind",
"=",
"cls",
".",
"_get_raw_entity_kind",
"(",
"entity_kind",
")",
"if",
"shard_count",
"==",
"1",
":",
"# With on... | 31.949367 | 19.012658 |
def resolve(self, from_email, resolution=None):
"""Resolve an incident using a valid email address."""
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
endpoint = '/'.join((self.endpoint, self.id,))
add_headers = {'fro... | [
"def",
"resolve",
"(",
"self",
",",
"from_email",
",",
"resolution",
"=",
"None",
")",
":",
"if",
"from_email",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"from_email",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"MissingFromEmail",
"(",
"from_e... | 33.772727 | 15.863636 |
def unescape_sql(inp):
"""
:param inp: an input string to be unescaped
:return: return the unescaped version of the string.
"""
if inp.startswith('"') and inp.endswith('"'):
inp = inp[1:-1]
return inp.replace('""','"').replace('\\\\','\\') | [
"def",
"unescape_sql",
"(",
"inp",
")",
":",
"if",
"inp",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"inp",
".",
"endswith",
"(",
"'\"'",
")",
":",
"inp",
"=",
"inp",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"inp",
".",
"replace",
"(",
"'\"\"'",
... | 33 | 10 |
def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
... | [
"def",
"get_abs",
"(",
"msrc",
",",
"mrec",
",",
"srcazm",
",",
"srcdip",
",",
"recazm",
",",
"recdip",
",",
"verb",
")",
":",
"# Get required ab's (9 at most)",
"ab_calc",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"11",
",",
"12",
",",
"13",
"]",
",",... | 35.942529 | 23.965517 |
def dump_pdb(filename, molecule, atomnames=None, resnames=None, chain_ids=None, occupancies=None, betas=None):
"""Writes a single molecule to a pdb file.
This function is based on the pdb file specification:
http://www.wwpdb.org/documentation/format32/sect9.html
For convenience, the relevant t... | [
"def",
"dump_pdb",
"(",
"filename",
",",
"molecule",
",",
"atomnames",
"=",
"None",
",",
"resnames",
"=",
"None",
",",
"chain_ids",
"=",
"None",
",",
"occupancies",
"=",
"None",
",",
"betas",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",... | 46.69697 | 22.257576 |
def polygon(self, vertexes, attr=0, row=None):
'adds lines for (x,y) vertexes of a polygon'
self.polylines.append((vertexes + [vertexes[0]], attr, row)) | [
"def",
"polygon",
"(",
"self",
",",
"vertexes",
",",
"attr",
"=",
"0",
",",
"row",
"=",
"None",
")",
":",
"self",
".",
"polylines",
".",
"append",
"(",
"(",
"vertexes",
"+",
"[",
"vertexes",
"[",
"0",
"]",
"]",
",",
"attr",
",",
"row",
")",
")"... | 55.333333 | 15.333333 |
def register(self, event_name):
"""
Decorator,
Registers the decorated function as a callback for the `event_name`
given.
:param event_name: The name of the event to register for.
Example:
>>> callbacks = Callbacks()
>>> @callbacks.register("my_... | [
"def",
"register",
"(",
"self",
",",
"event_name",
")",
":",
"def",
"registrar",
"(",
"func",
")",
":",
"self",
".",
"callbacks",
"[",
"event_name",
"]",
".",
"append",
"(",
"func",
")",
"return",
"func",
"return",
"registrar"
] | 24.730769 | 19.346154 |
def _is_intersect_results(results):
"""Returns False if `results` has an n-gram that exists in only one
label, True otherwise.
:param results: results to analyze
:type results: `pandas.DataFrame`
:rtype: `bool`
"""
sample = results.iloc[0]
ngram = sample... | [
"def",
"_is_intersect_results",
"(",
"results",
")",
":",
"sample",
"=",
"results",
".",
"iloc",
"[",
"0",
"]",
"ngram",
"=",
"sample",
"[",
"constants",
".",
"NGRAM_FIELDNAME",
"]",
"label",
"=",
"sample",
"[",
"constants",
".",
"LABEL_FIELDNAME",
"]",
"r... | 35.8 | 13.266667 |
def density_matrix_from_state_vector(
state: Sequence,
indices: Iterable[int] = None
) -> np.ndarray:
r"""Returns the density matrix of the wavefunction.
Calculate the density matrix for the system on the given qubit
indices, with the qubits not in indices that are present in state
traced out. ... | [
"def",
"density_matrix_from_state_vector",
"(",
"state",
":",
"Sequence",
",",
"indices",
":",
"Iterable",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"np",
".",
"ndarray",
":",
"n_qubits",
"=",
"_validate_num_qubits",
"(",
"state",
")",
"if",
"indices",
"is",
... | 31.709677 | 23.129032 |
def init(self):
"""Creates context, when context is ready context_notify_cb is called"""
# Wrap callback methods in appropriate ctypefunc instances so
# that the Pulseaudio C API can call them
self._context_notify_cb = pa_context_notify_cb_t(
self.context_notify_cb)
s... | [
"def",
"init",
"(",
"self",
")",
":",
"# Wrap callback methods in appropriate ctypefunc instances so",
"# that the Pulseaudio C API can call them",
"self",
".",
"_context_notify_cb",
"=",
"pa_context_notify_cb_t",
"(",
"self",
".",
"context_notify_cb",
")",
"self",
".",
"_sin... | 50.916667 | 23.666667 |
def register_fetcher(self, name, fetcher):
"""Register a fetcher.
:param name: Fetcher name.
:param fetcher: The new fetcher.
"""
assert name not in self.fetchers
self.fetchers[name] = fetcher | [
"def",
"register_fetcher",
"(",
"self",
",",
"name",
",",
"fetcher",
")",
":",
"assert",
"name",
"not",
"in",
"self",
".",
"fetchers",
"self",
".",
"fetchers",
"[",
"name",
"]",
"=",
"fetcher"
] | 29.25 | 6.375 |
def count(self):
"The number of items, pruned or otherwise, contained by this branch."
if getattr(self, '_count', None) is None:
self._count = getattr(self.node, 'count', 0)
return self._count | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_count'",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"_count",
"=",
"getattr",
"(",
"self",
".",
"node",
",",
"'count'",
",",
"0",
")",
"return",
"self",
".",
"_co... | 44.8 | 20 |
def extractLargestSubNetwork(cls,
network_file,
out_subset_network_file,
river_id_field,
next_down_id_field,
river_magnitude_field,
... | [
"def",
"extractLargestSubNetwork",
"(",
"cls",
",",
"network_file",
",",
"out_subset_network_file",
",",
"river_id_field",
",",
"next_down_id_field",
",",
"river_magnitude_field",
",",
"safe_mode",
"=",
"True",
")",
":",
"network_shapefile",
"=",
"ogr",
".",
"Open",
... | 41.941176 | 18.029412 |
def has_unsent(self):
"""Return whether there is any unsent record in the accumulator."""
for tp in list(self._batches.keys()):
with self._tp_locks[tp]:
dq = self._batches[tp]
if len(dq):
return True
return False | [
"def",
"has_unsent",
"(",
"self",
")",
":",
"for",
"tp",
"in",
"list",
"(",
"self",
".",
"_batches",
".",
"keys",
"(",
")",
")",
":",
"with",
"self",
".",
"_tp_locks",
"[",
"tp",
"]",
":",
"dq",
"=",
"self",
".",
"_batches",
"[",
"tp",
"]",
"if... | 36.625 | 9 |
def do_flip(dec=None, inc=None, di_block=None):
"""
This function returns the antipode (i.e. it flips) of directions.
The function can take dec and inc as seperate lists if they are of equal
length and explicitly specified or are the first two arguments. It will then
return a list of flipped decs a... | [
"def",
"do_flip",
"(",
"dec",
"=",
"None",
",",
"inc",
"=",
"None",
",",
"di_block",
"=",
"None",
")",
":",
"if",
"di_block",
"is",
"None",
":",
"dec_flip",
"=",
"[",
"]",
"inc_flip",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"le... | 32.267857 | 23.125 |
def view_as_consumer(
wrapped_view: typing.Callable[[HttpRequest], HttpResponse],
mapped_actions: typing.Optional[
typing.Dict[str, str]
]=None) -> Type[AsyncConsumer]:
"""
Wrap a django View so that it will be triggered by actions over this json
websocket consumer.
... | [
"def",
"view_as_consumer",
"(",
"wrapped_view",
":",
"typing",
".",
"Callable",
"[",
"[",
"HttpRequest",
"]",
",",
"HttpResponse",
"]",
",",
"mapped_actions",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"... | 28.636364 | 15.090909 |
def select_fields(doc, field_list):
'''
Take 'doc' and create a new doc using only keys from the 'fields' list.
Supports referencing fields using dotted notation "a.b.c" so we can parse
nested fields the way MongoDB does. The nested field class is a hack. It should
be a sub-class... | [
"def",
"select_fields",
"(",
"doc",
",",
"field_list",
")",
":",
"if",
"field_list",
"is",
"None",
"or",
"len",
"(",
"field_list",
")",
"==",
"0",
":",
"return",
"doc",
"newDoc",
"=",
"Nested_Dict",
"(",
"{",
"}",
")",
"oldDoc",
"=",
"Nested_Dict",
"("... | 35.3 | 20.6 |
def get_day_and_year():
"""
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
... | [
"def",
"get_day_and_year",
"(",
")",
":",
"pattern_year",
"=",
"r\"201[5-9]|202[0-9]\"",
"pattern_day",
"=",
"r\"2[0-5]|1[0-9]|[1-9]\"",
"stack",
"=",
"[",
"f",
"[",
"0",
"]",
"for",
"f",
"in",
"traceback",
".",
"extract_stack",
"(",
")",
"]",
"for",
"name",
... | 39.030769 | 19.8 |
def cli(env, context_id, static_ip, remote_ip, note):
"""Add an address translation to an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
... | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"static_ip",
",",
"remote_ip",
",",
"note",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"# ensure context can be retrieved by given id",
"manager",
".",
"get_tunnel... | 44.1875 | 17.4375 |
def diffuser_conical(Di1, Di2, l=None, angle=None, fd=None, Re=None,
roughness=0.0, method='Rennels'):
r'''Returns the loss coefficient for any conical pipe diffuser.
This calculation has four methods available.
The 'Rennels' [1]_ formulas are as follows (three different formulas a... | [
"def",
"diffuser_conical",
"(",
"Di1",
",",
"Di2",
",",
"l",
"=",
"None",
",",
"angle",
"=",
"None",
",",
"fd",
"=",
"None",
",",
"Re",
"=",
"None",
",",
"roughness",
"=",
"0.0",
",",
"method",
"=",
"'Rennels'",
")",
":",
"beta",
"=",
"Di1",
"/",... | 37.693989 | 24.688525 |
def translate_identifier(self, identifier, target_namespaces=None, translate_ncbi_namespace=None):
"""Given a string identifier, return a list of aliases (as
identifiers) that refer to the same sequence.
"""
namespace, alias = identifier.split(nsa_sep) if nsa_sep in identifier else (Non... | [
"def",
"translate_identifier",
"(",
"self",
",",
"identifier",
",",
"target_namespaces",
"=",
"None",
",",
"translate_ncbi_namespace",
"=",
"None",
")",
":",
"namespace",
",",
"alias",
"=",
"identifier",
".",
"split",
"(",
"nsa_sep",
")",
"if",
"nsa_sep",
"in"... | 61.727273 | 29.272727 |
def get_bbox(self):
"""Returns bounding box (xmin, xmax, ymin, ymax)"""
x_min = self.x
x_max = x_min + self.width
y_min = self.y
y_max = self.y + self.height
return x_min, x_max, y_min, y_max | [
"def",
"get_bbox",
"(",
"self",
")",
":",
"x_min",
"=",
"self",
".",
"x",
"x_max",
"=",
"x_min",
"+",
"self",
".",
"width",
"y_min",
"=",
"self",
".",
"y",
"y_max",
"=",
"self",
".",
"y",
"+",
"self",
".",
"height",
"return",
"x_min",
",",
"x_max... | 25.888889 | 16.444444 |
def get_obj_frm_str(obj_str, **kwargs):
"""
Returns a python object from a python object string
args:
obj_str: python object path expamle
"rdfframework.connections.ConnManager[{param1}]"
kwargs:
* kwargs used to format the 'obj_str'
"""
obj_str = obj_str.for... | [
"def",
"get_obj_frm_str",
"(",
"obj_str",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_str",
"=",
"obj_str",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"params",
"=",
"[",
"]",
"# parse the call portion of t... | 29.708333 | 14.666667 |
def _set_policy_map(self, v, load=False):
"""
Setter method for policy_map, mapped from YANG variable /policy_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_policy_map is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_policy_map",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 124.5 | 59.363636 |
def handleServerEvents(self, msg):
""" dispatch msg to the right handler """
self.log.debug('MSG %s', msg)
self.handleConnectionState(msg)
if msg.typeName == "error":
self.handleErrorEvents(msg)
elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]:
if sel... | [
"def",
"handleServerEvents",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'MSG %s'",
",",
"msg",
")",
"self",
".",
"handleConnectionState",
"(",
"msg",
")",
"if",
"msg",
".",
"typeName",
"==",
"\"error\"",
":",
"self",
"."... | 35.808219 | 22.315068 |
def _get_zk_consumer_offsets(self, zk_hosts_ports, consumer_groups=None, zk_prefix=''):
"""
Fetch Consumer Group offsets from Zookeeper.
Also fetch consumer_groups, topics, and partitions if not
already specified in consumer_groups.
:param dict consumer_groups: The consumer gro... | [
"def",
"_get_zk_consumer_offsets",
"(",
"self",
",",
"zk_hosts_ports",
",",
"consumer_groups",
"=",
"None",
",",
"zk_prefix",
"=",
"''",
")",
":",
"zk_consumer_offsets",
"=",
"{",
"}",
"# Construct the Zookeeper path pattern",
"# /consumers/[groupId]/offsets/[topic]/[partit... | 51.5 | 26.757143 |
def header_to_id(header):
"""
We can receive headers in the following formats:
1. unsigned base 16 hex string of variable length
2. [eventual]
:param header: the header to analyze, validate and convert (if needed)
:return: a valid ID to be used internal to the tracer
"""
if not isin... | [
"def",
"header_to_id",
"(",
"header",
")",
":",
"if",
"not",
"isinstance",
"(",
"header",
",",
"string_types",
")",
":",
"return",
"BAD_ID",
"try",
":",
"# Test that header is truly a hexadecimal value before we try to convert",
"int",
"(",
"header",
",",
"16",
")",... | 28.851852 | 19.296296 |
def _batch_iterator(self, N=1):
"""Returns N lists of records.
This can be used on any iterator, for example to batch up
SeqRecord objects from Bio.SeqIO.parse(...), or to batch
Alignment objects from Bio.AlignIO.parse(...), or simply
lines from a file handle.
This is a... | [
"def",
"_batch_iterator",
"(",
"self",
",",
"N",
"=",
"1",
")",
":",
"batch_size",
"=",
"math",
".",
"ceil",
"(",
"self",
".",
"num_records",
"/",
"float",
"(",
"N",
")",
")",
"handle",
"=",
"self",
".",
"_open",
"(",
"self",
".",
"filename",
")",
... | 39.105263 | 18.421053 |
def _merge_model_defined_relation_wheres_to_has_query(self, has_query, relation):
"""
Merge the "wheres" from a relation query to a has query.
:param has_query: The has query
:type has_query: Builder
:param relation: The relation to count
:type relation: orator.orm.rela... | [
"def",
"_merge_model_defined_relation_wheres_to_has_query",
"(",
"self",
",",
"has_query",
",",
"relation",
")",
":",
"relation_query",
"=",
"relation",
".",
"get_base_query",
"(",
")",
"has_query",
".",
"merge_wheres",
"(",
"relation_query",
".",
"wheres",
",",
"re... | 36.6 | 23 |
def save_profile_as(self):
"""Save the minimum needs under a new profile name.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
file_name_dialog.setNameFilter(self.tr('JSON files (*.... | [
"def",
"save_profile_as",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"file_name_dialog",
"=",
"QFileDialog",
"(",
"self",
")",
"file_name_dialog",
".",
"setAcceptMode",
"(",
"QFileDialog",
".",
"AcceptSave",
")",
"file_name_dialog",
".",
"setNa... | 47.387097 | 12.548387 |
def get_record(self, record):
""" Reads a dom xml element in oaidc format and
returns the bibrecord object """
self.document = record
rec = create_record()
language = self._get_language()
if language and language != 'en':
record_add_field(rec, '041', subfi... | [
"def",
"get_record",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"document",
"=",
"record",
"rec",
"=",
"create_record",
"(",
")",
"language",
"=",
"self",
".",
"_get_language",
"(",
")",
"if",
"language",
"and",
"language",
"!=",
"'en'",
":",
"... | 46.9 | 16.28 |
def channel_W(self):
"""
The minimum and hence optimal channel width of the flocculator.
This
The channel must be
- wide enough to meet the volume requirement (channel_est_W)
- wider than human access for construction
- wider than hydraulic requirement to meet H/S... | [
"def",
"channel_W",
"(",
"self",
")",
":",
"channel_est_W",
"=",
"(",
"self",
".",
"vol",
"/",
"(",
"self",
".",
"downstream_H",
"*",
"(",
"self",
".",
"channel_n",
"*",
"self",
".",
"max_L",
"-",
"self",
".",
"ent_tank_L",
")",
")",
")",
".",
"to"... | 51.210526 | 28.684211 |
def set_joint_mode(self, ids):
""" Sets the specified motors to joint mode. """
self.set_control_mode(dict(zip(ids, itertools.repeat('joint')))) | [
"def",
"set_joint_mode",
"(",
"self",
",",
"ids",
")",
":",
"self",
".",
"set_control_mode",
"(",
"dict",
"(",
"zip",
"(",
"ids",
",",
"itertools",
".",
"repeat",
"(",
"'joint'",
")",
")",
")",
")"
] | 52.666667 | 14 |
def __strip_extra_attributes(self, node: yaml.Node,
known_attrs: List[str]) -> None:
"""Strips tags from extra attributes.
This prevents nodes under attributes that are not part of our \
data model from being converted to objects. They'll be plain \
Comm... | [
"def",
"__strip_extra_attributes",
"(",
"self",
",",
"node",
":",
"yaml",
".",
"Node",
",",
"known_attrs",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"known_keys",
"=",
"list",
"(",
"known_attrs",
")",
"known_keys",
".",
"remove",
"(",
"'self'... | 42.481481 | 16.62963 |
def login(username):
"""
return user
"""
from uliweb.utils.date import now
from uliweb import request
User = get_model('user')
if isinstance(username, (str, unicode)):
user = User.get(User.c.username==username)
else:
user = username
user.last_login = no... | [
"def",
"login",
"(",
"username",
")",
":",
"from",
"uliweb",
".",
"utils",
".",
"date",
"import",
"now",
"from",
"uliweb",
"import",
"request",
"User",
"=",
"get_model",
"(",
"'user'",
")",
"if",
"isinstance",
"(",
"username",
",",
"(",
"str",
",",
"un... | 21.705882 | 16.411765 |
def _update_persistent_boot(self, device_type=[], persistent=False):
"""Changes the persistent boot device order in BIOS boot mode for host
Note: It uses first boot device from the device_type and ignores rest.
:param device_type: ordered list of boot devices
:param persistent: Boolean... | [
"def",
"_update_persistent_boot",
"(",
"self",
",",
"device_type",
"=",
"[",
"]",
",",
"persistent",
"=",
"False",
")",
":",
"tenure",
"=",
"'Once'",
"new_device",
"=",
"device_type",
"[",
"0",
"]",
"# If it is a standard device, we need to convert in RIS convention",... | 43.545455 | 20.145455 |
def get_membership_cache(self, group_ids=None, is_active=True):
"""
Build a dict cache with the group membership info. Keyed off the group id and the values are
a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids
are passed, then all gr... | [
"def",
"get_membership_cache",
"(",
"self",
",",
"group_ids",
"=",
"None",
",",
"is_active",
"=",
"True",
")",
":",
"membership_queryset",
"=",
"EntityGroupMembership",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"entity__isnull",
"=",
"True",
")",
"|",
"(... | 48.925926 | 33.37037 |
def add_weekdays2df(time_df, holidays=None, holiday_is_sunday=False):
r"""Giving back a DataFrame containing weekdays and optionally holidays for
the given year.
Parameters
----------
time_df : pandas DataFrame
DataFrame to which the weekdays should be added
Optional Parameters
--... | [
"def",
"add_weekdays2df",
"(",
"time_df",
",",
"holidays",
"=",
"None",
",",
"holiday_is_sunday",
"=",
"False",
")",
":",
"time_df",
"[",
"'weekday'",
"]",
"=",
"time_df",
".",
"index",
".",
"weekday",
"+",
"1",
"time_df",
"[",
"'date'",
"]",
"=",
"time_... | 28.897436 | 21.25641 |
def resetPassword(self, userId):
'''
Changes a user's password to a system-generated value.
'''
self._setHeaders('resetPassword')
return self._sforce.service.resetPassword(userId) | [
"def",
"resetPassword",
"(",
"self",
",",
"userId",
")",
":",
"self",
".",
"_setHeaders",
"(",
"'resetPassword'",
")",
"return",
"self",
".",
"_sforce",
".",
"service",
".",
"resetPassword",
"(",
"userId",
")"
] | 32.333333 | 18 |
def makePacket(ID, instr, reg=None, params=None):
"""
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instruction ... | [
"def",
"makePacket",
"(",
"ID",
",",
"instr",
",",
"reg",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"pkt",
"=",
"[",
"]",
"pkt",
"+=",
"[",
"0xFF",
",",
"0xFF",
",",
"0xFD",
"]",
"# header",
"pkt",
"+=",
"[",
"0x00",
"]",
"# reserved byt... | 24.030303 | 22.333333 |
def number(v):
"""Convert a value to a number."""
if nodesetp(v):
v = string(v)
try:
return float(v)
except ValueError:
return float('NaN') | [
"def",
"number",
"(",
"v",
")",
":",
"if",
"nodesetp",
"(",
"v",
")",
":",
"v",
"=",
"string",
"(",
"v",
")",
"try",
":",
"return",
"float",
"(",
"v",
")",
"except",
"ValueError",
":",
"return",
"float",
"(",
"'NaN'",
")"
] | 21.5 | 18.25 |
def heartbeat(self):
"""Sends an empty request over the streaming pull RPC.
This always sends over the stream, regardless of if
``self._UNARY_REQUESTS`` is set or not.
"""
if self._rpc is not None and self._rpc.is_active:
self._rpc.send(types.StreamingPullRequest()) | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rpc",
"is",
"not",
"None",
"and",
"self",
".",
"_rpc",
".",
"is_active",
":",
"self",
".",
"_rpc",
".",
"send",
"(",
"types",
".",
"StreamingPullRequest",
"(",
")",
")"
] | 39 | 14.875 |
def with_item(self, context, as_opt):
"""(2.7, 3.1-) with_item: test ['as' expr]"""
if as_opt:
as_loc, optional_vars = as_opt
return ast.withitem(context_expr=context, optional_vars=optional_vars,
as_loc=as_loc, loc=context.loc.join(optional_vars.l... | [
"def",
"with_item",
"(",
"self",
",",
"context",
",",
"as_opt",
")",
":",
"if",
"as_opt",
":",
"as_loc",
",",
"optional_vars",
"=",
"as_opt",
"return",
"ast",
".",
"withitem",
"(",
"context_expr",
"=",
"context",
",",
"optional_vars",
"=",
"optional_vars",
... | 51.777778 | 21.888889 |
def queryBM(query_attributes,query_dataset,query_filter=None,query_items=None,query_dic=None,host=biomart_host):
"""
Queries BioMart.
:param query_attributes: list of attributes to recover from BioMart
:param query_dataset: dataset to query
:param query_filter: one BioMart filter associated with th... | [
"def",
"queryBM",
"(",
"query_attributes",
",",
"query_dataset",
",",
"query_filter",
"=",
"None",
",",
"query_items",
"=",
"None",
",",
"query_dic",
"=",
"None",
",",
"host",
"=",
"biomart_host",
")",
":",
"server",
"=",
"BiomartServer",
"(",
"host",
")",
... | 45.45 | 27.25 |
def extract_all(self, directory=".", members=None):
"""Extract all member from the archive to the specified working
directory.
"""
if self.handle:
self.handle.extractall(path=directory, members=members) | [
"def",
"extract_all",
"(",
"self",
",",
"directory",
"=",
"\".\"",
",",
"members",
"=",
"None",
")",
":",
"if",
"self",
".",
"handle",
":",
"self",
".",
"handle",
".",
"extractall",
"(",
"path",
"=",
"directory",
",",
"members",
"=",
"members",
")"
] | 40.166667 | 12.833333 |
def _make_graph(self):
"""Init common graph svg structure"""
self.nodes['graph'] = self.svg.node(
class_='graph %s-graph %s' % (
self.__class__.__name__.lower(),
'horizontal' if self.horizontal else 'vertical'
)
)
self.svg.node(
... | [
"def",
"_make_graph",
"(",
"self",
")",
":",
"self",
".",
"nodes",
"[",
"'graph'",
"]",
"=",
"self",
".",
"svg",
".",
"node",
"(",
"class_",
"=",
"'graph %s-graph %s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",... | 31.557143 | 14.028571 |
def create_cursor(self, name=None):
"""
Returns an active connection cursor to the database.
"""
return Cursor(self.client_connection, self.connection, self.djongo_connection) | [
"def",
"create_cursor",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"Cursor",
"(",
"self",
".",
"client_connection",
",",
"self",
".",
"connection",
",",
"self",
".",
"djongo_connection",
")"
] | 40.6 | 14.2 |
def _detect_cms(self, tries=0):
"""
Detect CMS using whatcms.org.
Has a re-try mechanism because false negatives may occur
:param tries: Count of tries for CMS discovery
"""
# WhatCMS is under CloudFlare which detects and blocks proxied/Tor traffic, hence normal request.
... | [
"def",
"_detect_cms",
"(",
"self",
",",
"tries",
"=",
"0",
")",
":",
"# WhatCMS is under CloudFlare which detects and blocks proxied/Tor traffic, hence normal request.",
"page",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"\"https://whatcms.org/?s={}\"",
".",
"format",
... | 42.52 | 20.36 |
def write(self, value): # type: (int) -> None
"""Write a raw byte to the LCD."""
# Get current position
row, col = self._cursor_pos
# Write byte if changed
try:
if self._content[row][col] != value:
self._send_data(value)
self._conten... | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"# type: (int) -> None",
"# Get current position",
"row",
",",
"col",
"=",
"self",
".",
"_cursor_pos",
"# Write byte if changed",
"try",
":",
"if",
"self",
".",
"_content",
"[",
"row",
"]",
"[",
"col",
"]"... | 36.462963 | 12.722222 |
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
"""Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Neg... | [
"def",
"ones_matrix_band_part",
"(",
"rows",
",",
"cols",
",",
"num_lower",
",",
"num_upper",
",",
"out_shape",
"=",
"None",
")",
":",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"el",
",",
"int",
")",
"for",
"el",
"in",
"[",
"rows",
",",
"cols",
",",
... | 32.657143 | 19.428571 |
def getOutputName(self,name):
""" Return the name of the file or PyFITS object associated with that
name, depending on the setting of self.inmemory.
"""
val = self.outputNames[name]
if self.inmemory: # if inmemory was turned on...
# return virtualOutput object saved w... | [
"def",
"getOutputName",
"(",
"self",
",",
"name",
")",
":",
"val",
"=",
"self",
".",
"outputNames",
"[",
"name",
"]",
"if",
"self",
".",
"inmemory",
":",
"# if inmemory was turned on...",
"# return virtualOutput object saved with that name",
"val",
"=",
"self",
".... | 43 | 10.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.