content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def flip(tensor, dim=1):
""" Just flip a tensor dim."""
fliped_idx = torch.arange(tensor.size(dim)-1, -1, -1).long().to(tensor.device)
fliped_tensor = tensor.index_select(dim, fliped_idx)
return fliped_tensor | 468acf204c0a597e2420f97ca7b417635fc554dc | 685,750 |
def unpack_dtype(dtype):
"""Return list of tuples needed to construct the dtype
dtype == np.dtype(unpack_dtype(dtype))
"""
result = []
fields = dtype.fields
for field_name in dtype.names:
fieldinfo = fields[field_name]
if len(fieldinfo) == 3:
# The field has a "title... | 769e059db26e358d18e1deff959517c9845c6380 | 685,751 |
def kinematics(x, i, dt=1E-6):
"""Will calculate velocity and acceleration given well-formatted
data set of positions x[] and desired position i."""
dt = 1E-6
v = []
a = []
for k in range(1, len(x)-2):
#for each value of the x, this appends v[] appropriately
r = (x[k+1] - x[k-1]... | 915edb6ccc2202743c7ad541aefba8d6d25ddb3f | 685,752 |
import requests
from typing import Optional
def size_from_headers(response: requests.Response) -> Optional[int]:
"""
Return the size of the download based on the response headers.
Arguments:
response {requests.Response} -- the response
Returns:
Optional[int] -- the size
"""
i... | 9b55a6edc6458380d46ac6a6116b0f5cc804c3b8 | 685,755 |
def try_or_none(f):
"""wraps f to return None if f raises an exception
assumes f takes only one input"""
def f_or_none(x):
try:
return f(x)
except:
return None
return f_or_none | 543987e698fbd10855a1cec527b46a52e0f5e0ac | 685,756 |
def n_mod(num, div):
"""returns nonpositive modulo residue"""
if (res := num % div):
return res - div
else:
return 0 | 03b9e02ab1d188c2146d79d8a04d849436b2c51c | 685,757 |
def sadd(self, labr="", lab1="", lab2="", fact1="", fact2="", const="",
**kwargs):
"""Forms an element table item by adding two existing items.
APDL Command: SADD
Parameters
----------
labr
Label assigned to results. If same as existing label, the existing
values will be ... | 40ea11facf12b13590c9912e8c30b706b5d764dc | 685,758 |
def GetAllLengths( tbl_nrdb, nids ):
"""retrieve all lengths for a set of nids.
"""
lengths = []
for nid in nids:
lengths.append( tbl_nrdb.GetLength( nid ))
return lengths | 70a762f1b6349df255cc377cd60c8c63ee0bbc47 | 685,759 |
import glob
import os
import random
def populate_data_list(input_path, depth_path, gt_path, image_type):
"""
populate the data list
"""
image_list = glob.glob(os.path.join(input_path, f"*.{image_type}"))
postfix = not os.path.exists(image_list[0].replace(input_path, depth_path))
data_list = ... | a2910dccd7cfb55bcf7e02d532f1f8e9db823f3c | 685,760 |
def removeInvalidParentheses(s):
"""
:type s: str
:rtype: List[str]
"""
def judge_error(s):
left = 0
right = 0
for i in s:
if i == "(": left +=1
elif i == ")":
if left>0: left -= 1
else: right +=1
return left, ri... | 34dec65df34efcb8729c9aae8d88e76d9a3b1c25 | 685,761 |
def min_max_scaler(x):
"""Returns a numpy array with all of the original values scaled between 0 and 1"""
return (x - x.min()) / (x.max() - x.min()) | 37bd39d267691b981e2f84871990ec1f03fafe14 | 685,762 |
def filterActions(pattern,actions):
"""
:type pattern: dict
:return: the subset of given actions that match the given pattern
"""
return filter(lambda a: a.match(pattern),actions) | 9e9269dc52bac3d3efca049b8cf8dd9f06557dd5 | 685,763 |
import argparse
def parse_master_args():
"""
Setting MASTER lmdb maker parameter.
:return:
"""
parser = argparse.ArgumentParser(description='Lmdb marker')
parser.add_argument("--is-shuffle", action='store_true', help='shuffle or not.')
parser.add_argument('--lmdb-root', type=str, default='... | be01de1463308ee2e1466d6861c76fa3389fc798 | 685,764 |
def route_index():
"""
主页的处理函数
:return: 主页的响应
"""
header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
body = '<h1>Hello world</h1><img src="doge.gif"/>'
r = header + '\r\n' + body
return r.encode(encoding='utf-8') | 229ca512f0d7057959dbd3281bc66c605f604eea | 685,765 |
def find_lambda_jit(target, source):
"""
Finds the longest subsequence of the target array,
starting from index 0, that is contained in the source array.
Returns the length of that subsequence + 1.
i.e. returns the length of the shortest subsequence starting at 0
that has not previously a... | 32bf57d78834bd78d51480dfa1f16eae24f148f6 | 685,766 |
import ast
def maybe_unicode(node : ast.AST) -> bool:
"""Return False iff node will definitely not produce an instance of str"""
return not isinstance(node,(ast.Num,ast.Bytes,ast.Ellipsis,ast.List,ast.Tuple)) | 82ec31dd5e5d3907a0c21d4e5dbd3f188d0bc681 | 685,767 |
def cityscapes_classes():
"""Cityscapes class names for external use."""
return [
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
'bicycle'
... | cf97dead434ab75fff8e67dd5af6aaad27346ac5 | 685,768 |
def readip():
"""
create a file named arpscan.txt in the folder where the script is executed.
In the file enter one ip address range compatable with arp-scan.
The script will read the file and insert the ip address when
prompting for an ip address. Simply hit [Enter] to accept the IP.
You can o... | f3f14fa3e4f536faed917da22d9e71f9667f0a31 | 685,769 |
def getPlayer(f,columns,x):
"""Return the dataframe of a specific player with subject ID x"""
return f[f['Subject'].isin([x])] | ba1b7a3671376158d9662df9d4123f9e3dec3c8f | 685,770 |
def _get_tmpdir_fixture_name(scope: str) -> str:
"""Get appropriately-scoped tmpdir fixture."""
if scope == 'session':
return 'session_tmpdir_path'
else:
return 'tmpdir_path' | d4ad8c41cda756d08f4afb52f3276e7c01379471 | 685,771 |
def strip_comments(s):
"""Strips comment lines and docstring from Python source string."""
o = ''
in_docstring = False
for l in s.split('\n'):
if l.strip().startswith(('#', '"', "'")) or in_docstring:
in_docstring = l.strip().startswith(('"""', "'''")) + in_docstring == 1
... | 8adeecc8181ae69da94271025c23f6a5692589fa | 685,772 |
def find_keywords_sentences(keywords, cleaned_lines):
"""
Find the occurrences of the keywords in the text.
:param keywords: The keywords to be searched in the lines
:param cleaned_lines: The lines of the document
:return: The lines with the given keywords
"""
accepted_lines = list()
for... | d22bfdb40bc5cb9b27dd021eff519a05026e017e | 685,773 |
def distance(word_1, word_2):
"""
calcule la distance d'édition entre les deux mots arguments
"""
if len(word_1) < len(word_2):
return distance(word_2, word_1)
if word_1 == word_2:
return 0
elif len(word_1) == 0:
return len(word_2)
elif len(word_2) == 0:
retu... | 42e3616999aa05d8822868493c31e38c536a9b6a | 685,774 |
def resolveArgPrefix(function) -> str:
"""
Resolve the command line prefix for a function.
:param function: The function to resolve.
:return: The value of the '_func' property set by @ArgMap or the function name if not set.
"""
# Handle _func in argMap
prefix = function.__name__ + ':'
i... | 627095545f7101cd1b699d29a294f450fe089e7b | 685,775 |
import os
import csv
def add_city(city, lat, lon):
"""Add a new city to list of known cities
Arguments:
city -- name of the location
lat -- latitude value of a city
lon -- longitude value of a city
"""
if not os.path.exists('cities.txt'):
return None
else:
with open('c... | 49fe320ecb1c1182e5b1dac33fec862f1f886725 | 685,776 |
from bs4 import BeautifulSoup
import requests
def download_html(url: str) -> BeautifulSoup:
"""The download_html method downloads the html tree based on the argument `url`.
Args:
url (str): the url that users want to scrap
Returns:
a BeautifulSoup object
"""
res = requests.get(url... | bd436ed76d84786259329604c3c2954746817f7e | 685,777 |
import requests
def get_active_fires():
"""Get the latest ative fires from CalFire.
Returns GeoJSON with point geometry
"""
# Request data
r = requests.get(
"https://www.fire.ca.gov/umbraco/api/IncidentApi/GeoJsonList?inactive=false"
)
if r.status_code != 200:
raise Except... | 547d66441d2d84b3d9c111981664215dde3c9ffe | 685,778 |
def check_output_format(expected_formats):
"""
Decorator for stream outputs that checks the format of the outputs after modifiers have been applied
:param expected_formats: The expected output formats
:type expected_formats: tuple, set
:return: the decorator
"""
def output_format_decorator(f... | 8cfcca474d3d008835f9cd722cfc9f567c7a53da | 685,779 |
def get_transform_type(tile_id):
"""
Get the transform type specified in the tile id.
Parameters
----------
cooler_tile_id: str
A tile id for a 2D tile (cooler)
Returns
-------
transform_type: str
The transform type requested for this tile
"""
tile_id_parts = tile... | 704eb27d779146e5b5a4a4694386ad39e1ac5916 | 685,780 |
import os
def ensure_dirs(
dir_name: str, silent: bool = False, raise_on_error: bool = True
) -> bool:
"""Create directories if they do not exist.
Args:
dir_name: Directory name on local machine.
silent: Whether to suppress printing info message. (Defaults to False)
raise_on_error... | 50a34a7db2f166ba9634effd89fd7af35a7fcb10 | 685,782 |
def get_hex(num, digits=2):
"""
Convert an integer to a hex string of 'digit' characters.
Args:
num (int): The value to be converted.
digits (int): The number of characters the final string should comprise. Default: 2.
Returns:
str: The hex string.
"""
format_str = ... | 5062523cbc4c6064f8e7a509eee5147590cdb9c7 | 685,783 |
def icecreamParlor(m, arr):
"""
This involves using a sorted array, and binary search. This method works,
but I still have yet to truely understand how it works; more thinking about
it needs to be done.
https://github.com/ashikrafi/Ice-Cream-Parlor-Binary-Search-Python-HackerRank/
:param m: H... | 0e5c05b1b6118fa5ef2ae7002d051700f24380cd | 685,784 |
from typing import Dict
from typing import Callable
from datetime import datetime
from typing import Tuple
def season_binner(rules: Dict[int, str]) -> Callable[[datetime], str]:
"""
Construct mapping from datetime to a string in the form like 2010-06--P3M
:param rules: Is a mapping from month (1-Jan, 2-F... | 41bfa2593ec9b3555622d4b373a1020a7fca7928 | 685,785 |
from datetime import datetime
def l2l_dt(value):
"""
Detects if value is a datetime object. If it is, object is converted to a string that is formatted '%Y-%m-%d %H:%M:%S'.
If value is a string, we convert it to a datetime object and then perform the step mentioned above.
"""
format = "%Y-%m-%d... | 37dd6b38763ac4a85f144295b5744d735e98b4a1 | 685,787 |
def calcCodePageRanges(unicodes):
"""Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158
"""
codepageRanges = set(... | 82c7248c3eb27aba4efb2c0dda0834b45b2f5b0e | 685,788 |
import os
def filter_includes(include_dirs):
"""
Filter the list of compiler includes.
We want to elide GCC's include-fixed and intrinsic directory.
See docs/gcc_incompatibilities.md.
"""
def contains_intrinsic_headers(include_dir):
"""
Return True if the given directory contai... | e548fa5597f701419cd4e2bbf5639593a9dbf8bd | 685,789 |
def _enum_to_int(value):
"""Convert an IntEnum member to a numeric value.
If it's not an IntEnum member return the value itself.
"""
try:
return int(value)
except (ValueError, TypeError):
return value | 4119801cf1b2ea891b1225e56aeec5a1d78bd4b1 | 685,790 |
def elgamal_enc(params, gamma, m, h):
""" encrypts the values of a message (h^m) """
(G, o, g1, hs, g2, e) = params
k = o.random()
a = k * g1
b = k * gamma + m * h
return (a, b, k) | e42827f9565a67db5dd3707f2087c1c125fd4124 | 685,791 |
def setup(forge):
"""
Help with first time setup of forge.
Forge needs access to a container registry and a kubernetes
cluster in order to deploy code. This command helps setup and
validate the configuration necessary to access these resources.
"""
return forge.setup() | e569b079c20856e84a4d676914bd51c3a4ab95e7 | 685,792 |
def locate(actuator, *extra_args, **extra_kwargs):
"""
Example target function for example-locate
Any parameter of an OpenC2-Command message can be used as an argument [action, actuator, args, id as cmd_id, target]
Target will be the contents of the target object
:param actuator: the instance of the... | 063481298060ec4909cafbc163efff6b212a55f6 | 685,793 |
def _jinja2_filter_currency(value):
""" Format the crypto tokens properly
:param float value: The amount to format as string
"""
return "{:,.3f}".format(value) | f1695b922861c515d690ad395208c09e6bd9d265 | 685,794 |
import struct
def pack_dint(n):
"""pack 32 bit into 4 bytes little endian"""
return struct.pack('<i', n) | 88f7410e6b3fdb9a6e724d6ed64f4fef12030749 | 685,795 |
def truncate(toTruncate, charsToKeep=50):
"""
Returns a string truncated to 'charsToKeep' length plus ellipses.
"""
if len(toTruncate) > charsToKeep:
truncated = toTruncate[:charsToKeep] + "..."
return truncated
else:
return toTruncate | 8dd75b9f2c24c895deb8d988ed16d41539473c88 | 685,796 |
import math
def compute_distance(x1, y1, x2, y2):
"""
function to compute distance between points
Inputs:
x1: x-coordinate of point1
y1: y-coordinate of point1
x2: x-coordinate of point2
y2: y-coordinate of point2
Outputs:
dist: ... | 9d916849c6370cdb458726196d64a5754afc9dad | 685,797 |
def mock_ingest_queue(mocker):
"""
Mock the IngestRun queue.
"""
ingest_queue = mocker.patch(
"creator.ingest_runs.mutations.ingest_run.IngestRun.queue",
)
return ingest_queue | cf5b1c50483990ec382b52eff5dd14fd86c5fa18 | 685,798 |
def _indent_genbank(information, indent):
"""Write out information with the specified indent (PRIVATE).
Unlike _wrapped_genbank, this function makes no attempt to wrap
lines -- it assumes that the information already has newlines in the
appropriate places, and will add the specified indent to the start... | a6e8f7108801baad017e4602341d7f8bc04e9cc1 | 685,799 |
def in_box(landmark, bbox):
"""
check if the landmark is in the box
"""
assert landmark.shape == (10,), 'error landmark shape'
assert bbox.shape[0] >= 4, 'error bbox shape'
xs = landmark.reshape(-1, 2)[:, 0]
ys = landmark.reshape(-1, 2)[:, 1]
return True if ((xs > bbox[0]).all() & (xs < bbox[2]).all()... | ee318319e7dae356af0059d7494307a9d81e3d0d | 685,800 |
import os
def flags_to_mode(flags):
"""Convert an os.O_* flag bitmask into an FS mode string."""
if flags & os.O_WRONLY:
if flags & os.O_TRUNC:
mode = "w"
elif flags & os.O_APPEND:
mode = "a"
else:
mode = "r+"
elif flags & os.O_RDWR:
... | 02fd501455bd3e1143d21b7e28a0ce65e3ed50c8 | 685,801 |
import argparse
def check_per_page(arg: str):
"""
Function used to verify the number of QR codes to put per page
"""
# if the argument is max, then most amount of images will be attempted to be fitted on each page
if arg == "max":
return arg
# otherwise ensures the argument is a positi... | 955a1738888a7a9c7f654bad6a2d38fb99805351 | 685,803 |
import random
def random_subset(seq, n):
"""
Return n unique elements from seq.
"""
res = set()
while len(res) < n:
x = random.choice(seq)
res.add(x)
return res | 7954b3fdd9bb6a4d831845598a473965662aa27e | 685,804 |
def is_prime(n):
"""
>>> is_prime(10)
False
>>> is_prime(7)
True
"""
factor = n - 1
while factor > 1:
if n % factor == 0:
return False
factor -= 1
return True | 8b188da9484959088ff26f9a1353de7192770930 | 685,805 |
def __decodeframe__(data):
"""Decode a websocket frame."""
second_byte = data[1]
length = second_byte & 127 # may not be the actual length in the two special cases
index_first_mask = 2 # if not a special case
if length == 126: # if a special case, change index_first_mask
index_first_mask ... | 746e25f98546410622e0e9d7b469aafbb9a4b1c9 | 685,807 |
def partition(l, start, end):
"""
计算基准值的索引值
:type l: list 待排序的列表
:type start: int 列表开始索引值
:type end: int 列表结束索引值
"""
base = l[start] # 选择开始元素为基准值
i = start # 基准值的索引值
for j in range(start+1, end+1): # l[j] from l[start+1] to l[end]
if l[j] < base: # l[j] < l[start], 基准值索引位置右移,... | fb6b282425f70c16ac142f28407b60ca45be380f | 685,808 |
def rpad(ls, size, val):
"""Right-pads a list with a prescribed value to a set length."""
return ls + (size - len(ls))*[val] | 9cbc1a2e925efd90c75ead2a108ff19436441682 | 685,809 |
def _nice_case(line):
"""Makes A Lowercase String With Capitals."""
l=line.lower()
s=""
i=0
nextCap=1
while i<len(l):
c=l[i]
if c>='a' and c<='z' and nextCap:
c=c.upper()
nextCap=0
elif c==' ' or c=='.' or c==',' or c==';' or c==':' or c=='\t' or\
... | b2ec567aed45e57e9e280389b667d0fa1af4a18b | 685,810 |
def join_by_comma(iterable, key=None):
"""
Helper to create a comma separated label out of an iterable.
:param iterable: an iterable to be joined by comma
:param key: if the iterable contains dicts, which key would you want to extract
:return: comma separated string
"""
if key:
thing... | fed4f83029f8e055b394452fc195663a8bf99117 | 685,812 |
import os
import select
import errno
def multi_fan_out(stream_tuples):
"""
Copy data from multiple streams to multiple streams, line by line.
May raise IOError exceptions.
Parameters:
stream_tuples: a list of tuples, each of which must have two
elements (input and out... | 3a682e090ff4569730fcde0a90cbfdd9b76c5609 | 685,813 |
import os
def getfileextension(file_path):
"""returns the extension of a file, e.g. '/a/b/c.txt' -> 'txt'."""
ext = os.path.splitext(file_path)[1]
if ext.startswith("."):
ext = ext[1:]
return ext.lower() | bdf26c1716fa521d71d4e01b78893fc39a4eca42 | 685,814 |
import json
def rpc_payload(method, id, args):
""" Takes parameters, then constructs a JSONRPC payload for sending
"""
payload = {
"id": id,
"method": method,
"params": args,
"jsonrpc": "2.0"
}
return json.dumps(payload) | dfebd21a44fdb6f2e6eab011b02d625cab0be0aa | 685,817 |
def resolve_cyvcf2_genotype(cyvcf2_gt):
"""
Given a genotype given by cyvcf2, translate this to a valid
genotype string.
Args:
cyvcf2_gt (cyvcf2.variant.genotypes)
Returns:
genotype (str)
"""
if cyvcf2_gt[2]:
separator = "|"
else:
... | 7964d034dbbc7fc5613b334a8c297770f30adc1a | 685,818 |
import re
def question5(records):
"""Donner le contenu de la précision donnée entre parenthèses la plus longue du
fichier.
"""
# NOTE: la consigne était ambigue et donnait deux possibilités de réponse finale: `"NOX y
# compris NO2"` et `"et ses composants"`.
noms = set(r.substance for r in rec... | 7749f851873d66340737dd2f388976e153c5afd9 | 685,819 |
def find_start_end(case, control):
"""
Find the measurement start and end of a control, treatment pair.
:param case: The treatment ExperimentalCondition
:param controL: The control ExperimentalCondition
:return a [tuple]:
- the start index point
- the end index point
"""
if c... | 187f665cea0243ad45491becf98b1e0f4fe2a16b | 685,820 |
def two_sided_f(count1, count2, sum1, sum2):
"""computes an F score like measure"""
# check input
if not (sum1 and sum2):
print("got empty sums for F scores")
return 0
if sum1 < count1 or sum2 < count2:
print("got empty sums for F scores")
return 0
# calculate
pr... | 878d50478110331af75205fceb27d645b5b631d2 | 685,821 |
from typing import List
import os
import pathlib
def get_paths(directory_path: str, ext: str = '') -> List[str]:
"""
Get the paths of every file with a specified extension in a directory
Args:
directory_path: the path of the directory of interest
ext: the extensions of the files of interes... | 59f9ccd6a5ccc9f33a022ec64974c285fa87b1ec | 685,822 |
def is_in_prereg_group(user):
"""Determines whether a user is in the prereg_group
:param user: User wanting access to prereg material
:return: True if prereg False if not
"""
return user.is_in_group('prereg_group') | bd5fbf934ec29720966e203c0b12ec7bab02aeb4 | 685,823 |
def home():
"""
Home page for the flask app
"""
return "<h1>Flask Home Page</h1>" | d21fa8372d19a73ae0db1bcbe2d3d5febcd26342 | 685,824 |
def get_message_type(type_in_bytes):
"""Return the type of a binary message as a string."""
return type_in_bytes.decode('ascii') | 5ce0de9493de447092fc55e4891b46cf20f34bdf | 685,825 |
import json
def get_r_version(path):
"""Get the version of R specified in the renv.lock file
Parameters
----------
path : str
Path to the project directory. The file path/renv.lock must exist.
Returns
-------
str
R version
"""
with open(f"{path}/renv.lock", "r") a... | 16a5157aa78cacaad946a9df18a580851a4ef5da | 685,826 |
import string
def is_pangram(text: str) -> bool:
"""Determine if text is a pangram.
..note:: A pangram is a string that contains every single letter of the \
alphabet at least once (case is irrelevant).
:param text: text to evaluate
:return: True if text is a pangram
"""
return set(st... | a74ad9de080077474735d9242beee33355750988 | 685,827 |
import dis
def is_simple(fun):
"""A heuristic to find out if a function is simple enough."""
seen_load_fast_0 = False
seen_load_response = False
seen_call_fun = False
for instruction in dis.get_instructions(fun):
if instruction.opname == 'LOAD_FAST' and instruction.arg == 0:
s... | 11db5353ec9d483fd9184266cf5e7c7424e7bc62 | 685,828 |
from typing import Union
from typing import Mapping
from typing import Sequence
from typing import Any
def get_nested(obj: Union[Mapping, Sequence], path: Sequence) -> Any:
"""Get element of a sequence or map based on multiple nested keys.
Args:
obj: Object to index from
path: Sequence of nes... | ebce08c9323861c3edcbeb520efe512fa412be1c | 685,829 |
def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
"""
result = list()
while n:
result.append(str(n%2))
n = int(n/2)
if (width is not None) and len(result) < width:
result.extend(['0'] * (width - len(... | 5231967892d9358ee67393bbcbfe1a424d3fd30e | 685,830 |
import gzip
import json
def load_gzipped_jsonl(filename: str, encoding: str = 'UTF-8') -> dict:
"""
Function loads data stored in gzipped JSON Lines.
Parameters
----------
filename : str
Path to the file.
encoding : str, default = 'utf-8'
Returns
-------
: dict
... | b610ceb8aecf8fe704b84ead0e296ea2cbb33923 | 685,831 |
def _merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
See http://stackoverflow.com/a/26853961/2680824
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return r... | 04e4b2bf97cd7d38828cc47e5bcc25c9bb952a52 | 685,832 |
def standardize_subsequence(tokenized_subsequence):
"""
@input : tokenized sequence
@output: standardized tokenized sequence: Sequences that are uniform in length
"""
standardized_subsequence = []
cutoff = 16 # this value was determined from analysis of our tokenized_subsequence
# I need t... | 5f335e36950144a4bdaf7be6dba5d7d6be76bd0a | 685,833 |
def get_host_names():
"""Get the required host names for ALLOWED_HOSTS"""
print("""
As a security measure, the web applications need to know the host names that will be used by the users to access them.
We need to configure the host for the public web and another for the admin web.
The OCSP reponder also needs... | 99e457ec0a59f365e9061e9c09515fdb236589cc | 685,834 |
def set_client(bq):
"""
Set BigQuery client
"""
return bq.setClient() | 511c156e645788c38c7c4b715b2f3bd82ad70867 | 685,835 |
def seconds_to_hours(secs):
""" Convert Seconds to Hours """
minute, second = divmod(secs, 60)
hour, minute = divmod(minute, 60)
return "%d:%02d:%02d" % (hour, minute, second) | 04ff3765ec26a3608e82b7045b7eaf04346ca712 | 685,836 |
import itertools
def validate_compress(container_, sequence_):
"""
NAME : compress()
Arguments : data, selectors
Results : (d[0] if s[0]), (d[1] if s[1]), …
Example : compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
"""
return list(
itertools.compress(container_, sequence_)
) | 3ac6c212d2517ef3b892b932d1a11bcd330ae997 | 685,837 |
def timestamptz_to_unix(timestamptz):
"""
Converts timestamp with time zone to epoch
"""
return timestamptz.timestamp() | 1c0e7639815dbb817872f5c7e82273d3e8de0ef2 | 685,838 |
def calc_bpm(peaks, fs):
"""Calculates average HR based on array of peaks found in ECG strip
Args:
peaks (ndarray): array of indices corresponding to location of R peaks
fs (float): sampling frequency of ECG strip
Returns:
float: average heart rate in bpm
"""
sec_per_beat =... | e214141c26158ad0cba0f79999c8e15a4edc737d | 685,839 |
def inv_price_sigmoid(forecast_price, w_param, m_bet_size):
"""
Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price.
Based on a sigmoid function for a bet size algorithm.
:param forecast_price: (float) Forecast price.
:param w_param: (float) Coefficient ... | cb0c15643c73d29e75547ba273d74ba3587fe88c | 685,841 |
import math
def diagonal_res_to_pixel_res(res):
"""
>>> '%.2f' % round(diagonal_res_to_pixel_res(14.14214), 4)
'10.00'
"""
return math.sqrt((float(res)**2)/2) | a2706c7a8250e94d7cb7946b937ab28de7ccff5b | 685,842 |
from typing import Dict
def _sum_expectation_values(
expectation_values_per_bitstring: Dict[str, float],
probability_per_bitstring: Dict[str, float],
alpha: float,
) -> float:
"""Returns the cumulative sum of expectation values until the cumulative probability of bitstrings
s_k = p(x_1) + … + p(x_... | b2527ea7b70eb862467ec797a6eed4642423c091 | 685,843 |
def is_auto_primary_key(primary_key: bool, autoincrement: bool) -> bool:
"""
Checks if field is an autoincrement pk -> if yes it's optional.
:param primary_key: flag if field is a pk field
:type primary_key: bool
:param autoincrement: flag if field should be autoincrement
:type autoincrement: b... | 3c3c06b9b7e3453cb5078e9c4e5d2355724d1dad | 685,844 |
def create_primes(threshold):
"""
Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``.
"""
if threshold == 2:
return... | eeb5f1b389163cc6861a363796c1cfc1f6ee3ae3 | 685,845 |
import pathlib
import shutil
def prep_dir(dir_path, clobber=False):
"""Create (or delete and recreate) a directory.
Args:
dir_path (path-like): path to the directory that you are trying to
clean and prepare.
clobber (bool): If True and dir_path exists, it will be removed and
... | 6af0481a6f66935812cd0e872c579807ad0fc3c7 | 685,846 |
from typing import Tuple
from typing import Optional
def normalize_parameter(parameter: str, expression: str) -> Tuple[Optional[str], str, str]:
"""Normalize runtime expressions.
Runtime expressions may have parameter names prefixed with their location - `path.id`.
At the same time, parameters could be d... | d77cf1916376e13db6aed7e4f662fc74e2a998fe | 685,848 |
def isoformat(dt):
"""a small helper to user ``Z`` for UTC ISO strings"""
return dt.isoformat().replace("+00:00", "Z") | 896391361a6e08c58dfbf63be0c3a07b2985cc57 | 685,849 |
from typing import TextIO
from typing import Tuple
from typing import Mapping
import toml
def parse_pyproject_toml(file: TextIO) -> Tuple[Mapping, Mapping]:
""" Parse a pyproject.toml file
This function assumes that the pyproject.toml contains a poetry and
poetry2conda config sections.
Parameters
... | d6459f0f7b9bbee125d766150708d4c985c08f8d | 685,850 |
def _gr_xminmax_ ( graph ) :
"""Get x-minmax for the graph
>>> xmin,xmax = graph.xminmax()
"""
#
return graph.xmin() , graph.xmax() | a7e2e1160329cb0c1ff8a99ec7c8db2181a59f89 | 685,852 |
async def u2_get_some_ele_height(ele):
"""
u2得到某一个ele块的height
:param ele: eg: d(resourceId="com.taobao.taobao:id/topLayout")
:return:
"""
return ele.info.get('bounds', {}).get('bottom') \
- ele.info.get('bounds', {}).get('top') | 5a700cffe4b9296e62aa6c5eb9916d1fe8e49342 | 685,854 |
def stations_level_over_threshold(stations, tol):
"""returns a list of tuples (MonitoringStation, MonitoringStation.relative_water_level) where
all relative water levels are > tol"""
statlist = []
for i in stations:
if i.relative_water_level() == None: #discounts all invalid data
... | 8b368ea664b5884e81d3ccb3d00560a37b90cf2f | 685,855 |
import tempfile
import os
import subprocess
import shutil
def _fetch_file(host, user, filename):
"""Function to fetch a file from the server and copy it to the
local machine. A temporary file name is created for """
handle, tmpfile = tempfile.mkstemp(text=True)
os.close(handle)
if host != "l... | 8885c65e10322b2faddd30751165ecd4ce5f7b1d | 685,856 |
def get_no_scoreboard_json_leagues():
""" Scoreboard json isn't easily available for some leagues, have to grab the game_ids from sportscenter_api url """
return ["wnba", "nhl"] | 426ef4e21fb89d5cbb4e5ceb2f5b42885882db49 | 685,857 |
def score4_evaluation_function(game_state, agent, **context):
"""
This evaluation function comes from Score4 project:
https://github.com/ttsiodras/Score4
"Speaking of the scoreBoard function, I tried various forms to evaluate the
board. I ended up on a simple policy: measuring how many chips of th... | 47f017f34c4a40d784336866877a06598fcbccc8 | 685,858 |
def binarize_predictions(relevant_list, predicted_list):
#print(predicted_list)
"""Returns 2 if the first entry is present in the predictions, 1 if one of the
other relevant items is present in the predictions, 0 otherwise."""
#bin_list = []
#for ground_truth, pred in zip(relevant_list, predicted_li... | c40a3927b887f20f7a6eb36f62e517ac963304df | 685,859 |
from tifffile import TiffFile # type: ignore
import os
def read_tifftag(
filename: os.PathLike | str, tag: int | str, /, pageindex: int = 0
) -> bytes | None:
"""Return tag value from TIFF file."""
with TiffFile(filename) as tif:
data = tif.pages[pageindex].tags.valueof(tag)
# if data is... | 01d0aab5a3325845009981bdce5ca78277f9c0bc | 685,860 |
def collate(it):
"""
Unpack C{(key, value)} pairs from C{it} and collate overlapping keys.
For example::
>>> collate([(1, 'foo'), (2, 'bar'), (1, 'baz')])
{1: ['foo', 'baz'], 2: ['bar']}
@type it: C{iterable}
@rtype: C{dict}
"""
d = {}
for key, value in it:
d.... | e56b00848ae5f8009fd29a93acd2c8362611c972 | 685,861 |
def cache_man(mocker):
"""
Mocked cache manager
"""
class MockCacheMan:
def __init__(self):
self._map = {}
self.ready = False
def isReady(self): return self.ready
def get(self, key): return self._map.get(key)
def set(self, key, val): self._map[key] = val
cac... | 308e594d2f026c122235b6351f18748b506f69fe | 685,862 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.