content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Any
from contextlib import suppress
def safe_get(key, obj, default=None) -> Any:
"""
Safely retrieve key from object
Args:
obj: Any. target object
key: inner object adders token
default: value to return on failure
Returns:
on success: value of request... | 21929399b123f46e7a24289052b1e9a9bbc71fa0 | 648,116 |
import json
def pretty_json(json_str):
"""Generates a pretty-print json from any json."""
return json.dumps(json.loads(json_str), indent=4) | e1d16fcc91c7d212130af115eb0cad2fbd73a99c | 648,117 |
import os
def getPyoExamples(fullpath=False):
"""
Returns a listing of the examples, as a dictionary, installed with pyo.
:Args:
fullpath: boolean
If True, the full path of each file is returned. Otherwise, only the
filenames are listed.
>>> examples = getPyoExamples... | 676d00b38cb648480836408ca1b490073d5f017b | 648,118 |
def default_parameter_f(x, y=3):
""" default_parameter_f """
z = x + y
return z | 0c6c08162662adb2cd0677343a151317f58e3d7d | 648,119 |
def _sensor(product_id):
"""Find sensor ID from product ID."""
sid = product_id[:2]
if sid == 'LC':
return 'OLI_TIRS'
elif sid == 'LO':
return 'OLI'
elif sid == 'LE':
return 'ETM'
elif sid == 'LT':
return 'TM'
elif sid == 'LM':
return 'MSS' | 164d166e4e1d519ffb9d810df34a1e2e9b8ff06c | 648,120 |
def test_ptr_assign():
"""A simple pointer dereference assignment."""
return """
fn main() {
var x := 1000::*u8;
*x = 4;
}
""" | 8fb1be3a3713a1d9e7056a54bee849ba2387ecf1 | 648,121 |
import math
def get_int_percent(float_value):
"""
floatを整数のパーセント値に変換して返す[0.275 >> 28]
:param float_value: float
:return: int
"""
return int(math.ceil(float_value * 100)) | 7312b5c02e9902ca704e8b6a3f3cba070f063c69 | 648,122 |
from datetime import datetime
def extract_date_sitename(directory_path,
sitename_location,
datetime_location):
"""Extract datetime and sitename from directory path names.
Parameters
-----------
directory_path : string
A path to the directory... | df2c30d0b9629cd150a5168fbb403442682e190d | 648,123 |
import collections
def _initial_gradients(vspace, target, output_gradients, tensor_usage_counts):
"""Computes the initial gradients for each Tensor."""
# Initialize the backprop stack
gradients = collections.defaultdict(list)
for i, t in enumerate(target):
if vspace.tensor_id(t) in tensor_usage_counts:
... | fe9947e05e9708765981addfac1abf2e8f7dd3cd | 648,124 |
def intracluster_links_aux(adj, indices):
"""Computes intra-cluster links or weights given nodes indices.
:param adj: [description]
:type adj: [type]
:param indices: [description]
:type indices: [type]
:return: [description]
:rtype: [type]
"""
n_links = 0
for ii in indices:
... | 5f2409f59b0380b21e0943a33693a5d6177c9493 | 648,125 |
import requests
import yaml
def load_yaml_from_url(url):
"""
Helper method for grabbing yaml files
"""
response = requests.get(url)
if response.status_code != 200:
raise RuntimeError(f'Unable to access Biolink Model at {url}')
return yaml.load(response.text, Loader=yaml.FullLoader) | 35f3d37117b2a82f67ba03762b3e8970ff774ccc | 648,126 |
def triple_length(m: int, n: int) -> int:
"""Returns the length of the triangle formed by the Pythagorean triple
(m^2 - n^2, 2mn, m^2 + n^2)."""
return 2 * m * (m + n) | 002bfdb2bf4d5b73bb90394681b0ef5156b6da7e | 648,127 |
import itertools
import random
def random_tuple_list(lst1, lst2, lb=1):
"""
Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2;
"""
product = list(itertools.product(lst1, lst2))
if len(product) == 0:
k = 0
else:
k = random.randint(lb, len(product))
... | 53d7c124b0b2f3721da21a77ec4bda792119efc8 | 648,128 |
def compress_string(string) -> str:
"""
big O:
linear time
linear space
"""
# validate the string
if isinstance(string, str) is False:
raise ValueError(f"Error while validating input. {string} is not of type str.")
# compress the string
output = string
if len(string) > 0:... | afdde96d70de4e99594446423ab272d3a0abd8b4 | 648,129 |
def extract_container_id_removal(line):
"""
Extract container id from a Removing line
Removing intermediate container 816abeca3961
"""
parts = line.strip().split(' ')
if len(parts) == 4:
return parts[3]
else:
raise Exception("Unrecognized docker removing line: " + l... | dc73ced5b0ab6169c9b4ed9e615e6c54a05e4de7 | 648,130 |
import sys
def make_hypothesis(val: int):
"""Create a hypothesis that checks if `val` is in actions."""
def hypothesis(env):
print("hypothesis?()", env.actions, val in env.actions, file=sys.stderr)
return val in env.actions
return hypothesis | 265ba69c06290abb7f5d9bedd89895845a811eef | 648,131 |
def get_recommendation(risk_level):
"""
Returns a investment recommendation based on the choice of risk level
"""
recommendation = ""
if risk_level == 'None' or risk_level == 'none':
recommendation = "Investment recommendation: 100% bonds (AGG), 0% equities (SPY)"
elif ris... | 98779343f5a01bc4d91af8079ca403d0413c5951 | 648,132 |
def digit_that_breaks_ordering_index(digits: list) -> int:
"""
Starting from last digit of given number, find the first
digit which breaks the sorted ordering. Let the index of
this found digit be 'i' and the digit be number[i].
:param digits: list of digits
:return: the index of the first digi... | e4b24a94d04efdaa8311da7878e500e80f066d00 | 648,133 |
def filter_insertchars(s,chars=None,space=' '):
"""insertchars(s,chars=None,space=' ') -> str
Insert space before each occurence of a character in chars."""
xchars = str(chars)
out = ''
for x in s:
if x in xchars:
out += space
out += x
return out | a422a394ef27f41624831dd682ffe1a9293a40ff | 648,134 |
def specindex(nu1, nu2, f1, alpha):
"""
Calculate some flux given two wavelengths, one flux, and the spectral
index.
"""
return f1*(nu2/nu1)**(alpha) | 0884206d0aedfb9ee92df93f9bbd7d82ab81af0d | 648,135 |
import requests
def get_name(qids, queryProperty):
"""
Get labels of list of qnodes (max 50)
"""
url = "https://www.wikidata.org/w/api.php"
params = {
"action":"wbgetentities",
"format":"json",
"props":queryProperty,
"languages":"en",
"limit":"max",
}
... | 19fba8fc2c605150454a7b2bd80abed997cde4a0 | 648,136 |
import os
def _oneLevelAbove_oneSubDirSatisfies(dir_path, judgeFunction): #--- low level function
"""
Returns True if "judgeFunction" return True on one of the
subdirectories of "dir_path".
"""
for name in os.listdir(dir_path):
full_path = os.path.join(dir_path, name)
if os... | 262e82e2040079d28e6de0439694603fcc6fe965 | 648,137 |
def get_yaml_config(unusued_file_name): # pylint: disable-msg=unused-argument
"""Return an empty dict.
This is only implemented to make sure that analyzers attempting
to call this function still work.
Args:
unused_file_name: String that defines the config file name.
Returns:
An e... | d7b535632857b94f1d959e7a75e21e0149fe0322 | 648,138 |
def _translate(text, table):
""" Converts a continuous string to codes specified in a table """
ptr = 0
encoded = ""
# Stop when we're past the strig
while ptr < len(text):
# end is how many bits ahead we look
end = 1
# Keep looking ahead while no match in reverse dict
... | 62426e34cd89f8f09541cf34664b1bf480f38c24 | 648,139 |
import os
def _order_fpaths(soundfpaths):
"""
Order the sound files according to their phase and articulation group.
So, Phase0 comes first, then Phase1_0, then Phase1_1, etc.
If there are any left over, they are appended at the end.
"""
ordered = []
soundfpaths = list(soundfpaths) # We w... | 0014bf11de8c865ee2a6edb076781f03bb37f939 | 648,140 |
def f_factory(W):
"""
For given network parameters, returns the function f,
where f(V)[:,p] is the instantaneous change in network state V[:,p]
"""
return lambda V: (W.dot(V))*(1 - V**2) | 19b2d9159a2b4eb7e440090e95bb5950bf332c32 | 648,141 |
def find_sols(f, arr, sign_check_func = lambda x, y: x*y < 0, verbose = False):
"""
Given an array of section points, checks if function *f* has a solution
in any of the intervals formed by said points.
"""
sols = []
for i in range(len(arr)-1):
if sign_check_func(f(arr[i]), f(arr[i+1])):... | 36ff973789c645d65645ea4a902c2a80f9548b5a | 648,142 |
def motifs_from_proto(motifs, is_one_dimensional=False):
"""
Utility function to transform motif locations back to single dimension
or multi-dimension location.
Parameter
---------
motifs : array_like
The protobuf formatted array.
is_one_dimensional : boolean
A flag to indic... | b848b0262fb2c82da95b5ef9d9095d1bb80ad13b | 648,143 |
import os
def manage_py_dir():
"""Returns the directory holding the manage.py file as a string."""
return os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + os.pardir +\
os.sep + os.pardir + os.sep) + os.sep | 563e8b1e7a9c6a87925ff4b60d9511b166d09059 | 648,144 |
def knapsack(max_weight, items):
"""
0 1 2 3 ... w
0 no item
1 item 1
2 item 2
...
n item n
"""
n = len(items) + 1
m = max_weight + 1
dp = [[0] * m for _ in range(n)]
for i_index in range(1, n):
current_item = items[i_index... | b38cf6c67ec58b4429c188bd7d707b56b38e9f70 | 648,145 |
def replacePlaceholder(sentence,placeholder,subsitute):
"""
This function replaces in a sentence a placeholder with a specified substitute
Input:
sentence: string representing a sentence
placeholder: string representing a placeholder that occurs in the supplied sentence
subsitute: s... | 85345f9c00a3b1334057de2a32ea390e76a511d4 | 648,146 |
def list_as_comma_string(bits, serial_comma=False):
"""
>>> list_as_comma_string([])
''
>>> list_as_comma_string(['hi'])
'hi'
>>> list_as_comma_string(['hi', 'there'])
'hi and there'
>>> list_as_comma_string(['hi', 'there', 'world'], serial_comma=False)
'hi, there and world'
... | 58ce30d3cf8e2812c057f3f3303e03e5f8a1a11d | 648,147 |
def auto_label(callable_or_expr):
"""
Given a callable or a string, extract a name for labeling axes.
Parameters
----------
callable_or_expr : String | Callable
Returns
-------
label : String
"""
if callable(callable_or_expr):
return getattr(callable_or_expr, "__name__"... | 470df5bcee871c72eecdf14fb337f5bb1ca3ba11 | 648,148 |
from typing import Counter
def lex_smallest_string(s):
"""
:type s: str
:rtype: str
"""
char_counter = Counter(s)
# "".join(item[0] for item in Counter.items() for x in range(item[1])])
smallest_s = ""
for item in char_counter.items():
for _ in range(item[1] // 2):
... | 7e8fdaabe1eb3aa2cddfdbb9ff69a4ae235b83c3 | 648,149 |
import argparse
def parse_args():
"""Parse in command line arguments"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument(
'--dataset',
help='training dataset')
parser.add_argument(
'--cfg', dest='cfg_file', required=True,
hel... | a0693df53df19bffee3d278af7c352a34322ac3a | 648,150 |
def floor_diff(floor1, floor2):
"""
:param floor1: represents a floor in the building
:param floor2: represents a floor in the building
:return: the distance between both floors
"""
return abs(int(floor1) - int(floor2)) | efba568206a87522d322357544fcd7d6ad1760ba | 648,151 |
import re
def replace_factors(product_string, name, value):
"""Takes a `product_string` and replaces all factors with `name` by `value`.
Arguments:
- `product_string`: input string containing a product
- `name`: name of the factor
- `value`: value of the factor
"""
value = str(value) ... | a742df3a1d2d4eb75c078d5dcf3f7ea7aee18f44 | 648,152 |
def to_readable(o, fields, translated):
"""
Convert object properties to nice title readable
"""
res = {}
if o:
for f in fields:
if o.get(f):
if translated.get(f):
res[translated.get(f)] = o.get(f)
else:
res[... | dc7f61909be3d737d863d436194fb5caea365639 | 648,153 |
def get_chord_notes(chord, a_train=False):
"""Given a chord root, returns list of valid scale notes encoded in extended-duration between 1 and 21
Args:
chord (int): chord root [1,7]
a_train (bool, optional): efaults at False. If True, returns valid scale notes for Take the A Train by Duke ... | ea9e3eb852806edb5316f618cc018b45a31287de | 648,155 |
def delete_tasks(project, params, items):
""" Delete tasks by ids
"""
project.delete_tasks(items)
return {'processed_items': len(items),
'detail': 'Deleted ' + str(len(items)) + ' tasks'} | cf32be2942586c0db6c7d36d35876f8adefcace3 | 648,156 |
def user_to_name(argument):
"""Switch functionality
"""
switcher = {
"lopezobrador_": "A. López Obrador",
"RicardoAnayaC": "R. Anaya Cortés",
"luisederbez": "L. Dervez Bautista",
"RafaMorenoValle": "R. Moreno Valle",
"JCRomeroHicks": "J. Romero Hicks",
"eruvie... | 5d007837f796dac6be4c02ed1850681050092536 | 648,157 |
import math
import random
def get_path(start_position: tuple, end_position: tuple, step: int) -> tuple:
"""
Составляет маршрут до конечной точки, формируя кривую линию.
:param start_position: начальная позиция.
:param end_position: конечная позиция.
:param step: длина шага.
:return: следующую ... | 694db7e1bd3973d080c788f33db1d89f50f405e7 | 648,158 |
import shutil
def dir_remove(rm_dir):
"""
Recursively remove all files in the specified directory
"""
try:
shutil.rmtree(rm_dir)
return True
except:
return False | 0a7421bade215e118bbe505f79ea95d9291f6c4b | 648,159 |
import numpy
def _normalise_image(images):
"""
normalise image to 0.0 to 1.0
:param images:
:return:
"""
# Convert from [0, 255] -> [0.0, 1.0].
images = images - 128
images = numpy.multiply(images, 1.0 / 255.0)
return images | 56997e9eff2611d61cac87d11e4e8feb77dab6b5 | 648,160 |
def index_page():
"""
"""
with open('html/index.html', 'rt') as index_file:
index_page=index_file.read()
return index_page | 5447c879e61d9a46f96d42626778133611c48a4f | 648,161 |
def valid_att_in_label(arch):
"""A `for` and `string` attribute must be on a `label` node."""
return not arch.xpath('//label[not ((@for) or (@string))]') | 268a0b56eecc1964484f6b542d6ff6d3019e99e3 | 648,162 |
def get_x_indicator_variable_index(i, j, k, l, m, n):
"""
Map the i,j,k,l indices to the sequential indicator variable index
as generated by linear_objective_function_coefficients().
This is basically the (4-dimensional) 'array equation' (as per
row-major arrays in C for example).
Note that for... | 2bfa271663b00709cfc9e0b858b4a5f17395970e | 648,163 |
import re
from pathlib import Path
def import_public_key(app_path, device_name, keystring):
"""Import a public key for hyperglass-agent.
Arguments:
app_path {Path|str} -- hyperglass app path
device_name {str} -- Device name
keystring {str} -- Public key
Raises:
RuntimeErr... | 8786cd3bafb23125930b2fd3a6f7f35d265171c1 | 648,164 |
def _toString(cls, typeSpec):
"""
Make flag from string and fail if any unknown words are encountered.
Notes
-----
This converts a flag from ``Flags.A|B`` to ``'A B'``
"""
return str(typeSpec).split("{}.".format(cls.__name__))[1].replace("|", " ") | 569ff5be2540d4bdb83520532bc047cc5f8ab34e | 648,165 |
def infix_string(name, infix, delimiter="."):
"""
:param name:
:param infix:
:param delimiter:
:return:
"""
tokens = name.split(delimiter)
*pre_name, end_name = tokens
name = ''.join([delimiter.join(pre_name), infix, delimiter, end_name])
return name | 6843457e182caea9a72c7862e4bd51a5f24cb617 | 648,166 |
def get_path(it, selector):
"""Finds a value deep within a collection of collections, hopefully without throwing any KeyErrors along the way.
NOTE: Assumes no lists are involved. Please patch to account for these."""
args = selector.split('.')
for arg in args:
if not hasattr(it, 'get'):
return None
it = it.... | 3f25553217d441ee9530b78a86400f756a737e8f | 648,167 |
def heartbeat():
"""return an OK message for simple testing of app deployment"""
return "OK" | 6cde2f3014945b68472941f2d7f886d425158fbe | 648,168 |
import random
def make_marker(bits=64):
""" Return a unique string that , for marking boundaries in text """
# i.e. '|-b1dda1c7f14cd89e-|'
# In python2, hex() on big numbers gives i.e. '0x3333333333L'.
# I'll drop the 1st two and last chars with [2:-1].
return '|-'+hex(random.getrandbits(64))[2:-... | 6b1e09aa68ecea9aae504c0356653b1dbb468292 | 648,169 |
from typing import Callable
from typing import Dict
from typing import Set
def clean_dictionary_of_tmpdir_prefix(remove_tmpdir_path_prefix: Callable) -> Callable:
"""
Cleans a given dependency graph to make it more human-readable. The output
should resemble what a user would see if they ran dgtest in the ... | c33cca84937610368090f86ab226a49c223ed90c | 648,170 |
import os
def which(file):
"""
find a file in the os PATH
"""
for path in os.environ["PATH"].split(":"):
if os.path.exists(path + "/" + file):
return path + "/" + file
return None | d91aaac4f727a60b9ad0b452d56e0e4a30f5c418 | 648,171 |
import sys
import os
def check_argv(this_file, resource):
"""
checks errors
"""
if len(sys.argv) != 2:
print("Usage:", file=sys.stderr)
print("$ ./modules/{} resources/{}".format(this_file, resource), file=sys.stderr)
sys.exit(1)
INPUT_FILE = sys.argv[1]
if not os.path.... | e6fd16d457bf8175d79169e09e7c8008371d44a5 | 648,173 |
def check_if_param_valid(params: dict) -> bool:
"""
Check if the parameters are valid.
"""
for i in params:
if i == "filter_speech_first":
if not type(params["filter_speech_first"]) == bool:
raise ValueError("Invalid inputs! filter_speech_first should be either True o... | 2b6429431b51ea5ee99f3e56ee99099e009ad6f8 | 648,174 |
import re
def html_example(**kwargs):
""" 移除html 标签,转换特殊符号"""
exclude_word = [' ', ' ', ' ']
replace_word = {'<': '< ', '>': '>', '&': '&', '"': '"', '®': '®', '©': '©', '™': '™'}
content = kwargs.pop("content")
cont = re.sub(r'</?\w+[^>]*>', '', conten... | 1db09b0c551c622048beefd9aa0ff7b4a025a239 | 648,176 |
def cursor_fetcher(cursor):
""" Fetcher that simply returns the cursor. """
return cursor | 02d5150975387455d4c2b8ab9081315e72884e64 | 648,177 |
def run_app(qt_app, button_window):
"""Run the QT application."""
button_window.show()
retcode = qt_app.exec_()
button_window.quit()
return retcode | 84fcc2783192683bd7856b57e0fd7fd089b5ad85 | 648,178 |
def fuse_left(A):
"""
Joins the left bond with the physical index.
"""
oldshp = A.shape
d, chiL, chiR = oldshp
A = A.reshape(d*chiL, chiR)
return A | e451755b90db7cbd394b5d7c32000f653f9fb23d | 648,179 |
import math
import torch
def get_mask(input_size, window_size, inner_size, device):
"""Get the attention mask of PAM-Naive"""
# Get the size of all layers
all_size = []
all_size.append(input_size)
for i in range(len(window_size)):
layer_size = math.floor(all_size[i] / window_size[i])
... | a2874f5f9f95e9582bf2fc4ceb22060c32ccdc1b | 648,180 |
def course_data(final_workout):
"""
Return the actual time/power data for the MRC
file
"""
fullmrc = ""
fullmrc += "[COURSE DATA]\n"
start_time = 0
end_time = 0
for interval in final_workout:
fullmrc += "%f %f\n" % (start_time, interval[1])
end_time += interval[0]
... | 3ca8a08d3633d00fa46ee3de41ed12b088eb9faf | 648,181 |
from typing import List
from typing import Tuple
def _apply_SEAR_2(question_postagged: List[Tuple[str, str]]):
"""
SEAR 2: What NOUN -> Which NOUN
"""
output = ""
applied = False
idx = 0
while idx < len(question_postagged):
word = question_postagged[idx][0]
tag = question_p... | 13d831e225b5c8c2e9a4eb01f6fb342af8ee2fed | 648,182 |
def str_code_to_id(str_class_code, class_base=2):
"""
str_class_code: string
"""
id = 0
codes_length = len(str_class_code)
for i in range(codes_length):
id = id + int(str_class_code[i]) * (class_base**(codes_length - 1 - i))
return id | f8fd62e5ad09ce7170a5b2628dfe8d000d2e2568 | 648,183 |
def get_openlibrary_key(key):
"""convert /books/OL27320736M into OL27320736M"""
return key.split("/")[-1] | b4b266e8d79d9b5cd4401439835eff1175ae4d7c | 648,184 |
import os
import logging
import configparser
def read_config(filename):
"""
Read config ini file and return configparser object
Parameters
----------
filename: str
path of ini file to parse
Returns
-------
configparser.ConfigParser(): configparser object
"""
config = No... | dea0fad1a497e9b5ab6b96fe34ed1359d85c82fc | 648,186 |
import requests
def placeimg_com_download(width, height, category):
""""placeimg.com downloader generator.
You can choose width, height and category and it will return argumentless
callable that will donwload such images and return file-like object.
"""
def wrapped_func():
"""Actual call... | 0369f0fc93d03e95cad3c8ed621408a971847a63 | 648,187 |
def deemphasize(marker):
"""Though the knowledge of emphasis is helpful for determining depth, it
is _unhelpful_ in other scenarios, where we only care about the plain
text. This function removes <E> tags"""
return marker.replace('<E T="03">', '').replace('</E>', '') | 6ee1e1b0c8a532950d6a5edfa0d024c06058b94e | 648,188 |
def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.... | 5a4aa5b2908ce40ebbcd69093c528467ee45f31e | 648,189 |
def remove_duplicates(citation):
"""takes dataset as input and drops all unique traffic stop ids' from the d
ataset"""
citation.drop_duplicates(subset='seq_id', keep=False, inplace=True)
return citation | 1e2342fbdfa5b0231ac20855855ed742431ab195 | 648,190 |
def hpo_checkboxes():
"""Returns a list of dictionaries representing HPO checkboxes"""
checkbox1 = {
"_id": "HP:0025190",
"hpo_id": "HP:0025190",
"description": "Bilateral tonic-clonic seizure with generalized onset",
"children": ["HP:0032661"],
"ancestors": [],
}
... | e579b7840ee43962ebda9394dcfb0e6dd1414618 | 648,191 |
def parseTraderGrade(grade):
"""Converts a decimal trader grade into a text representation (defined by NeonMob)
:param float grade: The decimal trader grade to convert
:return: The text representation of the given trader grade
:rtype: str
"""
grades = ['F', 'F+', 'D-', 'D', 'D+', 'C-', 'C', 'C+... | 9121071b4c72bf03e0769f9077661fb58999afbe | 648,192 |
import socket
def uds_reachable(uds_path, return_sock=False):
""" Check if the unix domain socket at path `uds_path` is reachable.
Parameters
----------
uds_path : str
return_sock: bool, optional (default is False)
Return the socket.
Returns
-------
bool, socket
If th... | 4c79a301dc4dfea5a3741325fe5abfc373d4c5e1 | 648,193 |
def delete_ListNode(head, delete_node):
"""
:param head: head of NodeList
:param delete_node: node
:return: head
"""
next_node = delete_node.next
if next_node:
# not del end
delete_node.val, next_node.val = next_node.val, delete_node.val
delete_node.next = next_node.n... | b2d005e4ba1af3cc6cce6db967b8b6ff9a6f204d | 648,194 |
def createRankedClusters(PC, clusterlabels):
"""Create cluster colors from labels."""
clustertypes = set(clusterlabels)
PC_ranked = []
c_and_s = []
for klass in clustertypes:
PC_k = PC[clusterlabels == klass]
PC_ranked.append(PC_k)
c_and_s.append((klass, len(PC_k)))
PC_r... | 870f53ad4c28abab71895f775aa0ad9ebb9ecd1c | 648,196 |
def mid_color(c1, c2):
"""Returns medium color between c1 and c2"""
r = int(0.5 * (c1[0] + c2[0]))
g = int(0.5 * (c1[1] + c2[1]))
b = int(0.5 * (c1[2] + c2[2]))
try:
a = int(0.5 * (c1[3] + c2[3]))
return (r, g, b, a)
except IndexError:
return (r, g, b) | c2a0f7161020cfd7538837c22b48dd418d027616 | 648,197 |
def b_to_s(value):
"""[binary to string]"""
try:
return value.decode()
except:
return value | 02e3d7eb611bba3a29302f2953f42b0df416d02b | 648,198 |
from pathlib import Path
def validate_path(file_name):
"""
Validates if the passed-in argument is a valid path
Parameters
----------
file_name: str
Path to be validated
Returns
-------
tuple
Boolean status and dict to identify if the path is a file or directory
""... | 2c2469268161854104206955258b35a54a3a9222 | 648,200 |
def _get_operator(spec, context):
"""
Gets operator from context
"""
try:
return context[spec]
except KeyError:
print(
f"Error: Operator ${spec} is not defined. Make sure you are importing it in the modules section."
)
raise | bea70c4c49b4b5302d6e60a0a35a5547d764e305 | 648,201 |
import time
import sys
import os
def printC(s='',fontColor='red',backgroundColor='white',displayWay=0,LogPath=''):
"""
默认字体为红色。背景色为白色
能够按照颜色在控制台打印出来。可以自定义背景色和字体颜色。下划线等
:param s:打印的内容
:param str fontColor: red | green | yellow | pink | blue| gray | black
:param backgroundColor: (str) red | g... | f71ce61eabe2ae990f5662ad5fefb51de92d4f71 | 648,202 |
def ese(pred, target):
"""
takes in predicted values and actual values, returns elementwise squared error
via (x-y)^2
"""
errs = (pred - target)**2
return errs | 4a4a444cd9a04d1a56e08f7e491086741bfc8534 | 648,204 |
import os
def get_qafile(date, exp_id):
"""Get the Nightwatch QA file for a given date and exposure ID.
Parameters
----------
date : str
Observation date [YYYYMMDD]
exp_id : int
Exposure ID
Returns
-------
filename : str
Path to Nightwatch qa-*.fits file.
... | 8088afd20261587c7f61427ea9e0d8cd6cddc8e2 | 648,205 |
def obtenir_points(ligne,colonne, joueur):
"""
renvoie les points gagnées sur le mur du joueur en plaçant une tuile dans son mur
dans la ligne et la colonne précisée
"""
points = 1
taille_mur = len(joueur["mur"][ligne])
if colonne < taille_mur-1:
for i in range(colonne+1,taille_mur):... | a28ae5dedd9a34b70af32d35462e0dbd0d5c5874 | 648,206 |
def suffix():
"""Provides a dummy option to use as a suffix for tests."""
return '-ltr' | 9191d0563073225eade28b51ce2cee5c9d501f6e | 648,207 |
def empty_freq_dict():
"""mapping of English letters to their frequency in a text initialized to 0"""
return {
"A": 0,
"B": 0,
"C": 0,
"D": 0,
"E": 0,
"F": 0,
"G": 0,
"H": 0,
"I": 0,
"J": 0,
"K": 0,
"L": 0,
"... | 6f936181e34b582d2f82e5bccdcf73b6aef9eba0 | 648,208 |
import os
def is_running_in_databricks():
""" Check if the currently running Python Process is running in Databricks or not
If any Enviroment Variable name contains 'DATABRICKS' this will return True, otherwise False"""
for k in os.environ.keys() :
if 'DATABRICKS' in k :
return True
... | 7ddae64aec25980d161da4226ec2a400c1469774 | 648,209 |
import os
def if_fs_client_ok(fs_client: str) -> bool:
"""If file-system executable file ok for using with command line.
Args:
fs_client: Ref to `py_dict_rdd2disk`.
"""
client_path: str = os.popen("which %s" % fs_client).read().strip("\n")
return len(client_path) > 2 | 5b8c8f985a5e9e60a071c2286297b61c8b6837d2 | 648,210 |
import time
import socket
def recvTimeOut(open_socket, timeOut=2):
"""
Description
Receive a message of unknown length on socket. While receiving a message, if no
more characters are sent on socket after timeOut seconds, it is assumed that the
message has ended. Therefore, it will always, whatever the lenght ... | 3a1724d04124e1657c342214c4aabda713d7d07d | 648,211 |
def cli(ctx, feature_id, attribute_key, attribute_value, organism="", sequence=""):
"""Delete an attribute from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.delete_attribute(feature_id, attribute_key, attribute_value, organism=organism, s... | 95b6f851b5522e0c258dc14f958c4ec2af52ecff | 648,212 |
def read_list(path):
"""
Reads a list containing one file per line.
Returns an index of line number - line content
"""
with open(path, 'r') as fhandle:
fdata = {}
for nline, line in enumerate(fhandle):
if not line.strip():
continue
# Remove ex... | 7d43ece95a4a062b77395a3a215573c771555911 | 648,213 |
def prepend_experiment(
CONFIG_PARAMS,
datadict,
num_experiments,
camnames,
cameras,
dannce_prediction=False,
):
"""
Adds necessary experiment labels to data structures. E.g. experiment 0 CameraE's "camname"
Becomes 0_CameraE.
"""
cameras_ = {}
datadict_ = {}
new_... | 5cee0161f690e03c8a2d2f26d9a3cdccbbff7bb1 | 648,214 |
import re
def version_cmp(v1, v2):
"""
Compare two version strings and returns:
* `-1`: if `v1` is less than `v2`
* `0`: if `v1` is equal to `v2`
* `1`: if `v1` is greater than `v2`
Raises `ValueError` if versions are not well formated.
"""
vregex = r"(?P<whole>\d+(\.(\d+))*)"
v1... | 46928c36abce879c5c6e1616af668bb2b4dfa5c6 | 648,215 |
from typing import Sequence
def string_list_to_html(string_list: Sequence[str]) -> str:
"""
Converts a string list to an HTML bullet list.
"""
if not string_list:
return "<p>None</p>"
item_list = [f"<li><code>{item}</code></li>" for item in string_list]
return "<ul>" + "".join(item_lis... | c4891a8fb0317d6fd9b5ca14240894e4f30ad15f | 648,216 |
def package_installed(module, package):
"""
Determine if the package is already installed
"""
rc, _, _ = module.run_command(['pacman', '-Q', package], check_rc=False)
return rc == 0 | d934bc0f9db4824f0bbe1d4014fad50021aefb64 | 648,217 |
def wrap(node, tag):
"""Wrap the given tag around a node."""
wrap_node = node.ownerDocument.createElement(tag)
parent = node.parentNode
if parent:
parent.replaceChild(wrap_node, node)
wrap_node.appendChild(node)
return wrap_node | 82126216ebfd0bcd008f27eb24fb0361934bb2c2 | 648,218 |
def square(x):
"""
Return x squared.
>>> square(3)
9
Extra tests:
>>> square(1)
1
>>> square(0)
0
>>> square(-4)
16
"""
return x * x | d431c12ca3d3270e97f6679d139406d8524594fc | 648,219 |
import re
def part1(parser):
"""
count the number of imputs that complete match rule zero
"""
rule_count = 0
for line in parser.inputs:
match = re.match("^"+parser.rules['0']+"$", line)
if match:
rule_count+=1
return rule_count | 3a7730f816f147220412de683ab8fc58773b4804 | 648,220 |
import re
def read_avg_strength(infile):
"""Read residue interaction strength from PSN avg files
:param infile: File handle pointing to WORDOM avgpsn output file
"""
m_start = re.compile("^\*\*\* Averaged Interaction Strength \*\*\*")
m_end = re.compile("^===")
m_entry = re.compile("^\s*.:.\d... | 8cee9f9093ce09f5ea626ba25cc8dfac00aede1a | 648,222 |
import os
import subprocess
def extract_video_frames(video_path, frames_dir,
n, mode='fps', pad=0, verbose=False):
"""Extracts video frames using ffmpeg.
Parameters
----------
video_path : str
Video path.
frames_dir : str
Frames output dir, created if does not exist.
n: int
... | 25eec736aaa9f420822a0512af37faebc96d533f | 648,224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.