content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def _flood_vol_op(
rainfall_depth, q_pi_array, q_pi_nodata, pixel_area, target_nodata):
"""Calculate vol of flood water.
Parmeters:
rainfall_depth (float): depth of rainfal in mm.
q_pi_array (numpy.ndarray): quick flow array.
q_pi_nodata (float): nodata for q_pi.
... | 6c23b4d92b37ed5ebbbecceee51a642abc20a1a5 | 654,296 |
def parse_labels(raw_labels, is_train=True):
"""
FOR TRAIN LABELS
raw labels form: [x,y,w,h, x1,y1,x2,y2, x3,y3,w3,h3, occ_type, occ_degree,
gender, race, orientation, x4,y4,w4,h4]
(a) (x,y,w,h) is the bounding box of a face,
(b) (x1,y1,x2,y2) is the position of two eyes.
... | a3cd08975137692db57e9189f6ac210a7db330f5 | 654,297 |
def pop_int(conn):
"""Decode bytes from protocol."""
acc = 0
shift = 0
byte = ord(conn.recv(1))
while byte & 0x80:
acc = acc | ((byte & 0x7f) << shift)
shift = shift + 7
byte = ord(conn.recv(1))
return acc | (byte << shift) | f2dc00b5737f135ce5a93f5675ac481cf979040c | 654,298 |
import random
import copy
def _random_decomposition_h(self,current_built=None,lower=1,upper=5):
"""Returns a new target silhouette, which is a subset of the full silhouette of the world. Moves the construction paper horizontally upwards by a random increment given. Call this from wrapper functions."""
if curr... | 665cf0e38e883745bd77ca5bf4fde4c11c907e9e | 654,299 |
import hashlib
def md5(s: str) -> str:
"""
>>> md5('abc')
'900150983cd24fb0d6963f7d28e17f72'
"""
return hashlib.md5(s.encode("utf8")).hexdigest() | 9becffe26724e046c14cf902ed88d8b00d3fe6de | 654,300 |
import torch
def euler_to_q(euler):
"""Converts an Euler angle vector to Quaternion.
The Euler angle vector is expected to be (X, Y, Z).
Arguments:
euler (B,3) - Euler angle vectors.
Returns:
q (B,4) - Quaternions.
"""
euler *= 0.5
cx = euler[:, 0].cos()
sx = euler[:,... | 8ffdce3ad43cf47000f50c0fb8807d2e6cef603d | 654,301 |
import torch
import math
def mean_logits(logits, dim=0):
"""Return the mean logit, where the average is taken over across `dim` in probability space."""
# p = e^logit / (sum e^logit) <=> log(p) = logit - log_sum_exp(logit)
log_prob = logits - torch.logsumexp(logits, -1, keepdim=True)
# mean(p) = 1/Z s... | c54250b6083fdaafcc544ca7c9ebfca18ae8efd6 | 654,302 |
import subprocess
def call(bin_with_args, stdin_bytes):
""" Execute the binary and return (stdout, stderr). """
proc = subprocess.Popen(bin_with_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
... | 0b7293d1f26ef7ec530eab91c035f92862cf2af9 | 654,303 |
def rotate(string, n):
"""Rotate characters in a string. Expects string and n (int) for
number of characters to move.
"""
if type(n) != int:
return "Not an integer"
if n == 0:
return string
if n > 0:
s_new = string[0:n]
l = list(string)
l[0:n] = ""
... | 0044e7d6f4bdf5dd96e256e0d9f911263aa5cf28 | 654,304 |
import os
import shutil
import time
def remove(path: str, max_retries: int = 3) -> bool:
"""
Removes the specified path from the local filesystem if it exists.
Directories will be removed along with all files and folders within
them as well as files.
:param path:
The location of the file ... | a87f8121a4cd2e036ac206649487bf69c4bdcd5b | 654,305 |
def extract_telemarketer_code(number):
"""
Telemarketers' numbers have no parentheses or space, but they start
with the area code 140.
"""
return "140" | 3cf53318247c1f39f8c77e8d13075e96328bcea5 | 654,306 |
def get_seating_row(plan, seat_number):
"""
Given a seating plan and a seat number, locate and return the dictionary
object for the specified row
:param plan: Seating plan
:param seat_number: Seat number e.g. 3A
:raises ValueError: If the row and/or seat number don't exist in the seating plan
... | e6cee54011e3c14fb362ad8e92641b2712b2ad7c | 654,307 |
def hex_to_int(hexa):
"""Convert a hexadecimal string to an int"""
vals = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
num = 0
power = 0
for d in hexa[::-1]:
try:
num += int(d) * 16 ** power
except ValueError:
num += vals[d] * 16 ** power
po... | 77edf012bcc3a0ebacbd0d2cfee99ee4c028b8fd | 654,308 |
def get_e_rtd(e_dash_rtd, bath_function):
"""「エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器)
に定義される「エネルギー消費効率」 から 当該給湯器の効率を取得 (9)
Args:
e_dash_rtd(float): エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器)に定義される「エネルギー消費効率」
bath_function(str): ふろ機能の種類
Returns:
... | 91ba3840857d8f22b808a6ab74baa84a51bdcf5b | 654,309 |
import torch
def flatten(lst):
"""
Flattens a list or iterable. Note that this chunk allocates more memory.
Argument:
lst (list or iteratble): input vector to be flattened
Returns:
one dimensional tensor with all elements of lst
"""
tmp = [i.contiguous().view(-1, 1) for i in lst]
... | 8a6d38c2e8d8e031f19bd7860237a32475709bea | 654,310 |
import logging
def parse_duration(string):
"""Parse a duration of the form ``[hours:]minutes:seconds``."""
if string == "":
return None
duration = string.split(":")[:3]
try:
duration = [int(i) for i in duration]
except ValueError:
logger = logging.getLogger(__name__)
... | b239cb4c28ac6579c3ad1b42b5b13c33b32a6d64 | 654,311 |
def get_all_subclasses(cls):
"""
Get all subclasses of a given class. Note that the results will depend on current imports.
:param cls: a class.
:return: the set of all subclasses.
"""
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in get_all_subclasses(c... | 7dff16dc4dbd481558f86fb8ac17a273ee0c742a | 654,312 |
from typing import List
def to_pylist(jlist) -> List:
"""Convert Java list types to :class:`list`."""
try:
return list(jlist[:])
except Exception:
# java.LinkedList
return list(jlist.toArray()[:]) | df9a0e8468be4dcd4a0ea38443d0f1992aa0fce3 | 654,313 |
def module_level_function(param1, param2=None, *args, **kwargs):
"""Evaluate to true if any paramaters are greater than 100.
This is an example of a module level function.
Function parameters should be documented in the ``Parameters`` section.
The name of each parameter is required. The type and descr... | b3a6ca94904bf1f1fe4d0b69db03df9f87bb1e26 | 654,314 |
import os
def sirsam_rf_precomp_predict(sirsam_rf_precomp):
"""
Path to SirSam random forest precomputed predict outputs.
"""
return os.path.join(sirsam_rf_precomp, 'predict') | 676948b0bddaa54b1fc23365ba235d83a024090e | 654,315 |
def create_filename(directory, name, figure_format, base, distance, value):
"""
Creation of a unique filename
"""
filename = directory + name
filename += '-'
filename += '{:.2f}'.format(base)
filename += '-'
filename += '{:.2f}'.format(distance)
filename += '-'
filename += '{:.2... | a3acd36bc439d13063eeffc60ce997fa099b84a8 | 654,316 |
def join(*paths, seperator="@"):
"""Join with @."""
non_empty = []
for p in paths:
non_empty.append(p)
return seperator.join(non_empty) | f81f6f9732bbdd112885bd6fd9e7c25e288818a4 | 654,318 |
def readList_fromFile(fileGiven):
"""Reads list from the input file provided. One item per row."""
# open file and read content into list
lineList = [line.rstrip('\n') for line in open(fileGiven)]
return (lineList) | e89003bf74abcd805aa4d3718caec32a7aae4df6 | 654,319 |
def rho_dust(f):
"""
Dust density
"""
return f['u_dustFrac'] * f['rho'] | 3c4d990b9f2fcb01c0183cedd7b66a2721001de7 | 654,320 |
def swap_subtree(subtree, primitive_set, terminal_set, tree):
"""
Args:
subtree: New tree
primitive_set: dictionary where (key, value) is (output_type, [{"name", "input_types", "group"}, ...])
terminal_set: dictionary where (key, value) is (output_type, [{"name", "generator", "static"},... | 68c2dc12833c7f611005dea8d18e19e786f54c8d | 654,321 |
def findMedian(x):
"""Compute the median of x.
Parameters
----------
x: array_like
An array that can be sorted.
Returns
-------
median_x: float
If there are an odd number of elements in x, median_x is the
middle element; otherwise, median_x is the average of the two... | 6717dd19859476708b2dd3fbf5c63eb0a1832559 | 654,322 |
from typing import List
def remove_existing_nodes_from_new_node_list(new_nodes, current_nodes) -> List[str]:
"""Return a list of nodes minus the nodes (and masters) already in the inventory (groups 'nodes' and 'masters')."""
return [node for node in new_nodes if node not in current_nodes] | e87e29ee0e9592922e568a1eec1f63d5065b7bc5 | 654,323 |
from typing import Dict
def get_anthropometrics(segment_name: str,
total_mass: float) -> Dict[str, float]:
"""
Get anthropometric values for a given segment name.
For the moment, only this table is available:
D. A. Winter, Biomechanics and Motor Control of Human Movement,
... | be1f1ebdcbaddcc6e9fd26ab60fb72fccd89acc2 | 654,324 |
def flatten_voting_method(method):
"""Flatten a voting method data structure.
The incoming ``method`` data structure is as follows. At the time of
writing, all elections have an identical structure. In practice. the None
values could be different scalars. ::
{
"instructions": {
... | 14095dc027ea011d4a28df85cf0f1113d04f88e5 | 654,325 |
def get_youtube_url(data: dict) -> str:
"""
Returns the YouTube's URL from the returned data by YoutubeDL, like
https://www.youtube.com/watch?v=dQw4w9WgXcQ
"""
return data['entries'][0]['webpage_url'] | 076a76f5df6ceb605a201690ac5c39972c3ddf5c | 654,326 |
def expand_request_pixels(request, radius=1):
""" Expand request by `radius` pixels. Returns None for non-vals requests
or point requests. """
if request["mode"] != "vals": # do nothing with time and meta requests
return None
width, height = request["width"], request["height"]
x1, y1, x2, ... | d0c69a5a722aef3f74863868a8687e6dca0468f2 | 654,327 |
import torch
def resolve_instability(i, pair, stability, sample_rate, actived, not_actived, active):
"""Resolve stability issue in input list of value and num_consecutive_occ
Args:
i (int): The index of the considered pair of value and num_consecutive_occ.
pair (list) : Value and num_consecut... | 61a1b7c5e3870efba21fa94d6867ac1a17f18feb | 654,328 |
def enumerate_tagged_methods(instance, tag, expected_value=None):
"""Enumerates all methods of instance which has an attribute named tag."""
methods = []
for attr in dir(instance):
value = getattr(instance, attr)
if callable(value):
try:
tagged_value = getattr(va... | 665a5cd11581ad857cd3242e36ee69f21af92f89 | 654,330 |
def verify_result(result, logger, command):
""" return True if result contains lines, False otherwise
"""
if not result.report_lines:
logger.warn(f"Command {command.as_string} produced no output")
return False
if len(result.error_report_lines) > 0:
logger.error(f"Command {command... | 616121204f1aa97f22bc2b1d0612f7071020a7c6 | 654,331 |
def compute_internet_checksum(data):
"""
Function for Internet checksum calculation. Works
for both IP and UDP.
"""
checksum = 0
n = len(data) % 2
# data padding
pad = bytearray('', encoding='UTF-8')
if n == 1:
pad = bytearray(b'\x00')
# for i in range(0, len(data + pad)... | 73b0750c8fbdf8b3a37a8479b12ff1d2dda0b8f5 | 654,332 |
import os
def pwd():
"""Get the current working directory"""
return os.getcwd() | 4dfb4d8039f4224e94c143187483679c2ed150c5 | 654,333 |
def get_bit(z, i):
"""
gets the i'th bit of the integer z (0 labels least significant bit)
"""
return (z >> i) & 0x1 | 3d103fd14e13d168b1e89ede01db20a923169ef8 | 654,334 |
import locale
def _encoding():
"""Tries to guess the encoding uses by the terminal."""
try:
return locale.getdefaultlocale()[1] or 'utf8'
except ValueError:
# Invalid locale environment variable setting. To avoid
# failing entirely for no good reason, assume UTF-8.
return '... | c7170082214e5ea9de5dd21a434d2ba023a40c41 | 654,335 |
import random
import time
def calculate_send_time(delay_time):
""" delay_time in seconds """
delay_time = random.uniform(0, 2 * delay_time)
return time.time() + delay_time | 8a52fa111ac1dfa08f0b890f2936be4b51ee017f | 654,336 |
import torch
def unit_sphere(points, return_inverse=False):
"""Normalize cloud to zero mean and within unit ball"""
mean = points[:, :3].mean(axis=0)
points[:, :3] -= mean
furthest_distance = torch.max(torch.linalg.norm(points[:, :3], dim=-1))
points[:, :3] = points[:, :3] / furthest_distance
... | 02814ffee5332448a0427130d4f40352e943b21c | 654,337 |
import sys
def propertyx(function):
"""Decorator to easily create properties in classes.
Example:
class Angle(object):
def __init__(self, rad):
self._rad = rad
@property
def rad():
def fget(self):
return self._r... | c0e9975e71972bd38b9d60d508282d0d0dfd369e | 654,338 |
def case4():
"""
:path: '/anything/test/anything/low'
:status_code: 200
:metrics: product hits, slash backend hits and low method increase, rest didn't increase
"""
return "/anything/test/anything/low", 200, [1, 1, 0, 1, 0, 0] | d505a3c355eb12ee00918746ff2799e76890b5a4 | 654,339 |
import math
def cart2pol_wind(u, v, axes_rotation = 0, magnetic_declination = 0):
"""
Converts meridional and zonal wind components into speed and direction (in degrees) values.
Parameters
----------
u = zonal component
v = meridional component
axes_rotation = undo axes rotation with p... | c2c10dfce6159c7452130d92ea4fc1bc9b3837d3 | 654,340 |
import html
import re
def data_cleaning(data, mode):
"""Fixing known differences in input files that are caused by differing
versions of pdi but don't result in functional changing of the file."""
# return data
data = html.unescape(data)
if mode == "PDI":
# Issue: Changing whitespaces on e... | ae601e90368caec4beda95d2347a86633456ba61 | 654,341 |
def sanitize_str_xml(text, no_newlines=False):
"""Returns an instance of the input text with all characters
which comply with the xml1.0 charset specification. ie. no
NULL characters, ASCII control characters (except newline), etc.
text : str input text
"""
def is_valid_xml_char(c):
c = ... | 9d6d261a58eec4f0e06b3247b2333034c686c6a7 | 654,342 |
def check_dims(matIn1, matIn2):
"""
function to check if dimensions of two matrices are compatible for multiplication
input: two matrices matIn1(nXm) and matIn2(mXr)
returns: Boolean whether dimensions compatible or not
"""
m,n = matIn1.shape
r,k = matIn2.shape
if r == n:
return True
else:
return False | 0b3baadb9902b8ad57481f06adf3910b80ba2953 | 654,343 |
def check_ascending(ra, dec, vel, verbose=False):
"""
Check if the RA, DEC and VELO axes of a cube are in ascending order.
It returns a step for every axes which will make it go in ascending order.
:param ra: RA axis.
:param dec: DEC axis.
:param vel: Velocity axis.
:returns: Step for R... | 89e9fb25eab2e0684d18b0c5123cce831521f03b | 654,344 |
def process_binding_data(raw_bricks, raw_linkers):
"""
Takes raw SDF files, processes them into a usable format
Args:
raw_bricks: brick SDFs
raw_linkers: linker SDFs
Returns: Two lists detailing what mols can bind to what, where, and how
"""
binding_sites_for_bricks = [
... | 417eec3ff7cf863d40f846923dbe2bd1f8977458 | 654,346 |
import inspect
def get_estimator(estimator):
""" Returns an estimator object given an estimator object or class
Parameters
----------
estimator : Estimator class or object
Returns
-------
estimator : Estimator object
"""
if inspect.isclass(estimator):
estimator = estimat... | e583f78659c85697e57fe01a718414175fcb2e20 | 654,347 |
def cmd_erasure_code_profile(profile_name, profile):
"""
Return the shell command to run to create the erasure code profile
described by the profile parameter.
:param profile_name: a string matching [A-Za-z0-9-_.]+
:param profile: a map whose semantic depends on the erasure code plugin
:ret... | c17375dc07b1c99e9886fa14bdc10ec5ccd0a022 | 654,348 |
def read_version():
"""
Reads the version without self importing
"""
with open("notepad/__init__.py") as f:
lines = f.read().splitlines()
for l in lines:
if "__version__" in l:
return l.split("=")[1].strip().replace('"', "") | 70da4dcd7080ec98d34f7a2479d66e0c719ecc9f | 654,349 |
def mask_positions(pos_c, k_length, mask_l=100, mask_r=100):
"""Return positional counts with removed positions around crosslinks."""
shift = int((k_length + 1) / 2)
mask = list(range(-mask_l + shift, mask_r + shift))
for _, value in pos_c.items():
for pos in mask:
value.pop(pos, Non... | bd88aded407e2700cf050515f16acdc27ae7183b | 654,350 |
import re
import sys
def sanitise_url(url: str) -> str:
"""
Make sure the URL correspond to 4chan, trim useless parts and makes it HTTPS
:param url: a string corresponding to a 4chan URL
:return: a string URL with HTTPS
"""
# https://boards.4chan.org/s/thread/17829010#p17837211
c = re.comp... | 54d4fbc1b49e02ee1cc76aeedf24612dc2b25cad | 654,351 |
from pkgutil import iter_modules
from typing import Iterable
from typing import List
def check_dependencies(dependencies: Iterable[str], prt: bool = True) -> List[str]:
"""
Check whether one or more dependencies are available to be imported.
:param dependencies: The list of dependencies to check the availability ... | d677dcec8a112cba50aa16b37487366e13962c2b | 654,352 |
def outName(finpName):
"""Returns output filename by input filename"""
i = finpName.rfind('.')
if i != -1:
finpName = finpName[0:i]
return finpName + '.hig' | b23092a5356bd6f37ac76bab5af422feb446a3f3 | 654,353 |
def _convert_node_attr_types(G, node_type):
"""
Convert graph nodes' attributes' types from string to numeric.
Parameters
----------
G : networkx.MultiDiGraph
input graph
node_type : type
convert node ID (osmid) to this type
Returns
-------
G : networkx.MultiDiGraph... | 388d8b6c148ceebdad85f2b1d4ccbed7ca5d9e32 | 654,354 |
import hashlib
import requests
def resolve_gravatar(email):
"""
Given an email, returns a URL if that email has a gravatar set.
Otherwise returns None.
"""
gravatar = 'https://gravatar.com/avatar/' + hashlib.md5(email).hexdigest() + '?s=512'
if requests.head(gravatar, params={'d': '404'}):
... | 91342a976953eafcdf8e6ddbd6881f6722b68034 | 654,355 |
import inspect
def get_custom_class_mapping(modules):
"""Find the custom classes in the given modules and return a mapping with class name as key and class as value"""
custom_class_mapping = {}
for module in modules:
for obj_name in dir(module):
if not obj_name.endswith("Custom"):
... | c9682ee84c64019a17c5b4b1f3e12cba71e1463e | 654,356 |
def enough_ambient(df):
"""
Check to see if there is enough ambient to remove
"""
S4 = df['SENSOR 4']
value = (S4.max() - S4.min()) / S4.mean()
print("Ambient Sensor Change: %s" % value)
if value > 1.0:
return True
else:
print("Ambient threshhold is not met by this measu... | 708bfb5902889e38222f92f268a1c2ed7cdc1b49 | 654,357 |
def labels_trick(outputs, labels, criterion):
"""
Labels trick calculates the loss only on labels which appear on the current mini-batch.
It is implemented for classification loss types (e.g. CrossEntropyLoss()).
:param outputs: The DNN outputs of the current mini-batch (torch Tensor).
:param labels... | 5f74a1b73b6903816ff12f1e63f403754ed4810e | 654,358 |
def BiCG(Afun, ATfun, B, x0, par=None, callback=None):
"""
BiConjugate gradient solver.
Parameters
----------
Afun : Matrix, LinOper, or numpy.array of shape (n, n)
it stores the matrix data of linear system and provides a matrix by
vector multiplication
B : VecTri or numpy.arra... | 86af50a8505f3fb1e86746faa0c4f90668437e50 | 654,359 |
import warnings
def neutralize(weights, assets, group = 'market'):
"""
:param weights: xarray with weights of the algorithm
:param assets: qndata.load_assets
:param group: neutralize positions by 'market', 'industry' or 'sector'
:return: xarray with neutrlized positions
"""
result = weight... | 06e7a39890fd94677759d4869786227b8b8446b4 | 654,360 |
def lfu(x):
"""
Lfu function
"""
return 1 | f5218957448513c10ea6cec89631d908cb4f8df5 | 654,362 |
def calculate_tweaked_uc_pc(job):
"""Calculate unit cell and primitive cell coordinates with tweaked Hydrogen coordinates"""
return "../../../codes/calc_htweaked_pc_uc" | b4f89b4138ab0abaa6cd4cc09eb03e4ce8e799a0 | 654,364 |
def fill_context_mask(mask, sizes, v_mask, v_unmask):
"""Fill attention mask inplace for a variable length context.
Args
----
mask: Tensor of size (B, N, D)
Tensor to fill with mask values.
sizes: list[int]
List giving the size of the context for each item in
the batch. Posit... | 5eb4e3613ff595a18708dd0130a27ce22bfe0ad4 | 654,365 |
def is_validated_morse_code(user_input):
"""
Input:
- user_input : 문자열값으로 사용자가 입력하는 문자
Output:
- 입력한 값이 아래에 해당될 경우 False, 그렇지 않으면 True
1) "-","."," "외 다른 글자가 포함되어 있는 경우
2) get_morse_code_dict 함수에 정의된 Morse Code 부호외 다른 코드가 입력된 경우 ex)......
Examples:
>>> import ... | 22997d4b2732c9d44602a4088b896366ad1caeaf | 654,367 |
def has_leaf_sum_helper(root, target, partial_sum):
"""
Helper function to keep track of partial
sum while trying to hit target
"""
if root is None:
return False
partial_sum += root.val
if partial_sum == target:
return True
return has_leaf_sum_helper(root.left, target, ... | 10b90339d88079aa73769af1377900c2e8dbda8c | 654,368 |
import csv
from typing import Counter
def csv_reader(file_obj):
"""
Read a csv file
:return: list 404 pages, count of pages
"""
reader = csv.reader(file_obj)
error = list()
for row in reader:
error.append(row[1])
cnt = Counter(error)
types_er = []
count_er = []
for... | 663e82fb4ee9cb74f9bcba93e156f52eb5a9aa10 | 654,369 |
def build_dictionary(chars):
"""
Organizes data read from files in a dictionary
:param chars: all chars read from files to learn
:return: the dictionary
"""
d = {}
for key in chars:
for c in chars[key]:
if c[3] not in d:
d[c[3]] = set(c[1])
e... | 3dacd5e4229d11e6962eb7383cf9259efbb8e194 | 654,370 |
def index(args):
"""A welcome page."""
return {"message": "Welcome, {}!".format(args["name"])} | 0543b64bde1ba3212b0f3184fcd312dd7e21bf37 | 654,371 |
def celsius_to_fahrenheit(T_celsius):
"""
Convert celsius temperature to fahrenheit temperature.
PARAMETERS
----------
T_celsiu: tuple
A celsius expression of temperature
RETURNS
----------
T_fahrenheit: float
The fahrenheit expression of temperature T_celsius
... | 91196ec090b775681ba0d47fb6f49c485f373522 | 654,372 |
from threading import Thread
import time
def coding_problem_10():
"""
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
Example:
>>> coding_problem_10()
Before
Hello from thread
After
"""
def delayed_execution(f, ms):
... | fd64d2c2dacfc6935d04efb6eebf669cbbab1ad5 | 654,373 |
def application(environ, start_response):
"""
符合WSGI标准的一个HTTP处理函数,web程序入口
:param environ: 请求的信息
:param start_response: 返回响应的回调函数
:return:
"""
# 响应信息
start_response("200 OK", [("Content-Type", "text/html")])
text = "<h1>hello world</h1>"
for i in environ.items():
print(i)... | 7b2a8fd72192d3c4791018a09598598bfe3c1b77 | 654,374 |
import requests
import time
def find_route(from_code, to_code, date_to, date_back=None, timeout=0.01, max_attempts=10, timeout_inc=0.01):
""" Получение списка маршрутов из А в Б на определённую дату.
from_code и to_code - коды станций отправления и назначения (берутся из suggest_stations).
date_to и date... | 504554b859ba444d521ae30066c09bc09b51ef94 | 654,375 |
import torch
def shuffler(data):
"""
shuffle the DMM datasets by both permuting the order of GMM instances (w.r.t. DIM1) and permuting the order of data points in each instance (w.r.t. DIM2)
"""
DIM1, DIM2, DIM3 = data.shape
indices_DIM1 = torch.randperm(DIM1)
data = data[indices_DIM1]
ind... | 7e5c00930cfc6f922efb9038ff7ba34862e5dfb6 | 654,376 |
def merge(dct1, dct2):
"""Merges two dictionaries"""
return {**dct1, **dct2} | f58de5109cdfc88913edfd60b954e63b5584b831 | 654,377 |
def validFSUNum(req):
"""
Valid FSU Num
- returns False if FSU Num contains characters, True otherwise
"""
return str(req['FsuNum']).isdigit() | 63f330222eefb15b3b5960224f0e868db663c762 | 654,378 |
import os
def ckrflex(filenm: str) -> bool:
"""Checking file existence or an empty file"""
if os.path.exists(filenm):
with open(filenm) as rd:
if rd.readline():
return False
else:
return True
else:
return True | 4b5c7a3f1f737928287854293f0d4d15452d79b3 | 654,380 |
import os
def rainfallChart():
"""
function: rainfallChart
Write a function rainfallChart that displays this data as a textual bar chart using
one asterisk for each mm of rainfall; e.g., given the above data the output should be:
Portsmouth ********
London *****
... | 73740eb9678e35890d1d907049e28017d37f64a5 | 654,381 |
def remove_duplicates(lst):
""" Return input list without duplicates. """
seen = []
out_lst = []
for elem in lst:
if elem not in seen:
out_lst.append(elem)
seen.append(elem)
return out_lst | b06ca47b843a941c653bd4127104625cd61456ce | 654,382 |
import stat
import os
def is_executable(path):
"""is the given path executable?
Limitations:
* Does not account for FSACLs.
* Most times we really want to know "Can the current user execute this
file" This function does not tell us that, only if an execute bit is set.
"""
# These are a... | 3d20c6549c41c325ec4a528e4c1597e1eea094ad | 654,383 |
def add_dicts(*args, **kwargs):
"""
Utility to "add" together zero or more dicts passed in as positional
arguments with kwargs. The positional argument dicts, if present, are not
mutated.
"""
result = {}
for d in args:
result.update(d)
result.update(kwargs)
return result | 8a2ee0486798d7a292610a2b197445cc6d902235 | 654,384 |
def in_board(pos, board):
"""returns True if pos (y, x) is within the board's Rect."""
return bool(board.rect.collidepoint(pos)) | fd25f12b09d1f365bd10f274d93e6a30765fee6a | 654,386 |
import subprocess
def apply_dummynet_rules(rule):
"""
Applies dummynet rules
:param rule: Dummynet rule to be applied
:return: True if successfully applied or False if failure
"""
try:
print("Applying dummynet rules")
output = subprocess.check_output(
"dnctl <<< ech... | b67a4e33c906eb7f6c4256f6408f272f69a5facf | 654,387 |
import re
def preprocess(sent):
""" text preprocessing using regular expressions
"""
# remove tags
new_sent = re.sub(r'(<!--.*?-->|<[^>]*>|{[^}]*}|\([^\)]*\)|\[[^\]]*\])',' ', sent)
# replace apostrophe and convert letters to lower case
new_sent = new_sent.replace('\\\'','\'').lower()
# de... | e401ccfb1640a10efa32730a4f4b286b21895519 | 654,388 |
import argparse
def build_parser():
"""Creates a command line argument parser."""
parser = argparse.ArgumentParser(
description='Copies files from an archive location to a new dated directory in a backup '
'directory, hardlinking to files in the previous date where possible')
parser.add_ar... | a09f8dc425668f96635433ddd63f0bdb9b4401d0 | 654,389 |
def cases(arg, case_result_pairs, default=None):
"""
Create a case expression in one shot.
Returns
-------
case_expr : SimpleCase
"""
builder = arg.case()
for case, result in case_result_pairs:
builder = builder.when(case, result)
if default is not None:
builder = bu... | 4a0331dbfce592d7909b86e6dea1ab07aaa981a4 | 654,390 |
from typing import Dict
def update_nested_dict(d: Dict, u: Dict) -> Dict:
"""
Merge two dicts.
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
:param d: dict to be overwritten in case of conflicts.
:param u: dict to be merged into d.
:return:
... | dd83799110eb2f118910aa12fc57a1d4c3d934f4 | 654,391 |
def to_list(v):
"""Convert any non list to a singleton list"""
if isinstance(v, list):
return v
else:
return [v] | 97136a291c136fbc0032bc617c06031bc90e374a | 654,392 |
import pickle
def debrine(filename, encoding='latin1'):
"""pickle.load(open(filename))
Use encoding='latin1' to load datetime, numpy, or scikit objects pickled in
Python 2 in Python 3. (Latin-1 works for any input as it maps the byte
values 0-255 to the first 256 Unicode codepoints directly:
http... | dfe187b3b44cad09ad7b5022381a20e0a2bad7fe | 654,394 |
def __indent_text_block(text):
""" Indent a text block """
lines = text.splitlines()
if len(lines) > 1:
out = lines[0] + "\r\n"
for i in range(1, len(lines)-1):
out = out + " " + lines[i] + "\r\n"
out = out + " " + lines[-1]
return out
return tex... | 9d2e933a7b8ae2a82d91e18ca67f795f6db7d089 | 654,395 |
def read_conll_corpus(filename):
"""
Read a corpus file with a format used in CoNLL.
"""
data = list()
data_string_list = list(open(filename,'r',encoding="utf-8"))
element_size = 0
X = list()
Y = list()
for data_string in data_string_list:
words = data_string.strip().split('\t')
if len(words) is 0 or len(w... | 802672f9aa18ac7079c00e1cfe7a070fdd096a21 | 654,396 |
def get_tag_list(element_tree):
"""
Function to generate a list of all element tags from an xml file
:param element_tree:
:return:
"""
return list(set([c.tag for c in element_tree.iter()])) | e011011e12c41033ba03c53b3c4fdabcf3f5b305 | 654,397 |
def scan(ln, char_maps, tokenize=True):
"""Scan beginning of each line for BASIC keywords, petcat special
characters, or ascii characters, convert to tokenized bytes, and
return remaining line segment after converted characters are removed
Args:
ln (str): Text of each line segment to pars... | 381921fe75839b83b4aac00528ad92f3acc9e510 | 654,398 |
def discrete_signal(signal0, step_size):
"""
SNIPPET 10.3 - SIZE DISCRETIZATION TO PREVENT OVERTRADING
Discretizes the bet size signal based on the step size given.
:param signal0: (pandas.Series) The signal to discretize.
:param step_size: (float) Step size.
:return: (pandas.Series) The discre... | 279fc47068c706f7634d37e1e49d44cf291bd9dd | 654,400 |
def overlap_coefficient(label1, label2):
""" Distance metric comparing set-similarity. """
#the original formula used float, but it doesn't seem to make any difference
#return float(len(label1 & label2)) / min(len(label1), len(label2))
if min(len(label1), len(label2)) == 0:
return 0
else:
return len(label1.int... | 72406ed3820dc59adb9c41a52abe2aa0d9be10d6 | 654,401 |
from typing import OrderedDict
def separate_orders_by_ticket_type(list_in, ticket_types):
"""
Inputs:
list_in - List containing ticket orders
ticket_types - List of all ticket types
Outputs:
dict_out - A dictionary keyed to ticket types, containing a list of
ticket ord... | 3d5fe2e1489c4902bee23254a926e5f96be000eb | 654,402 |
import argparse
def create_parser():
""" Creates the parser for the command line arguments"""
lparser = argparse.ArgumentParser("Parse a config file and verifies it")
lparser.add_argument('--filename', default="experiment_ng.yaml", help="Config file to verify")
return lparser | 09fbc1e971de9f1a807c12d63ac4943c2a616512 | 654,403 |
def loadText():
"""[loads the text from 'message.txt' file]"""
with open("whatsapp-bot/message.txt", "r") as text_file:
message = text_file.read().replace("\n", " ")
return message | c9bb4e7a7573d37063e747929eb446034eab4a9a | 654,404 |
import math
def split_of_number(regular_number):
"""
split regular number
"""
return math.floor(regular_number / 2), math.ceil(regular_number / 2) | ae2dcb0c19fa16b8b2c4b4be425c592f6de4ba23 | 654,406 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.