text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def writeToFile(self, f, packed=True):
"""
Write serialized object to file.
:param f: output file
:param packed: If true, will pack contents.
"""
# Get capnproto schema from instance
schema = self.getSchema()
# Construct new message, otherwise refered to as `proto`
proto = schema.n... | [
"def",
"writeToFile",
"(",
"self",
",",
"f",
",",
"packed",
"=",
"True",
")",
":",
"# Get capnproto schema from instance",
"schema",
"=",
"self",
".",
"getSchema",
"(",
")",
"# Construct new message, otherwise refered to as `proto`",
"proto",
"=",
"schema",
".",
"ne... | 23.380952 | 17.095238 |
def rgbmap_cb(self, rgbmap, channel):
"""
This method is called when the RGBMap is changed. We update
the ColorBar to match.
"""
if not self.gui_up:
return
fitsimage = channel.fitsimage
if fitsimage != self.fv.getfocus_fitsimage():
return ... | [
"def",
"rgbmap_cb",
"(",
"self",
",",
"rgbmap",
",",
"channel",
")",
":",
"if",
"not",
"self",
".",
"gui_up",
":",
"return",
"fitsimage",
"=",
"channel",
".",
"fitsimage",
"if",
"fitsimage",
"!=",
"self",
".",
"fv",
".",
"getfocus_fitsimage",
"(",
")",
... | 32.545455 | 10 |
def convert_cityscapes_instance_only(
data_dir, out_dir):
"""Convert from cityscapes format to COCO instance seg format - polygons"""
sets = [
'gtFine_val',
'gtFine_train',
'gtFine_test',
# 'gtCoarse_train',
# 'gtCoarse_val',
# 'gtCoarse_train_extra'
... | [
"def",
"convert_cityscapes_instance_only",
"(",
"data_dir",
",",
"out_dir",
")",
":",
"sets",
"=",
"[",
"'gtFine_val'",
",",
"'gtFine_train'",
",",
"'gtFine_test'",
",",
"# 'gtCoarse_train',",
"# 'gtCoarse_val',",
"# 'gtCoarse_train_extra'",
"]",
"ann_dirs",
"=",
"[",
... | 38.45045 | 20.027027 |
def play_human(env):
"""
Play the environment using keyboard as a human.
Args:
env (gym.Env): the initialized gym environment to play
Returns:
None
"""
# play the game and catch a potential keyboard interrupt
try:
play(env, fps=env.metadata['video.frames_per_second... | [
"def",
"play_human",
"(",
"env",
")",
":",
"# play the game and catch a potential keyboard interrupt",
"try",
":",
"play",
"(",
"env",
",",
"fps",
"=",
"env",
".",
"metadata",
"[",
"'video.frames_per_second'",
"]",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
... | 22.388889 | 22.277778 |
def __set_bp(self, aProcess):
"""
Writes a breakpoint instruction at the target address.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
address = self.get_address()
self.__previousValue = aProcess.read(address, len(self.bpInstruction))
i... | [
"def",
"__set_bp",
"(",
"self",
",",
"aProcess",
")",
":",
"address",
"=",
"self",
".",
"get_address",
"(",
")",
"self",
".",
"__previousValue",
"=",
"aProcess",
".",
"read",
"(",
"address",
",",
"len",
"(",
"self",
".",
"bpInstruction",
")",
")",
"if"... | 40.5 | 13.214286 |
def windows_k_distinct(x, k):
"""Find all largest windows containing exactly k distinct elements
:param x: list or string
:param k: positive integer
:yields: largest intervals [i, j) with len(set(x[i:j])) == k
:complexity: `O(|x|)`
"""
dist, i, j = 0, 0, 0 # dist = |{x[i], ..... | [
"def",
"windows_k_distinct",
"(",
"x",
",",
"k",
")",
":",
"dist",
",",
"i",
",",
"j",
"=",
"0",
",",
"0",
",",
"0",
"# dist = |{x[i], ..., x[j-1]}|",
"occ",
"=",
"{",
"xi",
":",
"0",
"for",
"xi",
"in",
"x",
"}",
"# number of occurrences in x[i:j]",
"w... | 38.217391 | 17.304348 |
def __get_bundle(self, io_handler, bundle_id):
"""
Retrieves the Bundle object with the given bundle ID. Writes errors
through the I/O handler if any.
:param io_handler: I/O Handler
:param bundle_id: String or integer bundle ID
:return: The Bundle object matching the giv... | [
"def",
"__get_bundle",
"(",
"self",
",",
"io_handler",
",",
"bundle_id",
")",
":",
"try",
":",
"bundle_id",
"=",
"int",
"(",
"bundle_id",
")",
"return",
"self",
".",
"_context",
".",
"get_bundle",
"(",
"bundle_id",
")",
"except",
"(",
"TypeError",
",",
"... | 41.8125 | 14.6875 |
def root_item_selected(self, item):
"""Root item has been selected: expanding it and collapsing others"""
if self.show_all_files:
return
for root_item in self.get_top_level_items():
if root_item is item:
self.expandItem(root_item)
else:
... | [
"def",
"root_item_selected",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"show_all_files",
":",
"return",
"for",
"root_item",
"in",
"self",
".",
"get_top_level_items",
"(",
")",
":",
"if",
"root_item",
"is",
"item",
":",
"self",
".",
"expandItem... | 39.666667 | 9 |
def reportPrettyData(root, worker, job, job_types, options):
""" print the important bits out.
"""
out_str = "Batch System: %s\n" % root.batch_system
out_str += ("Default Cores: %s Default Memory: %s\n"
"Max Cores: %s\n" % (
reportNumber(get(root, "default_cores"), options),
... | [
"def",
"reportPrettyData",
"(",
"root",
",",
"worker",
",",
"job",
",",
"job_types",
",",
"options",
")",
":",
"out_str",
"=",
"\"Batch System: %s\\n\"",
"%",
"root",
".",
"batch_system",
"out_str",
"+=",
"(",
"\"Default Cores: %s Default Memory: %s\\n\"",
"\"Max C... | 45.375 | 18.541667 |
def advance(self):
"""Carry out one iteration of Arnoldi."""
if self.iter >= self.maxiter:
raise ArgumentError('Maximum number of iterations reached.')
if self.invariant:
raise ArgumentError('Krylov subspace was found to be invariant '
'in ... | [
"def",
"advance",
"(",
"self",
")",
":",
"if",
"self",
".",
"iter",
">=",
"self",
".",
"maxiter",
":",
"raise",
"ArgumentError",
"(",
"'Maximum number of iterations reached.'",
")",
"if",
"self",
".",
"invariant",
":",
"raise",
"ArgumentError",
"(",
"'Krylov s... | 41.045455 | 16.488636 |
def create_thread(cls, session, conversation, thread, imported=False):
"""Create a conversation thread.
Please note that threads cannot be added to conversations with 100
threads (or more), if attempted the API will respond with HTTP 412.
Args:
conversation (helpscout.model... | [
"def",
"create_thread",
"(",
"cls",
",",
"session",
",",
"conversation",
",",
"thread",
",",
"imported",
"=",
"False",
")",
":",
"return",
"super",
"(",
"Conversations",
",",
"cls",
")",
".",
"create",
"(",
"session",
",",
"thread",
",",
"endpoint_override... | 44.814815 | 25.888889 |
def check(self):
"""
Compare the :func:`os.stat` for the pam_env style environmnt file
`path` with the previous result `old_st`, which may be :data:`None` if
the previous stat attempt failed. Reload its contents if the file has
changed or appeared since last attempt.
:re... | [
"def",
"check",
"(",
"self",
")",
":",
"st",
"=",
"self",
".",
"_stat",
"(",
")",
"if",
"self",
".",
"_st",
"==",
"st",
":",
"return",
"self",
".",
"_st",
"=",
"st",
"self",
".",
"_remove_existing",
"(",
")",
"if",
"st",
"is",
"None",
":",
"LOG... | 31.909091 | 21.454545 |
def stop(self):
"""
Stop this instance.
:return: None
"""
instance_status = Instance.InstanceStatus(status='Terminated')
xml_content = instance_status.serialize()
headers = {'Content-Type': 'application/xml'}
self._client.put(self.resource(), xml_conten... | [
"def",
"stop",
"(",
"self",
")",
":",
"instance_status",
"=",
"Instance",
".",
"InstanceStatus",
"(",
"status",
"=",
"'Terminated'",
")",
"xml_content",
"=",
"instance_status",
".",
"serialize",
"(",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'applicati... | 27.333333 | 21.666667 |
def _ParsePathSpecification(
self, knowledge_base, searcher, file_system, path_specification,
path_separator):
"""Parses a file system for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
searcher (dfvfs.FileSystemSearcher): file s... | [
"def",
"_ParsePathSpecification",
"(",
"self",
",",
"knowledge_base",
",",
"searcher",
",",
"file_system",
",",
"path_specification",
",",
"path_separator",
")",
":",
"try",
":",
"file_entry",
"=",
"searcher",
".",
"GetFileEntryByPathSpec",
"(",
"path_specification",
... | 40.5625 | 22.09375 |
def export(self, id, exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Export a result.
:param id: Result ID as an int.
:param exclude_captures: If bool `True`, don't export capture files
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self... | [
"def",
"export",
"(",
"self",
",",
"id",
",",
"exclude_captures",
"=",
"False",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"export",
"(",
"self",
".",
"base",
",",
"id",
",",
"params",
"=",
"{",
"'exc... | 48.75 | 24.25 |
def prop2b(gm, pvinit, dt):
"""
Given a central mass and the state of massless body at time t_0,
this routine determines the state as predicted by a two-body
force model at time t_0 + dt.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prop2b_c.html
:param gm: Gravity of the central ma... | [
"def",
"prop2b",
"(",
"gm",
",",
"pvinit",
",",
"dt",
")",
":",
"gm",
"=",
"ctypes",
".",
"c_double",
"(",
"gm",
")",
"pvinit",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"pvinit",
")",
"dt",
"=",
"ctypes",
".",
"c_double",
"(",
"dt",
")",
"pvprop"... | 35.869565 | 13.956522 |
def add_eval(self, agent, e, fr=None):
"""Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluat... | [
"def",
"add_eval",
"(",
"self",
",",
"agent",
",",
"e",
",",
"fr",
"=",
"None",
")",
":",
"self",
".",
"_evals",
"[",
"agent",
".",
"name",
"]",
"=",
"e",
"self",
".",
"_framings",
"[",
"agent",
".",
"name",
"]",
"=",
"fr"
] | 40.3 | 13 |
def count_sequences(infile):
'''Returns the number of sequences in a file'''
seq_reader = sequences.file_reader(infile)
n = 0
for seq in seq_reader:
n += 1
return n | [
"def",
"count_sequences",
"(",
"infile",
")",
":",
"seq_reader",
"=",
"sequences",
".",
"file_reader",
"(",
"infile",
")",
"n",
"=",
"0",
"for",
"seq",
"in",
"seq_reader",
":",
"n",
"+=",
"1",
"return",
"n"
] | 26.571429 | 18.285714 |
def add_minrmsd_to_ref(self, ref, ref_frame=0, atom_indices=None, precentered=False):
r"""
Adds the minimum root-mean-square-deviation (minrmsd) with respect to a reference structure to the feature list.
Parameters
----------
ref:
Reference structure for computing th... | [
"def",
"add_minrmsd_to_ref",
"(",
"self",
",",
"ref",
",",
"ref_frame",
"=",
"0",
",",
"atom_indices",
"=",
"None",
",",
"precentered",
"=",
"False",
")",
":",
"from",
".",
"misc",
"import",
"MinRmsdFeature",
"f",
"=",
"MinRmsdFeature",
"(",
"ref",
",",
... | 47.28125 | 29.4375 |
def searchsorted(arr, N, x):
"""N is length of arr
"""
L = 0
R = N-1
done = False
m = (L+R)//2
while not done:
if arr[m] < x:
L = m + 1
elif arr[m] > x:
R = m - 1
elif arr[m] == x:
done = True
m = (L+R)//2
if L>R:
... | [
"def",
"searchsorted",
"(",
"arr",
",",
"N",
",",
"x",
")",
":",
"L",
"=",
"0",
"R",
"=",
"N",
"-",
"1",
"done",
"=",
"False",
"m",
"=",
"(",
"L",
"+",
"R",
")",
"//",
"2",
"while",
"not",
"done",
":",
"if",
"arr",
"[",
"m",
"]",
"<",
"... | 18.722222 | 18.611111 |
def default_file_encoder():
"""
Get default encoder cwr file
:return:
"""
config = CWRConfiguration()
field_configs = config.load_field_config('table')
field_configs.update(config.load_field_config('common'))
field_values = CWRTables()
for entry in field_configs.values():
i... | [
"def",
"default_file_encoder",
"(",
")",
":",
"config",
"=",
"CWRConfiguration",
"(",
")",
"field_configs",
"=",
"config",
".",
"load_field_config",
"(",
"'table'",
")",
"field_configs",
".",
"update",
"(",
"config",
".",
"load_field_config",
"(",
"'common'",
")... | 30.055556 | 15.944444 |
def attribute_value(self, doc: Document, attribute_name: str):
"""
Access data using attribute name rather than the numeric indices
Returns: the value for the attribute
"""
return doc.cdr_document.get(self.header_translation_table[attribute_name]) | [
"def",
"attribute_value",
"(",
"self",
",",
"doc",
":",
"Document",
",",
"attribute_name",
":",
"str",
")",
":",
"return",
"doc",
".",
"cdr_document",
".",
"get",
"(",
"self",
".",
"header_translation_table",
"[",
"attribute_name",
"]",
")"
] | 35.25 | 22.5 |
def generate_access_token_from_authorization_code(request, client):
""" Generates a new AccessToken from a request with an authorization code.
Read the specification: http://tools.ietf.org/html/rfc6749#section-4.1.3
"""
authorization_code_value = request.POST.get('code')
if not authorization_code_value:
... | [
"def",
"generate_access_token_from_authorization_code",
"(",
"request",
",",
"client",
")",
":",
"authorization_code_value",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'code'",
")",
"if",
"not",
"authorization_code_value",
":",
"raise",
"InvalidRequest",
"(",
"'... | 37.476923 | 22.384615 |
def _writeMzmlIndexList(xmlWriter, spectrumIndexList, chromatogramIndexList):
""" #TODO: docstring
:param xmlWriter: #TODO: docstring
:param spectrumIndexList: #TODO: docstring
:param chromatogramIndexList: #TODO: docstring
"""
counts = 0
if spectrumIndexList:
counts += 1
if chr... | [
"def",
"_writeMzmlIndexList",
"(",
"xmlWriter",
",",
"spectrumIndexList",
",",
"chromatogramIndexList",
")",
":",
"counts",
"=",
"0",
"if",
"spectrumIndexList",
":",
"counts",
"+=",
"1",
"if",
"chromatogramIndexList",
":",
"counts",
"+=",
"1",
"if",
"counts",
"=... | 31 | 19.28 |
def update_tabs_text(self):
"""Update the text from the tabs."""
# This is needed to prevent that hanged consoles make reference
# to an index that doesn't exist. See issue 4881
try:
for index, fname in enumerate(self.filenames):
client = self.clients[in... | [
"def",
"update_tabs_text",
"(",
"self",
")",
":",
"# This is needed to prevent that hanged consoles make reference\r",
"# to an index that doesn't exist. See issue 4881\r",
"try",
":",
"for",
"index",
",",
"fname",
"in",
"enumerate",
"(",
"self",
".",
"filenames",
")",
":",... | 42.357143 | 17.428571 |
def remove(self, auto_confirm=False, verbose=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to uninstall.",
self.dist.project... | [
"def",
"remove",
"(",
"self",
",",
"auto_confirm",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"paths",
":",
"logger",
".",
"info",
"(",
"\"Can't uninstall '%s'. No files were found to uninstall.\"",
",",
"self",
".",
"dist"... | 33.866667 | 21.533333 |
def terminate(self):
"""Delete all files created by this index, invalidating `self`. Use with care."""
try:
self.id2sims.terminate()
except:
pass
import glob
for fname in glob.glob(self.fname + '*'):
try:
os.remove(fname)
... | [
"def",
"terminate",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"id2sims",
".",
"terminate",
"(",
")",
"except",
":",
"pass",
"import",
"glob",
"for",
"fname",
"in",
"glob",
".",
"glob",
"(",
"self",
".",
"fname",
"+",
"'*'",
")",
":",
"try",
... | 32.444444 | 15.611111 |
def compose_object(self, file_list, destination_file, content_type):
"""COMPOSE multiple objects together.
Using the given list of files, calls the put object with the compose flag.
This call merges all the files into the destination file.
Args:
file_list: list of dicts with the file name.
... | [
"def",
"compose_object",
"(",
"self",
",",
"file_list",
",",
"destination_file",
",",
"content_type",
")",
":",
"xml_setting_list",
"=",
"[",
"'<ComposeRequest>'",
"]",
"for",
"meta_data",
"in",
"file_list",
":",
"xml_setting_list",
".",
"append",
"(",
"'<Componen... | 36.0625 | 18.5 |
def worker_main(self):
"""
The main function of for the mux process: setup the Mitogen broker
thread and ansible_mitogen services, then sleep waiting for the socket
connected to the parent to be closed (indicating the parent has died).
"""
self._setup_master()
sel... | [
"def",
"worker_main",
"(",
"self",
")",
":",
"self",
".",
"_setup_master",
"(",
")",
"self",
".",
"_setup_services",
"(",
")",
"try",
":",
"# Let the parent know our listening socket is ready.",
"mitogen",
".",
"core",
".",
"io_op",
"(",
"self",
".",
"child_sock... | 40.227273 | 22.136364 |
def superclasses(self, inherited=False):
"""Iterate over the superclasses of the class.
This function is the Python equivalent
of the CLIPS class-superclasses command.
"""
data = clips.data.DataObject(self._env)
lib.EnvClassSuperclasses(
self._env, self._cl... | [
"def",
"superclasses",
"(",
"self",
",",
"inherited",
"=",
"False",
")",
":",
"data",
"=",
"clips",
".",
"data",
".",
"DataObject",
"(",
"self",
".",
"_env",
")",
"lib",
".",
"EnvClassSuperclasses",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_cls",
... | 29.642857 | 17 |
def tokenize_akkadian_words(line):
"""
Operates on a single line of text, returns all words in the line as a
tuple in a list.
input: "1. isz-pur-ram a-na"
output: [("isz-pur-ram", "akkadian"), ("a-na", "akkadian")]
:param: line: text string
:return: list of tuples: (word, language)
"""... | [
"def",
"tokenize_akkadian_words",
"(",
"line",
")",
":",
"beginning_underscore",
"=",
"\"_[^_]+(?!_)$\"",
"# only match a string if it has a beginning underscore anywhere",
"ending_underscore",
"=",
"\"^(?<!_)[^_]+_\"",
"# only match a string if it has an ending underscore anywhere",
"tw... | 39.644444 | 16.711111 |
def start(self, container, instances=None, map_name=None, **kwargs):
"""
Starts instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to start. If not specified, will start all instances as spec... | [
"def",
"start",
"(",
"self",
",",
"container",
",",
"instances",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'start'",
",",
"container",
",",
"instances",
"=",
"instances",
"... | 56.117647 | 25.411765 |
def json_files_serializer(objs, status=None):
"""JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`.
"""
... | [
"def",
"json_files_serializer",
"(",
"objs",
",",
"status",
"=",
"None",
")",
":",
"files",
"=",
"[",
"file_serializer",
"(",
"obj",
")",
"for",
"obj",
"in",
"objs",
"]",
"return",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"files",
")",
",",
"st... | 37.454545 | 12.909091 |
def to_serializable_value(self):
"""
Run through all fields of the object and parse the values
:return:
:rtype: dict
"""
return {
name: field.to_serializable_value()
for name, field in self.value.__dict__.items()
if isinstance(field, F... | [
"def",
"to_serializable_value",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"field",
".",
"to_serializable_value",
"(",
")",
"for",
"name",
",",
"field",
"in",
"self",
".",
"value",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",... | 28.25 | 17.583333 |
def get_alert_log(self,
current=0,
minimum=0,
maximum=100,
header="",
action_key=None):
"""Get the alert log."""
return self.get_alert(current=current,
minimum=mini... | [
"def",
"get_alert_log",
"(",
"self",
",",
"current",
"=",
"0",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"100",
",",
"header",
"=",
"\"\"",
",",
"action_key",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_alert",
"(",
"current",
"=",
"curre... | 38.230769 | 6.384615 |
def get_new_service_instance_stub(service_instance, path, ns=None,
version=None):
'''
Returns a stub that points to a different path,
created from an existing connection.
service_instance
The Service Instance.
path
Path of the new stub.
ns
... | [
"def",
"get_new_service_instance_stub",
"(",
"service_instance",
",",
"path",
",",
"ns",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"# For python 2.7.9 and later, the default SSL context has more strict",
"# connection handshaking rule. We may need turn off the hostname ch... | 32.414634 | 16.902439 |
def drop_table(self, table):
"""
Drop a table from the MyDB context.
## Arguments
* `table` (str): The name of the table to drop.
"""
job_id = self.submit("DROP TABLE %s"%table, context="MYDB")
status = self.monitor(job_id)
if status[0] != 5:
... | [
"def",
"drop_table",
"(",
"self",
",",
"table",
")",
":",
"job_id",
"=",
"self",
".",
"submit",
"(",
"\"DROP TABLE %s\"",
"%",
"table",
",",
"context",
"=",
"\"MYDB\"",
")",
"status",
"=",
"self",
".",
"monitor",
"(",
"job_id",
")",
"if",
"status",
"["... | 27.461538 | 17.923077 |
def label(self):
"Label inherited from items"
if self._label:
return self._label
else:
if len(self):
label = get_ndmapping_label(self, 'label')
return '' if label is None else label
else:
return '' | [
"def",
"label",
"(",
"self",
")",
":",
"if",
"self",
".",
"_label",
":",
"return",
"self",
".",
"_label",
"else",
":",
"if",
"len",
"(",
"self",
")",
":",
"label",
"=",
"get_ndmapping_label",
"(",
"self",
",",
"'label'",
")",
"return",
"''",
"if",
... | 29.6 | 16.6 |
def get_block_height(self, is_full: bool = False) -> int or dict:
"""
This interface is used to get the decimal block height in current network.
Return:
the decimal total height of blocks in current network.
"""
response = self.get_block_count(is_full=True)
r... | [
"def",
"get_block_height",
"(",
"self",
",",
"is_full",
":",
"bool",
"=",
"False",
")",
"->",
"int",
"or",
"dict",
":",
"response",
"=",
"self",
".",
"get_block_count",
"(",
"is_full",
"=",
"True",
")",
"response",
"[",
"'result'",
"]",
"-=",
"1",
"if"... | 34.416667 | 18.416667 |
def td_waveform_to_fd_waveform(waveform, out=None, length=None,
buffer_length=100):
""" Convert a time domain into a frequency domain waveform by FFT.
As a waveform is assumed to "wrap" in the time domain one must be
careful to ensure the waveform goes to 0 at both "bo... | [
"def",
"td_waveform_to_fd_waveform",
"(",
"waveform",
",",
"out",
"=",
"None",
",",
"length",
"=",
"None",
",",
"buffer_length",
"=",
"100",
")",
":",
"# Figure out lengths and set out if needed",
"if",
"out",
"is",
"None",
":",
"if",
"length",
"is",
"None",
"... | 50.946429 | 23 |
def _get_local_files(self, path):
"""Returns a dictionary of all the files under a path."""
if not path:
raise ValueError("No path specified")
files = defaultdict(lambda: None)
path_len = len(path) + 1
for root, dirs, filenames in os.walk(path):
for name i... | [
"def",
"_get_local_files",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"No path specified\"",
")",
"files",
"=",
"defaultdict",
"(",
"lambda",
":",
"None",
")",
"path_len",
"=",
"len",
"(",
"path",
")",
"+"... | 41.636364 | 10.454545 |
def show_keyword_help(cur, arg):
"""
Call the built-in "show <command>", to display help for an SQL keyword.
:param cur: cursor
:param arg: string
:return: list
"""
keyword = arg.strip('"').strip("'")
query = "help '{0}'".format(keyword)
log.debug(query)
cur.execute(query)
if... | [
"def",
"show_keyword_help",
"(",
"cur",
",",
"arg",
")",
":",
"keyword",
"=",
"arg",
".",
"strip",
"(",
"'\"'",
")",
".",
"strip",
"(",
"\"'\"",
")",
"query",
"=",
"\"help '{0}'\"",
".",
"format",
"(",
"keyword",
")",
"log",
".",
"debug",
"(",
"query... | 33.375 | 14.625 |
def pathFromHere_walk(self, astr_startPath = '/'):
"""
Return a list of paths from "here" in the stree, using
the internal cd() to walk the path space.
:return: a list of paths from "here"
"""
self.l_lwd = []
self.treeWalk(startPath ... | [
"def",
"pathFromHere_walk",
"(",
"self",
",",
"astr_startPath",
"=",
"'/'",
")",
":",
"self",
".",
"l_lwd",
"=",
"[",
"]",
"self",
".",
"treeWalk",
"(",
"startPath",
"=",
"astr_startPath",
",",
"f",
"=",
"self",
".",
"lwd",
")",
"return",
"self",
".",
... | 33.545455 | 16.818182 |
def _init_append(self):
"""
Initializes file on 'a' mode.
"""
if self._content_length:
# Adjust size if content length specified
with _handle_azure_exception():
self._resize(
content_length=self._content_length, **self._client_k... | [
"def",
"_init_append",
"(",
"self",
")",
":",
"if",
"self",
".",
"_content_length",
":",
"# Adjust size if content length specified",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_resize",
"(",
"content_length",
"=",
"self",
".",
"_content_length"... | 34 | 12.923077 |
def get_bounds(locations, lonlat=False):
"""
Computes the bounds of the object in the form
[[lat_min, lon_min], [lat_max, lon_max]]
"""
bounds = [[None, None], [None, None]]
for point in iter_coords(locations):
bounds = [
[
none_min(bounds[0][0], point[0]),
... | [
"def",
"get_bounds",
"(",
"locations",
",",
"lonlat",
"=",
"False",
")",
":",
"bounds",
"=",
"[",
"[",
"None",
",",
"None",
"]",
",",
"[",
"None",
",",
"None",
"]",
"]",
"for",
"point",
"in",
"iter_coords",
"(",
"locations",
")",
":",
"bounds",
"="... | 27.52381 | 14.285714 |
def is_iso8601(instance: str):
"""Validates ISO8601 format"""
if not isinstance(instance, str):
return True
return ISO8601.match(instance) is not None | [
"def",
"is_iso8601",
"(",
"instance",
":",
"str",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"str",
")",
":",
"return",
"True",
"return",
"ISO8601",
".",
"match",
"(",
"instance",
")",
"is",
"not",
"None"
] | 33.2 | 8 |
def restart(self, container, instances=None, map_name=None, **kwargs):
"""
Restarts instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will restart all instances as... | [
"def",
"restart",
"(",
"self",
",",
"container",
",",
"instances",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'restart'",
",",
"container",
",",
"instances",
"=",
"instances",... | 56.764706 | 25.823529 |
def _merge_parameters(self, other_trajectory, remove_duplicates=False,
trial_parameter_name=None,
ignore_data=()):
"""Merges parameters from the other trajectory into the current one.
The explored parameters in the current trajectory are directly enla... | [
"def",
"_merge_parameters",
"(",
"self",
",",
"other_trajectory",
",",
"remove_duplicates",
"=",
"False",
",",
"trial_parameter_name",
"=",
"None",
",",
"ignore_data",
"=",
"(",
")",
")",
":",
"if",
"trial_parameter_name",
":",
"if",
"remove_duplicates",
":",
"s... | 48.293578 | 27.720183 |
def pre_disconnect(self, sid, namespace):
"""Put the client in the to-be-disconnected list.
This allows the client data structures to be present while the
disconnect handler is invoked, but still recognize the fact that the
client is soon going away.
"""
if namespace not... | [
"def",
"pre_disconnect",
"(",
"self",
",",
"sid",
",",
"namespace",
")",
":",
"if",
"namespace",
"not",
"in",
"self",
".",
"pending_disconnect",
":",
"self",
".",
"pending_disconnect",
"[",
"namespace",
"]",
"=",
"[",
"]",
"self",
".",
"pending_disconnect",
... | 44.6 | 15 |
def profiler(self):
"""Creates a dictionary from the profile scheme(s)"""
# Initialise variables
profiledata = defaultdict(make_dict)
profileset = set()
# supplementalset = ''
genedict = {}
# Find all the unique profiles to use with a set
for sample in sel... | [
"def",
"profiler",
"(",
"self",
")",
":",
"# Initialise variables",
"profiledata",
"=",
"defaultdict",
"(",
"make_dict",
")",
"profileset",
"=",
"set",
"(",
")",
"# supplementalset = ''",
"genedict",
"=",
"{",
"}",
"# Find all the unique profiles to use with a set",
"... | 54.377049 | 21.672131 |
def _get_all_constants():
"""
Get list of all uppercase, non-private globals (doesn't start with ``_``).
Returns:
list: Uppercase names defined in `globals()` (variables from this \
module).
"""
return [
key for key in globals().keys()
if all([
not ... | [
"def",
"_get_all_constants",
"(",
")",
":",
"return",
"[",
"key",
"for",
"key",
"in",
"globals",
"(",
")",
".",
"keys",
"(",
")",
"if",
"all",
"(",
"[",
"not",
"key",
".",
"startswith",
"(",
"\"_\"",
")",
",",
"# publicly accesible",
"key",
".",
"upp... | 31.625 | 23.125 |
def validate_relation_data(self, sentry_unit, relation, expected):
"""Validate actual relation data based on expected relation data."""
actual = sentry_unit.relation(relation[0], relation[1])
return self._validate_dict_data(expected, actual) | [
"def",
"validate_relation_data",
"(",
"self",
",",
"sentry_unit",
",",
"relation",
",",
"expected",
")",
":",
"actual",
"=",
"sentry_unit",
".",
"relation",
"(",
"relation",
"[",
"0",
"]",
",",
"relation",
"[",
"1",
"]",
")",
"return",
"self",
".",
"_val... | 65.5 | 16.5 |
def register_add_user_command(self, add_user_func):
"""
Add the add-user command to the parser and call add_user_func(project_name, user_full_name, auth_role)
when chosen.
:param add_user_func: func Called when this option is chosen: upload_func(project_name, user_full_name, auth_role).
... | [
"def",
"register_add_user_command",
"(",
"self",
",",
"add_user_func",
")",
":",
"description",
"=",
"\"Gives user permission to access a remote project.\"",
"add_user_parser",
"=",
"self",
".",
"subparsers",
".",
"add_parser",
"(",
"'add-user'",
",",
"description",
"=",
... | 61.642857 | 29.928571 |
def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v} | [
"def",
"string_to_identity",
"(",
"identity_str",
")",
":",
"m",
"=",
"_identity_regexp",
".",
"match",
"(",
"identity_str",
")",
"result",
"=",
"m",
".",
"groupdict",
"(",
")",
"log",
".",
"debug",
"(",
"'parsed identity: %s'",
",",
"result",
")",
"return",... | 41.333333 | 5.666667 |
def _addPolylineToElements(self):
"""Creates a new Polyline element that will be used for future movement/drawing.
The old one (if filled) will be stored on the movement stack.
"""
if (len(self._pointsOfPolyline) > 1):
s = ''
for point in self._pointsOfPolyline:
... | [
"def",
"_addPolylineToElements",
"(",
"self",
")",
":",
"if",
"(",
"len",
"(",
"self",
".",
"_pointsOfPolyline",
")",
">",
"1",
")",
":",
"s",
"=",
"''",
"for",
"point",
"in",
"self",
".",
"_pointsOfPolyline",
":",
"s",
"+=",
"str",
"(",
"point",
")"... | 52.615385 | 18.461538 |
def decode(self, X, lengths=None, algorithm=None):
"""Find most likely state sequence corresponding to ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequenc... | [
"def",
"decode",
"(",
"self",
",",
"X",
",",
"lengths",
"=",
"None",
",",
"algorithm",
"=",
"None",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"startprob_\"",
")",
"self",
".",
"_check",
"(",
")",
"algorithm",
"=",
"algorithm",
"or",
"self",
".",... | 33.407407 | 19.981481 |
def pop(self):
"""
Pop the frame at the top of the stack.
@return: The popped frame, else None.
@rtype: L{Frame}
"""
if len(self.stack):
popped = self.stack.pop()
#log.debug('pop: (%s)\n%s', Repr(popped), Repr(self.stack))
return ... | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"stack",
")",
":",
"popped",
"=",
"self",
".",
"stack",
".",
"pop",
"(",
")",
"#log.debug('pop: (%s)\\n%s', Repr(popped), Repr(self.stack))",
"return",
"popped",
"else",
":",
"#log.debug('stac... | 29.571429 | 13.571429 |
def _get_warped_mean(self, mean, std, pred_init=None, deg_gauss_hermite=20):
"""
Calculate the warped mean by using Gauss-Hermite quadrature.
"""
gh_samples, gh_weights = np.polynomial.hermite.hermgauss(deg_gauss_hermite)
gh_samples = gh_samples[:, None]
gh_weights = gh_w... | [
"def",
"_get_warped_mean",
"(",
"self",
",",
"mean",
",",
"std",
",",
"pred_init",
"=",
"None",
",",
"deg_gauss_hermite",
"=",
"20",
")",
":",
"gh_samples",
",",
"gh_weights",
"=",
"np",
".",
"polynomial",
".",
"hermite",
".",
"hermgauss",
"(",
"deg_gauss_... | 52.625 | 19.875 |
def export_model(self, format, file_name=None):
"""Save the assembled model in a modeling formalism other than PySB.
For more details on exporting PySB models, see
http://pysb.readthedocs.io/en/latest/modules/export/index.html
Parameters
----------
format : str
... | [
"def",
"export_model",
"(",
"self",
",",
"format",
",",
"file_name",
"=",
"None",
")",
":",
"# Handle SBGN as special case",
"if",
"format",
"==",
"'sbgn'",
":",
"exp_str",
"=",
"export_sbgn",
"(",
"self",
".",
"model",
")",
"elif",
"format",
"==",
"'kappa_i... | 37.840909 | 20 |
def prepare_parameters(self, multi_row_parameters):
""" Attribute sql parameters with meta data for a prepared statement.
Make some basic checks that at least the number of parameters is correct.
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows)
... | [
"def",
"prepare_parameters",
"(",
"self",
",",
"multi_row_parameters",
")",
":",
"self",
".",
"_multi_row_parameters",
"=",
"multi_row_parameters",
"self",
".",
"_num_rows",
"=",
"len",
"(",
"multi_row_parameters",
")",
"self",
".",
"_iter_row_count",
"=",
"0",
"r... | 60 | 25 |
def cli(wio, send):
'''
Sends a UDP command to the wio device.
\b
DOES:
Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0"
"APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n",
Note:
1. Ensure your device is Configure Mode.
... | [
"def",
"cli",
"(",
"wio",
",",
"send",
")",
":",
"command",
"=",
"send",
"click",
".",
"echo",
"(",
"\"UDP command: {}\"",
".",
"format",
"(",
"command",
")",
")",
"result",
"=",
"udp",
".",
"common_send",
"(",
"command",
")",
"if",
"result",
"is",
"... | 27.173913 | 23.782609 |
def _options_browser(cfg, ret_config, defaults, virtualname, options):
"""
Iterator generating all duples ```option name -> value```
@see :func:`get_returner_options`
"""
for option in options:
# default place for the option in the config
value = _fetch_option(cfg, ret_config, vir... | [
"def",
"_options_browser",
"(",
"cfg",
",",
"ret_config",
",",
"defaults",
",",
"virtualname",
",",
"options",
")",
":",
"for",
"option",
"in",
"options",
":",
"# default place for the option in the config",
"value",
"=",
"_fetch_option",
"(",
"cfg",
",",
"ret_con... | 28.72 | 21.36 |
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = [('time', pymongo.DESCENDING)]
recs = self.db.pastes.find(query).sort(order).limit(1)
try:
return next(recs)['uid']
e... | [
"def",
"lookup",
"(",
"self",
",",
"nick",
")",
":",
"query",
"=",
"dict",
"(",
"nick",
"=",
"nick",
")",
"order",
"=",
"[",
"(",
"'time'",
",",
"pymongo",
".",
"DESCENDING",
")",
"]",
"recs",
"=",
"self",
".",
"db",
".",
"pastes",
".",
"find",
... | 34.8 | 12.1 |
def ignore_import_warnings_for_related_fields(orig_method, self, node):
"""
Replaces the leave_module method on the VariablesChecker class to
prevent unused-import warnings which are caused by the ForeignKey
and OneToOneField transformations. By replacing the nodes in the
AST with their type rather ... | [
"def",
"ignore_import_warnings_for_related_fields",
"(",
"orig_method",
",",
"self",
",",
"node",
")",
":",
"consumer",
"=",
"self",
".",
"_to_consume",
"[",
"0",
"]",
"# pylint: disable=W0212",
"# we can disable this warning ('Access to a protected member _to_consume of a clie... | 46.666667 | 27.481481 |
def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... | [
"def",
"pulse_train",
"(",
"time",
",",
"start",
",",
"duration",
",",
"repeat_time",
",",
"end",
")",
":",
"t",
"=",
"time",
"(",
")",
"if",
"start",
"<=",
"t",
"<",
"end",
":",
"return",
"1",
"if",
"(",
"t",
"-",
"start",
")",
"%",
"repeat_time... | 37 | 22.583333 |
def get_storage_info(self, human=False):
"""
Get storage info
:param bool human: whether return human-readable size
:return: total and used storage
:rtype: dict
"""
res = self._req_get_storage_info()
if human:
res['total'] = humanize.naturals... | [
"def",
"get_storage_info",
"(",
"self",
",",
"human",
"=",
"False",
")",
":",
"res",
"=",
"self",
".",
"_req_get_storage_info",
"(",
")",
"if",
"human",
":",
"res",
"[",
"'total'",
"]",
"=",
"humanize",
".",
"naturalsize",
"(",
"res",
"[",
"'total'",
"... | 30.642857 | 17.928571 |
def delete_view(self, query_criteria=None, uid='_all_users'):
'''
a method to delete a view associated with a user design doc
:param query_criteria: [optional] dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to up... | [
"def",
"delete_view",
"(",
"self",
",",
"query_criteria",
"=",
"None",
",",
"uid",
"=",
"'_all_users'",
")",
":",
"# https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/query/delete__db___design__ddoc_",
"title",
"=",
"'%s.del... | 40.94382 | 26.247191 |
def calc_frip(self, input_bam, input_bed, threads=4):
"""
Calculate fraction of reads in peaks.
A file of with a pool of sequencing reads and a file with peak call
regions define the operation that will be performed. Thread count
for samtools can be specified as well.
:... | [
"def",
"calc_frip",
"(",
"self",
",",
"input_bam",
",",
"input_bed",
",",
"threads",
"=",
"4",
")",
":",
"cmd",
"=",
"self",
".",
"simple_frip",
"(",
"input_bam",
",",
"input_bed",
",",
"threads",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"c... | 46 | 20.533333 |
def is_new_namespace_preorder( self, namespace_id_hash, lastblock=None ):
"""
Given a namespace preorder hash, determine whether or not is is unseen before.
"""
if lastblock is None:
lastblock = self.lastblock
preorder = namedb_get_namespace_preorder( self.db, names... | [
"def",
"is_new_namespace_preorder",
"(",
"self",
",",
"namespace_id_hash",
",",
"lastblock",
"=",
"None",
")",
":",
"if",
"lastblock",
"is",
"None",
":",
"lastblock",
"=",
"self",
".",
"lastblock",
"preorder",
"=",
"namedb_get_namespace_preorder",
"(",
"self",
"... | 35.916667 | 20.583333 |
def _items(self):
"""Extract a list of (key, value) pairs, suitable for our __init__."""
for name in self.declarations:
yield name, self.declarations[name]
for subkey, value in self.contexts[name].items():
yield self.join(name, subkey), value | [
"def",
"_items",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"declarations",
":",
"yield",
"name",
",",
"self",
".",
"declarations",
"[",
"name",
"]",
"for",
"subkey",
",",
"value",
"in",
"self",
".",
"contexts",
"[",
"name",
"]",
".",
... | 48.833333 | 10.833333 |
def syslog(server, enable=True, host=None,
admin_username=None, admin_password=None, module=None):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed b... | [
"def",
"syslog",
"(",
"server",
",",
"enable",
"=",
"True",
",",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"if",
"enable",
"and",
"__execute_cmd",
"(",
"'config -g c... | 43.6875 | 20.75 |
def profile_detail(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String represe... | [
"def",
"profile_detail",
"(",
"request",
",",
"username",
",",
"template_name",
"=",
"userena_settings",
".",
"USERENA_PROFILE_DETAIL_TEMPLATE",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"get_object_or_404",
"(",
"get_user_... | 35.375 | 21.9375 |
def from_string(string):
"""Return the mnemonic represented by the given string.
"""
mnemonics = {
# Arithmetic Instructions
"add": ReilMnemonic.ADD,
"sub": ReilMnemonic.SUB,
"mul": ReilMnemonic.MUL,
"div": ReilMnemonic.DIV,
... | [
"def",
"from_string",
"(",
"string",
")",
":",
"mnemonics",
"=",
"{",
"# Arithmetic Instructions",
"\"add\"",
":",
"ReilMnemonic",
".",
"ADD",
",",
"\"sub\"",
":",
"ReilMnemonic",
".",
"SUB",
",",
"\"mul\"",
":",
"ReilMnemonic",
".",
"MUL",
",",
"\"div\"",
"... | 29.435897 | 10.410256 |
def sweepCrossValidation(self):
"""
sweepCrossValidation() will go through each of the crossvalidation input/targets.
The crossValidationCorpus is a list of dictionaries of input/targets
referenced by layername.
Example: ({"input": [0.0, 0.1], "output": [1.0]}, {"input": [0.5, 0.... | [
"def",
"sweepCrossValidation",
"(",
"self",
")",
":",
"# get learning value and then turn it off",
"oldLearning",
"=",
"self",
".",
"learning",
"self",
".",
"learning",
"=",
"0",
"tssError",
"=",
"0.0",
"totalCorrect",
"=",
"0",
"totalCount",
"=",
"0",
"totalPCorr... | 47.736842 | 16.578947 |
def spanning_2d_grid(length):
"""
Generate a square lattice with auxiliary nodes for spanning detection
Parameters
----------
length : int
Number of nodes in one dimension, excluding the auxiliary nodes.
Returns
-------
networkx.Graph
A square lattice graph with auxilia... | [
"def",
"spanning_2d_grid",
"(",
"length",
")",
":",
"ret",
"=",
"nx",
".",
"grid_2d_graph",
"(",
"length",
"+",
"2",
",",
"length",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"# side 0",
"ret",
".",
"node",
"[",
"(",
"0",
",",
"i",
... | 20.571429 | 24.685714 |
def _weight_by_hue(self):
"""
Returns a list of (hue, ranges, total weight, normalized total weight)-tuples.
ColorTheme is made up out of (color, range, weight) tuples.
For consistency with XML-output in the old Prism format
(i.e. <color>s made up of <shade>s) we need a group
... | [
"def",
"_weight_by_hue",
"(",
"self",
")",
":",
"grouped",
"=",
"{",
"}",
"weights",
"=",
"[",
"]",
"for",
"clr",
",",
"rng",
",",
"weight",
"in",
"self",
".",
"ranges",
":",
"h",
"=",
"clr",
".",
"nearest_hue",
"(",
"primary",
"=",
"False",
")",
... | 39.606061 | 19.787879 |
def run(self):
"""Run find_route_functions_taint_args on each CFG."""
function_cfgs = list()
for _ in self.cfg_list:
function_cfgs.extend(self.find_route_functions_taint_args())
self.cfg_list.extend(function_cfgs) | [
"def",
"run",
"(",
"self",
")",
":",
"function_cfgs",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"self",
".",
"cfg_list",
":",
"function_cfgs",
".",
"extend",
"(",
"self",
".",
"find_route_functions_taint_args",
"(",
")",
")",
"self",
".",
"cfg_list",
".",... | 42 | 13.333333 |
def list(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''):
'''
a method to list keys in the collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value results must not contain (after prefix)
... | [
"def",
"list",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"''",
",",
"filter_function",
"=",
"None",
",",
"max_results",
"=",
"1",
",",
"previous_key",
"=",
"''",
")",
":",
"title",
"=",
"'%s.list'",
"%",
"self",
".",
"__class__",
... | 41.848739 | 22.436975 |
def read_dependencies(filename):
"""Read in the dependencies from the virtualenv requirements file.
"""
dependencies = []
filepath = os.path.join('requirements', filename)
with open(filepath, 'r') as stream:
for line in stream:
package = line.strip().split('#')[0].strip()
... | [
"def",
"read_dependencies",
"(",
"filename",
")",
":",
"dependencies",
"=",
"[",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'requirements'",
",",
"filename",
")",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"stream",
":",
"... | 35.75 | 12.333333 |
def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 = np.log(1-z**2)
a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
b = 2/(np.pi * a) + ln1z2/2
inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
return ... | [
"def",
"inv_std_norm_cdf",
"(",
"x",
")",
":",
"z",
"=",
"2",
"*",
"x",
"-",
"1",
"ln1z2",
"=",
"np",
".",
"log",
"(",
"1",
"-",
"z",
"**",
"2",
")",
"a",
"=",
"8",
"*",
"(",
"np",
".",
"pi",
"-",
"3",
")",
"/",
"(",
"3",
"*",
"np",
"... | 30 | 10.909091 |
def get_font_glyph_data(font):
"""Return information for each glyph in a font"""
from fontbakery.constants import (PlatformID,
WindowsEncodingID)
font_data = []
try:
subtable = font['cmap'].getcmap(PlatformID.WINDOWS,
... | [
"def",
"get_font_glyph_data",
"(",
"font",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"(",
"PlatformID",
",",
"WindowsEncodingID",
")",
"font_data",
"=",
"[",
"]",
"try",
":",
"subtable",
"=",
"font",
"[",
"'cmap'",
"]",
".",
"getcmap",
"(... | 33.2 | 17.366667 |
async def install_mediaroom_protocol(responses_callback, box_ip=None):
"""Install an asyncio protocol to process NOTIFY messages."""
from . import version
_LOGGER.debug(version)
loop = asyncio.get_event_loop()
mediaroom_protocol = MediaroomProtocol(responses_callback, box_ip)
sock = create_so... | [
"async",
"def",
"install_mediaroom_protocol",
"(",
"responses_callback",
",",
"box_ip",
"=",
"None",
")",
":",
"from",
".",
"import",
"version",
"_LOGGER",
".",
"debug",
"(",
"version",
")",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"mediaroom_p... | 30.285714 | 25.5 |
def add_object(self, object):
"""Add object to db session. Only for session-centric object-database mappers."""
if object.id is None:
object.get_id()
self.db.engine.save(object) | [
"def",
"add_object",
"(",
"self",
",",
"object",
")",
":",
"if",
"object",
".",
"id",
"is",
"None",
":",
"object",
".",
"get_id",
"(",
")",
"self",
".",
"db",
".",
"engine",
".",
"save",
"(",
"object",
")"
] | 41.8 | 8 |
def dist_abs(self, src, tar):
"""Return the bag distance between two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
int
Bag distance
... | [
"def",
"dist_abs",
"(",
"self",
",",
"src",
",",
"tar",
")",
":",
"if",
"tar",
"==",
"src",
":",
"return",
"0",
"elif",
"not",
"src",
":",
"return",
"len",
"(",
"tar",
")",
"elif",
"not",
"tar",
":",
"return",
"len",
"(",
"src",
")",
"src_bag",
... | 22.111111 | 19 |
def convert_type(d, intype, outtype, convert_list=True, in_place=True):
""" convert all values of one type to another
Parameters
----------
d : dict
intype : type_class
outtype : type_class
convert_list : bool
whether to convert instances inside lists and tuples
in_place : bool
... | [
"def",
"convert_type",
"(",
"d",
",",
"intype",
",",
"outtype",
",",
"convert_list",
"=",
"True",
",",
"in_place",
"=",
"True",
")",
":",
"if",
"not",
"in_place",
":",
"out_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"else",
":",
"out_dict",
... | 24.068493 | 19.054795 |
def plot(self, title='TimeMoc', view=(None, None)):
"""
Plot the TimeMoc in a time window.
This method uses interactive matplotlib. The user can move its mouse through the plot to see the
time (at the mouse position).
Parameters
----------
title : str, optional
... | [
"def",
"plot",
"(",
"self",
",",
"title",
"=",
"'TimeMoc'",
",",
"view",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"from",
"matplotlib",
".",
"colors",
"import",
"LinearSegmentedColormap",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"if",
"se... | 33.571429 | 24.5 |
def from_custom_template(cls, searchpath, name):
"""
Factory function for creating a subclass of ``Styler``
with a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates
... | [
"def",
"from_custom_template",
"(",
"cls",
",",
"searchpath",
",",
"name",
")",
":",
"loader",
"=",
"ChoiceLoader",
"(",
"[",
"FileSystemLoader",
"(",
"searchpath",
")",
",",
"cls",
".",
"loader",
",",
"]",
")",
"class",
"MyStyler",
"(",
"cls",
")",
":",... | 29 | 18.703704 |
def _extents(self):
"""A (left, top, width, height) tuple describing range extents.
Note this is normalized to accommodate the various orderings of the
corner cells provided on construction, which may be in any of four
configurations such as (top-left, bottom-right),
(bottom-lef... | [
"def",
"_extents",
"(",
"self",
")",
":",
"def",
"start_and_size",
"(",
"idx",
",",
"other_idx",
")",
":",
"\"\"\"Return beginning and length of range based on two indexes.\"\"\"",
"return",
"min",
"(",
"idx",
",",
"other_idx",
")",
",",
"abs",
"(",
"idx",
"-",
... | 41.388889 | 19.722222 |
def get_root_path(obj):
"""
Get file path for object and returns its dirname
"""
try:
filename = os.path.abspath(obj.__globals__['__file__'])
except (KeyError, AttributeError):
if getattr(obj, '__wrapped__', None):
# decorator package has been used in view
ret... | [
"def",
"get_root_path",
"(",
"obj",
")",
":",
"try",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"obj",
".",
"__globals__",
"[",
"'__file__'",
"]",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"if",
"getattr",
"(",... | 35 | 9.833333 |
def rename(self, node):
"""
Translate a rename node into SQLQuery.
:param node: a treebrd node
:return: a SQLQuery object for the tree rooted at node
"""
child_object = self.translate(node.child)
from_block = '({child}) AS {name}({attributes})'.format(
... | [
"def",
"rename",
"(",
"self",
",",
"node",
")",
":",
"child_object",
"=",
"self",
".",
"translate",
"(",
"node",
".",
"child",
")",
"from_block",
"=",
"'({child}) AS {name}({attributes})'",
".",
"format",
"(",
"child",
"=",
"child_object",
".",
"to_sql",
"("... | 43.909091 | 13.181818 |
def get_collection(self, url):
""" Pages through an object collection from the bitbucket API.
Returns an iterator that lazily goes through all the 'values'
of all the pages in the collection. """
url = self.BASE_API2 + url
while url is not None:
response = self.get_da... | [
"def",
"get_collection",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"BASE_API2",
"+",
"url",
"while",
"url",
"is",
"not",
"None",
":",
"response",
"=",
"self",
".",
"get_data",
"(",
"url",
")",
"for",
"value",
"in",
"response",
"[",
... | 43.6 | 7.7 |
def _TypecheckDecorator(subject=None, **kwargs):
"""Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator.
"""
if subject is None:
return _TypecheckDecoratorFactory(kwargs)
elif inspect.... | [
"def",
"_TypecheckDecorator",
"(",
"subject",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"subject",
"is",
"None",
":",
"return",
"_TypecheckDecoratorFactory",
"(",
"kwargs",
")",
"elif",
"inspect",
".",
"isfunction",
"(",
"subject",
")",
"or",
"... | 36.666667 | 16.666667 |
def predict(self, dataset, output_type='cluster_id', verbose=True):
"""
Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : S... | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"'cluster_id'",
",",
"verbose",
"=",
"True",
")",
":",
"## Validate the input dataset.",
"_tkutl",
".",
"_raise_error_if_not_sframe",
"(",
"dataset",
",",
"\"dataset\"",
")",
"_tkutl",
".",
... | 38.0375 | 23.5875 |
def clear(self):
"""Clear current state."""
# Adapted from http://stackoverflow.com/a/13103617/1198772
for i in reversed(list(range(self.extra_keywords_layout.count()))):
self.extra_keywords_layout.itemAt(i).widget().setParent(None)
self.widgets_dict = OrderedDict() | [
"def",
"clear",
"(",
"self",
")",
":",
"# Adapted from http://stackoverflow.com/a/13103617/1198772",
"for",
"i",
"in",
"reversed",
"(",
"list",
"(",
"range",
"(",
"self",
".",
"extra_keywords_layout",
".",
"count",
"(",
")",
")",
")",
")",
":",
"self",
".",
... | 50.833333 | 19.833333 |
def _override_runner(runner):
"""
Context manager that monkey patches `bonobo.run` function with our current command logic.
:param runner: the callable that will handle the `run()` logic.
"""
import bonobo
_get_argument_parser = bonobo.util.environ.get_argument_parser
_run = bonobo.run
... | [
"def",
"_override_runner",
"(",
"runner",
")",
":",
"import",
"bonobo",
"_get_argument_parser",
"=",
"bonobo",
".",
"util",
".",
"environ",
".",
"get_argument_parser",
"_run",
"=",
"bonobo",
".",
"run",
"try",
":",
"# Original get_argument_parser would create or updat... | 37 | 26.916667 |
def post(self, request, bot_id, format=None):
"""
Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
return super(S... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"StateList",
",",
"self",
")",
".",
"post",
"(",
"request",
",",
"bot_id",
",",
"format",
")"
] | 29.5 | 11 |
def redispatch(obj, device_type, session_prep=True):
"""Dynamically change Netmiko object's class to proper class.
Generally used with terminal_server device_type when you need to redispatch after interacting
with terminal server.
"""
new_class = ssh_dispatcher(device_type)
obj.device_type = de... | [
"def",
"redispatch",
"(",
"obj",
",",
"device_type",
",",
"session_prep",
"=",
"True",
")",
":",
"new_class",
"=",
"ssh_dispatcher",
"(",
"device_type",
")",
"obj",
".",
"device_type",
"=",
"device_type",
"obj",
".",
"__class__",
"=",
"new_class",
"if",
"ses... | 37.181818 | 15.181818 |
def INIT(self):
"""INIT state.
[:rfc:`2131#section-4.4.1`]::
The client SHOULD wait a random time between one and ten
seconds to desynchronize the use of DHCP at startup
.. todo::
- The initial delay is implemented, but probably is not in other
... | [
"def",
"INIT",
"(",
"self",
")",
":",
"# NOTE: in case INIT is reached from other state, initialize attributes",
"# reset all variables.",
"logger",
".",
"debug",
"(",
"'In state: INIT'",
")",
"if",
"self",
".",
"current_state",
"is",
"not",
"STATE_PREINIT",
":",
"self",
... | 39.939394 | 17.121212 |
def update(self, data):
"""Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(ami)` on the object.
Args:
d... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"updated",
"=",
"self",
".",
"set_property",
"(",
"'description'",
",",
"data",
".",
"description",
")",
"updated",
"|=",
"self",
".",
"set_property",
"(",
"'state'",
",",
"data",
".",
"state",
")",
... | 36.888889 | 20.962963 |
def get_gene_leaves(graph) -> Iterable[BaseEntity]:
"""Iterate over all genes who have only one connection, that's a transcription to its RNA.
:param pybel.BELGraph graph: A BEL graph
"""
for node in get_nodes_by_function(graph, GENE):
if graph.in_degree(node) != 0:
continue
... | [
"def",
"get_gene_leaves",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"BaseEntity",
"]",
":",
"for",
"node",
"in",
"get_nodes_by_function",
"(",
"graph",
",",
"GENE",
")",
":",
"if",
"graph",
".",
"in_degree",
"(",
"node",
")",
"!=",
"0",
":",
"continue",
... | 30.375 | 16.6875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.