content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def events_filter_pretty(events, handler=None, indent=" "):
"""
Augment an XML event list for pretty printing.
This is a filter function taking an event stream and returning the
augmented event stream including ignorable whitespaces for an indented
pretty print. the generated events stream is stil... | 06e4b9c8df3c2aed6fde3cfb413b8b20b669507b | 677,668 |
def total_velocity(vel_l, vel_r):
"""
calculate total velocity
- given left and right velocity
"""
return (vel_l + vel_r) / 2 | 86cec75ef2b5fc32fe57952bde8bce82ffd9fe25 | 677,670 |
def get_role(obj, role_name):
"""Return a Role if the specified object has the specified role."""
for role in obj.roles:
if role.name == role_name:
return role
return None | 4a93748625e51b11e66311f420efe888fd4e6f14 | 677,671 |
def _handle_cate(df, col_pat, maps):
"""指定列更改为编码,输出更改后的表对象及类别映射"""
cols = df.columns[df.columns.str.startswith(col_pat)]
for col in cols:
values = {col: '未知'}
df.fillna(values, inplace=True)
c = df[col].astype('category')
df[col] = c.cat.codes.astype('int64')
maps[col... | fd8b5a85a23431c4d687b575a106678dd83f6c8c | 677,672 |
def parse_operand_subscripts(subscript, shape, op_label_dict):
"""Parse the subscripts for one operand into an output of 'ndim' labels
Parameters
----------
subscript : string
the subscript of the operand to be parsed.
shape : tuple of int
the shape of the input operand
op_label... | 05cb74d6fe8b6f8583ba87da4fadaeddd4571eea | 677,673 |
def format_tags(s):
"""Formatting for pretty printing"""
return ["{:<" + str(len(s[i])) + "}" for i in range(len(s) - 1, -1, -1)] | ba6b96eb91ba2caea88b69d2df28dc855d0f545c | 677,674 |
import re
def read_conversions(db):
"""Read the conversion factors we need and check we have the right time."""
mpart,Lbox,rsdfac,acheck = None,None,None,None
with open(db+"Header/attr-v2","r") as ff:
for line in ff.readlines():
mm = re.search("MassTable.*\#HUMANE\s+\[\s*0\s+(\d*\.\d*)... | d24d3fe9a2e6e28ad0459ed88407034531208698 | 677,675 |
import subprocess
def check_repository_changes():
"""
check if src-openeuler.yaml has been changed
"""
lst_files = subprocess.getoutput("git diff remotes/origin/master.. \
repository/src-openeuler.yaml | grep '^+- name' | awk '{print $NF}'")
return bool(lst_files.splitlines()) | 8aff9a28d6ce8fe01b400178d82d3a6702d456d0 | 677,676 |
def prepare_args(*args, **kwargs):
"""Arranges all positional and keyword arguments to match the structure of unittest.mock._CallList"""
return args, kwargs | e5f089fc5487940eb973fb68351418f1ce4fe204 | 677,677 |
from typing import Union
def atoi(text: str) -> Union[int, str]:
"""
Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``.
"""
return int(text) if text.isdig... | 7fdea41e41d4a6140e69f21f6d83ffc8ff757f7e | 677,679 |
def word_to_list(rw):
"""Convert the ran_word string into a list of letters"""
word = list(rw)
return word | 9a7f9ba1a5715b6f490d257e8225ccecd24c43ed | 677,680 |
from typing import Callable
import argparse
from typing import Any
def argparse_handler(inside_function: Callable) -> Callable[[argparse.Namespace], Any]:
"""
Wraps a function to make it an argparse handler (usable with the args.func(args) pattern).
Requires that the inside_function not have any purely po... | ad0d0b5d7c5fce14182837b51c2845d8cfd31c7f | 677,681 |
def increment_counts_with_province(counters, data):
"""
Counter structure:
{
"PROVINCE": {
"MUNICIPALITY": {
"YEAR": {
"PROGRAM": {
"budget": 123,
"count": 123,
"has_kml": 123,
... | 07c32239e5911132b473d6e2e87d8e1b8f8f6658 | 677,682 |
import pickle
def load_pickle(byte_file):
"""Loads a pickled object"""
with open(byte_file, "rb") as f:
return pickle.load(f) | 932f376bcd3a79398c600056fd327d5b54951e43 | 677,683 |
import os
def iter_files(root, exts=None, recursive=False):
"""
Iterate (recursive) over file paths within root filtered by specified extensions.
:param str root: Root folder to start collecting files
:param iterable exts: Restrict results to given file extensions
:param bool recursive: Wether to... | 634e04542443a5df4b7b6e14d3ab782061dfdc20 | 677,684 |
from functools import reduce
def composite_function(*funcs):
"""
compose
"""
def compose(f, g):
return lambda x: f(g(x))
return reduce(compose, reversed([f for f in funcs if f]), lambda x: x) | 12a764aa1ff0ce9f12bf1fe2cf9a146ef8ae7ef7 | 677,685 |
def guess_content_type(filename):
""" Return a content-type for a filename based on its suffix.
This implementation only supports '.html' and '.css' as suffixes.
"""
if filename.endswith('.html'):
return 'text/html'
elif filename.endswith('.css'):
return 'text/css'
else:
... | 6d2315e8fd7decab4fd91cd035e6b4188bf397a6 | 677,686 |
import os
import subprocess
def pgd_structure(outputfolder, inputfile, directorypath,spid):
"""Converts the user's VCF file into a STRUCTURE-formatted file"""
mypath = os.path.join(directorypath + "/STRUCTURE_directory")
if not os.path.isdir(mypath):
os.makedirs(mypath)
path_to_new_directory =... | fc3deddda15e33fcbf5078b1dc68455d8970d37e | 677,687 |
def parse_scoped_name(scoped_name):
"""
SCHEMA: my.module_name:MyClassName
EXAMPLE:
behave.formatter.plain:PlainFormatter
"""
scoped_name = scoped_name.strip()
if "::" in scoped_name:
# -- ALTERNATIVE: my.module_name::MyClassName
scoped_name = scoped_name.replace("::", ":... | 376148ff18dc89f50af6a83872ccab694e28b231 | 677,688 |
def package(qualified_name):
"""Return the enclosing package name where qualified_name is located.
`qualified_name` can be a module inside the package or even an object
inside the module. If a package name itself is provided it is returned.
"""
try:
module = __import__(qualified_name, from... | 91740fa2adfa37868c42144b47bf79617d23d3b9 | 677,689 |
def indent(text, chars=" ", first=None):
"""Return text string indented with the given chars
>>> string = 'This is first line.\\nThis is second line\\n'
>>> print(indent(string, chars="| ")) # doctest: +NORMALIZE_WHITESPACE
| This is first line.
| This is second line
|
>>> print(indent(... | a33fb6ca99b916ec4fe2899434fe31589fd98f6a | 677,690 |
def users_from_passwd(raw):
""" Extracts a list of users from a passwd type file. """
users = list()
for line in raw.split('\n'):
tmp = line.split(':')[0]
if len(tmp) > 0:
users.append(tmp)
return sorted(users) | 7d061146666ff75e1800285a6e3d153848c79312 | 677,691 |
def hasZ(pointlist):
""" determine if points inside coordinates have Z values """
points = pointlist[0]
first = points[0]
if len(first) == 3:
return True
else:
return False | 456832ccbd2729bd28258d4a1204895dff713dd2 | 677,692 |
def product(l1, l2):
"""returns the dot product of l1 and l2"""
return sum([i1 * i2 for (i1, i2) in zip(l1, l2)]) | 64c11575b4bfa50c035ebf965e6edfe9f07cd1a1 | 677,693 |
def windows():
"""This method is called when module is initialized. It returns a map of popup windows to be used by the module"""
wm = {}
return wm | 98b51cc710db052c464176af15c44e2c6313db1e | 677,694 |
import requests
def analyzeImg(imgResp, apiKey):
"""
Sends encoded image through Microsoft computer vision API to get tags and categories.
Args:
imgResp: image response from urlopening webcam image
apiKey: Computer Vision API key
Returns:
json object with 'categories' and 'tags' as keys
"""
headers = {
... | a0f020e4af9e6cabe8015bb03f0fad05966dbfaf | 677,695 |
def patch_prow_job_with_tab(prow_yaml, dash_tab, dashboard_name):
"""Updates a Prow YAML object.
Assumes a valid prow yaml and a compatible dashTab
Will create a new annotation or amend an existing one
"""
if "annotations" in prow_yaml:
# There exists an annotation; amend it
annotat... | f9c20dce6af2b32dc05be574c57c197b08d0ed94 | 677,696 |
def sum_items(a_list):
"""
@purpose Returns the sum of all items in a_list, and return 0 if empty list
@param
a_list: a list of items passed to this function to sum
@complexity:
Worst Case - O(N): When summing all values of a list with N items
Best Case - O(1): when passing empty... | 25f86f92ca0eedf29b9b7e8a1d8bcf4b4c024370 | 677,697 |
def parse_distance(distance):
"""parse comma delimited string returning (latitude, longitude, meters)"""
latitude, longitude, meters = [float(n) for n in distance.split(',')]
return (latitude, longitude, meters) | 954ef035e5aa5fa7965285622b5916ac1d51ac99 | 677,698 |
def find_pivot(array, high, low):
"""
Find the index of the pivot element
"""
if high < low:
return -1
if high == low:
return low
mid = (high + low)/2
if mid < high and array[mid] > array[mid + 1]:
return mid
if mid > low and array[mid] < array[mid - 1]:
return mid - 1
if array[low] >= array[mid]... | 8c55a377d1b518d0f9b85259088756ec2c67b172 | 677,699 |
def diff_eq(u, pe, h):
"""
Basic difference equation.
1/pe d^2C/dz^2 - dC/dz
"""
return (1 / pe / h**2 * (u[0] - 2 * u[1] + u[2])
- 1 / (2 * h) * (u[2] - u[0])) | f63460a09e695138e61adcb45d8d19ba04df7b7e | 677,700 |
def capacity_cost_rule(mod, g, p):
"""
The capacity cost for new storage projects in a given period is the
capacity-build of a particular vintage times the annualized power cost for
that vintage plus the energy-build of the same vintages times the
annualized energy cost for that vintage, summed over... | 65b0a53dc10e7a67031564255f4e70685834901d | 677,701 |
def subtract(d1, d2):
"""Returns a dictionary with all keys that appear in d1 but not d2.
d1, d2: dictionaries
"""
res = {}
for key in d1:
if key not in d2:
res[key] = None
return res | 620ec8edf22be2ad5ef4b1e704034e8a0b067ea4 | 677,702 |
import requests
import shutil
def download_file(url, local_file, *, allow_redirects=True, decode=True):
"""
Download a file.
Arguments:
url (str): URL to download
local_file (str): Local filename to store the downloaded
... | 173976c4581c2c437a4efec682abc0e4bb9dcda4 | 677,703 |
def pdf2cte(terms_table, table_name):
"""Generate SQL code to represent Pandas DataFrame as a Common Table Expression"""
quotify = lambda c: c # '[' + c + ']'
row2tuple_str = lambda row: '(' + ', '.join([ f"'{x}'" if (isinstance(x, str) or isinstance(x, bool)) else str(x)
... | 8dcd636a7b87712e48691d71f2798f82b071203f | 677,704 |
def always_roll(n):
""" Возвращает стратегию, по которой всегда происходит N бросков.
>>> strategy = always_roll(5)
>>> strategy(0, 0)
5
>>> strategy(99, 99)
5
"""
def strategy(score, opponent_score):
return n
return strategy | 7f6489a64dcb525a1467763cb68521bb37fefb35 | 677,705 |
def get_score(info, val, lb, ub, min_val, max_val, goal, check):
"""
Returns the solving score
"""
if info == 'unk':
return 0
elif info in ['opt', 'uns']:
return 1
if min_val == max_val:
return ub
s = (ub - lb) * (val - min_val) / (max_val - min_val)
if check:
assert 0 <= round(s, 5) <= ... | 884c8b82c3da446c6f588d43dac4848b5c779ddc | 677,706 |
import numpy
import math
def resize_list_of_arrays(array_list: list[numpy.ndarray]) -> list[numpy.ndarray]:
""" resize all arrays given to the size of the smallest array
will attempt to remove the same amount from each side of the array
:param array_list:
:return:
"""
min_x = min([arr.shape[0... | 0e92005946e27ab72c06bffec6e19b2302d6d086 | 677,707 |
def get_perms(s, i=0):
"""
Returns a list of all (len(s) - i)! permutations t of s where t[:i] = s[:i].
"""
# To avoid memory allocations for intermediate strings, use a list of chars.
if isinstance(s, str):
s = list(s)
# Base Case: 0! = 1! = 1.
# Store the only permutation as an im... | f6fb0871b1a9ff9ff661f10814f104875ffebe02 | 677,708 |
def saveUserDefinedIgnores():
"""
User can add their own ignores that won't be wiped out during the
updation of gitignore by adding a comment(#) before ignores at the
end of the file.
"""
try:
with open(".gitignore", "r") as gitIgn:
userIgn = gitIgn.read().split("#")[1]
... | 2bc1f736434b515f25a0fa1371d38b5e4ca2a613 | 677,709 |
def _get_stream_timestamps(stream: dict):
"""Retrieve the LSL timestamp array."""
return stream["time_stamps"] | 95dca853abfcd01e2baca49d3328a9414e102d3c | 677,710 |
def newline_space_fix(text):
"""Replace "newline-space" with "newline".
This function was particularly useful when converting between Google
Sheets and .xlsx format.
Args:
text (str): The string to work with
Returns:
The text with the appropriate fix.
"""
newline_space = '... | ed98677531545f869a649605f205bad6c862f453 | 677,711 |
def is_checkpoint_epoch(cfg, cur_epoch):
"""Determines if a checkpoint should be saved on current epoch."""
return (cur_epoch + 1) % cfg.TRAIN.CHECKPOINT_PERIOD == 0 | 64a05257bc616ef9fe2c53078c0607134923f868 | 677,712 |
def imagenet_policies():
"""AutoAugment policies found on ImageNet.
This policy also transfers to five FGVC datasets with image size similar to
ImageNet including Oxford 102 Flowers, Caltech-101, Oxford-IIIT Pets,
FGVC Aircraft and Stanford Cars.
"""
policies = [
[("Posterize", 0.4, 8), ("Rotate", 0.... | e7f2fa62c11b0639a353f4ca666e4d1a78c75df2 | 677,713 |
def getCommand(gameCounter: int):
"""Allows the gamer to enter a command from the console."""
return input("Dynasty (" + str(gameCounter) + ") > ") | 8eedb7a631055b4efe28e08e399c44d87467bd97 | 677,714 |
def hide_axis(ax, axis='x', axislabel=True, ticklabels=True, ticks=False,
hide_everything=False):
""" Hide axis features on an axes instance, including axis label, tick
labels, tick marks themselves and everything. Careful: hiding the ticks
will also hide grid lines if a grid is on!
Para... | 11160c6f928a8b5befd4a20cbd04f97a5f6dfae0 | 677,715 |
from functools import reduce
from sympy.core.power import Pow
from sympy.core.mul import Mul
from sympy import sqrt
def signed_sqrt(expr):
"""Signed sqrt operator
Args:
expr (sympy.expr): sympy expression
Returns:
sympy.expr: A simplified expression
"""
expr = expr.factor()
... | cca53245092e122ac4cda1285d8e78209033cbcf | 677,716 |
import hashlib
def md5_sign(text):
"""
生成md5
:param src: str, sentence
:return: str, upper of string
"""
md5_model = hashlib.md5(text.encode("utf8"))
return md5_model.hexdigest().upper() | 981afd8abf9a7d9152ebda4892a11ef795f65f26 | 677,718 |
def iterazioni(g, x0, tolx, nmax):
"""
Algoritmo di iterazione per il calcolo del punto fisso di una funzione.
:param g: la funzione di cui trovare il punto fisso
:param x0: il valore di innesco
:param tolx: la tolleranza
:param nmax: il numero massimo di iterazioni
:return: (punto fisso, n... | ebd65a51a401a207264c2a744910fa46d7c124a7 | 677,719 |
def categorical_values():
"""Return a list of all the categorical points possible for `supernaedo2` and `supernaedo3`"""
return [('rnn', 'rnn'), ('rnn', 'lstm_with_attention'), ('rnn', 'gru'),
('gru', 'rnn'), ('gru', 'lstm_with_attention'), ('gru', 'gru'),
('lstm', 'rnn'), ('lstm', 'lstm... | c395df9913dd023e36d79d6b3ea30d3594bdfefb | 677,720 |
def pretty_number(numbers):
"""Convert a list of numbers into a nice list of strings
:param numbers: Numbers to convert
:type numbers: List or other iterable of numbers
:rtype: A list of strings
"""
try:
return [pretty_number(n) for n in numbers]
except TypeError:
pass
... | b063cacec54c69bf5956b44f71b58e0b6845853e | 677,721 |
import math
def roundup(x, to):
"""Rounding up to sertain value
>>> roundup(7, 8)
>>> 8
>>> roundup(8, 8)
>>> 8
>>> roundup(9, 8)
>>> 16
:param x: value to round
:param to: value x will be rounded to
:returns: rounded value of x
:rtype: int
"""
return int(math.cei... | c15e4a5a751a428ee395fc96ee4845a95b3432f4 | 677,722 |
def getWaterYear(date):
""" Returns the water year of a given date
Parameters
----------
date : datetime-like
A datetime or Timestamp object
Returns
-------
wateryear : string
The water year of `date`
Example
-------
>>> import datetime
>>> import wqio
... | 5d81878833325337a652d4178ad22b5b566ef296 | 677,723 |
def find_collNames(output_list):
"""
Return list of collection names collected from refs in output_list.
"""
colls = []
for out in output_list:
if out.kind in {"STEP", "ITEM"}:
colls.append(out.collName)
elif out.kind == "IF":
colls.append(out.refs[0].collName... | cfcd9a8d8343009b09758a075b6b98a98a3ac0ea | 677,724 |
def session_new_user_fixture(session_base):
"""Load the new user session payload and return it."""
return session_base.format(user_id=1001) | 12202eb76eb05b840f2c20197978bf009a1eab4e | 677,725 |
def uniformCrossover(parent1: list, parent2: list, mask: list):
"""
This function performs uniform crossover and mutation with the help of a mask
...
Attributes
----------
parent1:List
features in vectorized form
parent2:List
features... | 2a88188d53ce63eb33b7b3ee50bf9ac6a53ef53a | 677,727 |
import os
from pathlib import Path
def get_download_path(fallback_dir: str) -> str:
"""Get base path for YouTube2Audio app"""
music_dir = os.path.join(Path.home(), "Music")
if os.path.isdir(music_dir):
y2a_dir = os.path.join(music_dir, "YouTube2Audio")
if not os.path.isdir(y2a_dir):
... | 0c18bdcbd16a9b9d06ecc7868fd8537b959cbd84 | 677,728 |
def collator(batch_list):
"""
Collate a bunch of multichannel signals based
on the size of the longest sample. The samples are cut at the center
"""
max_len = max([s[0].shape[-1] for s in batch_list])
n_batch = len(batch_list)
n_channels_data = batch_list[0][0].shape[0]
n_channels_targe... | 17015efa3acede877d88a53ce24e6812997e17c1 | 677,729 |
def text_count(widget, index1, index2, *options):
"""Hack Text count command. Return integer, or tuple if len(options) > 1.
Tkinter does not provide a wrapper for the Tk Text widget count command
at Python 2.7.1
widget is a Tkinter Text widget.
index1 and index2 are Indicies as specified in TkCmd ... | 7eb55ed7b0d659765a9a901eee8e8b66bf0549e2 | 677,730 |
def vectorize_label(df,label_column,num_labels,target_outcome):
"""
Vectorize input features wrt a label column.
"""
inputs = df[label_column].apply(lambda x: x== target_outcome).values
return inputs | f528c87aa3ac4e4ec1b57eac1b1b6dbb507c3678 | 677,731 |
def _rel_approx_equal(x, y, rel=1e-7):
"""Relative test for equality.
Example
>>> _rel_approx_equal(1.23456, 1.23457)
False
>>> _rel_approx_equal(1.2345678, 1.2345679)
True
>>> _rel_approx_equal(0.0, 0.0)
True
>>> _rel_approx_equal(0.0, 0.1)
False
>>> _rel_approx_equal(... | d25520d23cd3ace60d668dd41a12a3c0f09b697c | 677,732 |
def create_job(objectid, url, projectName, archive_filename, h5_file, sensor, direction,
track, longitude, startingLatBand, endingLatBand, temporalBaseline,
doppler, criticalBaseline, coherenceThreshold, wuid=None, job_num=None):
"""Map function for job json creation."""
if wuid i... | 070d104bd4235c6dbcd01d846ab7fd7fe748beee | 677,733 |
def compute_seq_acc(outputs, y, batch_size, max_len):
"""
outputs: [batch_size, max_len-1, vocab_size]
y: [batch_size, max_len]
"""
num_eq = (y[:, 1:].data == outputs.max(2)[1]).sum(dim=1)
accuracy_clevel = num_eq.sum() / batch_size / (max_len - 1)
accuracy_all = (num_eq == max_len - 1).sum(... | e6e04d2c69fcdedbc201fdb9f682a385f238b78e | 677,734 |
import os
def get_subject_id_from_t1(t1_file):
"""
This function...
:param t1_file:
:return:
"""
return os.path.abspath(t1_file).split("/")[-3] | 89d4ebabcea06ae835b3d9bcbb91d0edac4a35a5 | 677,736 |
def get(obj: dict, path, default=None):
"""Gets the deep nested value from a dictionary
Arguments:
obj {dict} -- Dictionary to retrieve the value from
path {list|str} -- List or . delimited string of path describing path.
Keyword Arguments:
default {mixed} -- default value to retur... | ff1a3e9548af68046864b79c8afd839d7cd99907 | 677,738 |
import importlib
def create_data_controller(data):
"""
创建基础数据
Args:
data:
Returns: 创建基础数据所用的数据表单
"""
tmp_cls = importlib.import_module("application.forms", data["type"] + "Form")
form = getattr(tmp_cls, data["type"] + "Form")()
delattr(form, "id")
return form | 009708b1f49ea31e9a9c375601906dcce2ebe2aa | 677,739 |
def dict_is_song(info_dict):
"""Determine if a dictionary returned by youtube_dl is from a song (and not an album for example)."""
if "full album" in info_dict["title"].lower():
return False
if int(info_dict["duration"]) > 7200:
return False
return True | b4792a850be39d4e9dc48c57d28d8e4f50751a75 | 677,740 |
def get_cloud_path(drive, instance_id, path=[]):
"""Get tree folder from cloud of this instance.
:param drive: Google Drive instance
:param instance_id: id of file or folder
:param path: initial empty list
:returns: path array contain tree folder from root
"""
try:
... | 16a510b2b0670646dd275d6a95acdbe89d2468bd | 677,741 |
def canonicalColor(s, bg=False, shift=0):
"""Assigns an (fg, bg) canonical color pair to a string based on its hash
value. This means it might change between Python versions. This pair can
be used as a *parameter to mircColor. The shift parameter is how much to
right-shift the hash value initially.
... | 50763cba173980994108a1b50a40688d51bc1d9b | 677,743 |
def _check_src_type(filters):
"""Check whether src_type is in filters and set custom warning."""
if 'src_type' not in filters:
filters['src_type'] = None
warn_text = ('The spatial filter does not contain src_type and a robust '
'guess of src_type is not possible without src. Conside... | a1a9d692c97df1a6304015fce3e3c715f8a02b8e | 677,745 |
import math
def count_squared_addends_max_four(input_int):
"""
Due to Lagrange's four square theorem all numbers are representable as the sum of at most 4 squares
https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem
Solution by Corey McCarty
Additional input by Charles Umiker
"""
... | 8a5e3a341f22bf9da0b1945f6da6a588fdcd1675 | 677,747 |
import os
def checkFiles(path, singleFile):
""" checkFiles(path,singleFile): That function will check if exist the file on the path create with the
createPathGoesData function
The variable path is create with the createPathGoesData
The singl... | 19529abbff8adab222173bd06df7b702e0d2a0a4 | 677,748 |
import socket
import ipaddress
def forward_lookup(hostname):
"""Perform a forward lookup of a hostname."""
ip_addresses = {}
addresses = list(
set(str(ip[4][0]) for ip in socket.getaddrinfo(hostname, None))
)
if addresses is None:
return ip_addresses
for address in addresses... | 1184ed5894c660efff88c9cf5910ce7864af30ed | 677,749 |
def dummy_add_partial_transcript():
"""Returns a dummy AddPartialTranscript message."""
return {
"message": "AddPartialTranscript",
"format": "2.1",
"metadata": {"start_time": 0.0, "end_time": 1.0, "transcript": "foo"},
"results": [
{
"type": "word",
... | 07f04ce61252e50b15afbc994965763eab84db64 | 677,750 |
def shiftRow(s):
"""ShiftRow function"""
return [s[0], s[1], s[3], s[2]] | f2532c0bb7f48c55ad1975c8e5c89439b08151db | 677,751 |
import math
def degrees_to_radians(degs):
"""
Convert from degrees to radians. Pff, who actually works in degrees?.
"""
return degs * math.pi / 180.0 | 3c238bd0a6db3df3d3b794b92de913a7226c7d3f | 677,752 |
import subprocess
def same_volume(a, b):
"""
From NFSLocalizer
Check if file a and b exist on same device
"""
vols = subprocess.check_output(
"df {} {} | awk 'NR > 1 {{ print $1 }}'".format(
a,
b
),
shell = True
)
return len(set(vols.decode("utf-8").rstrip... | 3039f24b05b0e76449547bfc893511633115fc80 | 677,753 |
def pots_to_volts(calibration_data):
"""Convert the potentiometer data units to volts.
Parameters
----------
calibration_data : dict
All of the digital (DIO) and analog data corresponding to the trodes
files for the a calibration recording. For example, as returned by
read_data... | b33bc729032797cbc04545dd0faa1584329ebba0 | 677,754 |
def parse_mid(request):
"""
Go through funky series of scenarios parsing out the mid
from the GET request.
"""
mid = request.args.get('mid')
if mid is not None:
return mid
link = request.args.get('link')
if link is None or not link:
return None
splits = link.split('... | 7782872f6f09bf2c08a669f9ca4779c98949d05d | 677,755 |
import re
def walltime_seconds(walltime):
"""Given a walltime string, return the number of seconds it represents.
Args:
walltime (str): Walltime, eg. '01:00:00'.
Returns:
int: Number of seconds represented by the walltime.
Raises:
ValueError: If an unsupported walltime forma... | 96b4ecda6231ae50948f44fdc99f8adced391e30 | 677,756 |
import argparse
import os
def handle_args():
"""Create the parser, parse the args, and return them."""
parser = argparse.ArgumentParser(description='Check Azure PAAS Deployments',
epilog='(c) MS Open Tech')
parser.add_argument('cloudservice',
h... | b0d93fd4c0308a860bb20489b61aa2cd266b74e6 | 677,757 |
def handle_num(val, ranges=(0, 100), res=list()):
"""处理纯数字"""
val = int(val)
if val >= ranges[0] and val <= ranges[1]:
res.append(val)
return res | 8d719f3888ae2c8f3a5258a3a9cdbc2aeaccdc06 | 677,758 |
import math
def sdi(data, scaled=True):
"""
Function to compute the scaled shannon
entropy.
if there is only one type in the dataset,
then sdi = 0
Maxium diversity is reach with 1
if the scaled factor is used
"""
def p(n, N):
""" Relative abundance """
if n is 0:... | 8225c1fc4642b5ad27fba5e1d9400dc5f1b5e9eb | 677,760 |
import threading
import functools
import inspect
def debounce(interval_s, keyed_by=None):
"""Debounce calls to this function until interval_s seconds have passed."""
def wrapper(func):
timers = {}
lock = threading.Lock()
@functools.wraps(func)
def debounced(*args, **kwargs):
... | 7c18a7595f11113e0ba9ffbca2941865ac41ab58 | 677,761 |
import operator
def valid_combination_two(variant, max_joltage):
"""
Faster ?
Test run with this method (test2-data.txt):
Current valid combinations for iteration 30 : 1
Current valid combinations for iteration 29 : 16
Current valid combinations for iteration 28 : 121
Current valid combin... | 0ad27faab20f17fa0db1e64123e9dc22bee9d7c4 | 677,762 |
def arange(start, end, step=1):
"""
arange behaves just like np.arange(start, end, step).
You only need to support positive values for step.
>>> arange(1, 3)
[1, 2]
>>> arange(0, 25, 2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
>>> arange(0, 1231, 34)
[0, 34, 68, 102, 136, 170... | a7278e1773a25db638662f6572b0fd6e3fcfef31 | 677,763 |
def mock_sign_function(credentials, method, path, headers, params):
"""
mock sign function
:param credentials:
:param method:
:param path:
:param headers:
:param params:
:return:
"""
return "Mocked" | b1b44bb8922556c79ee878a606f1d9bb2898b904 | 677,764 |
import json
def dumps_args_json(args=None):
"""
将内存中的数据转换为json格式,并排序
:param args: 内存中的数据,数据类型可以是字符串、列表、字典
:return: json数据
"""
format_result = json.dumps(args, indent=4, ensure_ascii=False, sort_keys=True)
return format_result | 53b5b5a5b3a7982d51e0c0ee7ad6c3b330943ce4 | 677,765 |
def get_index(user_dao):
"""
Summary: Get admin-level details for all campaigns.
Response model name: AdminCampaignIndex
Response model:
campaigns:
type: array
items:
type: AdminCampaignDetails
Errors:
403: User does not have permission to acc... | f8ff12e245af879cb683b154cdcded5ac7a258a1 | 677,766 |
def get_domain_id(ks_client, domain_name):
"""Return domain ID.
:param ks_client: Authenticated keystoneclient
:type ks_client: keystoneclient.v3.Client object
:param domain_name: Name of the domain
:type domain_name: string
:returns: Domain ID
:rtype: string or None
"""
all_domains... | df07d3a957cc520d180131b1475fadec8e5fa6cf | 677,767 |
def non_empty(answer):
"""
Validates that the answer is not empty.
:return: The non-empty answer, or None.
"""
return answer if answer != '' else None, "I need an answer. Please?" | 0ce607cb793e90f7c4e8dcc43ddba5012fce08e7 | 677,769 |
def clean_aliases(aliases):
"""
Removes unwanted characters from the alias name.
This function replaces:
-both '/' and '\\\\' with '_'.
-# with "", as it is not allowed according to the schema.
Can be called prior to registering a new alias if you know it may contain such unwanted
char... | 57fe5734b8912e17139e09d54d8ab7a45d121539 | 677,770 |
import click
def validate_fragment_type(ctx, param, value):
"""
Validate that a given fragment type exists.
"""
config = ctx.obj.config
if value and not config.has_fragment_type(value):
raise click.BadParameter(
'Missing or unknown fragment type: {}'.format(value))
return v... | 71b206c629037a6d6fa4a0441401803fd8ff6c46 | 677,771 |
import torch
def project(x, c):
"""Projects x into the Poincare ball with curvature, c."""
c = torch.as_tensor(c).type_as(x)
norm = torch.clamp_min(x.norm(dim=-1, keepdim=True, p=2), 1e-5)
maxnorm = (1 - 1e-3) / (c**0.5)
cond = norm > maxnorm
projected = x / norm * maxnorm
return torch.where(cond, proje... | ec18f3384f82e411aef458a975329108cffa9cd0 | 677,772 |
def _key_in_string(string, string_formatting_dict):
"""Checks which formatting keys are present in a given string"""
key_in_string = False
if isinstance(string, str):
for key, value in string_formatting_dict.items():
if "{" + key + "}" in string:
key_in_string = True
... | 706beaa06973b5071ecdbf255be83ee505202668 | 677,773 |
import argparse
def options(**kwargs):
"""Generate argparse.Namespace for our Application."""
kwargs.setdefault("verbose", 0)
kwargs.setdefault("output_file", None)
kwargs.setdefault("count", False)
kwargs.setdefault("exit_zero", False)
return argparse.Namespace(**kwargs) | a2c75026763b067515cb2acd944d3bf334960b13 | 677,774 |
def compare_two_model_index(index_1, index_2):
"""
If the two input index's row and column and their parent is equal, then they are equal for test.
"""
return (index_1.row() == index_2.row()) \
and (index_1.column() == index_2.column()) \
and (index_1.parent() == index_2.parent()) | 5f199812456ae74d2a65528610ca752a2771aad1 | 677,775 |
def enMajuscule(texte):
"""
paramètre texte : (str) Le texte sans accent qu'on veut mettre en majuscule
valeur renvoyée : (str) Le texte en majuscule
>>> enMajuscule('Ceci est un test.')
'CECI EST UN TEST.'
"""
sortie = ""
for c in texte:
if 'a' <= c <= 'z':
... | d8c08dcd5472c480ad37a09b09bd9a4bff16aed4 | 677,776 |
import json
def get_json_from_file_path(path):
"""
Get the content of the json file and convert it into an object
"""
f = None
result = None
# noinspection PyBroadException
try:
f = open(path, "r", encoding="utf-8")
json_str = f.read().strip()
result = json.loads(js... | 7cd67f4ffd9d583f203e46499ab45ac0667eab67 | 677,777 |
import csv
def manifest_to_file(manifest, filename):
"""
:param manifest:
:param filename:
:return:
"""
projected_manifest_entries = [{'filename': key, 'sha1': manifest[key]} for key in manifest]
manifest_file = open(filename, 'w', newline='')
fieldnames = ['filename', 'sha1']
man... | 1f2157cd5025b227093329f3fbf392926fcb2762 | 677,778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.