content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def Merge2LinkLists(lists1, lists2):
"""
链表合并的递归实现
:param lists1:
:param lists2:
:return:
"""
if not lists1:
return lists2
if not lists2:
return lists1
l = None
if lists1.val < lists2.val:
l = lists1
l.next_ = Merge2LinkLists(lists1.next_, lists2)... | da2ebf2a1716feb6b6810f9bf20c1dfdc9ce7edf | 675,671 |
def pow_notation(number, sig_fig=2):
"""
Converts a number to scientific notation keeping sig_fig signitifcant figures.
"""
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a,b = ret_string.split("e")
b = int(b) #removed leading "+" and strips leading zeros too.
return r"10^{{{0}... | e39a2429b87751fd8afb489469df6609b7f8ab59 | 675,672 |
def neg_edges(data):
"""
Negate edge half (non-middle) of spectra.
"""
data[..., :int(data.shape[-1] * 1. / 4)] = \
-data[..., :int(data.shape[-1] * 1. / 4)]
data[..., int(data.shape[-1] * 3. / 4):] = \
-data[..., int(data.shape[-1] * 3. / 4):]
return data | dbed9427d8a430a326255e86d5349b3f6b501311 | 675,673 |
def fake_agent() -> str:
"""
The original FAKE_USER_AGENT in config.py:
'Mozilla/5.0 (Windows NT 6.1; rv:84.0) Gecko/20100101 Firefox/84.0'
Works with Startpage when nothing else will.
:return: static user agent string.
"""
# NOTE that the Firefox ver can be any from firefox_agent()
re... | 27e944ab127f150704268ffcfed2c06cb20bb71c | 675,674 |
import os
def extract_frames(ffmpeg_path, img_path, video_path, n_frames=10):
"""
Extracts frames from video_path to img_path.
"""
error = ""
print('{} -i {} -framerate {} -vsync 0 -qscale:v 2 {}/%06d.jpg'.format(ffmpeg_path, video_path, n_frames, img_path))
failed_call = os.system('C:\ffmpeg\... | 6e865393304fefebdccf72e8463c08d3b3ecbd7f | 675,675 |
def data_reverse_(data):
"""
Reverses a stream of bytes
:param data:
:return:
"""
return [b for a in range(len(data) - 8, -1, -8) for b in data[a : a + 8]] | 8848593be8b67de903aacce810b9a5fe7ad01993 | 675,676 |
import math
def optimum_qubit_size(precision: int, error: float) -> int:
"""
Return the number of qubit required for targeted number of decimal
and error rate.
"""
return math.ceil(precision + math.log2(2+1/(2*error))) | 031f35f4d461d712b53f41e3697c73fad16b0b21 | 675,677 |
import json
import argparse
def _unpack_json_args(args):
"""Restore arguments from --json-args after a restart.
When restarting, we serialize the argparse namespace into json, and
construct a "fake" argparse.Namespace here based on the data loaded
from json.
"""
new_args = vars(args)
data... | d21348bc29e6f603e74d4ecc69f684ddc3f7366b | 675,678 |
def upper_triangle(n_df, n1, n2):
"""Makes a (sparse) matrix upper triangular.
"""
return [edge for edge in n_df if edge[n1] < edge[n2]] | c2f8a022e71eb1448e3c47dac79f0f3d1f4be7ac | 675,679 |
import requests
def associate_label(**validated_data):
"""Service to associate messenger labels to users.
:param validated_data: Serialized data from PSIDListSerializer.
:returns: Updated validated_data with label_associated_to field.
"""
url = 'https://graph.facebook.com'
batch_data = ''
... | 289f66c3772f0d3d8a49b8675e28df675d3bd6af | 675,680 |
def s_share_constant(params, substep, state_history, prev_state, policy_input):
"""
Checks share multiplicative constant. Use for i,j,k for now
"""
# MAKE a Product function loop through all assets dynamic
# print('constant here 1')
pool = prev_state['pool']
Si = pool.get_share('i')
Sj... | 68d27582115a17ad90f3b594d59eba0d3cd56a44 | 675,681 |
def gcp_monitoring_proto_deps():
"""Cc proto libraries for GCP monitoring APIs
"""
return [
"@com_google_googleapis//google/api:distribution_cc_proto",
"@com_google_googleapis//google/api:label_cc_proto",
"@com_google_googleapis//google/api:metric_cc_proto",
"@com_google_goog... | a5481fec7f7ade938eaddd8bd2830a89d6d6e560 | 675,682 |
def handle_refund(loan_id, amount):
"""Handles a refund postback for the specified loan_id and amount."""
return '' | 777da70dbecb2079cae51caaa601f15578d697ec | 675,683 |
def authors_string(authors):
"""Return formatted string of all authors."""
def is_primary(a):
return not isinstance(a, dict) or a.get('primary', True)
primary = ' and '.join(
a['name'] if isinstance(a, dict) else a
for a in authors
if is_primary(a))
secondary = ' and '.j... | f67df023dfdaea4848f792f6aac14dc13db680a8 | 675,684 |
import re
def parse_integrity_error_message(error):
"""Parse IntegrityError message
Keyword arguments:
error -- IntegrityError
"""
content = re.search('\((.*?)\)=\((.*?)\){1,}(.*)', str(error))
if content:
field = content.group(1).title().replace('_', '')
formatted = ... | 0b9cda84dd3691f2650d584169255d3bc893109a | 675,686 |
import re
def verify_installation(output):
"""Verify whether the installation is successful or not.
Args:
output (str): Output after the execution
Returns:
TYPE: bool
"""
found = re.findall(
r'([0-9]+\supgraded).*([0-9]+\snewly installed)',
output
)
upgra... | 8f0d1c08d96ab88d517e0efce0ecd7afeaf8beb1 | 675,687 |
def get_current_weather_desc(data):
"""Get the current weather description. These values are undocumented.
:param data:
:return: e.g. 'Partly Cloudy', 'Light Rain'
"""
return data['current_condition'][0]['weatherDesc'][0]['value'] | aebb28d30de09f14867aee8ffc0a6f1db31f5fd0 | 675,689 |
import torch
def max_score_context_matrix(context_matrix_dict, prediction_head):
"""For each context matrix value in a dict of matrices, project to BxMxK and take max as final score."""
batch_size, M, K, H = list(context_matrix_dict.values())[0].shape
preds_to_cat = []
for key in context_matrix_dict:
... | ee17714224077fd5ec69a4245cb7b3dbb84d3409 | 675,690 |
import csv
def save_to_csv(data: list, file_name: str) -> bool:
"""
Saved given data to .csv file.
Parameters
----------
data: list, required
Data produced by function prepare_data_to_save().
file_name: str, required
Path and file name to where save file. It should not include... | 02726bad42bc3817bbae5dbaf6252744361ee020 | 675,691 |
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value)):
"""Format an argument spec from the 4 values ret... | e649df3304da0687090e7e0520724b72edaff1d4 | 675,692 |
def get_roi_names(contour_data):
"""
This function will return the names of different contour data,
e.g. different contours from different experts and returns the name of each.
Inputs:
contour_data (dicom.dataset.FileDataset): contour dataset, read by dicom.read_file
Returns:
roi_se... | 431e52f70a1153af164f9babb6066bb52661a8f7 | 675,693 |
def get_error_title(error_path):
"""
return error title list.
"""
error_title_list = []
f = open(error_path, 'r')
lines = f.readlines()
for ind in range(len(lines)):
if '---' in lines[ind]:
ind_title = ind+1
title = lines[ind_title].strip()
error_t... | caefd494a68cd6bf322f1dd3497000418157d2b2 | 675,694 |
def create_primes_1(max_n):
""" creating primes up to a maximum value. The even numbers are not
touched. The primes itself are used to check for possible division. """
primes = []
for val in range(3, max_n+1, 2):
found = False
for divisor in primes:
if val % divisor == 0:... | a3dbe10a14448a6f71dc6ed99fd163a3a14e9f80 | 675,695 |
def is_empty(any_structure):
"""Helper method to check if structure is empty."""
if any_structure:
return False
else:
return True | e9287105f3742f7d7255b28fdc76635059a25a87 | 675,696 |
def shift_induction_times(exp, min_start=20, min_end=30):
"""
Shifts the induction start and end times forward or backward by separately
specified numbers of minutes. Returns an experiment object with a new
induction record.
:param min_start: int
Number of minutes to shift induction start ... | 2a0469c8cd1e15ea6938466ab2d4065b5fa1fc05 | 675,697 |
def subfile_time(uniform: int) -> str:
"""Time format of subtitle files"""
subtime = [uniform % 1000]
uniform //= 1000
subtime.append(uniform % 60) # seconds
uniform //= 60
subtime.append(uniform % 60) # minutes
uniform //= 60
subtime.append(uniform % 60) # hours
time_builder = [... | 6fd22106a10f78769c5ca0b25e0f8ffbae945aa9 | 675,698 |
def phalf_from_ps(bk, pk, ps):
"""Compute pressure of half levels of hybrid sigma-pressure coordinates."""
return ps*bk + pk | e664515195412c46fbef8d509c2b214c57c49cbb | 675,699 |
def clean_attribute_name(attribute_name):
""" Return the sanitised attribute name to use as parameter name """
new_name = attribute_name.lower()
new_name = ''.join(ch for ch in new_name if (ch.isalnum() or ch == '-'))
new_name = new_name.replace('-', '_')
return new_name | c69c98802b69a8c7087ccc18276c5e76e25741eb | 675,701 |
def get_values():
"""Get the acceleration measurements in all axes at once, as a three-element tuple of integers ordered as X, Y, Z. By default the accelerometer is configured with a range of +/- 2g, and so X, Y, and Z will be within the range of +/-2000mg."""
return (2,2,2) | c7f30cf0f87f11642ea7cc6d7ed536c1b5366d78 | 675,703 |
def get_shape_points(cur, shape_id):
"""
Given a shape_id, return its shape-sequence.
Parameters
----------
cur: sqlite3.Cursor
cursor to a GTFS database
shape_id: str
id of the route
Returns
-------
shape_points: list
elements are dictionaries containing th... | 35dba0d08c6f3e1fc53e3301f8fc9b0337fa2caf | 675,705 |
def control_surface_deflection_command(case,aircraft):
"""Writes the control surface command template
Assumptions:
None
Source:
None
Inputs:
avl_object
case
Outputs:
em_case_command
Properties Used:
N/A
"""
cs_template = \
... | 323499a8561a60b7b448001a86f3d61895918946 | 675,706 |
def preprocess_rsa_key(key_str):
"""Make Android and iOS RSA keys compatible with cryptography library.
Android and iOS have slightly wonky, non-standard key formats. This updates
the key to be standardized and compatible with pyca/cryptography.
"""
if key_str.startswith("-----BEGIN CERTIFICATE"):
... | 12edbe5b9ba34c4d1b483f25058f75109e1fc4c2 | 675,707 |
import random
def reproduce(parent1, parent2):
"""generate offspring using random crossover"""
# random crossover point
crossover = random.randrange(0, len(parent1))
# construct children
child1 = parent1[0:crossover] + parent2[crossover:]
child2 = parent2[0:crossover] + parent1[crossover:]
... | c366efecc2c61c3c1092ba73a54394cceb01e7ce | 675,708 |
import torch
def transfer_weights(tf_model, torch_model):
""" Example function on how to transfer weights from tensorflow model to pytorch model
Parameters
----------
tf_model : tensorflow model
Weight donor
torch_model : pytorch model (torch.nn.Modules)
Weight recipient
... | e5eb62c796375cd280700754689cda2aa8c8df3f | 675,709 |
import argparse
def get_python_args():
"""
set up to read project name from command line
Returns:
(string) the project name
"""
parser = argparse.ArgumentParser()
parser.add_argument("-p",
"--project",
type=str,
... | 0bc5c9eb3ba9117a241c296fa1f745df0bf5c2f1 | 675,710 |
from typing import List
def reverse_array2(input: List) -> List:
"""
Approach2: Sliding Window in place
1. count the number of elements
2. Swap elements in place
Time Complexity: O(n)
Space Complexity: 0/ no extra memory required
"""
inp_len = len(input)
l_pointer, r_pointer = 0, i... | 366fc85d6a2006079f1a489d7329ddd893b055b7 | 675,711 |
def Trouver_ligne(fichier_txt, string_a_chercher):
"""Donne la ligne du string (vecteur) string demandé"""
num_ligne = 0
resultat = []
with open(fichier_txt, 'r', encoding='utf-8') as fichier_lecture:
for ligne in fichier_lecture:
num_ligne += 1
if string_a_chercher in li... | dcb5bf92afdbe37620f5c3de4730aadfb3e8ab40 | 675,712 |
def service_level(orders_received, orders_delivered):
"""Return the inventory management service level metric, based on the percentage of received orders delivered.
Args:
orders_received (int): Orders received within the period.
orders_delivered (int): Orders successfully delivered within the p... | 8132596dbb8e845aa116bb2451ef89761897b5db | 675,713 |
import argparse
def parse_args():
"""parse"""
parser = argparse.ArgumentParser(description='Test an action recognizer')
parser.add_argument('config', help='test config file path')
args = parser.parse_args()
return args | 8a8f64e13c98dbd16781bf15b87020c7eaabe340 | 675,714 |
import requests
import re
def get(url: str) -> dict:
"""
imgs、text
"""
data = {}
headers = {
"user-agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/ 53\
6.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"
}
with requests.ge... | 6c7636f6e10b50d69c8b0ba717721c8d9721ad6a | 675,715 |
def easy_emptylist(l):
"""Takes a list and returns True for empty list, False for nonempty"""
return not l | 6336d0750de4626b94861bbdfc7b53d27b85d518 | 675,716 |
def remove_dash(string):
"""
Removes the dash from the end of the string if there is one there.
:string: (str) an input string
:returns: (str) input string with no dash at the end of it
"""
if string[-1]=='-':
return string[:-1]
else:
return string | a7f53417710cf9d8af2e2a96365e618c33a84136 | 675,717 |
def regroupOptionsByName(options):
"""
Regroupe les option d'une liste par nom
Args:
options: La liste d'option
Returns:
Liste d'option groupe
"""
groupedOptions = []
groups = {}
for option in options:
groups.setdefault(option.name, list()).append(option)
for... | 98b6d5a4fc763e3d295295da5226f44f56984219 | 675,718 |
def skewed_percentile_to_label(percentile):
"""
Assigns a descriptive term to the MMSE T-score based on its degree of skewness.
"""
if percentile > 24:
return 'WNL'
elif 9 <= percentile <= 24:
return 'Low Average'
elif 2 <= percentile <= 8:
return 'Below Average'
elif... | a1a6ea02c899b734f39f8f6d87477304f758ec41 | 675,719 |
import torch
def lossFunctionKLD(mu, logvar):
"""Compute KL divergence loss.
Parameters
----------
mu: Tensor
Latent space mean of encoder distribution.
logvar: Tensor
Latent space log variance of encoder distribution.
"""
kl_error = -0.5 * torch.sum(1 + logvar - mu.pow(2) ... | 2a9cc400d9a357f69f3f9964304c4cbc0ac4331e | 675,721 |
import torch
def constant_pad_1d(input,
target_size,
value=0,
pad_start=False):
"""
Assumes that padded dim is the 2, based on pytorch specification.
Input: (N,C,Win)(N, C, W_{in})(N,C,Win)
Output: (N,C,Wout)(N, C, W_{out})(N,... | 0353becc792e49406cdba9a3d981f44ffb362cb9 | 675,722 |
def deleted_genes_to_reactions(model, genes):
""" Convert a set of deleted genes to the respective deleted reactions.
Arguments:
model (CBModel): model
genes (list): genes to delete
Returns:
list: list of deleted reactions
"""
if isinstance(genes, str):
genes = [ge... | 22cd57d35efe6b02aaa0cb3d5e05b9f817f63d10 | 675,723 |
def paramsDictNormalized2Physical(params, params_range):
"""Converts a dictionary of normalized parameters into a dictionary of physical parameters."""
# create copy of dictionary
params = dict(params)
for key, val in params.items():
params[key] = val * (params_range[key][1]-params_ran... | f6608cf5b79ca7a0170efc34c98cc651289b6584 | 675,724 |
import sys
def ppm2netcdf(base_dir, region, npts, nproc, parameters, out_path, history):
"""
convert the ppm model to the netcdf model.
"""
result = ""
pyexec = sys.executable
result += f"srun -n {nproc} {pyexec} -m seisflow.scripts.mesh.convert_txt_output_2_netcdf --base_dir {base_dir} --regi... | 766b0091ba0e67001a1b0fb4bc5c97dd5ac7b191 | 675,725 |
def REDUCE(_input, initial_value, _in):
"""
Applies an expression to each element in an array and combines them into a single value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/
for more details
:param _input: Can be any valid expression that resolves to an array.
:... | 730433e32b7d99de794589064bb0a31394ae7b34 | 675,726 |
def linear(x: float) -> float:
""" Linear activation function (simply returns the input, unchanged). """
return x | 79e10846702d1364794c1b26c14192ae55409a10 | 675,727 |
def cross_platform_leading_zeros_removal(s, c="#"):
"""
| Removes leading zeros. For instance, #05h12 becomes 5h12.
|
| Required because strftime %#H (Windows) and %-H (Linux) are platform dependant
|
:param s: string
:param c: character that signals possible leading zeros
... | 09e25b31223bb228404fab917e0c73c4edfd3c8e | 675,728 |
def years_list(start_date: int, end_date: int) -> list:
"""
Create a list of all the years in the Calendar object.
:param start_date: Start date year.
:param end_date: End date year.
:return:
"""
years = list(range(start_date, end_date + 1, 1))
return years | 20220b1cb5e023c020090551bca84b35fbfd3294 | 675,729 |
def complementary_strand(strand):
"""Get complementary strand
Parameters
----------
strand: string
+/-
Returns
-------
rs: string
-/+
"""
if strand == "+":
return "-"
elif strand == "-":
return "+"
else:
raise ValueError("Not a v... | 09ea4a62f4943be7ae59a62285981048339c6818 | 675,730 |
def tree_map(f, *args):
"""Like the built-in :py:func:`map`, but applies to a tuple tree."""
nonleaf, = set(isinstance(arg, tuple) for arg in args)
if nonleaf:
ndim, = set(map(len, args)) # asserts equal arity of all args
return tuple(tree_map(f, *subargs) for subargs in zip(*args))
els... | 28cb5c372fb8a97537cea47e7adfc567c9139685 | 675,731 |
def _pop_next_function(function_list):
"""Pops and returns the next function in the list."""
if not function_list:
raise IndexError('in _pop_next_function: list of functions is empty')
return function_list.pop(0) | 74dfefcc02b1e8fcccaecdaaff6577d9b1473a17 | 675,732 |
def get_symbols(bv):
"""Return all symbols in binary.
Args:
bv (BinaryView): top-level binary view handler. Lots of
interesting methods can be accessed.
Returns:
list: list of symbols in binary.
"""
total_symbols = list()
for s in bv.symbols.values():
... | 9c49f2f7eda28635b122a7f12cd144192851afbb | 675,733 |
import sys
def extract_ind_income(loaded_df):
"""
Extracts the individual income of each row. The coded values are the following:
-1 - Invalid value
0 - Not applicable (the person is under 15 years of age)
1 - Less than 0 (net loss)
2 - 0 to 24,999
3 - 25k to 49,999
4 - 50k to 74,999
... | a0f38a1f7376d6e9a9acf38d24c375c15064b1bf | 675,734 |
def _flatten_list(nested_list):
"""
Given a nested list, returns flat list of all its elements
:param nested_list: nested list
:return: flat list
"""
if not isinstance(nested_list, list):
return [nested_list]
res = []
for sub_list in nested_list:
res += _flatten_list(su... | 036cc48295e8898c99dcf3b2688c746e0636bb23 | 675,735 |
def parse_numbers(raw_item):
"""Enable numerical values, like press codes for remotes."""
if isinstance(raw_item, dict):
return {parse_numbers(k): parse_numbers(v) for k, v in raw_item.items()}
try:
return int(raw_item)
except ValueError:
try:
return float(raw_item)
... | 10d2428578450853b51dd898e7f28dcf31e8db74 | 675,736 |
def dict_subset(d, keys):
"""Return a dict with the specified keys"""
result = {}
for key in keys:
if '.' in key:
field, subfield = key.split('.', 1)
if isinstance(d.get(field), dict):
subvalue = dict_subset(d[field], [subfield])
result.setdef... | 2e0053d68a911405379602f7b0db62a51a99edfa | 675,737 |
def ALMAGetBandLetter( freq ):
"""
Return the project observing band letter from frequency
* freq = Frequency in Hz
"""
if freq<117.0e9:
return "A3"
elif freq<163.0e9:
return "A4"
elif freq<211.0e9:
return "A5"
elif freq<275.0e9:
return "A6"
elif fre... | db544516104a3c993d9977fadb929177bdf15a0e | 675,738 |
import requests
def is_active(url:str) -> bool:
"""Checks if the url we are parsing is active link.
Args:
url (str): [description]
Returns:
bool: True if get a 200 response else
"""
resp = requests.get(url)
return True if resp.status_code == 200 else False | 350fa7a7daf5d15d88c3c0ef52cb92bc1aa45c63 | 675,739 |
import socket
def is_address_bindable(address,isTcp=True):
"""
Test address,port has been binded.
:param address: (host,port)
:return:
"""
if isTcp:
isTcp = socket.SOCK_STREAM
else:
isTcp = socket.SOCK_DGRAM
sock = socket.socket(type = isTcp)
try:
sock.bind(... | 67965d0c7220252c223e618dee83e82d7db6f93a | 675,741 |
def is_peer_tuple(p):
"""Is p a (str,int) tuple? I.E. an (ip_address,port)"""
if type(p) == tuple and len(p) == 2:
return type(p[0]) == str and type(p[1]) == int
else:
return False | 80e4d1c9774efa9a7616eb1d90eceba0ae764d29 | 675,742 |
def rgb_to_irb_array(im_rgb_array):
"""Transforms an RGB image into an IXY image, where I is intensity, X is related to G and Y is related to B."""
igb_3d_array = im_rgb_array.copy()
intensity = igb_3d_array.mean(axis=2)
igb_3d_array[:, :, 1] = (igb_3d_array[:, :, 1] - intensity + 170.0) / (intensity + ... | cecfa4eb8a975340e163e18c8f4be33ff5934fdd | 675,743 |
def convert_to_int(s):
"""
Convert string to integer
:param s: Input string
:return: Interpreted value if successful, 0 otherwise
"""
try:
nr = int(s)
except (ValueError, TypeError):
nr = 0
return nr | 9f1538cab692a0f50fcbc8d5662057dfea7975f7 | 675,744 |
import os
def get_dev_key():
"""Retrieves the API key for ADS Labs."""
ads_dev_key_filename = os.path.abspath(os.path.expanduser("~/.ads/dev_key"))
if os.path.exists(ads_dev_key_filename):
with open(ads_dev_key_filename, 'r') as fp:
dev_key = fp.readline().rstrip()
return de... | 7275126389a7a93bc80cad1db28999b6dd986223 | 675,745 |
def sub(proto, *args):
"""
Format string prototype I{proto} with I{args}. This really should
be a built-in function.
"""
try:
return proto.format(*args)
except:
raise ValueError("Proto '{}' couldn't apply args {}", proto, args) | 589b0a2071c42940e74c2cb9dc62422c5d4942df | 675,746 |
def flagCounter(df_wide, flag1, flag2):
"""
Description:
Calculates the frequency among the flags
Input:
df_wide: (Pandas DataFrame) with the flag file
flag1: (String) Name of the first flag.
flag2: (String) Name of the second flag.
Outpu... | bd95583970c4387a2028e340fd815de1e4cf425d | 675,747 |
def create_language_method(language_code):
""" Creates a manager method that filters given language code """
def get_language(self):
return self.filter(i18n_language=language_code)
return get_language | fd0b5d9d9d07fb59f874b9178cd1bd34a72bbe2e | 675,748 |
def addArray(pdo, field, vtkArray):
"""
Adds an array to a vtkDataObject given its field association
"""
# Point Data
if field == 0:
pdo.GetPointData().AddArray(vtkArray)
# Cell Data:
elif field == 1:
pdo.GetCellData().AddArray(vtkArray)
# Field Data:
elif field == 2:... | feff6377e444ac9187803f07aff55d887574aa92 | 675,749 |
def get_mrefresh_content(page):
"""Get the link of the metarefresh tag if it exists"""
tags = page.xpath('//meta[@http-equiv = "refresh"]/@content')
return tags[0] | ac960d533389098f4283ecf1af7168ac1a19fc6b | 675,750 |
def get_single_keyword(tokens):
"""If ``values`` is a 1-element list of keywords, return its name.
Otherwise return ``None``.
"""
if len(tokens) == 1:
token = tokens[0]
if token.type == 'ident':
return token.lower_value | d35375e7a43ee004e27bec6c3c4848f41c95d27d | 675,751 |
def get_filename(url):
"""
get_filename(string) -> string
extracts the filename from a given url
"""
pos = (url.rfind('/')+1)
return url[pos:] | 50fd8324ba5282be16b2bb65b2e4696c7c162f5a | 675,752 |
def to_bytes(value, bytes_num, order='big', signed=False) -> bytes:
"""
Convert value to bytes representation.
# Arguments
value: int, Value to be converted.
bytes_num: int > 0, Number of bytes in representation of `value`.
Must be sufficiently big to store `value`
order: 'big' or 'small', Ordering of byte... | c959a29ed15a73e1975e91602f75fba4356343cb | 675,753 |
def read_saved_comment() -> object:
""""It reads comment that have saved duiring write image content."""
with open('comment.txt') as file:
message = file.read()
return message | db022a44a3fd18bcc2b24d20426dd583e7865ec6 | 675,754 |
def bunch(**kw):
"""
Create object with given attributes
"""
x = type('bunch', (object, ), {})()
for k, v in kw.items():
setattr(x, k, v)
return x | 15aa82f415b2b56564fdb8e0189720b9044c670c | 675,755 |
def str2seq(st, func=int, sep=None):
""" "1 2 3" -> [func('1'), func('2'), func('3')]"""
# XXX check usage of this, check if we need list() at all
if sep is None:
return list(map(func, st.split()))
else:
return list(map(func, st.split(sep))) | ad04cef546f3048e6213504c1b8933cb6c503368 | 675,756 |
def detection_collate_fn(batch):
"""
Collate function used when loading detection datasets using a DataLoader.
"""
return tuple(zip(*batch)) | 562f1e5ff4eec8e47ed8f1464e5b6b58e0e55b0c | 675,757 |
def set_combinations(iterable):
"""
Compute all combinations of sets of sets
example:
set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}}
"""
def _set_combinations(iter):
current_set = next(iter, None)
if current_set is not None:
sets_to_combine_with = _set_combin... | 853d9c686f93a9dc21c1041fdcd440ab23488e28 | 675,758 |
def coins_distributed(a, b, c, n) -> str:
"""
"""
sum = a + b + c + n
if sum % 3 == 0:
if max(a,b,c) <= sum/3:
return "YES"
else:
return "NO"
else:
return "NO" | a43e51984b29b6d2c5bbfcf913aac72dd17e8eb1 | 675,759 |
from pathlib import Path
from typing import Dict
import glob
import os
def file_watcher_glob(cachedir_path: Path, pattern: str, prev_files: Dict[str, float]) -> Dict[str, float]:
"""Determines whether files (specified by the given glob pattern) have been either recently created or modified.\n
Note that this i... | a045a982c0752d12a8991b0b261ae7ce58400eb7 | 675,760 |
def _tuple_2_id(num_single, idx):
"""Transfrom from tuple representation to id.
If idx is a tuple representation of a member of a couple, transform it to
id representation. Otherwise do nothing.
Raises:
TypeError if idx is neither an integer or a tuple
"""
if isinstance(idx, int):
return idx
el... | 2f507cb929f68247c5945c4ad10ecbb4974d5605 | 675,761 |
def remove_title(soup):
"""
Remove the title element and return the str representation.
Args:
soup (BeautifulSoup): HTML parsed notebook.
Effect:
Changes soup object to have title (h1) element removed.
Returns:
(str): Title text
"""
title = str(soup.h1.contents[0])... | dfe068dda48c70c270e2021417e5c03c77f7ebe7 | 675,762 |
def bit_shifter(num: int, shiftright: int):
"""Shifts the bits of the given number (int) by the designated number (int) given to the "shiftright" parameter.
Examples:
>>> bit_shifter(151, 4)\n
9
>>> bin(151)\n
'0b10010111'
>>> bin(151 >> 1)\n
'0b1001011'
... | 82ee6c2b724d5bae130a901ce1b5529c4055688b | 675,763 |
import os
import re
def getFilename(s,extension = '.txt',dir=''):
"""everything that's not a letter or number turns into an underscore"""
return os.path.join(dir,re.sub('\W','_',s) + extension) | c7445071874f130212f2c7cc952fa24afa20417d | 675,764 |
def translate_points(points, translation):
"""
Returns the points translated according to translation.
"""
return points + translation | 6fc11502b47249c9b97e8e5a9d88f19c8db23fcd | 675,765 |
import argparse
def get_arguments():
"""Get command line arguments."""
parser = argparse.ArgumentParser(
description='Image colorization with GANs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--data_path', type=str, default='./data',
... | d01ef42ae50d24f953ee2a226ef418dbfe7eeb51 | 675,766 |
async def message_not_modified_handler(update, error):
"""
Error handler for except all of callback error
"""
return True | b43880b9789c1b7d4c8923b1183005f7f2d4b3c7 | 675,767 |
def _check_byte_size(size: int) -> bool:
"""
Checks whether size is a valid size. Sizes include None or >= 0
:param size: The size to check
:type size: int
:return: Whether the size is valid
:rtype: bool
"""
if size is None:
return True
return size >= 0 | 83921b744887b71a6303e8c4169fcf0ff9671ce7 | 675,768 |
def _check_boolean(input, name):
"""Exception raising if input is not a boolean
Checks whether input is not ``None`` and if not checks that the input is a
boolean.
Parameters
----------
input: any
The input parameter to be checked
name: str
The name of the variable for prin... | b9fb435efc9a2b22384f570f0fa5d5462c07a6a9 | 675,769 |
import re
def remove_space_coding(sentences):
""" Remove '\xa0' from every sentence """
return [re.sub(r'\xa0', ' ', sentence) for sentence in sentences] | 40c48a8b46497b218a47a9f5a19c4c93f42323f2 | 675,770 |
def calculate_attack_percents(result, event_list):
"""Calculates percentages of offensive events"""
result['Percents'] = {}
for event in event_list:
if event == 'Crits' and result[event_list[0]] > 0:
result['Percents'][event] = '{0:.2f}'.format(
float(result[event])/resul... | 05b4055d1fdcea8a3d943fee9ffcb15a218a5598 | 675,771 |
def time_at_timestamp(timestamp_ms: int) -> float:
"""Convert millisecond Epoch timestamp to Python float time value.
Args:
timestamp_ms: Epoch timestamp in milliseconds.
Returns:
Python time value in float.
"""
return float(timestamp_ms) / 1000.0 | 0b86d35a6a957c1c83326e852a647c9fc4b52a87 | 675,772 |
def update_project(p_dict, slug):
"""Updates project by slug"""
updated_param = {
"uri": p_dict["uri"] if "uri" in p_dict else None,
"name": p_dict["name"] if "name" in p_dict else "TimeSync API",
"slugs": p_dict["slugs"] if "slugs" in p_dict else [slug],
"created_at": "2014-04-1... | 20c8025bc0bdeb7d306858336231c4574a357368 | 675,773 |
from io import StringIO
import os
def run(script_runner, space_tmpdir):
"""Launch the space command in the dedicated tmp workdir
"""
def _run(args, stdin=None):
# kwargs = {'cwd': str(space_tmpdir)}
kwargs = {}
if stdin:
kwargs['stdin'] = StringIO(stdin)
kwa... | 72c32cb6e5469867cdf3575d3fdf26ddc2aa07f8 | 675,774 |
def args_to_str(
args,
positional_arg=None,
fields=None,
to_flag=True,
arg_joiner=' ',
val_sep=' ',
list_joiner=' ',
):
"""Convert an argparse.ArgumentParser object back into a string,
e.g. for running an external command."""
def val_to_str(v):... | 701efd4dfbadde94ee80b78504db720ac52d33a2 | 675,775 |
def _acer_input(endfin, pendfin, aceout, dirout, mat,
temp=293.6, iprint=False, itype=1, suff=".00",
header="sandy runs acer",
photons=True,
**kwargs):
"""Write acer input for fast data.
Parameters
----------
endfin : `int`
tap... | 53bd10121eb09de1185b1a2ba6aaa7adfe2bd10e | 675,776 |
def _splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
host, delim, port = host.rpartition(':')
if not... | a8af9a33b603d7e0b39bf2130c0eaf1e718f9589 | 675,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.