content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rayleigh_range(w0, k):
"""
Computes the rayleigh range, which is the distance along the propagation
direction of a beam from the waist to the place where the area of cross
section is doubled.
Args:
w0: waist radius of beam
k: wave number in the direction of propagation of beam
... | b6df563cf0139b65f3ed0067447fc2ea66e0c327 | 656,118 |
from pathlib import Path
def _check_inputs(filepath, order, compact, flatten):
"""
This function checks the input arguments to compute() for validity based
on descriptions below.
Parameters
----------
filepath : Path object
Valid path to file containing nucleotide sequence.
order ... | 71eada00f9ba5cce02758be3694517a6ce929f3c | 656,119 |
from pathlib import Path
def license_key_contents() -> str:
"""
Return a license key suitable for use with the latest version of DC/OS.
"""
return Path('/tmp/license-key.txt').read_text() | 589bf8ca208575cd681b6d3a9f5a7ae3536a50b1 | 656,120 |
def con_end_id(con):
"""id used for connection arrival node after time expansion"""
return con.uid*2+1 | eb178dd692be00ff652e5aa79e7e200f0510830c | 656,122 |
def binary_search(search_list, item):
"""
Finds the middle of the list,
checks where that number is relative to item,
and then splits on the side where item is supposed
to be and repeats this process until item is the
middle index.
List must be sorted
O log(n) time complexity
""... | d7b04220f7d58474806c260eb9ffede2acd63ed4 | 656,123 |
def behind_mt(back, combined):
"""
The author will stand behind the mountain.
Because of backlighting, The front scene is black and the sky is blue.
The front scene will cover the image again to make me look like standing behind mountain.
:param back: SimpleImage, background, this is a sunrise lands... | 6aa254478b449a045fe03b758ce83f1d24325e34 | 656,124 |
def bitmap(num, ind=0):
"""docstring"""
bits = []
bit = ind
while num:
if num & 1:
bits.append(bit)
#
num >>= 1
bit += 1
#
return bits | 5863c00d185b308fc5b1955ef12b065654a7aeea | 656,125 |
import re
def charset_from_headers(headers):
"""Parse charset from headers.
:param httplib2.Response headers: Request headers
:return: Defined encoding, or default to ASCII
"""
match = re.search("charset=([^ ;]+)", headers.get('content-type', ""))
if match:
charset = match.groups()[0... | 50fc897588b94b1b9d9af655244f97a5bb18face | 656,126 |
def parse_reqs(file_path):
"""Parse requirements from file."""
with open(file_path, 'rt') as fobj:
lines = map(str.strip, fobj)
lines = filter(None, lines)
lines = filter(lambda x: not x.startswith("#"), lines)
return tuple(lines) | 5e98df09561d6c89ce5e04dd0207fe288a3c7d8b | 656,129 |
def calculate_position_part2(infile_path: str) -> int:
"""
Read input, determine vertical and horizontal position and return the product of the values
:param infile_path: file path to input file with instructions separated by newlines
:type infile_path: str
:return: product of the vertical and horiz... | 3dfe30a9b4e2971385f610417d2e9cefa34fc1d8 | 656,130 |
def factorial(num, accumlator=1):
"""return factorial of num"""
if num == 1:
return accumlator
return factorial(num -1, accumlator * num) | 37c5c1f4541964a64bd988eb6dd46935ff622cc4 | 656,131 |
import argparse
def process_arguments():
"""Handle user-supplied arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('interface', type=str, action='store',
help='Network interface to listen on.')
parser.add_argument('--cert', '-c', type=str, action='store',
... | d7d7caae00eac9d2861d4390259bdcdaf4af961d | 656,132 |
def get_fpp(links, divisor: int = 4, min_fpp: int = 3):
""" flows per pair is dependent on the size of the links"""
flows_per_pair = max(int(len(links) / divisor), min_fpp)
return flows_per_pair | fa61e775f018791825b6da587f30468def0c8192 | 656,133 |
def not_implemented():
"""NotImplemented: Used for partial comparison implementation."""
class HugeValue:
"""Huge integer."""
def __gt__(self, other):
if isinstance(other, int):
return True
else:
return NotImplemented
huge = HugeValue... | 517ccca082e743c0d74517f438fa68eeee8495a6 | 656,134 |
def config_section_data():
"""
Produce add the default configuration section to app.config,
for fn_api_void when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_api_void]
apivoid_base_url=https://endpoint.apivoid.com
apivoid_sub_url=v1/pay-as-you-go
apivoid_api_key=<your-api-... | 4bc736f68732a74810b3b12d86476e769e317bc8 | 656,136 |
import os
def hasext(f, *exts):
"""判断文件f是否是exts扩展名中的一种,如果不是返回False,否则返回对应的值
所有文件名统一按照小写处理
"""
ext = os.path.splitext(f)[1].lower()
exts = tuple(map(lambda x: x.lower(), exts))
if ext in exts:
return ext
else:
return False | 6532b54941b22ced9dda9d8b302b01f35030b6fb | 656,137 |
import torch
def transform_G_xyz(G, xyz, is_return_homo=False):
"""
:param G: Bx4x4
:param xyz: Bx3xN
:return:
"""
assert len(G.size()) == len(xyz.size())
if len(G.size()) == 2:
G_B44 = G.unsqueeze(0)
xyz_B3N = xyz.unsqueeze(0)
else:
G_B44 = G
xyz_B3N =... | aa7a69f017d2cc3a1dca6caf2daf1f1eed4b4617 | 656,138 |
def gen_actiontype_sequence(uid, action_grouped):
""" 用户订单历史结果构成的序列 """
df = action_grouped[uid]
sequence = ' '.join(df['actionType'].astype(str).values.tolist())
return sequence | 65c24c9019d41dbd7bad94ec0591c1301a604190 | 656,139 |
def _estimate_geohash_precision(r: int):
"""
Returns hueristic geohash length for the given radius in meters.
:param r: radius in meters
"""
precision = 0
if r > 1000000:
precision = 1
elif r > 250000:
precision = 2
elif r > 50000:
precision = 3
elif r > 1000... | ecc96c5e991fb9792993b58ae77263935be44034 | 656,140 |
def merge_dicts(dict_a, dict_b):
"""Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a
:param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a
therefore is a default dicti... | 32e2823a7491f916fcdab8a28b94d5027c1f0306 | 656,141 |
def ensure_list(val):
"""Converts the argument to a list, wrapping in [] if needed"""
return val if isinstance(val, list) else [val] | 10ec23fac23e27defbf5a9325f3c863f8c0b6d50 | 656,142 |
import string
import random
def name_generator(size=6, chars=string.ascii_uppercase + string.digits):
""" Script that renames the file with trained model
Keyword arguments:
file_path -- path to the file
... params needed to constuct new name
Returns: ...
"""
return ''.joi... | fb7eacb9f79c12859b18dbbfcd11e464fc2268d9 | 656,143 |
import time
def edge_compute(track_id, image):
"""
computing part
"""
time.sleep(1)
feature_map = [0.0] * 16
return [1.0] + [0.0] * 9, feature_map | 891e402c61db5c62abbbb5391b2abfd2e839508d | 656,144 |
def k_fold(k, data_length):
"""
Returns indices for training, validation, and testing data
Args:
k - (int) Number of folds, minimum 3
data_length - (int) Total number of items in data
Returns:
train - (list)
validation - (list)
test - (list)
"""
assert k >... | 57b195c164b3fc05539fbc57f89b52fd33ee55ab | 656,145 |
def _process_id(url, tag):
"""
Extract an ID from a url (or just return the URL).
"""
if tag == 'tweet':
parts = url.split('/')
return parts[5]
else:
return url | 4c95cca427f95d178047b8147cf5d237e979b960 | 656,146 |
import numpy
def sample_from_distribution(dist):
"""dist is a dictionary of keys and their probabilities. Output is a single key sampled at random according to the distribution of probabilities."""
vals = []
probs = []
for k in dist:
if dist[k] is not None:
vals.append(k)
... | 01b65006bfa6b12ebe90c4e87fa8c8880ff55b5c | 656,147 |
def rttime(s):
"""返回时间分钟"""
if not s//60:
return '{:.0f}秒'.format( s % 60)
else:
return '{:.0f}分,{:.0f}秒'.format(s // 60, s % 60) | 5c6a54068d60ca0d3be03222c52f2da57cac0603 | 656,148 |
import os
def get_qualified_class_name_from_file(class_file_name, class_file_path):
""" terrible hack for now """
suffix = class_file_name.replace(class_file_path+os.sep, "")
mid_section = suffix.replace(".class", "")
return mid_section.replace(os.sep, ".") | 51bdef7e4f7ca27d3fc2eb570b0966b4a9e832db | 656,149 |
def _inc_volname(volfile, i, inc_chars):
"""increase digits with carry, otherwise just increment char
"""
fn = list(volfile)
while i >= 0:
if fn[i] == "9":
fn[i] = "0"
i -= 1
if i < 0:
fn.insert(0, "1")
elif "0" <= fn[i] < "9" or inc_ch... | df86052a769ac74dcccf8b623305f77011b08c31 | 656,150 |
def hideCells(notebook):
"""
Finds the tag 'hide' in each cell and removes it
Returns dict without 'hide' tagged cells
"""
clean = []
for cell in notebook['cells']:
try:
if 'hide' in cell['metadata']['tags']:
pass
else:
clean.appen... | 5920cbc30720bd637d11f14fea363797f328c099 | 656,153 |
from pathlib import Path
def parse_pb_name_data(file_name):
"""Returns data encoded in extraction files, such as datetime or itp id.
>>> parse_pb_name_data("2021-01-01__1__0__filename__etc")
{'extraction_date': '2021-01-01', 'itp_id': 1, 'url_number': 0, 'src_fname': 'filename'}
"""
extraction_... | c7f8be4638b6ddfe47475665ca8a3d9a31055000 | 656,155 |
def _apply_to_sample(func, sample, *args, nest_with_sample=0):
"""Apply to a sample traversing the nesting of the data (tuple/list).
Parameters
----------
func : callable
Function to be applied to every sample data object
sample : sample object or any nesting of those in tuple/list
... | 46fef5b4e32086a1fbcde4d1b63664c9ba9632f4 | 656,157 |
import re
def _translate_works_status(ws):
"""
multiple work stati are combined
:param ws: string of work status code
:return: new code
"""
if re.match(".*0$", ws):
return "a"
elif re.match(".*1$", ws):
return "b"
elif re.match(".*2$", ws):
return "c"
elif r... | 01a1d1793c277de33d68c77fe3682f63e9bda26c | 656,158 |
def exporter_memory_metrics_csv(test_result_ext, test_suite_properties=None):
"""! Export memory metrics as CSV
@param test_result_ext Extended report from Greentea
@details This function will create a CSV file that is parsable via CI software
@return String containing the CSV output
"""
metric... | 2142c49cbe482b266fc2a2c8d228c43ded7c327f | 656,159 |
def divide_contigs_chr(contigs, test_chr, valid_chr):
"""Divide list of contigs into train/valid/test lists
by chromosome."""
# initialize current train/valid/test nucleotides
train_nt = 0
valid_nt = 0
test_nt = 0
# initialize train/valid/test contig lists
train_contigs = []
valid_contigs = []
... | 86027143cee7e8884d3c9f96b5768ab928c364ca | 656,160 |
import json
def to_json_str(content: dict) -> str:
"""
serialize the JSON object to str \n
:param content: the target JSON object
:return: the JSON str
:rtype str
"""
return json.dumps(content, ensure_ascii=False) | 7730c411bb7612f6bcabb881eba40b8224e72dd3 | 656,162 |
import os
import platform
def get_maya_location(version):
"""Find the location of maya installation
If MAYA_LOCATION is present in system and/or user variables mayatest
will use whatever is stored there.
"""
if 'MAYA_LOCATION' in os.environ:
return os.environ['MAYA_LOCATION']
try:
... | bfcd316bdd9d60e30318720291c6bd51bba5acac | 656,163 |
def long_description():
"""
long_descriptions -> str
Return the long description text.
"""
with open("README.rst") as r:
long_description_1 = r.read()
with open("HISTORY.rst") as h:
long_description_2 = h.read()
return "\n".join([long_description_1, long_description_2, ]) | 75de05f440f5c2bf9790f259735123d74a2e9a86 | 656,164 |
def camelcase(s: str) -> str:
"""Convert snake case to camel case.
Example:
>>> camelcase("camel_case")
'camelCase'
"""
parts = iter(s.split("_"))
return next(parts) + "".join(i.title() for i in parts) | 3ccfa02c2bc7f6e590c3e445c9033e7e15568f1a | 656,165 |
def only_one(l):
"""false if list l contains more than one element"""
if len(l) != 1:
return(False)
else:
return(True) | 505e9bc478b0e9f14a840f12f456592f87758c90 | 656,166 |
import argparse
def get_argparse():
""" Return a littlecheck argument parser. """
parser = argparse.ArgumentParser(
description="littlecheck: command line tool tester."
)
parser.add_argument(
"-s",
"--substitute",
type=str,
help="Add a new substitution for RUN l... | 70a3dafa9b34ecc6e998ea153c30cc4520428269 | 656,167 |
def introducir_numero():
"""funcion que sirve para controlar que los datos que se introducen son correctos, es decir,
si se introduce un dato que no sea un número entero pide que se introduzca otra vez el dato"""
while True:
try:
num = int(input ("Ingrese un número entero",))
... | 63229cc09dba589778e1130b0599cf37482ecfc1 | 656,168 |
def link_regulator(incoming_links: list) -> list:
"""
Regulates the links coming from Google Search.
Input URL: "/url?q=https://www.example.com/SparqlEndpoint&sa=U&ved=2ahUKEwiU"
Output URL: "https://www.example.com/SparqlEndpoint"
:param incoming_links: List of links to be regulated
:return:... | 9c7c451c65da2f3f0240c26903cdfe2a9ced1913 | 656,169 |
import warnings
def _check_csv_params(**read_csv_params: dict):
"""
Args:
**read_csv_params: Read parameters.
Returns:
New parameters.
"""
for par in ['skiprows', 'nrows', 'index_col', 'header', 'names', 'chunksize']:
if par in read_csv_params:
read_csv_param... | 6000ad8931d59336202ee718e402392d085cd4e3 | 656,170 |
def middleware(get_response):
"""Set up middleware to add X-View-Name header."""
def add_view_name(request):
response = get_response(request)
if getattr(request, 'resolver_match', None):
response['X-View-Name'] = request.resolver_match.view_name
return response
return add... | 66d3f9179f3b35e18c474870806e72643d58a508 | 656,171 |
import sys
def RawScaffoldSequence():
"""
Returns raw scaffold sequence from input file
"""
print("Parsing scaffold sequence...")
# Find scaffold sequence file location from argument input
if len(sys.argv) < 3:
sys.exit(
"Not enough files provided.\nPlease use \"Python3 s... | c4831f43ddad20124d3f424705313e61e747a246 | 656,172 |
def enumerated_subsections(request):
"""Parametrized fixture of each subsection along with its index in the parent section."""
return request.param | 8433794d32e3913d8db5706367341f232db0cee4 | 656,173 |
import requests
import gzip
def _download(url: str, dst_file: str, timeout: int = 60):
"""Download file at URL."""
r = requests.get(url, stream=True, timeout=timeout)
r.raise_for_status()
with open(dst_file, "wb") as f:
if url.endswith(".gz"):
f.write(gzip.decompress(r.content))
... | ac7f60b904ebc8fcc1cca1fea059d55e2e5a11d3 | 656,174 |
def _MapObjcType(t, other_types):
"""Returns an Objective-C type name for the given IDL type."""
if t.element_type:
assert t.name == 'sequence'
return 'NSArray<%s>*' % _MapObjcType(t.element_type, other_types)
elif t.name in other_types:
return 'Shaka%s*' % t.name
else:
type_map = {
# ID... | 1604d372fa81feaaada09eb4c8551a1412e34afa | 656,175 |
def seq_names(fasta_file):
"""Get sequence names from fasta file."""
names = []
f = open(fasta_file)
fasta = f.read()
f.close()
for a in fasta.split(">"):
names.append(a.split("\n")[0])
return [a for a in names if a != ""] | 3fdc152552534353f75355004f37a3a7f923d488 | 656,176 |
def dict_to_aws_tags(d):
"""
Transforms a python dict {'a': 'b', 'c': 'd'} to the
aws tags format [{'Key': 'a', 'Value': 'b'}, {'Key': 'c', 'Value': 'd'}]
Only needed for boto3 api calls
:param d: dict: the dict to transform
:return: list: the tags in aws format
>>> from pprint import pprin... | 12680d9ccd1cfc04a6ac94910256d52018daa22d | 656,177 |
def is_comment_start(line):
"""Determine whether a *line* starts a new multi-line comment.
:param line: A properties line
:type line: unicode
:return: True if line starts a new multi-line comment
:rtype: bool
"""
stripped = line.strip()
return stripped.startswith('/*') and not stripped.... | 74e4f63e6a397fe7db12ed9a1c1e19fe080de6b7 | 656,178 |
def legrende_polynomials(max_n, v):
"""
Returns the legendre polynomials
Based on the algorithm here:
http://uk.mathworks.com/help/symbolic/mupad_ref/orthpoly-legendre.html
"""
poly = [1, v] + [0] * (max_n - 1)
for n in range(2, max_n + 1):
poly[n] = (2 * n - 1) / n * v * poly[n - 1]... | b714d84557c68cbd9ad58d8a41526b2b6033cc34 | 656,179 |
def agg_count_distinct(df, group_key, counted_key):
"""Returns a Series that is the result of counting distinct instances of 'counted_key' within each 'group_key'.
The series' index will have one entry per unique 'group_key' value.
Workaround for lack of nunique aggregate function on Dask df.
"""
re... | 9b980bf649ecfc1e240d09aae1eb79798f638a20 | 656,180 |
def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross s... | e85917e62d0ded26a57fa5f74a6f7d6db1c9d53e | 656,181 |
def get_err_msg(code):
"""
This function formats an error message depending on what error code is
generated by the HTTP request. We wrap the error message in a HTML page
so that it can be displayed by the client.
"""
if code == '404':
str = 'Function Not Implemented'
else:
st... | 7f08705f662a18cbe07fc4df8d2644b90a4e68df | 656,182 |
from typing import Counter
def count_neuron_frequency(neurons):
"""
Calculate neuron frequency for given labels sorted by id number and frequency (ensure the same frequency still keep sort by number )
Counter usage example: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elem... | b0c6601be8036d62581587f0f6b986f93ce6e6b0 | 656,183 |
import os
def get_package_name():
"""Return the model pkg name.
It is used by model pkg developer.
"""
return os.environ.get("_MLHUB_MODEL_NAME", "") | acd99fba9b312d32728fae6097d1382a446c59f1 | 656,184 |
def calculate_opt_dt(a, D):
"""Calculates the optimal dt based on size of pore
and diffusion coefficent
returns a value for dt
"""
return (a*1e-3) / (6*D) | 1520abdcc9c8cff0b83a89233eaf8e9aeda801d0 | 656,185 |
def read_infile(infile):
""" Read a .in file
"""
data = dict()
for line in open(infile, 'r'):
line = line.strip()
if line.startswith('#') or len(line)==0:
continue
line = line.split('!')[0]
namevalue = line.split('=')
if len(namevalue)==2:
name, value = namevalue
name = nam... | 5327e78f39620fd31712617458faee1e3134f9a2 | 656,186 |
def csv_format_gaus(gaus):
"""flattens and formats gaussian names and bounds for CSV file"""
# gaus_names = []
# gaus_bounds = []
gaus_flat = []
for g in gaus:
gaus_flat.append(g[0] if g[0] else "-")
this_bounds = [g[5],g[6],g[1],g[2],g[3],g[4]]
gaus_flat += this_bounds
# return gaus_names, gaus_bounds
ret... | 82a853e540853d434fe9a1ba907c6afc1d6495b6 | 656,187 |
import re
def aggregate_alignments(align_tokens):
"""
Parse the alignment file.
Return:
- s2t: a dict mapping source position to target position
- t2s: a dict mapping target position to source position
"""
s2t = {}
t2s = {}
# process alignments
for align_token in align_tok... | 101aff41e0c8a3e311e765a70535ca4fee13535f | 656,188 |
import numpy
def roofline(num_platforms, peak_performance, peak_bandwidth, intensity):
"""
Computes the roofline model for the given platforms.
Returns The achievable performance
"""
assert isinstance(num_platforms, int) and num_platforms > 0
assert isinstance(peak_performance, numpy.ndarray)... | d19e6ffb20513a1dd9875b35d839efa3d559bb36 | 656,189 |
def check_digit(option, num, min, max):
"""
文字列numが整数かチェックし, min-maxの範囲の数値であればTrueを返す
Args:
option: エラーメッセージに表示する文字列を指定. ''の場合はエラーメッセージを表示しない.
num: チェックする文字列
min: 数値の範囲の下限
max: 数値の範囲の上限
Returns:
bool: Trueなら問題なし. Falseなら整数でないか範囲外.
"""
val = False
try:
num_int = int(num)
... | c1a88535e8784bf0b8fd414ed72cce735296ea6c | 656,190 |
def thermal_diffusivity(tc, density, Cp):
"""
calc.thermal_diffusivity
Calculation of thermal diffusivity
Args:
tc: thermal conductivity (float, W/(m K))
density: (float, g/cm^3)
Cp: isobaric heat capacity (float, J/(kg K))
Return:
Thermal diffusivity (float, m^2/s... | 1edbf2489488d77d9028283569e1dc9372acc3d4 | 656,191 |
def hello():
"""
Simple GET call.
"""
return {"message": "Hello World!"} | a87f18c7763bcb17528f652adcfb275538164213 | 656,193 |
import gzip
def avg_fastq_quality(fastq_gz: str) -> float:
"""Calculate the mean quality for a set of sequencing reads in gzipped
FASTQ format with a quality offset of 33.
fastq: Path to a gzip-compressed FASTQ formatted set of sequencing reads
"""
total_length = 0
total_quality = 0
# D... | 89e706a7ddfae6fbf46c7deb577058047cc5cc02 | 656,195 |
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these... | 93a32d74674dc0a01d060fddd408ad93a08b77f7 | 656,196 |
def to_float(value: str) -> float:
"""Convert value to a floating point number"""
return float(value) | b6143a9211cd385bfd4ff6f171e01ce1a584b781 | 656,197 |
def count_min_flips(s: str) -> int:
"""https://leetcode.com/problems/flip-string-to-monotone-increasing"""
count_one = count_flip = 0
for char in s:
if char == '1':
count_one += 1
else:
count_flip = min(count_flip + 1, count_one)
return count_flip | dacb9fab7cf96f41c07933bd7470013e1ec22e28 | 656,198 |
def validate_on_batch(
network,
loss_fn,
X,
y_target
):
"""Perform a forward pass on a batch of samples and compute
the loss and the metrics.
"""
# Do the forward pass to predict the primitive_parameters
y_hat = network(X)
loss = loss_fn(y_hat, y_target)
return (
loss... | 9502bd0f04bc4c8504442e6952f514dbe3044e1d | 656,199 |
def returns(a_0, a_1):
"""linear returns formula"""
return (a_1 - a_0) / a_0 | 12e954d11b63ddfe832576989f6a89ec40e01e69 | 656,201 |
def remove_islands(matrix):
"""
for each row check row
for each index in row check same index in all rows
"""
pass
return matrix | 0bbc97c36ce8ee98ee54145065085f461dd407ac | 656,202 |
import platform
def is_rhel():
""""Check if OS is RHEL/Centos"""
return 'el' in platform.uname()[2] | bf78ef848b7de2ac183ed203645110db8c105dd9 | 656,203 |
def create_rule_based_input(citation_list, gold_labels_set=None):
"""Creates the expected input format for the rule based candidates from a citation list
output of the rule based model. This function is intended to be used for processing
test data, as the main function in this file will convert and sa... | 988b26cedb7932defa4da5399ea25656d486a16e | 656,204 |
def live_data2csv(dat, sep, header=True):
"""returns csv from live data dict"""
# define columns and assemble header
cols = (
"date",
"weekday",
"time",
"value",
"rawvalue",
"unit",
"range",
"mode",
"hold",
"apo",
"powe... | 5ba4558ebd198133ebe8fbf074f8a5044c12b466 | 656,205 |
def reopen_normal_read(file_obj, encoding):
"""Re-open a file obj in plain read mode"""
return open(file_obj.name, "r", encoding=encoding) | 65c927d9b349ad40f9a52927647bbe83ddf3b474 | 656,206 |
def unwrap_solt(dc):
"""
Extracts the augmented image from Solt format.
:param dc: Solt datacontainer
:return: Augmented image data
"""
return dc.data | 200498792ee8b4d590fb7701409c76810b22bc5a | 656,207 |
import yaml
def read_config(file_path) -> None:
""" read yaml config file and modify special properties"""
print(f"read_config: {file_path}")
with open(file_path, "r") as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
return cfg | 9d075701b78e5c5147029ef11a5b29de4869dab1 | 656,208 |
import functools
import sys
def onlyPy27OrNewer(test):
"""Skips this test unless you are on Python 2.7.x or later."""
@functools.wraps(test)
def wrapper(*args, **kwargs):
msg = "{name} requires Python 2.7.x+ to run".format(name=test.__name__)
if sys.version_info < (2, 7):
pyte... | f00f842f4c6331e92a30a41e30ceb6699aae6e95 | 656,209 |
import json
def dumps(var, indent=None):
"""python json dumps"""
return json.dumps(var, indent=indent, ensure_ascii=False) | f5c11105c752e96eba7404b4eb920c21c9be6ce0 | 656,210 |
def seen(params):
"""'.seen' & user || Report last time Misty saw a user."""
msg, user, channel, users = params
if msg.startswith('.seen'):
return "core/seen.py"
else:
return None | 2ddcf05ebb0edd83ac45574a9a682635b7914c94 | 656,211 |
import os
import subprocess
import sys
def error_check_python(filename):
"""
Check to see if there are any errors by checking the return
status of python after attempting to interpret the code.
"""
with open(os.devnull, "w") as devnull:
p = subprocess.Popen("python {}".format(filename).spl... | f15de2f54c877bcd1b5681d4d44933587aa1209f | 656,212 |
from typing import Dict
from typing import Any
def merge_dicts(*args: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Successively merge any number of dictionaries.
>>> merge_dicts({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
>>> merge_dicts({'a': 1}, {'a': 2}, {'a': 3})
{'a': 3}
Returns:
Dict: ... | 68cf2046f830610a9b386edebc8f16671dfc9293 | 656,213 |
import calendar
def get_month_number(month):
"""
Returns corresponding month number from month name
"""
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
month_number = abbr_to_num[month.capitalize()[:3]]
return month_number | e541d930c18724a59271fddf5e9251e110589ee7 | 656,215 |
def get_provenance_record(caption: str, ancestors: list):
"""Create a provenance record describing the diagnostic data and plots."""
record = {
'caption':
caption,
'domains': ['reg'],
'authors': [
'kalverla_peter',
'smeets_stef',
'brunner_lukas... | b4eba250f5a581989c80a8de727d7ed3e034bdd6 | 656,217 |
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = "red" if val < 0 else "black"
return "color: %s" % color | 34f52a7311f7284a1c861c23b0ae31f52d905feb | 656,218 |
def compute_document_vector(document_id, query, vocabulary, index):
"""Return the vector for a document, to be used in the cosine similarity check."""
vector = [0.0]*len(query)
for i, query_term in enumerate(query):
for current_doc_id, tfidf in index[vocabulary.index(query_term)]:
if do... | d7dfbc6f85f35aee8d52c3001606c55f61787cd5 | 656,220 |
def _human_readable(size_in_bytes):
"""Convert an integer number of bytes into human readable form
E.g.
_human_readable(500) == 500B
_human_readable(1024) == 1KB
_human_readable(11500) == 11.2KB
_human_readable(1000000) ==
"""
if size_in_byt... | e718b1cc047a1a7793e5c6a88d4251c17bf5fd0d | 656,221 |
def flatten_list(a, result=None):
"""Flattens a nested list.
>>> flatten_list([ [1, 2, [3, 4] ], [5, 6], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
if result is None:
result = []
for x in a:
if isinstance(x, list):
flatten_list(x, result)
else:
result... | 81dc2911951b8d2611b18219da92cbed1e64fa4a | 656,222 |
import itertools
def record_list(games, wins):
"""
Inputs:
games (integer) - total number of games played
wins (integer <= games) - total number of games won
Returns:
record_list (list) - all possible ways record could be achieved as binary
"""
record = list()
losses =... | f6fc39d0b2db81519b5919dbf745f5e2fb99d3e1 | 656,224 |
from pathlib import Path
import sys
def get_api_key_from_file(filename):
""" Return the API key from the first line of filename
Read the api_key from filename.
Parameters
----------
filename: str | pathlib.Path
The filename to read to get the api key
Returns
-------
api_key:... | 988137f97a12b31d11917c9694b58888b8405d85 | 656,225 |
def match_line(file_name, pattern):
""" loops through given file and returns first line matching given pattern
:returns: string with the matching line without end of line or None
"""
try:
with open(file_name, encoding="latin-1") as file_:
for line in file_:
if not li... | 7de0e337ae2205158e7956aeb8e3a5b853506aee | 656,226 |
def formula_to_flatzinc_bool(formula):
"""Converts a formula to a MiniZinc model using booleans."""
vardefs = []
constraints = []
boolvars = []
for i, n, t in formula:
if t == "atom":
if str(n.probability) == "?":
vardefs.append("var bool: B%s :: output_var;" % i... | e758244d90b7e7e1e3d42a877865ae5c469769a4 | 656,227 |
from typing import Union
import pathlib
import os
def last_n_bytes_of(target: Union[str, pathlib.Path], n: int = 1) -> bytes:
"""Return the last `n` bytes from a file, defaults to 1 byte."""
with open(target, "rb") as f:
f.seek(0, os.SEEK_END)
f.seek(f.tell() - n)
return f.read(n) | 9f015dc1a4abf2c715c02bb63add34ba45a08f5a | 656,228 |
import io
def spit(path, txt, encoding='UTF-8', append=False):
"""
Write a unicode string `txt` to file `path`.
By default encoded as UTF-8 and truncates the file prior to writing
Parameters
----------
path : str
File path to file on disk
txt : unicode
Text content to wr... | 75b406f81068006aba61f34395590b8a1948a469 | 656,229 |
def compare_candidates(art1, art2, art3, ft):
"""
compare edges of three nodes and calculate their shared and differed edges to examine if they could be merged
:param art1: first article to compare
:param art2: second article
:param art3: third article
:param ft: 'from' or 'to', determines if in... | abcd517a562eae861e1aa6d945edcc8f9448a8c5 | 656,230 |
def check_na(df, norm=False):
"""quick check the missing value stats for each column in a df."""
if norm:
return df.isna().sum()/df.shape[0]
else:
return df.isna().sum() | da716cff19e0dbbcf09258624bc7f9cfdcc605cd | 656,231 |
def indice_to_pos(image_size, indice):
"""Converts indice of a pixel in image(index number in array of pixels) to x,y coordinates.
Args:
image_size:
indice: index number in image's array of pixels.
Returns:
tuple: pair of values representing x,y coordinates corresponding to given i... | 05b46f4f2f5b782de9c9d310f1b3cd92c9ded985 | 656,232 |
def type_impl(context, builder, sig, args):
"""
One-argument type() builtin.
"""
return context.get_dummy_value() | cdf3cd9c708ddebb57220e8263595d79abc6c34f | 656,233 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.