content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _check_header(line, length):
"""check if headers
first_header_line :: <=>+
second_header_line :: <->+
normal_header :: <#>+<span_element>
"""
if length * '=' == line:
return {'prev_block_type': 'h1'}
if length * '-' == line:
return {'prev_block_type': 'h2'}
if length ... | 4674750c2c7bcd39327c1818a8d81f3e6671ec3b | 71,300 |
def power_spectrum(kx, ky, n):
"""
Calcs power specturm, which is proportional of k**n = (kx,ky)**n
:param kx:
:param ky:
:param n:
:return:
"""
if kx == 0 and ky == 0:
return 0
else:
return np.sqrt(kx ** 2 + ky ** 2) ** n | 1d0775bb55701fa7fa08066ed7c1ae5265d49fe2 | 71,301 |
def unwrapText(text):
"""Unwrap text to display in message boxes. This just removes all
newlines. If you want to insert newlines, use \\r."""
# Removes newlines
text = text.replace("\n", "")
# Remove double/triple/etc spaces
text = text.lstrip()
for i in range(10):
text = text.repl... | f37aafa3a003b3b06b8e9e1a03c833d05c5c0deb | 71,302 |
import urllib
import json
def get_sources(meals):
"""
Function to retrieve meals list from the api
"""
get_latest_url = 'http://www.themealdb.com/api/json/v1/1/latest.php'
get_category_url = 'http://www.themealdb.com/api/json/v1/1/list.php?c=list'
get_search_url = 'http://www.themealdb.com/a... | b93695fe79da47f52d2d4e3f863de26210292802 | 71,303 |
import urllib
def get_queue_length(queue_name, xqueue_session):
""" Returns the length of the queue """
try:
success, response = util._http_get(xqueue_session, urllib.parse.urljoin(settings.XQUEUE_INTERFACE['url'], urls.XqueueURLs.get_queuelen), {'queue_name': queue_name})
if not success:
... | 61fc0c73f300c93aaad449fd4386179601e8a5d2 | 71,304 |
import argparse
def get_argparser():
"""Manage user parameters"""
parser = argparse.ArgumentParser()
parser.add_argument(
help="evaluation file generated by evaluate_stacks_results.py",
dest="input",
)
parser.add_argument(
help="yaml file with expected values",
dest... | 59816f23ae0ae834a78363ccac870484b4c154dc | 71,305 |
from typing import Callable
from typing import List
from typing import Tuple
from typing import Union
from typing import Sequence
import torch
def calc_exact_shapley_values(
fn: Callable,
num_features: int,
shapley_factors: List[Tuple[List[int], int]],
new_data: Union[Tensor, Sequence[Tensor]],
ba... | 4b62855bb2eea715cb2920e5b218af6940768328 | 71,306 |
def imshow_det_rbboxes(img,
bboxes=None,
labels=None,
segms=None,
class_names=None,
score_thr=0,
bbox_color='green',
text_color='green',
... | 63d225dc0d016fdc434ea35fc65844ec9dc5c128 | 71,307 |
def lab2rgb(lab:np.ndarray):
"""
input lab as pytorch tensor of size (batch_size, 3, h, w) or (3, h, w)
"""
if ndim(lab)==4:
channel_idx=1
if int_shape(lab)[1]==3:
channel_idx = 1
elif int_shape(lab)[-1]==3:
channel_idx = -1
rgb=xyz2rgb(lab2xyz(la... | 969c7676cd3c030171ec7451b96274ea4ab7e349 | 71,308 |
def feed_clf(filename):
"""
prepare data for classifier
1. 6 subcategories: ['valueScore', 'locationScore', 'sleepScore', 'roomScore', 'cleanScore', 'serviceScore']
2. find sentences contain ['value', 'location', 'sleep', 'room', 'clean', 'service']
3. if the related score is 1,2, put nega... | cfb3a38d5fa73f650ff30b3ad382feb29117d084 | 71,309 |
import time
import os
import signal
def stop_maestral_daemon_process(
config_name: str = "maestral", timeout: float = 10
) -> Stop:
"""Stops a maestral daemon process by finding its PID and shutting it down.
This function first tries to shut down Maestral gracefully. If this fails and we
know its PID... | 4fc5ce16e9c5ae168b168d18deb77ddebb293939 | 71,310 |
def _play(agents, game_state, time_limit, match_id):
""" Run a match between two agents by alternately soliciting them to
select a move and applying it to advance the game state.
Parameters
----------
agents : tuple
agents[i] is an instance of isolation.Agent class (namedtuple)
game_st... | 2162f3d84856966699834066c227e4c163c0cfa9 | 71,311 |
import torch
def prepare_batch_tensor(batch, device, non_blocking, new_shape=None):
"""Prepare the batch data for training/inference, move data to GPU, reshape
the target if necessary.
Args:
batch (torch.Tensor): A batch of data.
device (torch.device or str): Device to load the backbone a... | 95594fea61dd598e2c6442211bc2ee72cad8af03 | 71,312 |
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
"""
return [
row['id'] for row in CommCareCase.get_db().view(
... | c5353088960671c14e1e48ad1f3fa497fdfff205 | 71,313 |
def getSubNode(prgNode, NodeName):
""" Find Sub-Node in Programm Node
Arguments:
prgNode {ua PrgNode} -- Programm node to scan
NodeName {[type]} -- Name of Sub-Node to find
Returns:
ua Node -- Sub-Node
"""
for child in prgNode.get_children():
if child.get_display_na... | 2da431eff566d7e2c76d4ca4646e15f762c00d4d | 71,314 |
def clean_data(df):
"""
Clean data and create categories Columns.
:param df: Pandas Dataframe. Dataframe Input
:return: Pandas Dataframe. Dataframe cleaned with categories at your own column
"""
# create a dataframe of the 36 individual category columns
categories = df['categories'].str.sp... | 38a6dec9e59c7e6ce10e9b66180332ac61c7c7bc | 71,315 |
def seq2ngrams(seq, n):
"""
'AGAMQSASM' => [['AGA', 'MQS', 'ASM'], ['GAM','QSA'], ['AMQ', 'SAS']]
"""
a, b, c = zip(*[iter(seq)] * n), zip(*[iter(seq[1:])] * n), zip(*[iter(seq[2:])] * n)
str_ngrams = []
for ngrams in zip(a, b, c):
for ngram in ngrams:
str_ngrams.append("".jo... | d207183aba274dc2c374dec5b9c6dc9c8c8e8847 | 71,316 |
import subprocess
def git_diff_pre_commit(fname):
"""Git diff for a pre-commit hook."""
diff = subprocess.check_output(["git",
"diff",
"--cached", fname])
return diff.splitlines() | f067b9bdcfdc0010f3840751722e1c5308a62592 | 71,317 |
def trampoline(fd, evtype, timeout=None, timeout_exc=Timeout):
"""Jump from the current greenlet to the hub and wait until the given file descriptor is ready
for I/O, or the specified timeout elapses
If the specified `timeout` elapses before the socket is ready to read or write, `timeout_exc`
will be r... | 507b2070f6e817146700174a7205aaf0bfdd0c05 | 71,318 |
def check_genotypes(glstring):
"""
Takes a GL String, and checks to see if any unphased genotypes
contain more than one locus. A list of tuples is returned. Each
tuple consists of the genotype, a set of loci found in the genotype,
and a text string. For unphased genotypes, the text string is either
... | 2dc0b0e3cbc148b90173e957dc5e0be738309623 | 71,319 |
def stations_by_river(stations):
"""This function returns a Python dict (dictionary) that maps river
names (the key) to a list of station objects on a given river."""
y = {}
for n in stations:
if n.river not in y:
y[n.river] = [n.name]
else: y[n.river].append(n.name)
ret... | 1e1023cdad87a3fdd5921d08448a4a2e9ceb311c | 71,320 |
def summary(request):
"""
View function for Summary of site.
"""
brokers = []
all_trades = Transaction.objects.filter(type='Buy').values()
for i in all_trades:
if i['broker'] not in brokers:
brokers.append(i['broker'])
summList = []
for i in brokers:
IPOPL... | df06ceb8aad283c61c13a5b3120c28a47d1b41ab | 71,321 |
def Tensor2Image(img):
"""
input (FloatTensor)
output (PIL.Image)
"""
img = img.cpu()
img = img * 0.5 + 0.5
img = transforms.ToPILImage()(img)
return img | dbf6510ef907a74adbbaa53415832212fb84a3aa | 71,322 |
def lc_ksvd(X, y, D, Q, alpha=1, beta=1, lambda1=1, lambda2=1,
sparse_coder=None, max_iter=2, approx=False, mmap=False, verbose=False, n_jobs=1):
"""
X: the data matrix with shape (n_features,n_samples)
y: the vector that contains the label of each datapoint
Q: a matrix with shape (n_atoms,n... | 2a46353a84357d314416b06303ff19b1472ca4c0 | 71,323 |
import re
def parse_align_seq(align_seq, ref_base, max_insertion_size):
"""
解析比对结果中某个位置的所有碱基
"""
base_list = []
it = re.finditer(pattern, align_seq)
for match in it:
base = match.group()
if base.startswith("^") or base == "$":
continue
elif base == "." or ba... | 3cadfa627f4398e9397474bdd914f3007da7a8da | 71,324 |
from typing import Tuple
def xyz_to_bev(
xyz: NDArrayFloat,
voxel_resolution: Tuple[float, float, float],
grid_size_m: Tuple[float, float, float],
cmap: NDArrayFloat,
) -> NDArrayByte:
"""Convert a set of points in Cartesian space to a bird's-eye-view image.
Args:
xyz: (N,3) List of p... | e06c154dcf1a725fa3a52c37d45556df0ac55909 | 71,325 |
import six
def determine_position(position, img, mark):
"""
Options:
TL: top-left
TR: top-right
BR: bottom-right
BL: bottom-left
C: centered
R: random
X%xY%: relative positioning on both the X and Y axes
X%xY: relative positioning on the X axis a... | b4a4ee83778723dceea6a10441d714f0c9b31064 | 71,326 |
import hmac
import hashlib
def verifySignature(message, signature, key, expiresStr=None):
"""
Verify the signature and also that the timestamp has not expired. If expiresStr is None, the timestamp is not checked.
Returns:
Valid - bool
"""
nowTime = Time.syncedNow()
try:
... | e6c85365ea85a8f949973d0dd20f5f0010070093 | 71,327 |
def is_serializable_descendant(base):
"""
Args:
base (type): Base class to examine
Returns:
(bool): True if `base` is a descendant of `Serializable` (but not `Serializable` itself)
"""
if "Serializable" in globals(): # We're doing a forward reference here, class is defined below
... | 1b2da0de39148ead3b9177496b7cdbd6895e3533 | 71,328 |
def part_2(input_data: str) -> int:
"""Need to rack an 'aim'.
Commands mean different:
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by... | 60cf6a884bb6a0a9c69d214a0b883ab7321f7d1b | 71,329 |
def doTest(n):
"""Runs a test. returns score."""
score = 0
l = list(range(1,16))
for i in l:
if input("what is {} to the power of 3? ".format(i)) == str(i**3):
score += 1
print("Correct.")
else:
print("Wrong, the correct answer is {}".format(i**3)... | 83f32bec718e7459218b8863e229d5ecbd479d2c | 71,330 |
def binarize_time_series(layer_state, threshold, absolute=False):
"""
Given a threshold return a binary matrix of 0's or 1's based on threshold
:param layer_state: TxN matrix where N is the number of neurons.
:param threshold: threshold above which the value is considered 1.
:param absolute: whether... | ae4b4059cc4eb85f07461e330c7389dbaa5efc83 | 71,331 |
def compoundInterestPresentValue(p, r, c, n):
"""Compound interest present value
Returns: present value
Input values:
p : principal
r : interest rate
c : number of compounding periods in a year
n : (c * t), total number of compounding periods
"""
pv = (p / ((1 + (r / c)) ** n))
... | eef2b1628caa7d0f986f6bfd06f336083e9cb76a | 71,332 |
def ResourcePageDetails(request, pk):
"""
Retrieve, update or delete a job posting.
"""
try:
resource_page = ResourcePage.objects.get(pk=pk)
except Resource.DoesNotExist:
return HttpResponse(status=500)
if request.method == "GET":
serializer = ResourcePageSerializer(reso... | 98e0ed57ffb2581bc69bc6fdcc2cc8e145f043c8 | 71,333 |
def cifar10_classification_model():
"""
CIFAR10 classification
"""
return get_model(
False,
(3, 32, 32),
[7,7,7],
[1,2,2],
[32,64,128],
10,
1,
13,
0.9,
1,
1,
1,
False,
False,
False,
... | f2d780f4e9568c0a7362d5a7858a898589713378 | 71,334 |
def build_turbine_loc(turbine_x, turbine_y):
"""
Make a DataFrame containing plant layout info
(wind turbine locations).
Args:
turbine_x (np.array): wind turbine locations (east-west).
turbine_y (np.array): wind turbine locations (north-south).
Returns:
turbineLoc (pd.DataF... | 2786e0539bcabbf099cfd540b90f84976b9b1b38 | 71,335 |
from typing import Dict
from typing import Any
def _BigQueryToElwc(pipeline: beam.Pipeline, exec_properties: Dict[str, Any],
split_pattern: str) -> beam.pvalue.PCollection:
"""Read from BigQuery and transform to ExampleListWithContext.
When a field has no value in BigQuery, a feature with no ... | 68a854cdd054cac5739a744ea69a05d35bff6d4f | 71,336 |
def clean_spiketimes(spikeTimes, mindT=0.7):
"""
Clean up spike time array, removing all less than mindT
spikeTimes is a 1-D list or array
mindT is difference in time, same units as spikeTimes
If 1 or 0 spikes in array, just return the array
"""
if len(spikeTimes) > 1:
dst = np.diff(... | 6e5667961243ac6a51173f7da6eb661f78c9d368 | 71,337 |
import os
def jupyter_visualize_beps_sho(pc_sho_dset, step_chan, resp_func=None, resp_label='Response', cmap=None, verbose=False):
"""
Jupyer notebook ONLY function. Sets up an interactive visualizer for viewing SHO fitted BEPS data.
Currently, this is limited to DC and AC spectroscopy datasets.
Para... | 24cb10fa9eca9aa84a3700818723bc5a88bd1971 | 71,338 |
from pathlib import Path
def euler(radius = 3, angle = 90, p = 1.0, use_eff = False, num_pts = 720):
""" Create an Euler bend (also known as "racetrack" or "clothoid" curves)
that adiabatically transitions from straight to curved. By default,
`radius` corresponds to the minimum radius of curvature of the... | e3808021e512bef6b6f4642f3a657893712dd317 | 71,339 |
import numpy
def best_dice(l_a, l_b):
"""
Best Dice function
:param l_a: list of binary instances masks
:param l_b: list of binary instances masks
:return: best dice estimation
"""
result = 0
for a in l_a:
best_iter = 0
for b in l_b:
inter = 2 * float(numpy.... | d00c668fe8c97fa2a78a62ac94492c665dc4a311 | 71,340 |
def isTestHub(node):
"""Check if a node is a Plugable 7-Port Hub
(Model USB2-HUB7BC)
The topology of this device is a 4-port hub,
with another 4-port hub connected on port 4.
"""
if not isinstance(node, find_usb_devices.USBDeviceNode):
return False
if 'Test HUB' not in node.desc:
return False
if... | c5255364d3fee0e5f30d08f0d1e6bb8273b63343 | 71,341 |
import pathlib
def get_mastodon(config_path):
"""Returns a Mastodon connection object."""
p = pathlib.Path(config_path)
instance = get_instance(p)
if instance is None or not is_configured(config_path):
raise RuntimeError("You must call generate_config first")
return mastodon.Mastodon(
... | 3e2d616b2a935c7e3c4a00582c72d01548e7b981 | 71,342 |
def dither(tensor, shape, amount, time=0.0, speed=1.0):
"""
"""
height, width, channels = shape
white_noise = basic([height, width], [height, width, 1], time=time, speed=speed,
distrib=ValueDistribution.simplex)
return effects.blend(tensor, white_noise, amount) | 7134eb292d276c735f23f27969aaf5ad77ada933 | 71,343 |
def _enum_font_names(logfont, textmetricex, fonttype, param):
"""callback function to be executed during EnumFontFamiliesEx
call for each font name. it stores names in global variable
"""
global FONTDB
lf = logfont.contents
name = lf.lfFaceName
if PY3K:
# [ ] check this works
name = name.decod... | 8baec5f660fac26f93d3dbeed2c27531331a0eb9 | 71,344 |
import os
import re
def fileFilter(infile, exists=True):
"""
checks that the input imagic file exists, and returns the filename
without the extension
"""
fname,ext=os.path.splitext(infile)
if exists is True:
if not (os.path.exists(fname+".hed") and os.path.exists(fname+".img")):
apDisplay.printError("inpu... | 1e8fb814b0ee84ff961dfa6cfd6bcdfb4d138394 | 71,345 |
def hex_list_to_dec(hex_list):
"""Takes a hexidecimal number as a list of its digits represented as
strings. Returns the base 10 conversion of the hex as an integer.
"""
hex_dict = gen_hex_dict()
hex_list.reverse()
dec_sum = 0
for i, h in enumerate(hex_list):
dec_sum += hex_dict[h] ... | f1814bea274e7c156dc471a88131d6a053a5a1e5 | 71,346 |
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
import os
def make_video_from_images(img_paths, outvid_path, fps=25, size=None,
is_color=True, format="XVID"):
"""
Create a video from a list of images.
@param outvid output video
@param images list of ... | e8fbd061f576c156491610a3f7b5caa164f694e1 | 71,347 |
def path_to_tensor(img_path):
"""
Getting a tensor from a given path.
"""
# Loading the image
img = image.load_img(img_path, target_size=(512, 512))
# Converting the image to numpy array
x = image.img_to_array(img)
# convert 3D tensor to 4D tensor with shape (1, 512, 512, 3)
x = ... | 42cf19b3f26afa02ba124ed8dd7f6b8fa7335ea1 | 71,348 |
def preorder(root):
"""Preorder depth-first traverse a binary tree."""
ans = []
stack = [root]
while stack:
node = stack.pop()
if node:
ans.append(node.val)
stack.extend([node.right, node.left])
return ans | e322df77a973f30b0745b36540a0f66b2ce29e6d | 71,349 |
def scramble(a, axis=0):
"""
Return an array with the values of `a` independently shuffled along the
given axis
"""
b = a.swapaxes(axis, -1)
n = a.shape[axis]
idx = np.random.choice(n, n, replace=False)
b = b[..., idx]
return b.swapaxes(axis, -1) | 94720f93886fd72163ede0e79c7423095a2a08bd | 71,350 |
def minify(f):
"""
Returns the "minified" file data with removed __debug__ code blocks.
"""
data = ''
debugBlock = False # Marks when we're in a __debug__ code block.
elseBlock = False # Marks when we're in an else code block.
# The number of spaces in which the __debug__ condition is i... | 8ae1101aafb922331e45e7354d9bd8b937044990 | 71,351 |
def cylindrical_to_cartesian(ro, phi, z, degrees=True):
"""
Convert cylindrical coordinates (ro, phi, zeta) to cartesian (x, y, z).
Parameters
----------
ro: (N,) ndarray
Radial distance.
phi: (N,) ndarray
Angular position.
z: (N,) ndarray
Altitude.
degrees: bool... | 8393d936c316605718fe20d7ae44cf9771394214 | 71,352 |
async def _get_subscribers_prompt(channel: str) -> str:
"""Take prompt about channel subscribers"""
subscribers = await MediatorDependency.mediator.channels.get_subscribers(channel)
prompt = f"<b>{channel} subscribers:</b>\n"
if subscribers:
prompt += "".join(f"/{s.telegram_id} - {s.name}\n" for... | cd5dc28ddffd777dc75b8dbc8a5ba28ced5ab1c8 | 71,353 |
import subprocess
def resolve_name(name):
"""Return the v4/v6 IP addresses for a given name, using local resolver"""
args = ['dig', '+short', name, 'A', name, 'AAAA']
return subprocess.check_output(args).decode().splitlines() | 2f63d2949bf6e66afa979b00fcb0c1b5a6ea2aed | 71,354 |
def dqAccelerationPropagationCOM(robot : object, dWdqCOM0 : np.array, Wdq : list, WdqCOM : list, dWdq : list, qd : np.array, qdd : np.array, symbolic = False):
"""Using Dual Quaternions, this function computes angular and linear acceleration to the j-th center of mass of a serial robot given reference frames' ones. S... | 9399e82ceb8ad8c9bd75b0ed36de70c6c314bbf3 | 71,355 |
def summarize_unexpected_results(port_obj, expectations, result_summary,
retry_summary):
"""Summarize any unexpected results as a dict.
FIXME: split this data structure into a separate class?
Args:
port_obj: interface to port-specific hooks
expectations: te... | f8ba1389aa6c576b1a845859077f17cbc1504b77 | 71,356 |
def joinfields(words, sep = ' '):
"""joinfields(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
res = ''
for w in words:
res = res + (sep + w)
return res[len(sep):] | 0941a43811c992417a24ea59c77b4172117d3510 | 71,357 |
def get_FID(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""
Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable version by Dougal J. ... | dc0bffb0a970c7cece9eda7925bb45ff2ce99a59 | 71,358 |
from typing import Callable
from typing import Any
def has_results(func: Callable[..., Any]) -> Callable[..., Any]:
"""Check whether a particular function has results when filtering its data.
Args:
func: The function to be decorated
Returns:
The decorated function.
Raises:
I... | d52d43f2044c325a7013a2257c07181742a36610 | 71,359 |
from datetime import datetime
def get_all_to_dest(spark, sqlContext, destination):
"""makes the link between destination and position tables"""
d, p = load_dest_data(spark, sqlContext)
# select every mmsi - day couple going to the destination
dest = d.filter(d.destination == destination).collect()
... | e0e92faa6a6a2332cf4bf04731a8159f05b08813 | 71,360 |
import requests
import shutil
def download(url):
"""Retrieve a file from the Web, return local path."""
filename = p.basename(url)
cache_file = p.join(data_dir, filename)
if not p.exists(cache_file):
print('Retrieving: {}'.format(url))
with requests.get(url, stream=True) as r:
... | 1a92a704139ea245db86db2f11927c54bbc1e07b | 71,361 |
def prompt_import_rsa_key_from_file(filepath):
"""Trys to load the key without password. If a CryptoError occurs, prompts
the user for a password and trys to load the the key again. """
password = None
try:
import_rsa_key_from_file(filepath)
except toto.ssl_commons.exceptions.CryptoError, e:
password ... | e7f77dcec3796e24a855b315eb46eaef656d850d | 71,362 |
def get_histograms(img_list):
"""creates a histogram for each image in the list
Args:
img_list (list): each entry is a decoded image in matrix form
Returns:
list: each entry in this list corresponds to a image from the img_list
each entry is a dict with red, green, blue as keys... | 700488f313eb05ae924933bd195ddba65ee6a515 | 71,363 |
def strip_quotes(want, got):
"""
Strip quotes of doctests output values:
>>> strip_quotes("'foo'")
"foo"
>>> strip_quotes('"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"... | 7696bc2db290cbba14821908cdbbae2c3c10eab2 | 71,364 |
import glob
import configparser
def load_species_from_param_files(fns,
init_world,
custom_module_fns=None):
"""
Load all available species parameter files.
Parameters
----------
fns : list of str
Input filenames of specie... | 6e82ddd44e394d970803e953fb6f18609b8e2eab | 71,365 |
import abc
def get_rename_function(mapper):
"""
Returns a function that will map names/labels, dependent if mapper
is a dict, Series or just a function.
"""
if isinstance(mapper, (abc.Mapping, ABCSeries)):
def f(x):
if x in mapper:
return mapper[x]
... | 1b5ef2d7454b4c4534886a5d0bddb4678f19ef4a | 71,366 |
import requests
from bs4 import BeautifulSoup
def get_channels(country):
"""
Get the list of channels.
:return: list
"""
channels = []
html = requests.get(MAINLIST[country]).text
mlink = SoupStrainer('div', {'class':'nav fusion-mobile-tab-nav'})
soup = BeautifulSoup(html, parseOnlyThes... | a0fddf203aad975e917b65882e470c4641631557 | 71,367 |
def encrypt_bytes(key, source):
"""
Encrypts pure bytes (used for small sources)
CBC mode, including PKCS#7 padding
"""
encryptor, IV = _build_encryptor(key)
byteOutput = IV
byteOutput += _encrypt_chunk(source, encryptor, True)
return byteOutput | a5234159d4052639ed876d504b6784d6a651a2d0 | 71,368 |
import time
def response_to_dict(response, spider, include_request=True, **kwargs):
"""Returns a dict based on a response from a spider"""
d = {
'time': time.time(),
'status': response.status,
'url': response.url,
'headers': dict(response.headers),
'body': response.body... | 35b725a67fdf025b879e97c5d68b321fedfaf313 | 71,369 |
import socket
import fcntl
import struct
def get_ip_address(ifname):
"""
Get the ip address from the specified interface.
>>> get_ip_address('eth0')
'192.168.0.7'
@type ifname: string
@param ifname: The interface name. Typical names are C{'eth0'},
C{'wlan0'}, etc.
@rtype: string
@retu... | 731575a6b642884d7aa74a950ed109fca1e2086a | 71,370 |
def edge_predicate(func: DictEdgePredicate) -> EdgePredicate: # noqa: D202
"""Decorate an edge predicate function that only takes a dictionary as its singular argument.
Apply this as a decorator to a function that takes a single argument, a PyBEL node data dictionary, to make
sure that it can also accept ... | e5db6490796bec57326e6cf6b36c5fd62bd9af59 | 71,371 |
def totient(n):
"""Takes integer n and returns Euler's Totient function (phi(n))"""
phi = n
factors = set(prime_factors(n))
for _ in factors:
phi *= (1 - 1/_)
return int(phi) | 6edbcf650ebc758daa37c3e527836d5b943611f0 | 71,372 |
import functools
def debug(func: callable, tag: str = DEFAULT_TAG):
"""
Print the function signature and return value
:param func: callable function to be debugged.
:param tag: a unique string to identify the output in the console window.
:return:
"""
name = GetFunctionName(func)
... | 46ab344e566c29706c4a876e1fa4628df6c6704c | 71,373 |
import copy
import sys
import time
import multiprocessing
def execute(args: dict) -> dict:
"""
Takes arguments in form of dictionary and runs Msf based on them.
:param args: Arguments from which is compiled and ran medusa command
:return: Module output containing:
return_code (0-succe... | 8390b01e65abb068cd8b47b69337cd2b23243947 | 71,374 |
def validate_id(id:int)->feed_models.Feed:
"""
Method to verify with id if a feed exists
:param id: feed id
:type id: int
:raise: ValueError
:return bool
"""
try:
feed = feed_models.Feed.objects.get(id=id)
except feed_models.Feed.DoesNotExist as e:
... | 79495ab4bbd62f155c4fd555bb957412dc5a0d94 | 71,375 |
def _parallel_build_trees(X, y, tree, interval, lag, acf_min_values):
"""
Private function used to fit a single tree in parallel.
"""
temp_lag = lag
if temp_lag > interval[1] - interval[0] - acf_min_values:
temp_lag = interval[1] - interval[0] - acf_min_values
if temp_lag < 0:
te... | 45e11faf6fa3a92fb6978759feb5ac3c487dd810 | 71,376 |
def drop_terms_containing(e, e_drops):
"""
Drop terms contaning factors in the list e_drops
"""
if isinstance(e, Add):
# fix this
#e = Add(*(arg for arg in e.args if not any([e_drop in arg.args
# for e_drop in e_drops])))
new_ar... | c2cb330e81cee9927ef2bdb08d1198a7f21488a4 | 71,377 |
def SetLabel(*labels):
"""Sets a label on a function so we can run tests with different types."""
def Decorator(f):
# If the method is not already tagged, we replace its label (the default
# label is "small").
function_labels = getattr(f, "labels", set())
f.labels = function_labels.union(set(labels)... | 8a4415e039d0cb7c69a9fd03a3c17c055d5e8fe4 | 71,378 |
from typing import Optional
def gather(
inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = None,
) -> Tensor:
"""
Create gather operator for collective communication.
:param inp: input tensor.
:param group: communication group.
:param device: execution device.
"""
o... | 7d5c5d42e5e403369c670a0b827fc07e460ffe70 | 71,379 |
def _talismane_tree(tree_str: ty.Iterable[str]) -> libginger.Tree:
"""Create an Universal Dependencies tree from a Talismane tree.
Talismane outputs are essentially CoNLL-X files, with incompatible
stylistic idiosyncrasies.
"""
conllx_str = [s.replace("|\t", "\t") for s in tree_str]
return _con... | cb22e30df813a8a4895a4f2746115322e9a35289 | 71,380 |
def get_table_list():
"""
Read the 'TABLES' table found under the hidden '_tables' worksheet.
This table is populated from launcher.json file and is used to
determine the table names defined under each worksheet
Returns:
table(dict): k,v, k=worksheet_name and v=list of tables
"""
t... | 0778e2849122751f12822cf0f0357d4c0b6b651d | 71,381 |
from typing import Counter
def percentile(data: list, p=0.5):
"""
:param data: origin list
:param p: frequency percentile
:return: the element at frequency percentile p
"""
assert 0 < p < 1
boundary = len(data) * p
counter = sorted(Counter(data).items(), key=lambda x: x[0])
keys, c... | ac0a3a4705579c1b6a5165b91e6dcad65afcd1f4 | 71,382 |
def parse(module_text, nodes=None):
"""Return abstract syntax tree for `str`ing `module_text`.
`module_text` is a module specification.
Use the syntax tree classes from `nodes`.
For example:
```python
from tla import parser
from tla.to_str import Nodes
module_text = r'''
---- MODU... | 1bdaf07b92963ecc596677327fcc300b572eaf27 | 71,383 |
def _MatchHandler(handler, path):
"""Match a path to a handler.
Args:
handler: A handler dictionary.
path: The path portion of the url.
Returns:
A Page object or None.
"""
if 'static_dir' in handler:
return _MatchStaticDir(handler, path)
elif 'static_files' in handler:
return _MatchSta... | 29713b4bf4728ee7bb430ad981541a2f48b39a6f | 71,384 |
def _get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
return self.get_path_from_parent(parent)
... | 8f213fcbe3612790d4922d53e0e2a4465b098fe6 | 71,385 |
def first_or_default(self, predicate=None, default_value=None):
"""Returns the first element of an observable sequence that satisfies
the condition in the predicate, or a default value if no such element
exists.
Example:
res = source.first_or_default()
res = source.first_or_default(lambda x: x ... | 35a9896cfec6e17ff0e3f1e8d8144ba1237fa03a | 71,386 |
def get_category(node):
"""Return a category label for a given specific protein ontology node."""
name = bio_ontology.get_name(*bio_ontology.get_ns_id(node))
category = categories.get(name)
if category:
category_node = category_map[category]
return category_node
return None | ed4da8fef5e44193122b02f5175c1708b0fe8f46 | 71,387 |
def selectCheckerPy(object):
"""Get a checker for the given object
The appropriate checker is returned or None is returned. If the
return value is None, then object should not be wrapped in a proxy.
"""
# We need to be careful here. We might have a proxy, in which case
# we can't use the type.... | bcd394adf5ab73e79b0aa12129f94614f7722c90 | 71,388 |
def assortative_mating(obs, exp, col_x, col_y, boundaries = None):
"""
Assortative mating between genotypes across the hybrid zone, and within
spatial bins.
Assortment probabilities for the whole population are calculated as the mean
number of mating events between individuals of the same genotype.... | 94d8301d0869180cefd68c6e48aa72f86d33887e | 71,389 |
def strdigit_normalize(digit):
"""Normalizes input to format '0x'. Example: '9' -> '09'"""
assert type(digit) is str, 'Invalid input. Must be a string.'
s = int(digit)
assert s >= 0, 'Invalid input. Must be string representing a positive number.'
if s < 10:
return '0' + str(s)
return digit | 41b119b4b8b19f978bf4445fc81273f7e62af59a | 71,390 |
import requests
def request_url(url):
"""
Function to send https or http request to this url and return code result.
Parameters
----------
url : string
This variable contain url must be checked
Returns
-------
status_code : int
Code result
"""
try:
ur... | 884d20d33f02110b31e47a29077cb4e093e93536 | 71,391 |
from typing import Type
from typing import Optional
from typing import List
from typing import Any
def _get_trials_sqa(
experiment_id: int,
trial_sqa_class: Type[SQATrial],
load_trials_in_batches_of_size: Optional[int] = None,
trials_query_options: Optional[List[Any]] = None,
) -> List[SQATrial]:
... | 53f31b62ed84260dd5fb50f43f6cbb23217641fc | 71,392 |
def overlap_and_add(spectrum,
signal,
sample_rate,
frame_length=32,
frame_shift=8,
window_type="hanning",
preemphasis=0.0,
use_log=False,
use_power=False,
... | 8f953bde0b8e9b2c20509f2e8e5dde90438ef0df | 71,393 |
def push_api(request):
""" Update the content of a tile (widget) """
if not check_sanity_request(request):
return handleHttpError(request)
HttpData = request.POST
tile_id = HttpData.get('tile_id', None)
tile_template = HttpData.get('tile_template', None)
tile_data = HttpData.get('data', ... | 4a606bd570a01748c2178406a28485f4d52a2744 | 71,394 |
import os
def get_geant_installation():
"""
By checking low energy data ftom G4 installation,
return path to the G4 setup, typically in /opt/Geant/vXXXX
:returns: formatted string
:rtype: str
"""
try:
g4ledata = os.environ["G4LEDATA"]
except KeyError:
raise RuntimeErr... | b3d64d41c519c8d8538348024dc442a6d2cdfa12 | 71,395 |
import csv
def csv_to_list(dataset_fname, header = False, y_column = -1):
"""
Reads a csv file and returns the contents of that file as a 2-D list.
Delineates x (independent) variables from y (dependent) variable.
dataset_fname - the file name for the dataset to read.
header - whether the dataset... | 0cceef9e80f1063305a77d420de5d7a2141ceec5 | 71,396 |
def share_emotion_book() -> FlaskResponse:
"""
XHR procedure adding a new entry into the visitor log. The emotion is
neutral if the user has open a book or it is a like if the user clicked
on the "Like" button.
Raises:
404: if the request is not POST.
"""
if "emotion" not in request... | 4e4ac6082f222a44c7a2443c7e500676729ac9f0 | 71,397 |
def make_field(field_name: str, schema: Schema) -> TextArea:
"""Create a field that's suitable to the specified schema, such as
a TextArea. The schema is used to determine the proper type of field
as well as the validator that applies.
"""
# At the moment, the only supported field type is TextArea. ... | 30f14aaa3fdd1a4ef9eac66b1837ab066ff045af | 71,398 |
import argparse
import os
import sys
import json
def main_handler():
"""do the work. CLI"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--threads", metavar="THREADS", type=int, default=1)
parser.add_argument("--tmpbucket", metavar="TMPBUCKET", help="bucket name in whi... | b6a4caaf7b2d8caa380b8ec612a1cf0c14176901 | 71,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.