text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_metadata(audio_filepaths):
""" Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """
artist, album, has_embedded_album_art = None, None, None
for audio_filepath in audio_filepaths:
try:
mf = mutagen.File(audio_filepath)
except Exception:
continue
i... | [
"def",
"get_metadata",
"(",
"audio_filepaths",
")",
":",
"artist",
",",
"album",
",",
"has_embedded_album_art",
"=",
"None",
",",
"None",
",",
"None",
"for",
"audio_filepath",
"in",
"audio_filepaths",
":",
"try",
":",
"mf",
"=",
"mutagen",
".",
"File",
"(",
... | 28.833333 | 0.015374 |
def order(self, piecewise=False):
"""
Returns the total number of nodes in the :class:`.GraphCollection`\.
"""
if piecewise:
return {k: v.order() for k, v in self.items()}
return self.master_graph.order() | [
"def",
"order",
"(",
"self",
",",
"piecewise",
"=",
"False",
")",
":",
"if",
"piecewise",
":",
"return",
"{",
"k",
":",
"v",
".",
"order",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"}",
"return",
"self",
".",
"master... | 35.714286 | 0.011719 |
def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD):
"""
Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framera... | [
"def",
"generate_wave",
"(",
"message",
",",
"wpm",
"=",
"WPM",
",",
"framerate",
"=",
"FRAMERATE",
",",
"skip_frame",
"=",
"0",
",",
"amplitude",
"=",
"AMPLITUDE",
",",
"frequency",
"=",
"FREQUENCY",
",",
"word_ref",
"=",
"WORD",
")",
":",
"lst_bin",
"=... | 35.851852 | 0.006036 |
def rotate(self, theta, around):
"""Rotate Compound around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The vector about which to rotate the Co... | [
"def",
"rotate",
"(",
"self",
",",
"theta",
",",
"around",
")",
":",
"new_positions",
"=",
"_rotate",
"(",
"self",
".",
"xyz_with_ports",
",",
"theta",
",",
"around",
")",
"self",
".",
"xyz_with_ports",
"=",
"new_positions"
] | 33.846154 | 0.004425 |
def get_document_value(document, key):
'''
Returns the display value of a field for a particular MongoDB document.
'''
value = getattr(document, key)
if isinstance(value, ObjectId):
return value
if isinstance(document._fields.get(key), URLField):
return mark_safe("""<a href="{0}... | [
"def",
"get_document_value",
"(",
"document",
",",
"key",
")",
":",
"value",
"=",
"getattr",
"(",
"document",
",",
"key",
")",
"if",
"isinstance",
"(",
"value",
",",
"ObjectId",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"document",
".",
"_fie... | 34.809524 | 0.001332 |
def process(self, raster):
""" Applies the morphological operation to the mask object
"""
dim = len(raster.shape)
if dim == 3:
for dim in range(raster.shape[2]):
raster[:, :, dim] = self.morph_operation(raster[:, :, dim], self.struct_elem)
elif ... | [
"def",
"process",
"(",
"self",
",",
"raster",
")",
":",
"dim",
"=",
"len",
"(",
"raster",
".",
"shape",
")",
"if",
"dim",
"==",
"3",
":",
"for",
"dim",
"in",
"range",
"(",
"raster",
".",
"shape",
"[",
"2",
"]",
")",
":",
"raster",
"[",
":",
"... | 45.071429 | 0.007764 |
def cooked(self, raw_args):
"""Return interpreted / typed list of args."""
args = []
for arg in raw_args:
# TODO: use the xmlrpc-c type indicators instead / additionally
if arg and arg[0] in "+-":
try:
arg = int(arg, 10)
... | [
"def",
"cooked",
"(",
"self",
",",
"raw_args",
")",
":",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"raw_args",
":",
"# TODO: use the xmlrpc-c type indicators instead / additionally",
"if",
"arg",
"and",
"arg",
"[",
"0",
"]",
"in",
"\"+-\"",
":",
"try",
":",... | 38.478261 | 0.002205 |
def get_datacenter(self, datacenter_id, depth=1):
"""
Retrieves a data center by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
... | [
"def",
"get_datacenter",
"(",
"self",
",",
"datacenter_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s?depth=%s'",
"%",
"(",
"datacenter_id",
",",
"str",
"(",
"depth",
")",
")",
")",
"return",
... | 29.866667 | 0.004329 |
def register_target(self, target: Target):
"""Register a `target` instance in this build context.
A registered target is saved in the `targets` map and in the
`targets_by_module` map, but is not added to the target graph until
target extraction is completed (thread safety considerations... | [
"def",
"register_target",
"(",
"self",
",",
"target",
":",
"Target",
")",
":",
"if",
"target",
".",
"name",
"in",
"self",
".",
"targets",
":",
"first",
"=",
"self",
".",
"targets",
"[",
"target",
".",
"name",
"]",
"raise",
"NameError",
"(",
"'Target wi... | 49.222222 | 0.002215 |
def prt_qualifiers(self, prt=sys.stdout):
"""Print Qualifiers: 1,462 colocalizes_with; 1,454 contributes_to; 1,157 not"""
# 13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
# 4 not contributes_to (TBD: CHK - Seen in gene2go, but not gafs)
self._prt_qualifiers(sel... | [
"def",
"prt_qualifiers",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"# 13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)",
"# 4 not contributes_to (TBD: CHK - Seen in gene2go, but not gafs)",
"self",
".",
"_prt_qualifiers",
"(",
"self",
... | 67.2 | 0.008824 |
def authorize(self, authentication_request, # type: oic.oic.message.AuthorizationRequest
user_id, # type: str
extra_id_token_claims=None
# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]]
... | [
"def",
"authorize",
"(",
"self",
",",
"authentication_request",
",",
"# type: oic.oic.message.AuthorizationRequest",
"user_id",
",",
"# type: str",
"extra_id_token_claims",
"=",
"None",
"# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[s... | 55.016949 | 0.007869 |
def _register_servicer(self, servicer):
"""register serviser
:param servicer: servicer
"""
name = servicer.__name__
if name in self._servicers:
raise exceptions.ConfigException(
'servicer duplicated: {}'.format(name))
add_func = self._get_serv... | [
"def",
"_register_servicer",
"(",
"self",
",",
"servicer",
")",
":",
"name",
"=",
"servicer",
".",
"__name__",
"if",
"name",
"in",
"self",
".",
"_servicers",
":",
"raise",
"exceptions",
".",
"ConfigException",
"(",
"'servicer duplicated: {}'",
".",
"format",
"... | 35.090909 | 0.005051 |
def get_subject(self, data):
""" Try to get a unique ID from the object. By default, this will be
the 'id' field of any given object, or a field specified by the
'rdfSubject' property. If no other option is available, a UUID will be
generated. """
if not isinstance(data, Mapping)... | [
"def",
"get_subject",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Mapping",
")",
":",
"return",
"None",
"if",
"data",
".",
"get",
"(",
"self",
".",
"subject",
")",
":",
"return",
"data",
".",
"get",
"(",
"self"... | 44.5 | 0.004405 |
def should_update(self, requirement, requirement_file):
"""
Determines if a requirement can be updated
:param requirement: Requirement
:param requirement_file: RequirementFile
:return: bool
"""
path = requirement_file.path
if self.config.can_update_all(pat... | [
"def",
"should_update",
"(",
"self",
",",
"requirement",
",",
"requirement_file",
")",
":",
"path",
"=",
"requirement_file",
".",
"path",
"if",
"self",
".",
"config",
".",
"can_update_all",
"(",
"path",
")",
"or",
"(",
"self",
".",
"config",
".",
"can_upda... | 39.733333 | 0.004918 |
def delay_response(delay):
"""Returns a delayed response (max of 10 seconds).
---
tags:
- Dynamic data
parameters:
- in: path
name: delay
type: int
produces:
- application/json
responses:
200:
description: A delayed response.
"""
delay = mi... | [
"def",
"delay_response",
"(",
"delay",
")",
":",
"delay",
"=",
"min",
"(",
"float",
"(",
"delay",
")",
",",
"10",
")",
"time",
".",
"sleep",
"(",
"delay",
")",
"return",
"jsonify",
"(",
"get_dict",
"(",
"\"url\"",
",",
"\"args\"",
",",
"\"form\"",
",... | 20.272727 | 0.002141 |
async def start(self):
"""Starts receiving messages on the underlying socket and passes them
to the message router.
"""
self._is_running = True
while self._is_running:
try:
zmq_msg = await self._socket.recv_multipart()
message = Messa... | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_is_running",
"=",
"True",
"while",
"self",
".",
"_is_running",
":",
"try",
":",
"zmq_msg",
"=",
"await",
"self",
".",
"_socket",
".",
"recv_multipart",
"(",
")",
"message",
"=",
"Message",
... | 34.047619 | 0.002721 |
def stats_totals(self, kind='R', summary=False):
"""Returns a DataFrame of total box score statistics by season."""
return self._get_stats_table('totals', kind=kind, summary=summary) | [
"def",
"stats_totals",
"(",
"self",
",",
"kind",
"=",
"'R'",
",",
"summary",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_stats_table",
"(",
"'totals'",
",",
"kind",
"=",
"kind",
",",
"summary",
"=",
"summary",
")"
] | 65.333333 | 0.010101 |
def delete_row_range(self, format_str, start_game, end_game):
"""Delete rows related to the given game range.
Args:
format_str: a string to `.format()` by the game numbers
in order to create the row prefixes.
start_game: the starting game number of the deletion.
... | [
"def",
"delete_row_range",
"(",
"self",
",",
"format_str",
",",
"start_game",
",",
"end_game",
")",
":",
"row_keys",
"=",
"make_single_array",
"(",
"self",
".",
"tf_table",
".",
"keys_by_range_dataset",
"(",
"format_str",
".",
"format",
"(",
"start_game",
")",
... | 45.023256 | 0.001011 |
def read_input_registers(slave_id, starting_address, quantity):
""" Return ADU for Modbus function code 04: Read Input Registers.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = ReadInputRegisters()
function.starting_address = starting_address
function.quantit... | [
"def",
"read_input_registers",
"(",
"slave_id",
",",
"starting_address",
",",
"quantity",
")",
":",
"function",
"=",
"ReadInputRegisters",
"(",
")",
"function",
".",
"starting_address",
"=",
"starting_address",
"function",
".",
"quantity",
"=",
"quantity",
"return",... | 35.090909 | 0.002525 |
def measure_states(states, measurement_matrix, measurement_covariance):
"""
Measure a list of states with a measurement matrix in the presence of
measurement noise.
Args:
states (array): states to measure. Shape is NxSTATE_DIM.
measurement_matrix (array): Each state in *states* is measu... | [
"def",
"measure_states",
"(",
"states",
",",
"measurement_matrix",
",",
"measurement_covariance",
")",
":",
"# Sanitise input",
"measurement_matrix",
"=",
"np",
".",
"atleast_2d",
"(",
"measurement_matrix",
")",
"measurement_covariance",
"=",
"np",
".",
"atleast_2d",
... | 39.157895 | 0.002623 |
def retry(self, func, partition_id, retry_message, final_failure_message, max_retries, host_id):
"""
Make attempt_renew_lease async call sync.
"""
loop = asyncio.new_event_loop()
loop.run_until_complete(self.retry_async(func, partition_id, retry_message,
... | [
"def",
"retry",
"(",
"self",
",",
"func",
",",
"partition_id",
",",
"retry_message",
",",
"final_failure_message",
",",
"max_retries",
",",
"host_id",
")",
":",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"loop",
".",
"run_until_complete",
"(",
... | 54.714286 | 0.012853 |
def _setup_tunnel(
self,
tunnelParameters):
"""
*setup a ssh tunnel for a database connection to port through*
**Key Arguments:**
- ``tunnelParameters`` -- the tunnel parameters found associated with the database settings
**Return:**
- ``... | [
"def",
"_setup_tunnel",
"(",
"self",
",",
"tunnelParameters",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_setup_tunnel`` method'",
")",
"# TEST TUNNEL DOES NOT ALREADY EXIST",
"sshPort",
"=",
"tunnelParameters",
"[",
"\"port\"",
"]",
"connected",
... | 36.87037 | 0.001957 |
def get_tasks(self):
"""Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict
"""
tasks = collect... | [
"def",
"get_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"dep",
"in",
"self",
".",
"ordered_dependencies",
":",
"tasks",
"[",
"dep",
".",
"name",
"]",
"=",
"dep",
".",
"task",
"return",
"tasks"
] | 36.5 | 0.008909 |
def import_(self, conn):
"""Do the actual import. Copy data and store in connection object.
This function:
- Creates the tables
- Imports data (using self.gen_rows)
- Run any post_import hooks.
- Creates any indexs
- Does *not* run self.make_views - those must be... | [
"def",
"import_",
"(",
"self",
",",
"conn",
")",
":",
"if",
"self",
".",
"print_progress",
":",
"print",
"(",
"'Beginning'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# what is this mystical self._conn ?",
"self",
".",
"_conn",
"=",
"conn",
"self... | 38.892857 | 0.002688 |
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"):
"Cargo el formato de campos a generar desde una planilla CSV"
# si no encuentro archivo, lo busco en el directorio predeterminado:
if not os.path.exists(archivo):
archivo = os.path.join(self.InstallDir, "planti... | [
"def",
"CargarFormatoPDF",
"(",
"self",
",",
"archivo",
"=",
"\"liquidacion_form_c1116b_wslpg.csv\"",
")",
":",
"# si no encuentro archivo, lo busco en el directorio predeterminado:",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archivo",
")",
":",
"archivo",
"=... | 38.76087 | 0.013676 |
def propinquity_fn_to_study_tree(inp_fn, strip_extension=True):
"""This should only be called by propinquity - other code should be treating theses
filenames (and the keys that are based on them) as opaque strings.
Takes a filename (or key if strip_extension is False), returns (study_id, tree_id)
prop... | [
"def",
"propinquity_fn_to_study_tree",
"(",
"inp_fn",
",",
"strip_extension",
"=",
"True",
")",
":",
"if",
"strip_extension",
":",
"study_tree",
"=",
"'.'",
".",
"join",
"(",
"inp_fn",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"# strip... | 42.157895 | 0.006105 |
def _add_singles_to_buffer(self, results, ifos):
"""Add single detector triggers to the internal buffer
Parameters
----------
results: dict of arrays
Dictionary of dictionaries indexed by ifo and keys such as 'snr',
'chisq', etc. The specific format it determined... | [
"def",
"_add_singles_to_buffer",
"(",
"self",
",",
"results",
",",
"ifos",
")",
":",
"if",
"len",
"(",
"self",
".",
"singles",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"self",
".",
"set_singles_buffer",
"(",
"results",
")",
"# convert to single detector... | 40.511111 | 0.001607 |
def get_parameters(self, grad_only=True):
"""Get parameters.
Args:
grad_only (bool, optional): Return parameters with `need_grad` option as `True`.
If you set this option as `False`, All parameters are returned. Default is `True`.
Returns:
dict: The dictionar... | [
"def",
"get_parameters",
"(",
"self",
",",
"grad_only",
"=",
"True",
")",
":",
"params",
"=",
"OrderedDict",
"(",
")",
"for",
"v",
"in",
"self",
".",
"get_modules",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"tuple",
")",
":",
"continue... | 38.652174 | 0.007684 |
def usn_v4_record(header, record):
"""Extracts USN V4 record information."""
length, major_version, minor_version = header
fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size)
raise NotImplementedError('Not implemented') | [
"def",
"usn_v4_record",
"(",
"header",
",",
"record",
")",
":",
"length",
",",
"major_version",
",",
"minor_version",
"=",
"header",
"fields",
"=",
"V4_RECORD",
".",
"unpack_from",
"(",
"record",
",",
"RECORD_HEADER",
".",
"size",
")",
"raise",
"NotImplemented... | 39.666667 | 0.004115 |
def _get_tagged_content_from_taskpaper_files(
self,
taskpaperFiles,
tagSet,
editorial=False,
workflowTagSet=False,
includeFileTags=True):
"""*get all tasks tagged with a sync-tag from taskpaper files*
**Key Arguments:**
... | [
"def",
"_get_tagged_content_from_taskpaper_files",
"(",
"self",
",",
"taskpaperFiles",
",",
"tagSet",
",",
"editorial",
"=",
"False",
",",
"workflowTagSet",
"=",
"False",
",",
"includeFileTags",
"=",
"True",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'st... | 39.133333 | 0.002077 |
def declare(full_table_name, definition, context):
"""
Parse declaration and create new SQL table accordingly.
:param full_table_name: full name of the table
:param definition: DataJoint table definition
:param context: dictionary of objects that might be referred to in the table.
"""
tabl... | [
"def",
"declare",
"(",
"full_table_name",
",",
"definition",
",",
"context",
")",
":",
"table_name",
"=",
"full_table_name",
".",
"strip",
"(",
"'`'",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"table_name",
")",
">",
"MAX_TAB... | 42.5 | 0.002555 |
def possible_forms(self):
""" Generate a list of possible forms for the current lemma
:returns: List of possible forms for the current lemma
:rtype: [str]
"""
forms = []
for morph in self.modele().morphos():
for desinence in self.modele().desinences(morph):
... | [
"def",
"possible_forms",
"(",
"self",
")",
":",
"forms",
"=",
"[",
"]",
"for",
"morph",
"in",
"self",
".",
"modele",
"(",
")",
".",
"morphos",
"(",
")",
":",
"for",
"desinence",
"in",
"self",
".",
"modele",
"(",
")",
".",
"desinences",
"(",
"morph"... | 39.8125 | 0.003067 |
def populate_link(self, finder, upgrade, require_hashes):
# type: (PackageFinder, bool, bool) -> None
"""Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If requi... | [
"def",
"populate_link",
"(",
"self",
",",
"finder",
",",
"upgrade",
",",
"require_hashes",
")",
":",
"# type: (PackageFinder, bool, bool) -> None",
"if",
"self",
".",
"link",
"is",
"None",
":",
"self",
".",
"link",
"=",
"finder",
".",
"find_requirement",
"(",
... | 50.55 | 0.002913 |
def fit(self, X, y, sample_weight=None, monitor=None):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the bina... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
",",
"monitor",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"X",
",",
"event",
",",
"time",
"=",
"check_array... | 39.740741 | 0.001819 |
def compile_binary(source):
"""
Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s
"""
cmd = 'make sense'
src = '/usr/local/bin/chkrootkit'
dst = '/usr/local/chkrootkit/chkrootkit'
... | [
"def",
"compile_binary",
"(",
"source",
")",
":",
"cmd",
"=",
"'make sense'",
"src",
"=",
"'/usr/local/bin/chkrootkit'",
"dst",
"=",
"'/usr/local/chkrootkit/chkrootkit'",
"# Tar Extraction",
"t",
"=",
"tarfile",
".",
"open",
"(",
"source",
",",
"'r'",
")",
"t",
... | 32.576923 | 0.002294 |
def set_pscale(self):
""" Compute the pixel scale based on active WCS values. """
if self.new:
self.pscale = 1.0
else:
self.pscale = self.compute_pscale(self.cd11,self.cd21) | [
"def",
"set_pscale",
"(",
"self",
")",
":",
"if",
"self",
".",
"new",
":",
"self",
".",
"pscale",
"=",
"1.0",
"else",
":",
"self",
".",
"pscale",
"=",
"self",
".",
"compute_pscale",
"(",
"self",
".",
"cd11",
",",
"self",
".",
"cd21",
")"
] | 36 | 0.013575 |
def get_job_errors(self, job_id):
"""GetJobErrors
https://apidocs.joyent.com/manta/api.html#GetJobErrors
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archi... | [
"def",
"get_job_errors",
"(",
"self",
",",
"job_id",
")",
":",
"try",
":",
"return",
"RawMantaClient",
".",
"get_job_errors",
"(",
"self",
",",
"job_id",
")",
"except",
"errors",
".",
"MantaAPIError",
"as",
"ex",
":",
"if",
"ex",
".",
"res",
".",
"status... | 45.9375 | 0.002667 |
def sometimes(fn):
"""
They've done studies, you know. 50% of the time,
it works every time.
"""
def wrapped(*args, **kwargs):
wrapped.x += 1
if wrapped.x % 2 == 1:
return fn(*args, **kwargs)
wrapped.x = 0
return wrapped | [
"def",
"sometimes",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wrapped",
".",
"x",
"+=",
"1",
"if",
"wrapped",
".",
"x",
"%",
"2",
"==",
"1",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
... | 20.461538 | 0.003597 |
def init(*, output_dir=FS_DEFAULT_OUTPUT_DIR, dry_run=False, **kwargs):
"""
Set up output directory
:param output_dir(str, optional): Output dir for holding temporary files
:param \*\*kwargs: arbitrary keyword arguments
"""
# Output directory
global _output_dir
_output_dir = output_dir
... | [
"def",
"init",
"(",
"*",
",",
"output_dir",
"=",
"FS_DEFAULT_OUTPUT_DIR",
",",
"dry_run",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Output directory",
"global",
"_output_dir",
"_output_dir",
"=",
"output_dir",
"# Dry run mode",
"global",
"_dry_run",
"_... | 31.612903 | 0.00297 |
def get_range_values_per_column(df):
"""
Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three
dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal,
minimal or median value of that column.
If... | [
"def",
"get_range_values_per_column",
"(",
"df",
")",
":",
"data",
"=",
"df",
".",
"get_values",
"(",
")",
"masked",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"data",
")",
"columns",
"=",
"df",
".",
"columns",
"is_col_non_finite",
"=",
"masked",
... | 44.441176 | 0.005181 |
def _get_netengine_arguments(self, required=False):
"""
returns list of available config params
returns list of required config params if required is True
for internal use only
"""
# inspect netengine class
backend_class = self._get_netengine_backend()
arg... | [
"def",
"_get_netengine_arguments",
"(",
"self",
",",
"required",
"=",
"False",
")",
":",
"# inspect netengine class",
"backend_class",
"=",
"self",
".",
"_get_netengine_backend",
"(",
")",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"backend_class",
".",
"_... | 37.2 | 0.003145 |
def _add_replace_pair(self, name, value, quote):
"""
Adds a replace part to the map of replace pairs.
:param name: The name of the replace pair.
:param value: The value of value of the replace pair.
"""
key = '@' + name + '@'
key = key.lower()
class_name... | [
"def",
"_add_replace_pair",
"(",
"self",
",",
"name",
",",
"value",
",",
"quote",
")",
":",
"key",
"=",
"'@'",
"+",
"name",
"+",
"'@'",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"class_name",
"=",
"value",
".",
"__class__",
".",
"__name__",
"if",
... | 32.347826 | 0.003916 |
def is_carrying_vespene(self) -> bool:
""" Checks if a worker is carrying vespene. """
return any(
buff.value in self._proto.buff_ids
for buff in {
BuffId.CARRYHARVESTABLEVESPENEGEYSERGAS,
BuffId.CARRYHARVESTABLEVESPENEGEYSERGASPROTOSS,
... | [
"def",
"is_carrying_vespene",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"buff",
".",
"value",
"in",
"self",
".",
"_proto",
".",
"buff_ids",
"for",
"buff",
"in",
"{",
"BuffId",
".",
"CARRYHARVESTABLEVESPENEGEYSERGAS",
",",
"BuffId",
".",
"C... | 38.4 | 0.005089 |
def mean(series):
"""
Returns the mean of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.mean()
else:
return np.nan | [
"def",
"mean",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"mean",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | 19.083333 | 0.004167 |
def remove(self, id_option_pool):
"""Remove Option pool by identifier and all Environment related .
:param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: Option Pool identifier is null and invalid.
... | [
"def",
"remove",
"(",
"self",
",",
"id_option_pool",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_option_pool",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Option Pool is invalid or was not informed.'",
")",
"url",
"=",
"'api/pools/optio... | 40.857143 | 0.005695 |
def from_session(cls, session):
"""Create a new Nvim instance for a Session instance.
This method must be called to create the first Nvim instance, since it
queries Nvim metadata for type information and sets a SessionHook for
creating specialized objects from Nvim remote handles.
... | [
"def",
"from_session",
"(",
"cls",
",",
"session",
")",
":",
"session",
".",
"error_wrapper",
"=",
"lambda",
"e",
":",
"NvimError",
"(",
"e",
"[",
"1",
"]",
")",
"channel_id",
",",
"metadata",
"=",
"session",
".",
"request",
"(",
"b'vim_get_api_info'",
"... | 39 | 0.002384 |
def color_square(self, x, y, unit_coords=False):
"""
Handles actually coloring the squares
"""
# Calculate column and row number
if unit_coords:
col = x
row = y
else:
col = x//self.col_width
row = y//self.row_height
... | [
"def",
"color_square",
"(",
"self",
",",
"x",
",",
"y",
",",
"unit_coords",
"=",
"False",
")",
":",
"# Calculate column and row number",
"if",
"unit_coords",
":",
"col",
"=",
"x",
"row",
"=",
"y",
"else",
":",
"col",
"=",
"x",
"//",
"self",
".",
"col_w... | 37.148148 | 0.001944 |
def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs):
'''
.. versionadded:: Fluorine
Lists the record sets of a specified type in a DNS zone.
:param zone_name: The name of the DNS zone (without a terminating dot).
:param resource_group... | [
"def",
"record_sets_list_by_type",
"(",
"zone_name",
",",
"resource_group",
",",
"record_type",
",",
"top",
"=",
"None",
",",
"recordsetnamesuffix",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"dnsconn",
"=",
"__utils__",
"[",
... | 33.413043 | 0.002528 |
def get_assignable_log_ids(self, log_id):
"""Gets a list of log including and under the given log node in which any log entry can be assigned.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
return: (osid.id.IdList) - list of assignable log ``Ids``
raise: NullArgument - ``log_id... | [
"def",
"get_assignable_log_ids",
"(",
"self",
",",
"log_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids",
"# This will likely be overridden by an authorization adapter",
"mgr",
"=",
"self",
".",
"_get_provider_manag... | 46.8 | 0.003141 |
def login(self, template='login'):
'''
This property will return component which will handle login requests.
auth.login(template='login.html')
'''
def _login(env, data):
form = self._login_form(env)
next = env.request.GET.get('next', '/')
... | [
"def",
"login",
"(",
"self",
",",
"template",
"=",
"'login'",
")",
":",
"def",
"_login",
"(",
"env",
",",
"data",
")",
":",
"form",
"=",
"self",
".",
"_login_form",
"(",
"env",
")",
"next",
"=",
"env",
".",
"request",
".",
"GET",
".",
"get",
"(",... | 45.565217 | 0.001869 |
async def check_response(response, valid_response_codes):
"""Check the response for correctness."""
if response.status == 204:
return True
if response.status in valid_response_codes:
_js = await response.json()
return _js
else:
raise PvApiResponseStatusError(response.stat... | [
"async",
"def",
"check_response",
"(",
"response",
",",
"valid_response_codes",
")",
":",
"if",
"response",
".",
"status",
"==",
"204",
":",
"return",
"True",
"if",
"response",
".",
"status",
"in",
"valid_response_codes",
":",
"_js",
"=",
"await",
"response",
... | 35 | 0.003096 |
def getobject_use_prevfield(idf, idfobject, fieldname):
"""field=object_name, prev_field=object_type. Return the object"""
if not fieldname.endswith("Name"):
return None
# test if prevfieldname ends with "Object_Type"
fdnames = idfobject.fieldnames
ifieldname = fdnames.index(fieldname)
p... | [
"def",
"getobject_use_prevfield",
"(",
"idf",
",",
"idfobject",
",",
"fieldname",
")",
":",
"if",
"not",
"fieldname",
".",
"endswith",
"(",
"\"Name\"",
")",
":",
"return",
"None",
"# test if prevfieldname ends with \"Object_Type\"",
"fdnames",
"=",
"idfobject",
".",... | 35.823529 | 0.0016 |
async def membership(client: Client, membership_signed_raw: str) -> ClientResponse:
"""
POST a Membership document
:param client: Client to connect to the api
:param membership_signed_raw: Membership signed raw document
:return:
"""
return await client.post(MODULE + '/membership', {'members... | [
"async",
"def",
"membership",
"(",
"client",
":",
"Client",
",",
"membership_signed_raw",
":",
"str",
")",
"->",
"ClientResponse",
":",
"return",
"await",
"client",
".",
"post",
"(",
"MODULE",
"+",
"'/membership'",
",",
"{",
"'membership'",
":",
"membership_si... | 40.555556 | 0.008043 |
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection
Args:
ws: websocket connection (now closed)
"""
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket() | [
"def",
"_ws_on_close",
"(",
"self",
",",
"ws",
":",
"websocket",
".",
"WebSocketApp",
")",
":",
"self",
".",
"connected",
"=",
"False",
"self",
".",
"logger",
".",
"error",
"(",
"'Websocket closed'",
")",
"self",
".",
"_reconnect_websocket",
"(",
")"
] | 32.222222 | 0.006711 |
def index_metrics(
config, start, end, incremental=False, concurrency=5, accounts=None,
period=3600, tag=None, index='policy-metrics', verbose=False):
"""index policy metrics"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logg... | [
"def",
"index_metrics",
"(",
"config",
",",
"start",
",",
"end",
",",
"incremental",
"=",
"False",
",",
"concurrency",
"=",
"5",
",",
"accounts",
"=",
"None",
",",
"period",
"=",
"3600",
",",
"tag",
"=",
"None",
",",
"index",
"=",
"'policy-metrics'",
"... | 39.826667 | 0.00098 |
def __calculate_farthest_distance(self, index_cluster1, index_cluster2):
"""!
@brief Finds two farthest objects in two specified clusters in terms and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
... | [
"def",
"__calculate_farthest_distance",
"(",
"self",
",",
"index_cluster1",
",",
"index_cluster2",
")",
":",
"candidate_maximum_distance",
"=",
"0.0",
"for",
"index_object1",
"in",
"self",
".",
"__clusters",
"[",
"index_cluster1",
"]",
":",
"for",
"index_object2",
"... | 46.157895 | 0.014525 |
def cli(variant_file, vep, split):
"""Parses a vcf file.\n
\n
Usage:\n
parser infile.vcf\n
If pipe:\n
parser -
"""
from datetime import datetime
from pprint import pprint as pp
if variant_file == '-':
my_parser = VCFParser(fsock=sys.stdin, spl... | [
"def",
"cli",
"(",
"variant_file",
",",
"vep",
",",
"split",
")",
":",
"from",
"datetime",
"import",
"datetime",
"from",
"pprint",
"import",
"pprint",
"as",
"pp",
"if",
"variant_file",
"==",
"'-'",
":",
"my_parser",
"=",
"VCFParser",
"(",
"fsock",
"=",
"... | 29.727273 | 0.005926 |
def new_dxfile(mode=None, write_buffer_size=dxfile.DEFAULT_BUFFER_SIZE, expected_file_size=None, file_is_mmapd=False,
**kwargs):
'''
:param mode: One of "w" or "a" for write and append modes, respectively
:type mode: string
:rtype: :class:`~dxpy.bindings.dxfile.DXFile`
Additional opt... | [
"def",
"new_dxfile",
"(",
"mode",
"=",
"None",
",",
"write_buffer_size",
"=",
"dxfile",
".",
"DEFAULT_BUFFER_SIZE",
",",
"expected_file_size",
"=",
"None",
",",
"file_is_mmapd",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"dx_file",
"=",
"DXFile",
"(",
... | 33.310345 | 0.003018 |
def load_tagged_classes(cls, tag, fail_silently=True):
"""
Produce a sequence of all XBlock classes tagged with `tag`.
fail_silently causes the code to simply log warnings if a
plugin cannot import. The goal is to be able to use part of
libraries from an XBlock (and thus have it... | [
"def",
"load_tagged_classes",
"(",
"cls",
",",
"tag",
",",
"fail_silently",
"=",
"True",
")",
":",
"# Allow this method to access the `_class_tags`",
"# pylint: disable=W0212",
"for",
"name",
",",
"class_",
"in",
"cls",
".",
"load_classes",
"(",
"fail_silently",
")",
... | 47.888889 | 0.002275 |
def become(cls, session_token):
"""
通过 session token 获取用户对象
:param session_token: 用户的 session token
:return: leancloud.User
"""
response = client.get('/users/me', params={'session_token': session_token})
content = response.json()
user = cls()
user... | [
"def",
"become",
"(",
"cls",
",",
"session_token",
")",
":",
"response",
"=",
"client",
".",
"get",
"(",
"'/users/me'",
",",
"params",
"=",
"{",
"'session_token'",
":",
"session_token",
"}",
")",
"content",
"=",
"response",
".",
"json",
"(",
")",
"user",... | 31.6 | 0.006148 |
def _prepare_uri(self, path, query_params={}):
"""
Prepares a full URI with the selected information.
``path``:
Path can be in one of two formats:
- If :attr:`server` was defined, the ``path`` will be appended
to the existing host, or
... | [
"def",
"_prepare_uri",
"(",
"self",
",",
"path",
",",
"query_params",
"=",
"{",
"}",
")",
":",
"query_str",
"=",
"urllib",
".",
"urlencode",
"(",
"query_params",
")",
"# If we have a relative path (as opposed to a full URL), build it of",
"# the connection info",
"if",
... | 34.965517 | 0.001919 |
def get_dimension_from_db_by_name(dimension_name):
"""
Gets a dimension from the DB table.
"""
try:
dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one()
return JSONObject(dimension)
except NoResultFound:
raise ResourceNotFoundError("Dimen... | [
"def",
"get_dimension_from_db_by_name",
"(",
"dimension_name",
")",
":",
"try",
":",
"dimension",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dimension",
")",
".",
"filter",
"(",
"Dimension",
".",
"name",
"==",
"dimension_name",
")",
".",
"one",
"(",
... | 38.666667 | 0.011236 |
def _find_countour_yaml(start, checked, names=None):
"""Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of countour.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do... | [
"def",
"_find_countour_yaml",
"(",
"start",
",",
"checked",
",",
"names",
"=",
"None",
")",
":",
"extensions",
"=",
"[",
"]",
"if",
"names",
":",
"for",
"name",
"in",
"names",
":",
"if",
"not",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
... | 28.974359 | 0.000856 |
def unders_to_dashes_in_keys(self) -> None:
"""Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
... | [
"def",
"unders_to_dashes_in_keys",
"(",
"self",
")",
"->",
"None",
":",
"for",
"key_node",
",",
"_",
"in",
"self",
".",
"yaml_node",
".",
"value",
":",
"key_node",
".",
"value",
"=",
"key_node",
".",
"value",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")"... | 45.8 | 0.004283 |
def parse_phones(self):
"""Parse TextGrid phone intervals.
This method parses the phone intervals in a TextGrid to extract each
phone and each phone's start and end times in the audio recording. For
each phone, it instantiates the class Phone(), with the phone and its
st... | [
"def",
"parse_phones",
"(",
"self",
")",
":",
"phones",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"phone_intervals",
":",
"start",
"=",
"float",
"(",
"i",
"[",
"i",
".",
"index",
"(",
"'xmin = '",
")",
"+",
"7",
":",
"i",
".",
"index",
"(",
... | 41.6 | 0.007051 |
def write_payload(payload=None, objectInput=None):
"""
This function writes a base64 payload or file object on disk.
Args:
payload (string): payload in base64
objectInput (object): file object/standard input to analyze
Returns:
Path of file
"""
temp = tempfile.mkstemp(... | [
"def",
"write_payload",
"(",
"payload",
"=",
"None",
",",
"objectInput",
"=",
"None",
")",
":",
"temp",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"[",
"1",
"]",
"log",
".",
"debug",
"(",
"\"Write payload in temp file {!r}\"",
".",
"format",
"(",
"temp",
... | 25.074074 | 0.001422 |
def get_contents_entry(node):
"""Fetch the contents of the entry. Returns the exact binary
contents of the file."""
try:
node = node.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Ent... | [
"def",
"get_contents_entry",
"(",
"node",
")",
":",
"try",
":",
"node",
"=",
"node",
".",
"disambiguate",
"(",
"must_exist",
"=",
"1",
")",
"except",
"SCons",
".",
"Errors",
".",
"UserError",
":",
"# There was nothing on disk with which to disambiguate",
"# this e... | 41.714286 | 0.001675 |
def get_or_add_video_media_part(self, video):
"""Return rIds for media and video relationships to media part.
A new |MediaPart| object is created if it does not already exist
(such as would occur if the same video appeared more than once in
a presentation). Two relationships to the med... | [
"def",
"get_or_add_video_media_part",
"(",
"self",
",",
"video",
")",
":",
"media_part",
"=",
"self",
".",
"_package",
".",
"get_or_add_media_part",
"(",
"video",
")",
"media_rId",
"=",
"self",
".",
"relate_to",
"(",
"media_part",
",",
"RT",
".",
"MEDIA",
")... | 53.357143 | 0.002632 |
def add_transition (self, input_symbol, state, action=None, next_state=None):
'''This adds a transition that associates:
(input_symbol, current_state) --> (action, next_state)
The action may be set to None in which case the process() method will
ignore the action and only set ... | [
"def",
"add_transition",
"(",
"self",
",",
"input_symbol",
",",
"state",
",",
"action",
"=",
"None",
",",
"next_state",
"=",
"None",
")",
":",
"if",
"next_state",
"is",
"None",
":",
"next_state",
"=",
"state",
"self",
".",
"state_transitions",
"[",
"(",
... | 41.0625 | 0.004464 |
def configure(self):
"""
Configure SPI controller with the SPI mode and operating frequency
"""
# Convert standard SPI sheme to USBISS scheme
lookup_table = [0, 2, 1, 3]
mode = lookup_table[self._mode]
# Add signal for SPI switch
iss_mode = self._usbiss.... | [
"def",
"configure",
"(",
"self",
")",
":",
"# Convert standard SPI sheme to USBISS scheme",
"lookup_table",
"=",
"[",
"0",
",",
"2",
",",
"1",
",",
"3",
"]",
"mode",
"=",
"lookup_table",
"[",
"self",
".",
"_mode",
"]",
"# Add signal for SPI switch",
"iss_mode",
... | 29.142857 | 0.004751 |
def apply_effect(layer, image):
"""Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
... | [
"def",
"apply_effect",
"(",
"layer",
",",
"image",
")",
":",
"for",
"effect",
"in",
"layer",
".",
"effects",
":",
"if",
"effect",
".",
"__class__",
".",
"__name__",
"==",
"'PatternOverlay'",
":",
"draw_pattern_fill",
"(",
"image",
",",
"layer",
".",
"_psd"... | 29.724138 | 0.001124 |
def bsp_traverse_pre_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.pre_order` instead.
"""
_bsp_traverse(node.pre_order(), callback, userData) | [
"def",
"bsp_traverse_pre_order",
"(",
"node",
":",
"tcod",
".",
"bsp",
".",
"BSP",
",",
"callback",
":",
"Callable",
"[",
"[",
"tcod",
".",
"bsp",
".",
"BSP",
",",
"Any",
"]",
",",
"None",
"]",
",",
"userData",
":",
"Any",
"=",
"0",
",",
")",
"->... | 28.181818 | 0.003125 |
def to_protobuf(self):
"""Return a protobuf corresponding to the key.
:rtype: :class:`.entity_pb2.Key`
:returns: The protobuf representing the key.
"""
key = _entity_pb2.Key()
key.partition_id.project_id = self.project
if self.namespace:
key.partitio... | [
"def",
"to_protobuf",
"(",
"self",
")",
":",
"key",
"=",
"_entity_pb2",
".",
"Key",
"(",
")",
"key",
".",
"partition_id",
".",
"project_id",
"=",
"self",
".",
"project",
"if",
"self",
".",
"namespace",
":",
"key",
".",
"partition_id",
".",
"namespace_id"... | 29.136364 | 0.003021 |
def goto_time(timeval):
'''Go to a specific time (in nanoseconds) in the current
trajectory.
'''
i = bisect.bisect(viewer.frame_times, timeval * 1000)
goto_frame(i) | [
"def",
"goto_time",
"(",
"timeval",
")",
":",
"i",
"=",
"bisect",
".",
"bisect",
"(",
"viewer",
".",
"frame_times",
",",
"timeval",
"*",
"1000",
")",
"goto_frame",
"(",
"i",
")"
] | 25.571429 | 0.005405 |
def update(domain):
"""
Update language-specific translations files with new keys discovered by
``flask babel extract``.
"""
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'update -i ... | [
"def",
"update",
"(",
"domain",
")",
":",
"translations_dir",
"=",
"_get_translations_dir",
"(",
")",
"domain",
"=",
"_get_translations_domain",
"(",
"domain",
")",
"pot",
"=",
"os",
".",
"path",
".",
"join",
"(",
"translations_dir",
",",
"f'{domain}.pot'",
")... | 39.888889 | 0.002725 |
def get_mass(self):
'''Returns mass'''
mass = parsers.get_mass(self.__chebi_id)
if math.isnan(mass):
mass = parsers.get_mass(self.get_parent_id())
if math.isnan(mass):
for parent_or_child_id in self.__get_all_ids():
mass = parsers.get_mass(parent... | [
"def",
"get_mass",
"(",
"self",
")",
":",
"mass",
"=",
"parsers",
".",
"get_mass",
"(",
"self",
".",
"__chebi_id",
")",
"if",
"math",
".",
"isnan",
"(",
"mass",
")",
":",
"mass",
"=",
"parsers",
".",
"get_mass",
"(",
"self",
".",
"get_parent_id",
"("... | 27.2 | 0.004739 |
def load_data(self, filename, *args, **kwargs):
"""
load data from text file.
:param filename: name of text file to read
:type filename: str
:returns: data read from file using :func:`numpy.loadtxt`
:rtype: dict
"""
# header keys
header_param = se... | [
"def",
"load_data",
"(",
"self",
",",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# header keys",
"header_param",
"=",
"self",
".",
"parameters",
".",
"get",
"(",
"'header'",
")",
"# default is None",
"# data keys",
"data_param",
"=",
... | 43.15625 | 0.001416 |
def set(self, key, value):
"""Sets the value for the key in the override register.
Will be used instead of values obtained via
args, config file, env, defaults or key/value store.
"""
k = self._real_key(key.lower())
self._override[k] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"k",
"=",
"self",
".",
"_real_key",
"(",
"key",
".",
"lower",
"(",
")",
")",
"self",
".",
"_override",
"[",
"k",
"]",
"=",
"value"
] | 40.428571 | 0.00692 |
def ROC_AUC_analysis(adata,groupby,group=None, n_genes=100):
"""Calculate correlation matrix.
Calculate a correlation matrix for genes strored in sample annotation using rank_genes_groups.py
Parameters
----------
adata : :class:`~anndata.AnnData`
Ann... | [
"def",
"ROC_AUC_analysis",
"(",
"adata",
",",
"groupby",
",",
"group",
"=",
"None",
",",
"n_genes",
"=",
"100",
")",
":",
"if",
"group",
"is",
"None",
":",
"pass",
"# TODO: Loop over all groups instead of just taking one.",
"# Assume group takes an int value for one gro... | 39.852459 | 0.010036 |
def get_user_timer(self, index):
"""Get the current value of a user timer."""
err, tick = self.clock_manager.get_tick(index)
return [err, tick] | [
"def",
"get_user_timer",
"(",
"self",
",",
"index",
")",
":",
"err",
",",
"tick",
"=",
"self",
".",
"clock_manager",
".",
"get_tick",
"(",
"index",
")",
"return",
"[",
"err",
",",
"tick",
"]"
] | 32.8 | 0.011905 |
def map(self, func: Callable[[Tuple[Any, Log]], Tuple[Any, Log]]) -> 'Writer':
"""Map a function func over the Writer value.
Haskell:
fmap f m = Writer $ let (a, w) = runWriter m in (f a, w)
Keyword arguments:
func -- Mapper function:
"""
a, w = self.run()
... | [
"def",
"map",
"(",
"self",
",",
"func",
":",
"Callable",
"[",
"[",
"Tuple",
"[",
"Any",
",",
"Log",
"]",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Log",
"]",
"]",
")",
"->",
"'Writer'",
":",
"a",
",",
"w",
"=",
"self",
".",
"run",
"(",
")",
"b",... | 30.083333 | 0.005376 |
def set_guess_to_fit_result(self):
"""
If you have a fit result, set the guess parameters to the
fit parameters.
"""
if self.results is None:
print("No fit results to use! Run fit() first.")
return
# loop over the results and set the guess values
... | [
"def",
"set_guess_to_fit_result",
"(",
"self",
")",
":",
"if",
"self",
".",
"results",
"is",
"None",
":",
"print",
"(",
"\"No fit results to use! Run fit() first.\"",
")",
"return",
"# loop over the results and set the guess values",
"for",
"n",
"in",
"range",
"(",
"l... | 29.866667 | 0.008658 |
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Called to initialize the HTTPAdapter when a proxy is used."""
try:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapte... | [
"def",
"proxy_manager_for",
"(",
"self",
",",
"proxy",
",",
"*",
"*",
"proxy_kwargs",
")",
":",
"try",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
"=",
"ssl",
".",
"PROTOCOL_TLS",
"except",
"AttributeError",
":",
"proxy_kwargs",
"[",
"'ssl_version'",
"]",
... | 51.857143 | 0.00542 |
def get_routing_attributes(obj, modify_doc=False, keys=None):
"""
Loops through the provided object (using the dir() function) and
finds any callables which match the name signature (e.g.
get_foo()) AND has a docstring beginning with a path-like char
string.
This does process things in alphabeti... | [
"def",
"get_routing_attributes",
"(",
"obj",
",",
"modify_doc",
"=",
"False",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"dir",
"(",
"obj",
")",
"for",
"val",
",",
"method_str",
"in",
"_find_routeable_attributes",
"... | 34.566667 | 0.000938 |
def get_number_footer_lines(docbody, page_break_posns):
"""Try to guess the number of footer lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of footer lines.
@param docbody: (list) of strings - each string being a line in t... | [
"def",
"get_number_footer_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
":",
"num_breaks",
"=",
"len",
"(",
"page_break_posns",
")",
"num_footer_lines",
"=",
"0",
"empty_line",
"=",
"0",
"keep_checking",
"=",
"1",
"p_wordSearch",
"=",
"re",
".",
"compile... | 48.345455 | 0.001106 |
def face_midpoints(self, simplices=None):
"""
Identify the centroid of every simplex in the triangulation. If an array of
simplices is given then the centroids of only those simplices is returned.
"""
if type(simplices) == type(None):
simplices = self.simplices
... | [
"def",
"face_midpoints",
"(",
"self",
",",
"simplices",
"=",
"None",
")",
":",
"if",
"type",
"(",
"simplices",
")",
"==",
"type",
"(",
"None",
")",
":",
"simplices",
"=",
"self",
".",
"simplices",
"mids",
"=",
"self",
".",
"points",
"[",
"simplices",
... | 33.461538 | 0.01566 |
def find(pattern, path=os.path.curdir, recursive=False):
"""
Find absolute file/folder paths with the given ``re`` pattern.
Args:
* pattern: search pattern, support both string (exact match) and `re` pattern.
* path: root path to start searching, default is current working directory.
... | [
"def",
"find",
"(",
"pattern",
",",
"path",
"=",
"os",
".",
"path",
".",
"curdir",
",",
"recursive",
"=",
"False",
")",
":",
"root",
"=",
"realpath",
"(",
"path",
")",
"Finder",
"=",
"lambda",
"item",
":",
"regex",
".",
"is_regex",
"(",
"pattern",
... | 37.92 | 0.007202 |
def delete(self, table, identifier):
"""Deletes a table row by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param identifier: the delete criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype:... | [
"def",
"delete",
"(",
"self",
",",
"table",
",",
"identifier",
")",
":",
"assert",
"isinstance",
"(",
"identifier",
",",
"dict",
")",
"sb",
"=",
"self",
".",
"sql_builder",
"(",
")",
".",
"delete",
"(",
"table",
")",
"for",
"column",
",",
"value",
"i... | 44.066667 | 0.005926 |
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.opts['grains'] = salt.loader.grains(self.opts)
self.opts['pillar'] = salt.pillar.ge... | [
"def",
"gen_modules",
"(",
"self",
",",
"initial_load",
"=",
"False",
")",
":",
"self",
".",
"opts",
"[",
"'grains'",
"]",
"=",
"salt",
".",
"loader",
".",
"grains",
"(",
"self",
".",
"opts",
")",
"self",
".",
"opts",
"[",
"'pillar'",
"]",
"=",
"sa... | 43.3 | 0.002822 |
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnod... | [
"def",
"differentForks",
"(",
"self",
",",
"lnode",
",",
"rnode",
")",
":",
"ancestor",
"=",
"self",
".",
"getCommonAncestor",
"(",
"lnode",
",",
"rnode",
",",
"self",
".",
"root",
")",
"parts",
"=",
"getAlternatives",
"(",
"ancestor",
")",
"if",
"parts"... | 44.9 | 0.004367 |
def process_sums(self):
"""
A redefined version of :func:`RC2.process_sums`. The only
modification affects the clauses whose weight after
splitting becomes less than the weight of the current
optimization level. Such clauses are deactivated and to be
r... | [
"def",
"process_sums",
"(",
"self",
")",
":",
"# sums that should be deactivated (but not removed completely)",
"to_deactivate",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"l",
"in",
"self",
".",
"core_sums",
":",
"if",
"self",
".",
"wght",
"[",
"l",
"]",
"==",
... | 36.851064 | 0.001687 |
def get_default_config_help(self):
"""
Return help text
"""
config_help = super(PassengerCollector, self).get_default_config_help()
config_help.update({
"bin": "The path to the binary",
"use_sudo": "Use sudo?",
"sudo_cmd": "Path t... | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"PassengerCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"\"bin\"",
":",
"\"The path to the binary\"",
",",
... | 38.4 | 0.00339 |
def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
... | [
"def",
"cleanup_sweep_threads",
"(",
")",
":",
"for",
"dict_name",
",",
"obj",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"TimedDict",
",",
")",
")",
":",
"logging",
".",
"info",
"(",
"'Stopping ... | 34.230769 | 0.002188 |
def rm_gos(self, rm_goids):
"""Remove any edges that contain user-specified edges."""
self.edges = self._rm_gos_edges(rm_goids, self.edges)
self.edges_rel = self._rm_gos_edges_rel(rm_goids, self.edges_rel) | [
"def",
"rm_gos",
"(",
"self",
",",
"rm_goids",
")",
":",
"self",
".",
"edges",
"=",
"self",
".",
"_rm_gos_edges",
"(",
"rm_goids",
",",
"self",
".",
"edges",
")",
"self",
".",
"edges_rel",
"=",
"self",
".",
"_rm_gos_edges_rel",
"(",
"rm_goids",
",",
"s... | 56.5 | 0.008734 |
def to_outgoing_transaction(self, using, created=None, deleted=None):
""" Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model.
"""
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "Outgo... | [
"def",
"to_outgoing_transaction",
"(",
"self",
",",
"using",
",",
"created",
"=",
"None",
",",
"deleted",
"=",
"None",
")",
":",
"OutgoingTransaction",
"=",
"django_apps",
".",
"get_model",
"(",
"\"django_collect_offline\"",
",",
"\"OutgoingTransaction\"",
")",
"c... | 43.566667 | 0.002246 |
def image_resolution(self) -> Optional[Tuple[int, int]]:
r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`,
:class:`int`]]) The (width, height) pair of the image.
It may be :const:`None` if it's not an image.
"""
images = self.attributes.get('imageinfo', [])... | [
"def",
"image_resolution",
"(",
"self",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"images",
"=",
"self",
".",
"attributes",
".",
"get",
"(",
"'imageinfo'",
",",
"[",
"]",
")",
"if",
"images",
"and",
"isinstance",
"("... | 43 | 0.004141 |
def _get_bandfile(self, **options):
"""Get the VIIRS rsr filename"""
# Need to understand why there are A&B files for band M16. FIXME!
# Anyway, the absolute response differences are small, below 0.05
# LOG.debug("paths = %s", str(self.bandfilenames))
path = self.bandfilenames... | [
"def",
"_get_bandfile",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"# Need to understand why there are A&B files for band M16. FIXME!",
"# Anyway, the absolute response differences are small, below 0.05",
"# LOG.debug(\"paths = %s\", str(self.bandfilenames))",
"path",
"=",
"self"... | 36.6 | 0.005329 |
def place_visual(self):
"""Places visual objects randomly until no collisions or max iterations hit."""
index = 0
bin_pos = string_to_array(self.bin2_body.get("pos"))
bin_size = self.bin_size
for _, obj_mjcf in self.visual_objects:
bin_x_low = bin_pos[0]
... | [
"def",
"place_visual",
"(",
"self",
")",
":",
"index",
"=",
"0",
"bin_pos",
"=",
"string_to_array",
"(",
"self",
".",
"bin2_body",
".",
"get",
"(",
"\"pos\"",
")",
")",
"bin_size",
"=",
"self",
".",
"bin_size",
"for",
"_",
",",
"obj_mjcf",
"in",
"self"... | 36.92 | 0.004224 |
def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None):
"""Retrieves a list of all the applications.
Important: The client_secret and encryption_key attributes can only be
retrieved with the read:client_keys scope.
Args:
fields (list of ... | [
"def",
"all",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"include_fields",
"=",
"True",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"extra_params",
"=",
"None",
")",
":",
"params",
"=",
"extra_params",
"or",
"{",
"}",
"params",
"[... | 41.875 | 0.002918 |
def write(self, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to e... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"==",
"'\\n'",
":",
"# print does this",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"data",
")",
"else",
":",
"bytes_",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"splitlines... | 39.333333 | 0.003311 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.