content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
def cmd_run(cmd):
"""Shortcut for the long and winding subprocess call output decoder."""
return subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True).stdout.decode("utf-8") | b606a0e5b5803ee00321eb56bf18d0220bf44856 | 671,376 |
def section_break(qty: int=2) -> str:
"""Return multiple line break characters.
:param int qty: number of line break characters (default: 2)
:returns: multiple new line characters
:rtype: str
"""
return '\n' * int(qty) | 3ca9ba1f4c90c0e145d56ef7cb8d052f892fafcc | 671,377 |
def generate_sons(s):
""" Gera os filhos possíveis para um determinado nó.
:param s: o nó no qual terá seus filhos gerados.
:return: lista de filhos que um nó possui.
"""
list_of_sons = []
# caminho da margem esquerda para a direita
if s[2] == 1:
if s[0] - 1 >= 0 and s[1] - 1 >= 0:
... | cbc7b1a5117d76eed6e0085236e88134f68113df | 671,378 |
def insert_or_ignore(session, model, **kwargs):
"""
adds data to specified table
if data is found to exist in the table nothing is added
parameters
----------
session: obj
sqlalchemy session
model : class
name of table
kwargs: dict
values to be entered to the tab... | 433a45e3081b26fd2ce1fdf859a889bd5a743f41 | 671,379 |
def runIn(object:str, cmd):
"""
runIn(object, cmd) -> bool
Execute commands with a given node/knob/field as the 'context'.
This means that all names are evaluated relative to this object, and commands that modify 'this' node will modify the given one.
@param object: Name of object.
@param cmd:... | cc70d4d1f3555d1e3633e36f82a3908682b1a540 | 671,380 |
import os
def landbosse_test_input_dir():
"""
This function is to find the input directory of the landbosse.
This function checks to see if the LANDBOSSE_INPUT_DIR environment
variable is defined. If so, it returns the value of that variable.
If the environment variable is not defined, it return... | c482cbb44044d9435a9b10869d66d99889d5a5e7 | 671,381 |
def str_to_intfl(value):
""" Cast to int/float or send back """
if not value:
return value
# i know...
try:
return_value = int(value)
except ValueError:
pass
else:
return return_value
try:
return_value = float(value)
except ValueErro... | 0eb3e6b7a456ebbc66cf18a37fac3ee3ceb1e39d | 671,382 |
import hashlib
def get_hash(text):
"""Return a hash of the given text for use as an id.
Currently SHA1 hashing is used. It should be plenty for our purposes.
"""
return hashlib.sha1(text.encode('utf-8')).hexdigest() | c95df6d389297b19aac49ca3a94ff8a44ac27620 | 671,383 |
def _select_class_label(top_k_rows, label_index):
""" Gets the class label based on majority voting
:param top_k_rows: a list in the form of [(dist, row),...]
:param label_index: the index in the rows where the label is located
:return: the most common label
"""
labels = []
for tuple in top... | 12d1f0ed1f6fe663e4e737243b85f02a4f0f124c | 671,385 |
def test_acc(test_num):
"""Accuracy that we wish to probe with
a particular test.
"""
if 0 <= test_num <= 3:
return 'LL'
return 'MLL' | f5a425f0420574521c4c18250d8bf44181c3eeed | 671,386 |
def ParallelCorFunction(nucleotide1, nucleotide2, phyche_index):
"""Get the cFactor.(Type1)"""
temp_sum = 0.0
phyche_index_values = list(phyche_index.values())
len_phyche_index = len(phyche_index_values[0])
for u in range(len_phyche_index):
temp_sum += pow(
float(phyche_index[nuc... | b95b3e83f4ae72b3d321cd739596d3c7934ad95f | 671,387 |
import os
def log(parent_directory, name):
"""The path where training/testing/validation logs are stored."""
return os.path.join(parent_directory, '{}.log'.format(name)) | 301182eb5e9e7842085b196980fd8e4da773ed4c | 671,388 |
import os
def load_spelling_ignore_file():
""" Loads file where words are defined that should be ignored - thus not be corrected - by LanguageTool """
file_path = os.path.join(os.path.dirname(__file__), "spelling_ignore.txt")
spelling_ignore_list_file = open(file_path)
spelling_ignore_list = [line.rs... | a85ec1ddbde29ad70a8e3e195ff09a0ba8bfc5ec | 671,390 |
def rotate3_inertia(RotMat,relInertia):
"""
Rotates an inertia tensor. A derivation of the formula in this function
can be found in Crandall 1968, Dynamics of mechanical and electromechanical
systems. This function only transforms an inertia tensor for rotations with
respect to a fixed point. To tra... | 1d12a001b42ad2054fa5f9a01c591091d36517d5 | 671,391 |
from typing import Union
from typing import Tuple
from typing import List
def increase_version_number(version_buffer: Union[Tuple[int, int, int], List[int]]) -> List[int]:
"""
Increases the number of the version with an increment of 0.0.1.
Args:
version_buffer: (Union[Tuple[int, int, int], List[i... | 15b6fca8a2652be39f6535206519486b55d64670 | 671,392 |
def default_params():
"""
Return dict of default parameters.
These can be set to different values in an input file by having a line of the
form:
## parametername parametervalue
e.g.
## missing_preferred_less False
## seed 3145
If the default value, set here, is equal to N... | 79108539b0301d89bd377b76568dfeb5e6806d99 | 671,393 |
import math
def get_num_elements(n):
"""Return the number of elements from the number of possible pairwise combinations.
Essentially, the reverse of the previous function. We only consider the solution
for [-b + sqrt(b^2 - 4ac)] for practical reasons.
"""
return int(1 + math.sqrt(1 + (8 * n))) //... | d0cf6541798784773f2bf12003b9f26ece182813 | 671,394 |
import torch
def weighted_binary_cross_entropy(sigmoid_x, targets, pos_weight, weight=None, size_average=True, reduce=True):
"""
Args:
sigmoid_x: predicted probability of size [N,C], N sample and C Class. Eg. Must be in range of [0,1], i.e. Output from Sigmoid.
targets: true value, one-hot-lik... | ee8701c3b046940e0d46a84e165c56e21965d856 | 671,395 |
def two_list_dictionary(keys, values):
"""Given keys and values, make dictionary of those.
>>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7])
{'x': 9, 'y': 8, 'z': 7}
If there are fewer values than keys, remaining keys should have value
of None:
>>> two_list_dicti... | af9a15e160036625a67f2086758951670a2e5771 | 671,396 |
def walk_to_s(tree, pos):
""" Takes the tree being searched and the position from which
the walk up is started. Returns the position of the first S
encountered and the path taken to get there from the
dominating NP. The path consists of a list of tree positions.
Args:
tree: the tree bein... | fd06eaa9594635c43e2b6319a8dd16631fe3db5b | 671,397 |
def digits(m) -> int:
"""Parses a phrase representing a digit sequence, returning it as an integer."""
return int(m.digit_string) | 297837223c0fd14c345246d58d50f23ef6354d09 | 671,398 |
import sys
import os
def getInstallPaths(install_file):
"""
Gets the paths needed to install environment variables onto a dcc.
Args:
install_file (string): Name of file used to write environment variables in dcc.
Returns:
(list): Install script as first value, piper directory as seco... | 8b21814f148e429a814b5d36f33a2dde1b3d794a | 671,399 |
def fedoralink_classes(obj):
"""
Get the original fedoralink classes of of a given object. They might be different to real classes (via getmro) because
fedoralink autogenerates types when deserializing from RDF metadata/Indexer data.
:param obj: an instance of FedoraObject
:return: list of class... | 9e280a4a15428e40c5973359c401f68159c84579 | 671,400 |
from datetime import datetime
def yearmonth(value):
""" Returns the input converted to a string in format YYYY-mm
Args:
value (datetime): date to convert
Returns:
output (str): formatted in YYYY-mm
"""
output = datetime.strftime(value, '%Y-%m')
return output | 9242c942f6843d6281f0d44fe9a3803005bb84df | 671,401 |
def smooth(cloud, radius=0.01):
"""
default radius for sampling is 1cm
"""
tree = cloud.make_kdtree()
#create moving least squares settings
mls = cloud.make_moving_least_squares()
mls.set_Compute_Normals(True)
mls.set_polynomial_fit(True)
mls.set_Search_Method(tree)
mls.set_sear... | 628d01dbfd824610903f04801fbde5b147b780a7 | 671,402 |
import requests
def url_check(url):
#Description
"""Boolean return - check to see if the site exists.
This function takes a url as input and then it requests the site
head - not the full html and then it checks the response to see if
it's less than 400. If it is less tha... | be058a1f3081bfda71c617e4a5b706ff2fc2bb40 | 671,403 |
def rule_separation(value: float, layer1: str, layer2: str):
"""Min space between different layers"""
error = f"min {layer1} {layer2} separation {value}um"
return f"{layer1}.separation({layer2}, {value})" f".output('{error}', '{error}')" | 6376ce117033c2269be5b74dfd6c083acd5f42b1 | 671,404 |
import re
def text_case(line):
"""Return the text case (lower case, upper case, title case or none of them)"""
is_title_case = True
for word in line.split():
if len(word) > 4 and not word.startswith('(') and not word.startswith('['):
is_title_case = is_title_case and (bool(re.match(r'^... | 1aa3b1b51491ee9b7f3c93d3effbb1ed05e4cc25 | 671,406 |
from textwrap import dedent
def txt(s: str) -> str:
"""
dedents a triple-quoted indented string, and strips the leading newline.
Converts this:
txt('''
hello
world
''')
into this:
"hello\nworld\n"
"""
return dedent(s.lstrip("\n")) | 6b5f78fd0b4bfb6e2fd57223d74f008f4ba83467 | 671,408 |
import re
def _clean_xml(xml_string):
"""Replace invalid characters with "?".
:type xml_string: str
:arg xml_string: XML string
:rtype: str
:returns: valid XML string
"""
invalid_chars = re.compile(r'[\000-\010\013\014\016-\037]')
return invalid_chars.sub('?', xml_string) | fec5b3735b1f51d98fd33faec42c2853eb73808e | 671,409 |
import functools
import warnings
def remove_parameters(removed_params,
reason,
end_version='future'):
"""Decorator to deprecate but not renamed parameters in the decorated
functions and methods.
Parameters
----------
removed_params : list[string]
... | 8eeff651359722af4894d6ea347b47cb1b7d2bd6 | 671,410 |
def massprops(client, file_=None):
"""Get mass property information about a model.
Notes: PTC's description of coord_sys_inertia:
"The inertia matrix with respect to coordinate frame:(element ij is
the integral of x_i x_j over the object)".
PTC's description of coord_sys_inertia_tensor:
"The in... | 0d675d86d9c64640f555ebd84e543481de924cc7 | 671,411 |
def degseq_to_data(degree_sequence):
"""
Takes a degree sequence list (of Integers) and converts to a sorted
(max-min) integer data type, as used for faster access in the
underlying database.
EXAMPLE::
sage: from sage.graphs.graph_database import degseq_to_data
sage: degseq_to_data... | 881ea34a958f0f4f4ec39957c1433d6aa3795424 | 671,412 |
def remaining(counts,player):
"""Calculates the sum of remaining opponent pieces"""
remaining = 0
player_info = {"w": "wW@","b":"bB$"}
for each in player_info["w" if player=="b" else "b"]:
if each in counts.keys():
remaining+=counts[each]
return remaining | 7b7b97d3bd7b28a0211421e8a7272c26aec40a22 | 671,413 |
def pivot_smooth_norm(df, smooth_value, rows_variable, cols_variable, values_variable):
"""
Turns the pandas dataframe into a data matrix.
Args:
df (dataframe): aggregated dataframe
smooth_value (float): value to add to the matrix to account for the priors
rows_variable (str): name o... | 15b0888b42600e41ab68927fb60430cb3a49cea8 | 671,414 |
import numpy
def referenceToSinglet(spectrum, ppm, peakRange):
"""
Find the highest point in the region indicated by the tuple of (*low bound*, *high bound*).
Where all values in peakRange are identical behaviour is undefined.
:param numpy.array spectrum: Vector of values representing the real part of the spect... | f613acc67b84212fd0d9f8821372d670b8dcace3 | 671,416 |
def detect(code):
"""Detects if a scriptlet is urlencoded."""
# the fact that script doesn't contain any space, but has %20 instead
# should be sufficient check for now.
return ' ' not in code and ('%20' in code or code.count('%') > 3) | 2e7c932a65cf08a460a83c8f9f691142722cc241 | 671,418 |
def parse_voice_flags(flags):
"""Parses flags and returns a dict that represents voice playing state."""
# flags: [0-9]{8}
if flags[0] == '0':
return {'voice': 'stop'}
else:
return {'voice': {
'number': int(flags[1:3]),
'repeat': int(flags[4:6])
}} | dcbdab0108ea4d5950d16338ff369920195e4335 | 671,419 |
def _fill_attrs(da, pos, axis):
"""Replace comdo attributes according to pos and axis"""
attrs = da.attrs
attrs["axis"] = axis
if pos == "center":
attrs.pop("c_grid_axis_shift", None)
elif pos in ["left", "outer"]:
attrs["c_grid_axis_shift"] = -0.5
elif pos in ["right", "inner"]... | d7b8dec12d766b1b90bd7cea1bcf4096ed46413f | 671,420 |
def get_durations_by_song(song):
"""
Iterate over all labels for a given song
to extract notes
"""
durations = {}
for segment in song:
# (start,end,(instrument,note,measure,beat,note_value))
duration = segment[2][4].decode('utf-8')
if duration not in durations:
... | d10179a4497d460efaf2d666abcd7f6588fe2c77 | 671,421 |
import random
def _SelectReviewer(possible_owners, used_reviewers):
"""Select a reviewer from |owners| and adds them to the set of used reviewers.
Returns:
The reviewer.
"""
# It's debatable whether we want to avoid reusing reviewers. It could be
# easier to ask the smallest possible amount of reviewe... | 1005c17b1e9387d26fb4c8a286758fe31073e13b | 671,422 |
import argparse
def parse_args():
""" Parse command line arguments """
parser = argparse.ArgumentParser(description='nsupdate-interactive')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--zone', type=str)
group.add_argument('--get-zone-slug', type=str)
parse... | 8fceafcee5e258e1f84a1384f9399028909aecc4 | 671,423 |
import warnings
def deprecated(replaced_by_func):
"""
This decorator is used to mark functions as deprecated. It also points
the user to the newer function that should be used instead.
"""
def wrap(f):
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWa... | f37ed5bb1bfaf1a6dc4d4dc9f379315e0ae006de | 671,424 |
def post(user, post_id):
"""User's post.
.. :quickref: User; Save user id
:param user: user login name
:param post_id: post unique id
:status 200: when user and post exists
:status 404: when user and post doesn't exist
"""
return str(post_id), 'by', user | 6cff4255c9f425e03d8391215626c31483d017bd | 671,425 |
from typing import Union
import grp
def gid2name(gid: Union[str, int]) -> str:
"""From the list of all groups return the name of gid"""
return str(grp.getgrgid(int(gid)).gr_name) | 3b9488e838f9336033bf873d024886bf3a0ff73c | 671,426 |
from pathlib import Path
def enterprise_1_11_artifact() -> Path:
"""
Return the path to a build artifact for DC/OS Enterprise 1.11.
"""
return Path('/tmp/dcos_generate_config_1_11.ee.sh') | 7a115360e94dc866b35b49df329b23547144fa05 | 671,427 |
def bb_filter_initial_features(bboxes, scores, features):
"""
Filter out elts of list that do not contain bbox
"""
bboxes_initial = []
scores_initial = []
features_initial = []
num_rois = len(scores)
for roi_ind in range(num_rois):
bboxes_roi = bboxes[roi_ind]
if bboxes_r... | 09311f351e832ba7aee0b163a68aeaf5f570efc6 | 671,429 |
def nocache(response):
"""Add Cache-Control headers to disable caching a response"""
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
return response | 4dff55d10245a51b131c2803f3cd109ab72d8bde | 671,430 |
from typing import List
def parse_pdv(text: str) -> List[List[str]]:
"""
Parse pipe delimited values.
"""
rows = []
lines = text.split('\n')
for line in lines:
row = []
cols = line.split('|')
for col in cols:
col2 = col.strip()
row.append(col2)... | e9dcf6a1cffcad1a4cbd8981fa3fcc105fa65103 | 671,431 |
def add_toc(txt):
"""Add github-style ToC to start of md content.
"""
lines = txt.split('\n')
toc_lines = []
mindepth = None
for line in lines:
if not line.startswith('#'):
continue
parts = line.split()
hashblock = parts[0]
if set(hashblock) != set(... | 708438467e3a429f13c82b9d38589d5a6a772f37 | 671,432 |
def checkLocator(subject: str, locator: int):
"""Returns False if the character at subject[locator] is not equal to its counterpart at
subject[-locator-1].
locator is the zero starting index of the current character to be checked.
This method recurs with incrementing locator until all characters in sub... | 12e56a5872053c1b4186bcc419b0bbc1fb54d017 | 671,433 |
import os
import glob
def find_counts_files(c):
"""Return a list of the counts files found in the supplied directory."""
cfiles = {}
apath = os.path.abspath(os.path.expanduser(c))
for cf in glob.iglob(apath + '/**/*.counts'):
sn = os.path.basename(cf).rstrip('.counts')
cfiles[sn] = cf
... | 82edacc44d8aa5e75f7fbaf166cff549c9e8ca70 | 671,434 |
import os
def check_file_name(file_name):
"""
Check For Existing Filename
credit: lastro
given: string containing file name.
return: string with additional number if file already exists with given
filename; otherwise returns original string.
"""
if os.path.isfile(file_name):
expand =... | 37ee1e0956043f95e66b40b91bcbc78a2af02572 | 671,435 |
def wall_dimensions(walls):
""" Given a list of walls, returns a tuple of (width, height)."""
width = max(walls)[0] + 1
height = max(walls)[1] + 1
return (width, height) | 8f11b07f6e50a04363caed8480f67383a322dce2 | 671,436 |
import math
def millify(n):
"""Abbreviate a number to nearest thousand, million, etc.
Adapted from: https://stackoverflow.com/a/3155023/10696164
Parameters
----------
n : int
The number to abbreviate
Returns
-------
millified : str
The number abbreviated to the neare... | f4b80ce0abb52e2f0985ced448d4d7daf686a6e8 | 671,437 |
def compile_create_table(qualified_name: str, column_statement: str,
primary_key_statement: str) -> str:
"""Postgresql Create Table statement formatter."""
statement = """
CREATE TABLE {table} ({columns} {primary_keys});
""".format(table=qualified_name,
... | 4828e65915e96d47149fdb2f83ce59976a3b5760 | 671,438 |
def add_ax(fig, rect):
"""
添加子图ax
pos_x, pos_y 子图左下角位置
width, height 子图宽高
注意:pos_x, pos_y, width, height 都是百分比形式
"""
return fig.add_axes(rect) | ce5c257f9a481baea53bad1117ef6cfb45bc023a | 671,439 |
def updateModulesIdList(campaign,m):
"""Updates the Modules ID list (main use is the argparse choices)"""
modules_ids = []
for c in campaign:
modules_ids.insert(len(modules_ids),c["id"])
if len(modules_ids) > 0 and m != "edit":
modules_ids.insert(len(modules_ids),"all")
return modul... | 2c6cf974adeab43be95b6edcf535e19eb19f67f1 | 671,440 |
def chunklistWithOverlap(inlist, size_per_chunk, overlap_per_chunk):
"""Convert list into a list of lists such that each element is a list
containing a sequential chunk of the original list of length
size_per_chunk"""
assert size_per_chunk >= 1 and overlap_per_chunk >= 0 and size_per_chunk > overlap_per... | f6a404b2b98e72eb50c04ba68f4d8a1582b4659e | 671,441 |
def expression(s):
"""expression(s) -> float
Parse a Nuke expression. Runs the same expression parser as is used by animations. This is not the same as the tcl expr parser. The main differences are:
- Only floating point numbers are calculated. There are no strings, boolean, or integer values.
- You can name any k... | fa26c052f68714f45966d8327c6ea143a3ff464f | 671,443 |
def insertionsort(list, descending=False):
"""
Takes in a list as an argument, and sorts it using an "Insertion Sort"-algorithm.
---
Args:
- list (list): The list to be sorted
- descending (bool): Set true if the list be sorted high-to-low. Default=False
Raises:
- T... | e6e995ba051a764845456ed02c63930fba662510 | 671,444 |
def GetArgsForMockCall(call_args_list, call_number):
"""Helper to more sanely get call args from a mocked method.
Args:
call_args_list: The call_args_list member from the mock in question.
call_number: The call number to pull args from, starting at 0 for the first
call to the method.
Returns:
... | 877c74760055484d64f4ca761316157498e82e23 | 671,445 |
import itertools
def find_idx_common3b(i, list_kappa_idx, solution_idx):
"""
Find the scalar products for common function with 3 solution consecutive kappas.
Parameters:
i -- integer
list_kappa_idx -- list
solution_idx -- list of Decimal
Return:
common3b_idx -- list
"""
common3b_idx = [sublist f... | 5cc021b2410650e758b00e313cae0b6f794f907c | 671,446 |
import torch
import math
def perplexity_of(model, samples, batch_size):
"""
:param model: a modelModel instance.
:param samples: a Samples instance.
:param batch_size: an (unsigned) int - the batch size with which
the model was trained.
:returns: a float - the perplexity of the model on the gi... | c7195bbd50dacf45bb72a2eb9d281a8a0f01ea96 | 671,447 |
def exp2(x):
"""
Returns the 2 to the power of x of FuncInput object.
Parameters
=======
FuncInput object or real number
Returns
=======
FuncInput object with value based on exp(x) and gradients based on 2**x * log(2) * x'
Examples
=======
>>> x = FuncInput(np.array([2]),n... | 6601c38fbc1535d7f69be2f7710def08a513226b | 671,448 |
def pid2index(painting_df, painting_id):
"""From the painting ID, returns the index of the painting in the painting dataframe
Input:
painting_df: dataframe of paintings
painting_list: list of paintings ID (e.g ['000-02T4-0000', '000-03WC-0000...'])
Output:
index_list: lis... | 3b73f3ed0905bdefd3ebce4699bf783a99227437 | 671,449 |
def change_style(style, representer):
"""
This function is used to format the key value as a multi-line string maintaining the line breaks
"""
def new_representer(dumper, data):
scalar = representer(dumper, data)
scalar.style = style
return scalar
return new_representer | 06af8dea5f7c82b2337e3599b138489bba1c4b9e | 671,450 |
import torch
def load_checkpoint(model, resume_path, logger):
"""
Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed
"""
logger.info("Loading checkpoint: {} ...".format(resume_path))
checkpoint = torch.load(resume_path)
epoch = checkpoint['epoch']
mnt_best... | 6ee8f821b8152d83d240acec8d621405d5dd6bc9 | 671,451 |
def filter_transmission_events(selected_events, transmission_events):
"""Filter transmission_events for node-links of interest.
:param selected_events: Specified organism_group-organism_group
relationships inside nested dictionary.
:type selected_events: dict[str, dict[str, None]]
:param transmissi... | 89a1026a02b52ce5c457d58edf864321c2f73f43 | 671,453 |
async def raceclass() -> dict:
"""Create a mock raceclass object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"name": "G16",
"ageclass_name": "G 16 år",
"order": 1,
"event_id": "event_id_1",
"distance": "5km",
} | 1d2ec3921c5d20b6a13ad5945569e15e4950b272 | 671,454 |
from typing import Tuple
import sysconfig
import os
def _find_executable_and_scripts(path: str) -> Tuple[str, str, str]:
"""
Detect the Python executable and script folder of a virtual environment.
:param path: The location of the virtual environment
:return: The Python executable, script folder, and... | 060a58bca01310ed410741037ee44800b57ace29 | 671,455 |
import os
def skippable(func):
"""
Makes a function skippable.
Saves the state before and after the function runs. Pass "skip=True" to the
function to load the previous save state from when the function finished.
"""
def wrapped_function(*args, **kwargs):
self = args[0]
skip =... | ecb2a06b920b762b7eb5d631825511e56a669de6 | 671,456 |
def bool_constructor(self, node):
"""
Args:
node:
Returns:
"""
value = self.construct_yaml_bool(node)
return '$true' if value else '$false' | 0b2cd0f1055b604d62fb9baab7f91b686c8d1baf | 671,458 |
import pandas
def totalDuration(
data,
duration,
id1,
id2,
verbose):
"""Extract the total duration of each query"""
# making functions more explicit
data = data
duration = duration
id1 = id1
id2 = id2
verbose = verbose
to... | 36095973cfd250b2c1b2e72fedd4c00c98f4aa79 | 671,459 |
import math
def mach_angle(M):
"""Calculate the Mach angle
:param <float> M: Mach #
:return <float> Mach angle, mu
"""
return math.asin(1 / M) | 7206357389cd24c5348f850ca3be335e1a3e93f0 | 671,460 |
import socket
def check_port(ip, port):
""" check if port is in use """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
s.shutdown(2)
print("port is used", int(port))
return True
except BaseException:
return False | 320fe5f7432904a48e8b5744b649c282f65c45ed | 671,462 |
def binarize_score(adata, score_label: str, threshold: float):
"""
Binarizes a provided key of an AnnData object by labeling values over a threshold as 'positive' or 'negative'.
Args:
adata: AnnData object to perform the binarization for
score_label: Label in adata.obs which will be used fo... | febaa211db11be45f859df3067b2034b1b651bb9 | 671,463 |
def _find_calframe(calframes, calpaths, values, calname, verbose=False):
""" Find the calibration frame and path from given dicts for dict values.
"""
if calframes is None:
calpath = None
calframe = None
else:
try:
calframe = calframes[values]
calpath = ca... | 0eedfa2d31a4e02a579841b13ad1fda872ade097 | 671,464 |
import sys
def weights_from_config(config):
"""
Construct a layer from a configuration.
Args:
A dictionary configuration of the layer metadata.
Returns:
An object which is a subclass of 'Weights'.
"""
layer_obj = getattr(sys.modules[__name__], config["layer_type"])
retur... | f24abfb87173882197192cee1cc0fc63d445ae66 | 671,465 |
def recv_all(sock):
"""Receive data until connection is closed."""
data = b''
while True:
chunk = sock.recv(1024)
if not chunk:
break
data += chunk
return data | 9e412f2f0913311d82b0e31ed788f48fc77e45d2 | 671,466 |
def rreplace(s, old, new, count):
"""
Replaces last occurance of something
stackoverflow.com/questions/2556108/
"""
return (s[::-1].replace(old[::-1], new[::-1], count))[::-1] | ec17e03b22bc478298ecddc55596754d1fa0f718 | 671,468 |
def _remove_seen_ids(ctrl, id_set):
"""Iterates through each bounded id-range, and removes IDs seen"""
partition_range = range(0, ctrl.config["partitions"])
unseen_ids = id_set.copy()
for partition_idx in partition_range:
lower_bound, upper_bound = ctrl.get_id_range_for_partition(partition_idx)
... | ae6a5c23fb6ff0b7bec64b529c202d3acd042066 | 671,469 |
def popis_pozici(pozice):
"""Popíše pozici pro lidi
např:
>>> popis_pozici(0, 0)
'a1'
"""
radek, sloupec = pozice
return "abcdefgh"[sloupec] + "12345678"[radek] | efb2df8715b30c04bfdeb82684084f2037ad5e7e | 671,470 |
def full_class(obj):
"""The full importable path to an object's class."""
return type(obj).__module__ + '.' + type(obj).__name__ | 77ade617d2b4e4c71de19d06e57f92136af92d44 | 671,471 |
def scale_data(Data,cscale,dscale,scaledown = True):
"""
Returns scaled data on both columns
Parameters
----------
Data: ndarray()
Array of data to be scaled
scaledown: bool
determines if data is scaled down or up
cscale: float
how much to multiply column 1 by
ds... | 34d24af1987a105564a6205c97288bf422d65cac | 671,473 |
def _normalize_input_name(input_name):
"""Remove :i suffix from input tensor names."""
return input_name.split(":")[0] | 3e75ae51a52a7c1ffe38dcf3483526af776d1b9c | 671,474 |
import sys
def _canonicalizePath(path):
"""
Support passing in a pathlib.Path-like object by converting to str.
"""
if sys.version_info[0] >= 3:
return str(path)
else:
# On earlier Python versions, str is a byte string, so attempting to
# convert a unicode string to str wil... | a7b4ea8c9ea4e01e5aba1faa77cb3dcff36f8b5e | 671,475 |
def getitemdata(data):
"""Populates global itemdata with next item ID data from queue
"""
itemdata = {}
if data is not None:
itemLevel = -1
requiredLevel = -1
if "itemLevel" in data:
itemLevel = data["itemLevel"]
if "requiredLevel" in data:
requir... | 303fa23018435ad46aefcfdfccccc6abdec24b9d | 671,476 |
def register_dictionary(nickname, email, password='default acceptable password', repeat_password='default acceptable password'):
"""creates the dictionary that can be used for registration"""
return dict(nickname=nickname, email=email, password=password, repeat_password=repeat_password) | fec2aa0e38c992ae2f48fbac261754c6333e581a | 671,477 |
def rectangles_circum(n: int):
"""Return `n` fixed circumference rectangles, w + h = n"""
output = list()
for i in range(1, n + 1):
output.append((i, n - i + 1))
output.sort(key=lambda x: x[1], reverse=True)
return output | ba3eced573953e9cf4951ec91f29d28b5363bda9 | 671,478 |
import os
def check_ping(hostname):
"""Run ping and return 1 if success"""
attempts = 1
response = os.system("ping -c {} {} >/dev/null".format(attempts, hostname))
# and then check the response...
if response == 0:
# Network is active
return attempts
return 0 | afc9403f62d404b12b9a73ae6d4d50dfc5443f6e | 671,479 |
def motion_dollar(input_line, cur, count):
"""Go to end of line and return position.
See Also:
`motion_base()`.
"""
pos = len(input_line)
return pos, False, False | 216cff1c8f3c6e658b681d423d6b4352ba18d343 | 671,480 |
import hashlib
def checksum_md5(filename):
"""computes MD5 for a file
@param filename filename
@return string or None if there was an error
"""
fname = filename
block_size = 0x10000
fd = open(fname, "rb")
try:
block = [fd.read(block_size)]
... | c0a9fbe621a975a0724d6f77cae9c5eaeba6d9e6 | 671,483 |
def check_is_user_owner_of_plant(user, target_rich_plant):
"""Check if user is owner of Rich plant"""
if user.id == target_rich_plant.owner:
return True
else:
return False | 420308af7546c4a9fb22a7805ef5735b016fe99e | 671,485 |
def make_connection(conn, input_only_nodes, output_only_nodes,
find_wire, find_pip, find_connector,
tile_name, loc, tile_type, pip, switch_pkey):
""" Attempt to connect graph nodes on either side of a pip.
Args:
conn (sqlite3.Connection): Routing database
input_only_nodes (set o... | 11ddebbe5452f64e9c066110f77ad3de9be95812 | 671,486 |
def pullColumnAll(cursor, ticker, column_name):
"""
Retrieves specific column data for the given parameter (column_name)
Arguments:
cursor: cursor object for the database
ticker: ticker for which we are collecting data
column_name: specific column we want data from
Returns:
... | 9482d04e91198b651650c2263858d6134493f89a | 671,487 |
import re
def regex_search(regex, text):
"""
Do regular expression search for text.
:param regex: Regular expression for search, if none then disabled
:param text: Text where to search
:return: True if search finds something or regex is None
"""
if regex:
return re.search(regex, t... | b1a040fa6ecb6a0a8840ec0aad1d4ff6d2217c24 | 671,488 |
import argparse
def parseArgs():
"""
Parsing and returning arguments
"""
# Definition of arguments
descr = "Feed VS result data (however many files), plots ROC curves or" \
" Enrichment curves"
descr_title = "Provide a title for the graph, also used as filename"
descr_results = "P... | b627b598c19317772938546a72931f54d3f33bed | 671,489 |
import re
def UpdateVerityTable(table, hash_offset):
"""Update the verity table with correct hash table offset.
Args:
table: the verity hash table content
hash_offset: the hash table offset in sector (each sector has 512 bytes)
Returns:
updated verity hash table content
"""
find_offset = re.c... | d45235dd0d201c269e299ba7fc2a0a60f8e84954 | 671,490 |
def read_lines(txt_name=""):
"""return the text in a file in lines as a list """
txt_name="./intermediate_file/detect_result/txt/"+txt_name
f = open(txt_name,'rU')
return f.readlines() | 2ec3a4f868775f0a682317405c4e10c9283ae5a3 | 671,491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.