content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _mpi_param_value(mpi_args, env, param_name, default=None):
"""Placeholder docstring"""
return mpi_args.get(param_name) or env.additional_framework_parameters.get(param_name, default) | 8478f5279380ed853c59f879429a93e897ad058f | 678,788 |
def read_lines(filename):
"""Read all lines from a given file."""
with open(filename) as fp:
return fp.readlines() | f3005b1e1bc8a98fe543a1e364eec70ad4d85188 | 678,789 |
import csv
from contextlib import suppress
def read_csv(filename):
"""
Reads csv files and returns them as a list of lists.
"""
results = []
with open(filename, newline='') as _file:
csvreader = csv.reader(
_file,
skipinitialspace=True,
)
for row... | d837f677cba00f396142db1793bb6a75e13377f6 | 678,790 |
import os
def last_dir(fname):
"""Splits pathnames into the last dir plus the filename.
:param fname: file name
"""
dirname, plain = os.path.split(fname)
prefix, last = os.path.split(dirname)
return last, plain | 1e4fc1206f1ca0f5e076e8efff8e32bdf9fec6d8 | 678,791 |
def split_board(board):
""" split board for possible winning combinations """
row1 = board[0]
row2 = board[1]
row3 = board[2]
diag1 = [row1[0], row2[1], row3[2]]
diag2 = [row1[2], row2[1], row3[0]]
col1 = [row1[0], row2[0], row3[0]]
col2 = [row1[1], row2[1], row3[1]]
col3 = [row1[2],... | 54672aaa69956c50c5bb29317883b55e23bf11a9 | 678,792 |
import os
def filename(file, include_extension):
""" Get the File Name including extension, or just the name of the file """
if include_extension:
# file.ext
return os.path.basename(file)
else:
# file
filename_, file_extension_ = os.path.splitext(file)
return os.pat... | b8610e31f1ac6cd216d4d6b73ac6fb7f2178e907 | 678,793 |
def prepToMatlab(detectorName, quantity):
"""Create a name of a variable for MATLAB"""
return detectorName + "_" + quantity | 16fd3d7d0f0b316da8afc7d2c14d24515ed0c2c4 | 678,794 |
from pathlib import Path
import re
def get_files(folder, name, indexes=None):
"""Get all files with given name in given folder (and in given order)
Parameters
----------
folder : str
path to files (folder name)
name : str
file name pattern
indexes : list
files order
... | 0fbeccc458e3f423af4c491d31f88d7764187da9 | 678,795 |
def total_words_extractor(word_tokens):
"""total_words
Counts the number of words in the text.
A "word" in this context is any token.text in the spacy doc instance which does
not match the regular expression '[^\w]+$'.
Known differences with Writeprints Static feature "total words": None.
No... | 348b3e00da823a044393be6f49d0ef02935a1972 | 678,799 |
def update_face(data):
"""update face user"""
return True | 4db9c08806727e06467eac0f94a3686782e36715 | 678,800 |
def literal(c, code):
"""literal value 0x00-0x1F (literal)"""
v = "0x%04X" % (code - 0x20)
return v | 9a98d1cf5cde8c5249be93959f86d433b1898178 | 678,801 |
import argparse
def build_cmd_interface():
""" Builds the command line interface parser using argparse.
Returns the parser built.
"""
parser = argparse.ArgumentParser(
description='Utility to bridge Pharo and Python through JRPC protocol.')
parser.add_argument('requests_count', metava... | 8befc2e7c9dc385c95b2def589b507c392122e6f | 678,802 |
import os
def get_filepaths_from_dir(dir_path):
"""Recursively walk through the given directory and return a list of file paths"""
data_list = []
for (root, directories, filenames) in os.walk(dir_path):
directories.sort()
filenames.sort()
for filename in filenames:
data... | 923031f680b18bc0cb5ff48d92f99e5c33652315 | 678,803 |
def get_phred_encoding():
"""Return a dict of {ascii character: quality score} providing an
encoding of ASCII characters 33 to 126 corresponding to values 0
to 93.
see https://en.wikipedia.org/wiki/FASTQ_format
"""
offset = 33
return {chr(i): i - offset for i in range(offset, 127)} | 23b29954b430f73d6c01fda9ed2842cc41941156 | 678,804 |
import click
def bool_option(name, short_name, desc, dflt=False, **kwargs):
"""Generic provider for boolean options
Parameters
----------
name : str
name of the option
short_name : str
short name for the option
desc : str
short description for the option
dflt : boo... | daadefb05964163df6f77bfd42f4d63157d895c7 | 678,805 |
import imp
import sys
def new_module(name):
"""
Do all of the gruntwork associated with creating a new module.
"""
parent = None
if '.' in name:
parent_name = name.rsplit('.', 1)[0]
parent = __import__(parent_name, fromlist=[''])
module = imp.new_module(name)
sys.modules[... | 6b589c7440830e50bf5f89b8f3b40dbffc53f28c | 678,806 |
import numpy
def mirror_uvw(uvw, vis):
"""Mirror uvw with v<0 such that all visibilities have v>=0
The result visibilities will be equivalent, as every baseline
`a->b` has a "sister" baseline `b->a` with a complex-conjugate
value. A dataset typically only contains one of the two, so here
we simpl... | 25bd2f8e3d383944e0cb8772214ae1343db24850 | 678,808 |
def seqStartsWith(seq, startSeq):
"""
Returns True iff sequence startSeq is the beginning of sequence seq or
equal to seq.
"""
if len(seq) < len(startSeq):
return False
if len(seq) > len(startSeq):
return seq[:len(startSeq)] == startSeq
return seq == startSeq | 5e9b910c05b3767045a09860f1e1daa203ab99a3 | 678,809 |
import hashlib
import os
def _md5_of_file(sub_string):
"""
This will return the md5 of the file in sub_string
:param sub_string: str of the path or relative path to a file
:return: str
"""
md5 = hashlib.md5()
file_path = sub_string
if not os.path.exists(file_path):
file_pat... | 7b417a5b5377414ce75cfd9f5947373ef7243759 | 678,810 |
import os
import requests
def setup_logging_zone():
"""
Attempt to get the project zone information.
return: Zone pb2 structure.
"""
zone = 'local-machine'
if 'GAE_SERVICE' in os.environ:
try:
resp = requests.get('http://metadata.google.internal/computeMetadata/v1/instance/... | 72b7f3d83728f0af78b967f38ab68d4c3f5c17ce | 678,812 |
def calc_center(eye):
"""
Using for further cropping eyes from images with faces
:param eye:
:return: x, y, of center of eye
"""
center_x = (eye[0][0] + eye[3][0]) // 2
center_y = (eye[0][1] + eye[3][1]) // 2
return int(center_x), int(center_y) | dc6fd0eebda480409fee28b7c4f2aded98a2044f | 678,813 |
def xyz_datashape(al, xyz):
"""Get datashape from axislabels and bounds."""
x, X, y, Y, z, Z = xyz
if al == 'zyx':
datalayout = (Z - z, Y - y, X - x)
elif al == 'zxy':
datalayout = (Z - z, X - x, Y - y)
elif al == 'yzx':
datalayout = (Y - y, Z - z, X - x)
elif al == 'yx... | 8215b7f5341a7f7e4d70c57c4641abfbf9f0e941 | 678,814 |
def has_group(user, group_name):
"""
Verify the user has a group_name in groups
"""
groups = user.groups.all().values_list('name', flat=True)
return True if group_name in groups else False | 094123f614873d049406059d53e7ab5a6e8224d2 | 678,816 |
from datetime import datetime
def get_file_name_by_time():
"""
根据当前时间获取一个文件名
:return: 文件名
"""
time_now = datetime.now()
return str(time_now.year) + '-' + str(time_now.month) + '-' + str(time_now.day) + '_' +\
str(time_now.hour) + '-' + str(time_now.minute) + '-' + str(time_now.second) | 1c40affc7f48e03d8cfd688d367143f2af6b66c6 | 678,817 |
import sys
def _system_library_dirs():
"""
:return: Platform dependent relative paths to directories containing library
files.
:rtype: str
"""
if sys.platform == "win32":
return ["bin"]
else:
return ["lib64", "lib"] | fffd3c8d7afa3f4cbb719c066afa46e5a4121e0f | 678,818 |
def output_dim(request) -> int:
"""Output dimension of the random process."""
return request.param | 741c55ef387786193b345d3eed1532197aa6de3c | 678,819 |
import os
def basename_and_extension(file_path):
"""
>>> file_path="a/b.c"
>>> basename_and_extension(file_path)
('b', '.c')
:param file_path:
:return:
"""
return os.path.splitext(os.path.basename(file_path)) | 0498621a12364684dda9f0b72f5cd1adea852267 | 678,820 |
from typing import List
import re
def clean_ud_tags(sents: List[str]) -> List[str]:
"""
Remove non-UD tags from input CoNLL-U sentences
Parameters
----------
sents: List[str]
List of str on CoNLL-U format.
Returns
-------
List[str]:
List of str with respective pos-tag... | 9a25a6ff10cccda4d707872af973ae48d79d3400 | 678,821 |
def movie(m,num):
"""iiehgf o h ghighighi"""
return m/num | 7d419ea970ebfbd23ace4d53ab7216f2648665b3 | 678,822 |
from typing import Tuple
from typing import Optional
def get_max_rdt_values(cbm_mask: str, platform_sockets: int,
rdt_mb_control_enabled, rdt_cache_control_enabled) \
-> Tuple[Optional[str], Optional[str]]:
"""Calculated default maximum values for memory bandwidth and... | 58227b7df90ce222e69879059d5ed47d687919f2 | 678,823 |
def _none():
"""Create registry entry for NoneType."""
entry = {
type(None): {
"flatten": lambda tree: ([], None), # noqa: U100
"unflatten": lambda aux_data, children: None, # noqa: U100
"names": lambda tree: [], # noqa: U100
}
}
return entry | d16d69d325c2d16f251ad396388e13492de5cd66 | 678,824 |
def getMean(list):
"""Returns a median value from the values in the given list."""
return sum(list) / len(list) | f738f236016e1935dcad00df671035d630cde6ac | 678,825 |
def num_gt_0(column):
"""
Helper function to count number of elements > 0 in an array like object
Parameters
----------
column : pandas Series
Returns
-------
int, number of elements > 0 in ``column``
"""
return (column > 0).sum() | bde07386c3c0beec1022ca002e80b9373df69aed | 678,826 |
def scope_contains_scope(sdict, node, other_node):
""" Returns true iff scope of `node` contains the scope of `other_node`.
"""
curnode = other_node
nodescope = sdict[node]
while curnode is not None:
curnode = sdict[curnode]
if curnode == nodescope:
return True
retur... | ec4613431715b68988527794fba24ed1860eeeac | 678,827 |
import os
def make_directories(dir_lst: list, verbose: bool = True) -> None:
"""Check if each directory within the passed list exists and create any
missing directories.
"""
for directory in dir_lst:
if not os.path.isdir(directory):
os.makedirs(directory)
if verbose:... | 553ec921c95460e23e459a03b6e8c0d8b208b705 | 678,828 |
def radio_text(route):
"""Returns a short representation of a Route
Args:
route: a Route object
Returns:
str: a string containing the route summary and duration
"""
text = " ".join([
"via " + route.summary,
f"({max(1, round(route.duration / 60))} minutes)"
])
... | 6dbbdbc1fe49421bdc39f3fe3a982b7e47b1dd82 | 678,829 |
def toMath(x):
"""Convert the expression to a math-latex readable expression."""
x = x.replace(" ", "")
x = x.replace("**", "^")
x = x.replace("^2.0", "^{2.0}")
x = x.replace("^0.5", "^{0.5}")
x = x.replace("^nexp", "^{n}")
x = x.replace("^cexp", "^{c}")
x = x.replace("gamma", "\\gamma ... | c7cc24c0b71abadb405d0e8345c69efb44a181f6 | 678,830 |
def snitch_last_contained(metadata):
"""Return the frame when snitch was last contained."""
last_contain = 0
for _, movements in metadata['movements'].items():
contain_start = False
for movement in movements:
if movement[0] == '_contain' and movement[1] == 'Spl_0':
... | 139719b3c4cd38aeab01e52078547da7501161cf | 678,831 |
def dict_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 08ef60c6ac4a72a7235d2f8d4a4bc215321b78b6 | 678,832 |
import torch
def gram_matrix(tensor):
""" Calculate the Gram Matrix of a given tensor
Gram Matrix: https://en.wikipedia.org/wiki/Gramian_matrix
"""
# get the batch_size, depth, height, and width of the Tensor
_, d, h, w = tensor.size()
# reshape so we're multiplying the features... | 135201cc65a701cda1fcfbd325537a4c0c538bd6 | 678,833 |
def isOnCorner(x, y):
"""Returns True if the position is in one of the four corners."""
return ((x == 0 and y == 0) or (x == 7 and y == 0)
or (x == 0 and y == 7) or (x == 7 and y == 7)) | 9f3a33a48d560e5f0eac0f90ec8832bc0a064c9a | 678,836 |
def is_paired(cursor, imei_norm):
"""
Method to check if an IMEI is paired.
:param cursor: db cursor
:param imei_norm: normalized imei
:return: bool
"""
cursor.execute("""SELECT EXISTS(SELECT 1
FROM pairing_list
WHER... | c01fee34f1572a6af31a70e4b31b42215fd10f70 | 678,838 |
import json
def lambda_handler(event, context):
"""
Example Lambda service
"""
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world, I'm an Example Lambda service",
"received_event": event,
}),
} | 1ad0ffb03a2f1d6d42e56ab585f1c6fd39e85a48 | 678,839 |
def addslashes(sstr):
"""
过滤/转义字符串中的非法参数
:param sstr:
:return:
"""
ss = sstr.strip().replace('\\', '\\\\').replace("'", "\\'").replace('"', '\\"').replace('<', '').replace('>', '')
return ss | 66da0f3b56bbf9c6ee08897f41c51b9571d4e076 | 678,840 |
def warnings(results):
"""Proof warnings."""
prefix = "**** WARNING:"
length = len(prefix)
return [warning[length:].strip() for warning in results.warning] | eac4d123ee5b0be47ae8f0fc723fe3a1144075f7 | 678,841 |
import os
def _swss_path(filename):
"""Helper function to transform swss config file path.
Copy files using 'docker cp swss' won't work if the destination path in 'swss' docker is '/tmp'.
This helper function is to transform path like '/tmp/filename.json' to '/filename.json'.
Args:
filename ... | 1a4339b579810d1efcc4903ef4b9ea286a6591e9 | 678,842 |
def canJump(nums):
"""check = ["0"] * (len(nums) - 1)
check.append("G")
return self.jump(nums, 0, check)"""
# ONE-PASS SOLUTION
last = len(nums) - 1
for i in range(len(nums) - 1, -1, -1):
if i + nums[i] >= last:
last = i
return last == 0 | b0a62f0761ccf02a333ba6beb625d40558347101 | 678,843 |
def run_dbcc():
"""Method: run_dbcc
Description: Stub holder for run_dbcc function.
Arguments:
"""
return True | 12b08158aecac6bf715352222e7b01dcdbbe9a80 | 678,845 |
def get_P_v(X_ex):
"""外気の水蒸気圧 式(2)
Args:
X_ex(ndarray): 絶湿[g/kg']
Returns:
ndarray: 外気の水蒸気圧
"""
return 101325 * (X_ex / (622 + X_ex)) | 7af2e09e1e8becb1f019c586d31c2dae3426cc8a | 678,846 |
import re
def remove_digits(string):
"""Removes digits from a string"""
return re.sub(r"\d+", "", string) | f5674f12d48a5d14ccaac207aa3b051bde7f1d61 | 678,847 |
def to_struct(model):
"""Cast instance of model to python structure.
:param model: Model to be casted.
:rtype: ``dict``
"""
model.validate()
resp = {}
for _, name, field in model.iterate_with_name():
value = field.__get__(model)
if value is None:
continue
... | 05e27da8c9fe97a5f47a361fa18b29cc3645509a | 678,849 |
import os
import re
def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier."""
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip... | a6507c3ac4f2ac754698b89782baf38d0896d998 | 678,850 |
import os
def get_walk_folders(path):
"""
填入文件夹路径获取该目录和其子目录下的所有文件夹列表
:param path
return a list of folders inside the path
"""
folder_name_list = [ ]
for root,dirs,files in os.walk(path):
for d in dirs:
folder_name_list.append(os.path.join(root,d))
return folder_name... | 935f6efaee89ffff5a18b6d6400732797b08166c | 678,851 |
import logging
def _execute_schedule(experiment, schedule):
"""Execute the method named `schedule` of `experiment`."""
if not hasattr(experiment, schedule):
logging.error("Schedule references non-existent task {}".format(schedule))
valid_tasks = [x for x in dir(experiment)
... | 0206a94cc1b9213ec721a1a55a0fe2cf5766b6b8 | 678,852 |
def _array_blocks(arr, step=1000):
"""
Break up large arrays so we have predictable updates or queries.
:param arr:
:param step:
:return:
"""
end = len(arr)
blocks = [0]
if end > step:
for start in range(step, end, step):
blocks.append(start)
return blocks | fdae9387c5b7557c2a8178db46f86688b76f16b5 | 678,853 |
def get_all_parents(key):
""""Returns list of all parent keys for ndb key"""
parent = key.parent()
if parent:
rv = get_all_parents(parent)
rv.append(parent)
return rv
else:
return [] | a7ee0aa6e0b1d1af2e371289eae1d4256fd564f6 | 678,854 |
def _trim_css_to_bounds(css, image_shape):
"""
Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.
:param css: plain tuple representation of the rect in (top, right, bottom, left) order
:param image_shape: numpy shape of the image array
:return: a trimmed plain ... | 6f87952f1d36e7a0473014b59049697d4a35f53f | 678,855 |
import math
def log(*args):
""" Evaluate a logarithm
Args:
*args (:obj:`list` of :obj:`float`): value optional proceeded by a base; otherwise the logarithm
is calculated in base 10
Returns:
:obj:`float`
"""
value = args[-1]
if len(args) > 1:
base = args[0]... | 0871722ee1b7d80f125de209e06b28b40a4fcae0 | 678,856 |
def get_updated_sheet_details(tracked_sheets, remote_sheets, sheet_frozen):
"""Format details from the various dicts to create rows for sheet.tsv."""
all_sheets = []
for sheet_title, details in tracked_sheets.items():
if sheet_title in remote_sheets:
sid = remote_sheets[sheet_title]
... | 41fd7145ecc876543eb39abb2237cfaff7762df8 | 678,857 |
import socket
import contextlib
def has_dual_stack(sock=None):
"""Return True if kernel allows creating a socket which is able to
listen for both IPv4 and IPv6 connections.
If *sock* is provided the check is made against it.
"""
try:
socket.AF_INET6; socket.IPPROTO_IPV6; socket.IPV6_V6ONLY... | 0a4d8a2bead681ec2c8a36ba69f5938a9aa72fc4 | 678,858 |
import os
def get_absolute_path(filename):
"""Returns the absolute path to the given file."""
return os.path.dirname(os.path.abspath(filename)) | 114a925021b4b906248cfa577c7720e7346d7278 | 678,859 |
def model_save_results(model, model_name, output_path):
"""
docstring
"""
model.save(f"{output_path}/{model_name}_last_w.h5")
return None | 1931ef1211ce2a19b399ef01b9115fa808495889 | 678,860 |
def compose_functions(*args):
""" Composes n functions passed as input arguments into a single lambda function efficienctly.
right-to-left ordering (default): compose(f1, f2, ..., fn) == lambda x: f1(...(f2(fn(x))...)
# OLD: left-to-right ordering: compose(f1, f2, ..., fn) == lambda x: fn(...(f2(f1(x))...)
... | 2393baf298e45842ba1a26abd41a8c05a0f3e366 | 678,861 |
def _print_dri(marker, offset, info):
"""String output for a DRI segment."""
m_bytes, fill, info = info
ss = []
ss.append(
'\n{:-^63}'.format(' {} marker at offset {}, length {} '
.format(marker, offset, info['Lr'] + 2))
)
ss.append(
"Ri={}".format(info['Ri'])
)
r... | 713b566754298c42cf02f620e01c3f312e8bce18 | 678,862 |
def filterByPolarisation(metalist, cmdargs):
"""
Filter the meta objects by polarisation. If no polarisation values present, then
all are acceptable (e.g. for Sentinel-2)
"""
if cmdargs.polarisation is not None:
metalistFiltered = []
reqdPolarisations = cmdargs.polarisation.spli... | d07040e7cd54e955b7ba5c968d20321f44950567 | 678,863 |
def merge_pk_maps(obj1, obj2):
"""
Merge pk map in `obj2` on `obj1`.
"""
for model, data in obj2.items():
m2_pks, m2_fields = data
m1_pks, m1_fields = obj1.setdefault(model, [set(), set()])
m1_pks.update(m2_pks)
m1_fields.update(m2_fields)
return obj1 | 7a696e706189dad22600a7a4367759b03a0747b7 | 678,864 |
import argparse
import os
import torch
def get_args():
"""
Arguments used to get input from command line.
:return: given arguments in command line
"""
parser = argparse.ArgumentParser(description='GRU to FSM')
parser.add_argument('--generate_train_data', action='store_true', default=False, hel... | 995a9f528b14ae404b99e6b9195278b55c705c8e | 678,865 |
def compute_alignment_matrix(seq_x, seq_y, scoring_matrix, global_flag=True):
""" str, str, dict of dict, boolean -> str, str
Takes two input sequences with a common alphabet and scoring matrix
and returns the alignment matrix.
"""
len_x = len(seq_x)
len_y = len(seq_y)
alignment = [[0 for du... | 070cd542360faf390eb95b209345b96e39d0122b | 678,866 |
from typing import Dict
from typing import Any
from typing import List
from functools import reduce
def traverse_dict(obj: Dict[Any, Any], properties: List[str]) -> Any:
"""
Traverse a dictionary for a given list of properties.
This is useful for traversing a deeply nested dictionary.
Instead of recu... | 94d1fe6a49aebc982db7e0dcadcddf2d51823c90 | 678,867 |
from datetime import datetime
import time
def to_http_date_string(date):
""" """
format = "%a, %d %b %Y %H:%M:%S GMT"
if isinstance(date, datetime):
return date.strftime(format)
return time.strftime(format, date) | 4a6edbc58ed4568b85c63a4cdd6374d8cef65495 | 678,868 |
def inc_num(num):
"""Rewriting to pass rather than disable pylint"""
return num + 1 | aa9430c7da3b612971bbb4e9ef5860aacf929e4a | 678,869 |
def byte_to_str_index(string, byte_index):
"""Converts a byte index in the UTF-8 string into a codepoint index.
If the index falls inside of a codepoint unit, it will be rounded down.
"""
for idx, char in enumerate(string):
char_size = len(char.encode('utf-8'))
if char_size > byte_index... | 2e840e63ae714fe7c53c84508eb58a6d051821f4 | 678,872 |
def get_op(op: str):
"""Given a string of aps.__ops__, return the function reference."""
return eval(op, globals()) | 1b80bed4af798d494b0cd7d2a2d20cb73b4adbd4 | 678,873 |
def _BuildRestrictionChoices(freq_restrictions, actions, custom_permissions):
"""Return a list of autocompletion choices for restriction labels.
Args:
freq_restrictions: list of (action, perm, doc) tuples for restrictions
that are frequently used.
actions: list of strings for actions that are relev... | 08940cd6d78125e2e8d6a58ac97b443f92e5653f | 678,874 |
import functools
def transform_indices(func):
"""transform reduced states toi full states"""
def transform_index(xi, center, ri):
xt = list(center)
for idx, ridx in enumerate(ri):
xt[ridx] = xi[idx]
return xt
@functools.wraps(func)
def inner(self, *args, **kwargs):... | 89c224ab91c281473cf90646ccc78a4fedfecdff | 678,875 |
import hashlib
def get_sha_digest(s, strip=True):
"""Generate digest for s.
Convert to byte string.
Produce digest.
"""
if strip:
s = s.rstrip()
s = s.encode("utf-8")
return hashlib.sha256(s).hexdigest() | 41a1b8d1088d86d283b12e382da4c3848608fd8c | 678,876 |
import subprocess
def openbsd():
""" OpenBSD; should work with all versions since 4 (possibly earlier) """
ac = charging = None
percent = lifetime = 999
def sysctl(name):
o = subprocess.Popen(['/sbin/sysctl', name], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0... | 7f30e856dca43766d41cea7a2564fe3c425fdd76 | 678,877 |
import hashlib
def hash_(list_):
"""Generate sha1 hash from the given list."""
return hashlib.sha1(str(tuple(sorted(list_))).encode("utf-8")).hexdigest() | 72d3642306070297693fc2ce3b3e9f1927aea54c | 678,878 |
def to_bgr(color):
"""
Convert to `colRGB`.
This is a `wxPython` type which is basically `BGR`. We don't want to work with
`BGR`, so being able to simply convert `RGB` is preferable.
"""
return ((color & 0xFF0000) >> 16) | (color & 0xFF00) | ((color & 0xFF) << 16) | 1e2bf884871abe945c183aea82e5825bc476cbbf | 678,879 |
import os
def get_config_path() -> str:
"""
Check OS and set the correct path for config.ini.
:return: path where the config.ini file must be stored.
"""
if os.name == 'nt':
return os.path.join(os.environ['APPDATA'], 'FRDownloader')
else:
return os.path.join(os.environ['HOME']... | 2f0e30f6b5fea8df891b3fd5ccaa5351923e4c03 | 678,880 |
def CampyParams():
"""
Default parameters for campy config.
Omitted parameters will revert to these default values.
"""
params = {}
# Recording default parameters
params["videoFolder"] = "./test"
params["frameRate"] = 100
params["recTimeInSec"] = 10
params["numCams"] = 3
params["cameraNames"] = ["Camera1",... | f86c6a205f84ba5c0efa60b3a86a9e83bc8f0d68 | 678,881 |
def _concordance_ratio(num_correct, num_tied, num_pairs):
"""
Code adapted from https://github.com/CamDavidsonPilon/lifelines/blob/master/lifelines/utils/concordance.py
to account for missing values in the context of the HECKTOR Challenge
"""
if num_pairs == 0:
raise ZeroDivisionError("No ad... | 67c075bc2e715d26d076d920d7b789ebfcf78bb0 | 678,882 |
def parse_hypothesis(hyp, char_list):
"""Function to parse hypothesis
:param list hyp: recognition hypothesis
:param list char_list: list of characters
:return: recognition text strinig
:return: recognition token strinig
:return: recognition tokenid string
"""
# remove sos and get result... | bb74bc7fbd2a4f1c09a80e6499820c17e8dea524 | 678,883 |
def minmax_scale(x):
"""Scales values in array to range (0, 1)
:param x: array of values to scale
"""
if min(x) == max(x):
return x * 0
return (x - min(x)) / (max(x) - min(x)) | 13216fd3ea5abc593ba660067e4d951f8a1fede5 | 678,885 |
def get_by_name(ast, name):
"""
Returns an object from the AST by giving its name.
"""
for token in ast.declarations:
if token.name == name:
return token
return None | caad2b27be6c25e7ed320847f75e265ac965755c | 678,886 |
import random
def get_random_word(dictionary_filepath):
"""Pulls one word (line) from the given dictionary."""
words = []
with open(dictionary_filepath) as f:
words = f.readlines()
# strip whitespace (newline) off the start/end of the string
return words[random.randint(0, len(words)-1)].st... | a8849950905fd1077dc8a4a7d3765ab5b7287393 | 678,887 |
def mock_main_runner_with_mapping(mock_main_runner, a_folder_with_mapping):
"""Mock runner where a mapping is defined in current dir"""
mock_main_runner.set_mock_current_dir(a_folder_with_mapping)
return mock_main_runner | f3afdc8eb0563a1301e075dd43565aad0e3347cb | 678,888 |
def _ecdf_y(data, complementary=False):
"""Give y-values of an ECDF for an unsorted column in a data frame.
Parameters
----------
data : Pandas Series
Series (or column of a DataFrame) from which to generate ECDF
values
complementary : bool, default False
If True, give the E... | 948d6db91d56c0f5edbaced6caa4c7927c9d90a7 | 678,889 |
def _calculate_bsize(stat):
"""
Calculate the actual disk allocation for a file. This works at least on OS X and
Linux, but may not work on other systems with 1024-byte blocks (apparently HP-UX?)
From pubs.opengroup.org:
The unit for the st_blocks member of the stat structure is not defined
wit... | cdf67cead1dac149ab255f12f1d8fc3f56120de1 | 678,890 |
import os
def get_file_path(year=2018, month=7, day=3, hour=15, quarter=0):
"""
:param year:
:param month:
:param day:
:param hour:
:param quarter:
:return:
"""
return "%s/external/export/%04d%02d%02d%02d%02d00.export.CSV.zip" % (
os.environ["DATA_PATH"], year, month, day,... | 8cb604aefa729b9de2c6d8f9af24af26ed3ecbba | 678,891 |
def vcum(self, key="", **kwargs):
"""Allows array parameter results to add to existing results.
APDL Command: *VCUM
Parameters
----------
key
Accumulation key:
Overwrite results. - Add results to the current value of the results parameter.
Notes
-----
Allows results f... | 1e21ba4abfc5bd321ab3c0ee7845bb3f12d6f38a | 678,892 |
def get_overlap_score(candidate, target):
"""Takes a candidate word and a target word and returns the overlap
score between the two.
Parameters
----------
candidate : str
Candidate word whose overlap has to be detected.
target : str
Target word against which the overlap will be ... | 8be20e25733bf0413a4c765a1e38fff36436e8b1 | 678,893 |
def remove_start_end_blanks(regex, list_span):
""" if regex starts with \n and end with multiple spaces
shortens the spans of the corresponing length"""
if regex[0:2]==r"\n":
list_span = [(x[0]+1, x[1]) for x in list_span]
if regex[-2:] == " ":
list_span = [(x[0], x[1]-2) for x in li... | 8509ca9f39cbd00086e60349d1c40b820d2299a0 | 678,895 |
def brightness_to_percentage(byt):
"""Convert brightness from absolute 0..255 to percentage."""
return round((byt * 100.0) / 255.0) | 81cd7be5d4fc7e966567963185223675e0aeb7f0 | 678,896 |
import random
def load_english_dataset():
"""
加载英文数据集
:return: 英文数据
"""
splits = dict()
splits['train'] = list()
for split in ['train_360', 'train_100', 'dev', 'test']:
filename = split
tagged_sents = list()
with open('./data/' + filename + '.txt') as f:
... | 093d5eb17765d8a0bcbdde42445f86df140ce6de | 678,897 |
def createString(days, hours, minutes, seconds, fullText=False):
"""
Create Different Readable Strings based on where that string should be used.
"""
if days == 0:
if fullText:
string = f"{hours} Hours {minutes} Minutes {seconds} Seconds"
else:
string = f"{hours} ... | 0f0e31011b3f537c52925edf4dc739af1e08892c | 678,898 |
def without_suffix(arg: str, suffix: str) -> str:
"""Remove `suffix` from the tail of `arg`."""
if not arg.endswith(suffix):
raise ValueError(f"{arg=} does not end with {suffix=}.")
return arg[: -len(suffix)] | 20f78ba3f833bfbb0077c0c0d947ef436fbbc300 | 678,899 |
def ensure_bool(val):
"""
Converts query arguments to boolean value.
If None is provided, it will be returned. Otherwise, value is lowered and
compared to 'true'. If comparison is truthful, True is returned, otherwise
False.
:param val: Value to convert to boolean.
:return: boolean value
... | 6d44a44e0010bdbcbf7739dbf319d6685c3dd4b5 | 678,900 |
import argparse
def parse_args(args):
"""define arguments"""
parser = argparse.ArgumentParser(description="TATA_enrichment_plots")
parser.add_argument(
"file_names",
type=str,
help="Name of folder and filenames for the promoters extracted",
)
parser.add_argument(
"g... | f894a8f8442db960d5b2ef6df599d52c80361b18 | 678,902 |
from typing import Tuple
def get_word_from_cursor(s: str, pos: int) -> Tuple[str, int, int]:
"""
Return the word from a string on a given cursor.
:param s: String
:param pos: Position to check the string
:return: Word, position start, position end
"""
assert 0 <= pos < len(s)
pos += 1... | b777bb454a4e3a206f57388c3136ddc6de7af544 | 678,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.