content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _trigonal_prism():
"""
Returns
-------
list of scitbx.matrix.col
"""
return _concatenate(
[i + col([0, 0, 1]) for i in _trigonal_plane()],
[i + col([0, 0, -1]) for i in _trigonal_plane()],
) | 812f586003c87a1376b9e298796b248b888be5e5 | 74,000 |
def get_lorenz_data(n_ics, noise_strength=0):
"""
Generate a set of Lorenz training data for multiple random initial conditions.
Arguments:
n_ics - Integer specifying the number of initial conditions to use.
noise_strength - Amount of noise to add to the data.
Return:
data - Di... | 8eb9d2d341cd94d445fa74a8fc914634f28dbab7 | 74,001 |
def flatten_set(curset):
"""
Flatten until we have a set of vector3d objects.
"""
newset = set()
for c in curset:
if isinstance(c,vector3d):
newset.add(c)
else:
newset.update(flatten_set(c))
return newset | 9fa633dd9b03aca753978d5adce52c1176eebd93 | 74,002 |
import os
import sys
def find_python():
""" work out which python to use """
generic_python = os.path.join('/', 'usr', 'bin', 'python')
python26 = generic_python + '2.6'
python27 = generic_python + '2.7'
paths_to_try = (python27, python26, generic_python, sys.executable)
python_exe = find_file... | 249cf5ba5c8d57e1bf1fb986adfc158f56c897ef | 74,003 |
def send_post(url, data=None, headers=None):
"""Send HTTP POST request via ``requests`` module."""
return send_any("POST", url, data=data, headers=headers) | 6a451f7b8b5658357c160ea6eee87f74483716ea | 74,004 |
def remove_sensitive_data_from_data_diff(unsafe_data_diff):
"""Removes 'before' and 'after' data for fields that are sensitive, such
as social security number and driver's license number
"""
safe_data_diff = {}
unsafe_changed_keys = []
for label, values in unsafe_data_diff.items():
if la... | ac5165aefc3ee6bd7db732e2a084fe793b849996 | 74,005 |
def json_return(code, message = '', data ={}):
"""
將資料轉換成dict作為API回傳的統一格式
:param code:
:param message:
:param data:
:return:
"""
return {'data': data, 'msg':message, 'code': code} | 70134c28c54d910c634c0ffd14b2416072ec730a | 74,006 |
import warnings
def dialog(message, timeout=0, buttons=DIALOGBUTTON_OK):
"""
Display a message box with an OK button.
This method is equivalent to `MSGBOX(message, BTN_OK)` in UWSC.
Parameters
----
message: str
Dialog messages
timeout: int
The dialog timeout.
buttons: int
Button flags.
... | 0c7dc7ee2900e3bc7d267e6cb17524646ed84b43 | 74,007 |
def _encode_mantissa_as_bitstring(mant):
"""
This is expecting an integer. The purpose of this function is to
return the bit_string representation of the mantissa. The length
of the string is 52 characters long and is meant to be combined
with the 11 bit exponent and 1 sign bit to form a 64 bit st... | 80c55419c724b7230de5f4ff492ec4af25c99a75 | 74,008 |
def depth(self, symbol: str, **kwargs):
"""Get orderbook
GET /fapi/v1/depth
https://binance-docs.github.io/apidocs/futures/en/#order-book
Args:
symbol (str): the trading symbol
Keyword Args:
limit (int, optional): limit the results. Default 500; valid limits:[5, 10, 20, 50, 100, 5... | 31f3edaf58629772b3dabc02c7e96f3014038870 | 74,009 |
def mnist_train_labels_file():
"""
Train images of MNSIT.
:return: filepath
:rtype: str
"""
return data_file('mnist/train_labels', HDF5_EXT) | 10f37546248aebbae9a6665071da21f8a021e7d4 | 74,010 |
def uevm(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"),
bitis_tarihi=__dt.datetime.today().strftime("%Y-%m-%d")):
"""
İlgili tarih aralığı için YEKDEM kapsamındaki santrallerin kaynak bazında uzlaştırmaya esas veriş miktarı (UEVM)
bilgisini vermektedir.
Parametreler
---------... | 1291f4a65d9088474abae297d8a6a2e297480da5 | 74,011 |
def connect_to_database():
"""
Connect to a database
Return:
Cursor for db operations
"""
try:
database = psycopg2.connect("dbname=news")
cursor = database.cursor()
except psycopg2.Error as err:
print("Failed to connect to the PSQL database: \n", err)
ret... | 59c959fba5c9cd303abfd1f714a16c33a57b967e | 74,012 |
def quadratic_formula(a, b, c):
"""Solve the quadratic equation 0 = a*x**2 + b*x + c using the quadratic formula."""
if a == 0:
return [-c / b, np.nan]
disc = b**2-4 * a * c
disc_sqrt = disc**0.5
den = 2 * a
roots = [(-b+disc_sqrt) / den, (-b-disc_sqrt) / den]
return roots | 765092d59c3fe5d8fd9a63d9238cb5b3c5662d5e | 74,013 |
from datetime import datetime
def get_data(
ticker: str,
limit: int,
subreddits: list,
before: str,
after: str,
minimum_upvote: int
) -> pd.DataFrame:
"""
Retrieve submissions from RedditAPI using predefined parameters
Args:
ticker (str): ticker to search for
l... | 6e97a28b2abe100f3221e2fda374ccf9dbc0ec42 | 74,014 |
def plot_regional_yw(wk_recent_regional_agg_df, regional_acc_color_pal):
"""
Plot Year Week graph across KPI and Regional account.
Parameters
----------
wk_recent_regional_agg_df : pandas.core.frame.DataFrame
Filtered grouped_summary_df obtained from get_regional_summary_df().
regional_... | de9ab1436d9dab7adfefb656e6100403ddcde6b2 | 74,015 |
from typing import Counter
def get_kl(a, b):
"""
Computes the KL divergence
"""
epsilon = 0.00000001
c1 = Counter(a)
total1 = sum(c1.values()) + len(c1) * epsilon
c1c = [(c1[cat] + epsilon) / total1 for cat in sorted(c1.keys())]
c2 = Counter(b)
total2 = sum(c2.values()) + len(c1) ... | d57b5d55bd6f9032dd48f193ff89194f1aed92d1 | 74,016 |
import copy
def convert_quantity(x_in, to_unit, factor=1.):
"""Check if astropy quantity and apply conversion factor
Parameters
----------
x_in : float or quantity
input
to_unit : astropy.units unit
unit to convert to
factor : float
Factor to apply if input is not a qu... | dda40b7de4fab15131c764585e28b79b35cb54bc | 74,017 |
from typing import List
def source_type_exclusion_criterion(source_types: List[str]) -> BinaryExpression:
"""Criterion to exclude sources that are of the given type."""
return DataSource.type.not_in(source_types) | 1188c35bdd51fa3121c776d7f25cbd16104390f5 | 74,018 |
def detect_publisher(extras):
"""
Detect publisher by package extras
:param extras: dict
:return: str
"""
publisher = None
if 'publisher' in extras and extras['publisher']:
publisher = strip_if_string(extras['publisher'])
for i in range(1, 6):
key = 'publisher_' + str(i... | 0ec0fc199f29ee4c372616f1819ae8454361a9f5 | 74,019 |
def checkValidity() -> bool:
"""
Checks whether the inputted matrix is square and non-singular. Returns
True if this is the case, false otherwise.
"""
if numRows != numCols:
print("inputted matrix is not square :(")
return False
if np.linalg.det(inputMatrix) == 0:
pr... | 24c796fd99124c1a200b245b3800ea1cae1f12eb | 74,020 |
def new_ca(request, sa_id):
"""Create a new competency area for a given general subject area."""
sa = SubjectArea.objects.get(id=sa_id)
organization = sa.organization
# Test if user allowed to edit this organization.
if not has_edit_permission(request.user, organization):
redirect_url = '/no... | 0c7cf2bcc6b5ed90e5ee3dec7c5905b84ff5b1cf | 74,021 |
def expected(player1, player2):
"""
Calculate expected score of player1 vs player2 given elo rankings.
Args:
player1 (BaseAgent): Agent for whom the score is being calculated.
player2 (BaseAgent): Agent against whom player1 played.
Returns:
The expected score of the matchup.
... | 90551b04b15ce62a1d2c5d7022d9402b3efdba60 | 74,022 |
def sorted_pos(labels):
""" Return unique positive labels in ascending order"""
idx = sum(labels, [])
pos = [i for i in idx if i > 0]
return list(np.sort(np.unique(pos))) | 90c80e75f8f1c4ec6e03f5629fcff7a1090eda78 | 74,023 |
from warnings import warn
from functools import reduce
def rreduce(fn, seq, default=None):
"""'readable reduce' - More readable version of reduce with arrity-based dispatch; passes keyword arguments
to functools.reduce"""
warn(DeprecationWarning(
"rreduce is deprecated and will be removed in futur... | bb82cdf712c87885103d61f7c37fa588e8bdac6b | 74,024 |
import hashlib
def write_to_blobstore(content, old_blobinfo=None):
"""Write content to blobstore.
Args:
content: A byte-string.
old_blobinfo: An optional BlobInfo object used for comparison. If the
md5_hash of the old blob and the new content are equal, the
old blobkey is returned and not... | 77654e8ee9d6065f741634d06554ab3dc1929d42 | 74,025 |
import os
def snake_string_path(p):
"""normpath drops leading ./
"""
if isinstance(p, SnakemakeDynamic):
return "dynamic('{}')".format(
os.path.normpath(p.path))
else:
return "'{}'".format(
os.path.normpath(p)) | c3e3f6e38d19ec9b544dd8fcb0a4fb057a6806d3 | 74,026 |
def compute_trunc_basis(D,U,eng_cap = 0.999999,user_rank={}):
"""
Compute the number of modes and truncated basis to use based on getting 99.9999% of the 'energy'
Input:
D -- dictionary of singular values for each system component
U -- dictionary of left singular basis vector arrays
eng_cap -- f... | cdd4837802934203e7c4d85a6874ce3d8d9747c6 | 74,027 |
def valid_pass(password):
""" Validar valores ingresados de password. """
return PASS_RE.match(password) | be8888a4499db2465db71b2ac741fbaf80b001a3 | 74,028 |
def retirement_401k_report(income=None, retirement=None, start=PeriodStart.this_year,
end=PeriodEnd.this_year, contribution_limit='18000.0'):
"""
Report that will calculate how much has been contributed to the retirement accounts from the income accounts
provided.
:param incom... | 04f8c8786f74d8f03d9af42ad18c22d62109fc55 | 74,029 |
def policy_query(policy, database):
"""
Renders a stripped policy creation query
:param policy: Policy config dictionary
:param database: Name of the database
:return: Stripped policy query
"""
return strip_query(
config['policy_template'].format(
policy=policy_name(poli... | 4065ee3f8bf1b55109117faa91ce4a3dc39d24ca | 74,030 |
def round_state_to_increment(state, increment):
"""
Extension of round to increment to the state vector
:param state array(3)[float]: [x, y, theta]
:param increment float: increment to round state to (just the position)
:return array(3)[float]: rounded state
"""
new_state = np.array(state)
... | 11bb9e5d9d6a30b2ceb664af086094b84ae67153 | 74,031 |
from numpy import dot, floor
from numpy.linalg import inv
from method import error
def are_periodic_images(pos0, pos1, invcell=None, cell=None, tolerance=1e-8):
""" True if two vector are periodic images of one another
:param pos0:
First position
:param pos1:
Second positi... | 4b28530d69baa54fd763703086ba110737261bda | 74,032 |
def get_contents_entry(node):
"""Fetch the contents of the entry. Returns the exact binary
contents of the file."""
try:
node = node.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Ent... | 44bdfe0ec5c118992896fca53658abf28d99c207 | 74,033 |
def make_page(s: str, f=lambda: {}, methods=['GET']):
""" Takes in a string which specifies both the url and the file name, as well as a function which provides the kwargs for render_template. """
title = s.split("/")[-1]
def func():
val = f()
if isinstance(val, dict):
return fla... | 74123efcff97040934fae635d1c393b243069e95 | 74,034 |
import torch
def lane_nms_gpu_old(dets, scores, pad_shape, iou_threshold=0.05):
"""
:param dets: (torch.Tensor): boxes in shape (N, 4).
:param scores: (torch.Tensor): scores in shape (N, ).
:param thresh:
:return:
"""
#print('nms_before_len', len(dets))
order = torch.argsort(scores, d... | a771a93a702d6e2d876093aa885c08c4ec4f522b | 74,035 |
def topography(x,y):
"""Complex topography defined by a function of vectors x and y."""
z = -x/100
# Step
id = ( 2 < x ) & (x < 4)
z[id] += 0.4 - 0.05*y[id]
# Permanent pole
id = (x - 8)**2 + (y - 2)**2 < 0.4**2
z[id] += 1
# Pole 2
#id = (x - 14)**2 + (y - 3.5)**2 < 0.4**2
... | dba3e02ff5c5dd11c60901318bc9550f2eecea60 | 74,036 |
def get_predictors(results):
"""Get predictors for logistic regression."""
assert len(results) == 200
y = []
x = []
for (_, trial1), (_, trial2) in zip(results.iloc[:-1].iterrows(), results.iloc[1:].iterrows()):
transition = 2 * int(trial1.common) - 1
reward = 2 * trial1.reward - 1
... | 240a0d32221e32eda58b86568b5975cdcdd3c475 | 74,037 |
def sanitized_string(text):
"""
Ensures strings are properly sanitized
and no special characters are present.
"""
r = inflection.transliterate(text)
r = r.replace(' ', '-')
return inflection.underscore(r).lower() | b5b22465a878ca2dceb194c4f0f09b3f5277b755 | 74,038 |
def graph_coordinates(list_of_chromosomes):
"""Iterate through list of chromosomes and return X
(as center for graph) and Y coordinates for plotting.
Args:
Returns:
chrom_ybase(int)
chrom_centers(int)
"""
ybase = YBASE
chrom_ybase = {}
chrom_centers = {}... | 145af5cac524c8de8eea46d2c59e92b2a0d8cf48 | 74,039 |
def preprocess(path2sample, config, config_Dataset):
""" preprocess each sample"""
data_list = []
label_list = []
# imread data and label
for time_iter in xrange(len(path2sample)):
data = cv2.imread(path2sample[time_iter][0], 3)
if config_Dataset.USE_IMAGE_ROI:
d... | e227c881186eac8d20f5838cad2bf304df43cbe0 | 74,040 |
def class_img2sino(x, phi, size, sinogram_shape):
"""Compute the mapping of the orientation class entry of the Wavefront set from images to
sinograms
Parameters
----------
x : numpy array, position of the singular point in the image
phi : float, orientation angle of the singular point in the i... | 9eaf0db4633ec7e66c3b270c09dea99d204c3762 | 74,041 |
def get_data_set(set_name, data_type, unique_answers=False):
"""
Retrieve all the question and their respective answers from a data set (possible options are
"test", "valid", and "train").
:param set_name: Name of data set.
:param unique_answers: Flag to indicate whether duplicate answers to a ques... | be6c4c977db897f3376f73a863a5b2cb534e1591 | 74,042 |
def offset_random_web(seed, amount=1):
"""
Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return:
"""
return rgb_to_web(offset_random_rgb(seed, amount)) | b07cfec9bd175c907345aa47d13b536e9f448c6d | 74,043 |
import re
def check_password_format(password):
"""校验密码格式
Args:
password (str): 密码
Returns:
boolean: 格式符合返回True,格式错误返回False
"""
pattern = re.compile('\w{8,16}')
if pattern.match(password):
if re.search('[0-9]', password) and re.search('[a-z]', password):
re... | b0923972f22b08298df8aa9c83314787ebefb8a8 | 74,044 |
import tqdm
import os
import subprocess
import sys
import traceback
def render_actions(renders: list):
"""
For every render directory, we render the actions
"""
good_renders = []
bad_renders = []
for recording_name, render_path in tqdm.tqdm(renders):
if E(J(render_path, 'network.npy')... | 534046f929cd791d9929ca7a14963fb9a442653b | 74,045 |
from .dc_mosaic import (ls7_unpack_qa, ls8_unpack_qa, ls5_unpack_qa)
processing_options = {
"LANDSAT_5": ls5_unpack_qa,
"LANDSAT_7": ls7_unpack_qa,
"LANDSAT_8": ls8_unpack_qa
}
clean_mask = None
# Keep all specified cover types (e.g. 'clear', 'water'), so logically or the separ... | 8749873fd96cec9faf046140728a9a01e41bab61 | 74,046 |
def MultipleRegression(x_names=None, y_name=None, df=None, alpha=0.05, precision=4, show_summary=True, assessment=True, t_test_c=0, t_test_option='two-tail'):
"""
assessment is equivalent to t_test: boolean
"""
res_dict = dict()
y_data = df[y_name]
X_data_T = np.array(df[x_names])
X_data = p... | b2b6e48e66f04e9b9141338c03010ec224013bd2 | 74,047 |
import logging
import os
import yaml
import tarfile
import shutil
def create_plugin_bundle_archive(mappings,
tar_name,
destination):
"""
:param mappings: A special metadata data structure.
:param tar_name: The name of the tar file.
:pa... | a464fc6ba4e819afc6d33c2fb7db50532dfe73aa | 74,048 |
def calc_pmi(counts, cds):
"""
Calculates e^PMI; PMI without the log().
"""
sum_w = np.array(counts.sum(axis=1))[:, 0]
sum_c = np.array(counts.sum(axis=0))[0, :]
if cds != 1:
sum_c = sum_c ** cds
sum_total = sum_c.sum()
sum_w = np.reciprocal(sum_w)
sum_c = np.reciprocal(sum_c... | 6686a7a1c9b11707c206734cfd096e5e24100271 | 74,049 |
def corpus(request):
"""
A utility fixture to merely execute the actual fixture logic as necessary.
Args:
request: The pytest indirect request object, which has a param object
for the underlying fixture argument.
Returns:
The value of the execution of the corpus fixture.
... | 3c6986296a17145bc3b40cc84e2b62acb5c8f00c | 74,050 |
def filtre_operations(operations: dict[int, any], objectif: int) -> dict[int, any]:
"""Exclus les opérations qui s'éloigne de l'objectif au lieu de s'en approcher"""
operations_filtrees = {}
for resultat in operations:
formules = operations[resultat]
min_distance = abs(objectif - resultat)
... | 171bfa62850fe8bcf6802a13e56f6b16cb77499f | 74,051 |
def generate_delay_matrix(pre_population, post_population, delay=0.25, std=0.1):
"""generate delay matrix between two populations"""
if type(pre_population) == int:
N = pre_population
else:
N = pre_population.N
if type(post_population) == int:
M = post_population
else:
M = post_population.N
... | 8b30fb9ee06c02d3d4ab0f03c5b855b516397cdb | 74,052 |
import random
def get_http_header():
"""
模拟浏览器爬取代理 http 头信息
:return:
"""
return {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'h-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.... | 8194714dadd305bdc3af28fb77ff570c1afefbf4 | 74,053 |
import math
def scaled_init_method_normal(sigma, num_layers):
"""Init method based on N(0, sigma/sqrt(2*num_layers)."""
std = sigma / math.sqrt(2.0 * num_layers)
def init_(tensor):
return nn.init.normal_(tensor, mean=0.0, std=std)
return init_ | 3d648e741b2ff423117b9a6d3f42dd3ae2dcfa87 | 74,054 |
def mat_toeplitz_1d(h, x):
"""
Constructs a Toeplitz matrix for 1D convolutions
Parameters
----------
h: list[]
The filter's vector
x: list[]
The signal's vector
Returns
-------
list[list]
A Toeplitz matrix T such that y = T(h) * x
"""
Nh, Nx = len(... | 45b03ecceb9663676d400dae06af57987f95f3b2 | 74,055 |
def viewCourse(request: HttpRequest):
"""
展示一门课程的详细信息
GET参数: ?courseid=<int>
用户权限: 不对用户类型作出限制,均正常显示内容
"""
valid, user_type, html_display = utils.check_user_type(request.user)
try:
course_id = int(request.GET.get("courseid", None))
course = Course.objects.filter(id=co... | 312b63339067801bcd4901b6a8b4085ffbd0d7d0 | 74,056 |
import subprocess
import sys
def get_token():
"""
Get authentication token using the cluster credentials on the OC command line tool
Returns:
The bearer token to the init_setup function
"""
try:
print("Logging into your OpenShift Cluster")
status, _ = subprocess.getstatusoutp... | 58ebb54f8056a59e939c4721aac24e17485a1689 | 74,057 |
import os
async def download_asset(genome: str, asset: str, tag: str = None):
"""
Returns an archive. Requires the genome name and the asset name as an input.
Optionally, 'tag' query parameter can be specified to get a tagged asset archive. Default tag is returned otherwise.
"""
tag = tag or rgc.... | 705f89b20b219bcb840355f37d81c4625ce8d401 | 74,058 |
def parse_input_file(input_dir, stopwords=False):
""" Parses 'contexts.xml' and 'substitutions' files.
Takes the directory of input files the only argument.
Returns list of tasks in form of pairs (sentence, list of possible subs).
Each sentence is a pair (list of strings, 0-based index of a st... | 7559ae44d6fd540ecbecbae5d3edb1211a5dc03a | 74,059 |
from math import floor, log10
def findSizeInt(number):
"""
#EN-US:
→ Calculates the number of digits in a number.
:param number: the number to be calculated.
:return: the number of digits of the number entered.
#PT-BR:
→ Calcula a quantidade de dígitos em um número.
:param number: o n... | 8b174183520337f31f17bfb4163d5ed5ff90e896 | 74,060 |
import operator
def _get_operator(comp_str):
"""Returns the operator function corresponding to the given comparison.
Args:
comp_str: str. One of: '<', '<=', '=', '>=', '>'.
Returns:
callable. The binary operator corresponding to the comparison.
Raises:
ValueError. The compar... | 123ca1e2be8abf81387fb5d2ffa559082116b959 | 74,061 |
def clean_text_simple(string):
"""
Remove all \x19 from the string formatted with simple colors:
\x198
"""
pos = string.find('\x19')
while pos != -1:
string = string[:pos] + string[pos+2:]
pos = string.find('\x19')
return string | a067f164be5677f6fb2029d5b839849ca50a230e | 74,062 |
import math
def knn(pnts, p, k):
"""
Calculates k nearest neighbours for a given point.
:param points: list of points
:param p: reference point
:param k: amount of neighbours
:return: list
"""
s = sorted(pnts,
key=lambda x: math.sqrt((x[0]-p[0])**2 + (x[1]-p[1])**2))[0:... | 2da3d4481db78910548eee04e0532e701e4c4201 | 74,063 |
def update_ip(ip_type, cache, dns, proxy_list):
"""
更新IP
"""
ipname = 'ipv' + ip_type
domains = get_config('ipv' + ip_type)
if not domains:
return None
address = get_ip(ip_type)
if not address:
return False
elif cache and (address == cache[ipname]):
print('.',... | f6c9bda9e5617bd210731a17f34b456ff52ed43f | 74,064 |
def one_sampling_round(model, dataset, Q, n_samples_per_round):
"""
Generate one round of samples
"""
samples_df = get_new_samples(model, dataset, Q, n_samples_per_round)
samples_df = compute_modlamp(samples_df)
mask_accept = samples_df['accept_z']
samples_df['accept'] = mask_accept
retu... | 4da5a58a7ff9e10bc99d1f77886ea968a25db6d8 | 74,065 |
from typing import Union
from typing import List
from typing import Any
def band_matrix(
band_coeffs: Union[List[float], List[complex], ndarray],
band_offsets: Union[List[int], ndarray],
dim: int,
dtype: Any = None,
has_corners: bool = False,
) -> dia_matrix:
"""
Returns a dim x dim sparse... | 2f50f2b9255aaeb42ab43e9e6f04780b0d2fbdba | 74,066 |
import struct
def read_section_header(stream):
"""
Read a section header block from a stream.
.. note::
The byte order magic will be removed from the returned data
This is ok as we don't need it anymore once we determined
the correct endianness of the section.
:returns: a dic... | bd93af921b4aa3b7d3912eb0c2c4071715b2bca9 | 74,067 |
from typing import Pattern
def matches(tag_idx: int, tag: Tag, pattern: Pattern) -> bool:
"""
A predicate for use in :func:`remove_tags`. Returns ``True`` if _tag_'s
``name`` is matched by ``pattern``.
.. note::
While this function can be imitated with
``lambda _, tag: tag.name in {...}``, th... | 6a213c37343b42efecf2d57f541a1f59516604b4 | 74,068 |
def aes_encrypt(msg, aes_key):
# type: (bytes, bytes) -> Tuple[Union[bytes, bytearray, memoryview], bytes, bytes]
"""
Encrypt a bytes message
:param msg: Message to encrypt
:param aes_key: AES encryption key
:return: (tuple) encrypted message composed of nonce, tag and ciphertext
"""
... | b571f0d46672e61e9de414596888dd6301437a96 | 74,069 |
from datetime import datetime
import time
def tdiff(times):
"""
This function calculates daytime and nighttime, as well as sunrise/sunset
times. It accepts two datetime.time objects and a string, and returns four
floats of the data needed for plotting.
"""
thyme = [times[0], times[2], times[3]... | b4e89aace9edb9bf7e505d1de5d65e4099928d94 | 74,070 |
import requests
from bs4 import BeautifulSoup
def scrape(start, end, logging=True):
"""
Scrape all the reviews from dealerrater.com for the McKaig
Chevrolet Buick dealership.
Parameters:
start: the page of reviews to start scraping
end: the last page of reviews to scrape
Ret... | 03dfd059a82c4c56dec47d772ef2e6ade905fac7 | 74,071 |
def readatm(atmfile, verb=0):
"""
This function reads an atmospheric file into a Numpy array.
Inputs
------
atmfile: string. Path/to/file for the atmospheric file used.
verb : int. Verbosity parameter to determine debug output messages (0 -- 5)
Returns
-------
mols : list of st... | b1f3d140d2416d40d90f08d880bcfee022d82022 | 74,072 |
def _cubeplane_ray_intersection(xyz, dxdydz, extent):
"""Intersects rays with a plane of cubes and returns data about
intersections
Suppose the walls of the cube are on integer boundaries in the space of
extent[0] <= x <= extent[1], extent[2] <= y <= extent[3], extent[4] <= z <=
extent[5]
Para... | 9bdb800ccf2a389d4933145e3537140b04453084 | 74,073 |
def _get_sparsity(matrix, tolerance=0.01):
"""Returns ~% of zeros."""
cnt = len(matrix.flatten())
non_zeros = np.count_nonzero(np.abs(matrix) > tolerance)
return (cnt-non_zeros) / cnt | 7ae83ae978892fa5e400db46565681e9d896cfb1 | 74,074 |
import os
import sys
import six
import gzip
import shutil
def maybe_download(filename, data_directory, source_url):
"""Download the data from source url, unless it's already here.
Args:
filename: string, name of the file in the directory.
work_directory: string, path to working directory.
... | a48989a2b8d21aa7d4c56bbf16b6731de75b5df1 | 74,075 |
def get_most_popular_three_articles_of_all_time():
"""Return what are the most popular three articles of all time."""
conn = psycopg2.connect("dbname=news")
cur = conn.cursor()
cur.execute(most_popular_three_articles_of_all_time)
results = cur.fetchall()
conn.close()
return results | 3f582a1559a1f0bdd80348983e8f446ba22ea731 | 74,076 |
def __process_args(args):
"""
Process the command-line arguments.
:param args: the command-line arguments list
:raises CLAException: if an error occurs while validating and processing the command-line arguments
"""
_method_name = '__process_args'
cla_util = CommandLineArgUtil(_program_name,... | 5bee03658ed053262dd1bb99fc4dd05b207d6260 | 74,077 |
def monotonic_decreasing(func):
"""Correctly round monotonic decreasing function."""
# pylint: disable=invalid-name, protected-access
@wraps(func)
def _wrapper(it):
inner = func(it)
return Interval(inner(it._upper, RM.RD), inner(it._lower, RM.RU))
return _wrapper | 18fbcd3403c921fba6be1fecfc96ab966ef99a0e | 74,078 |
import re
def multiple_replace(string, replacements):
"""
Given a string and a dictionary of replacements in the format:
{ <word_to_replace>: <replacement>, ... }
Make all the replacements and return the new string.
From: http://stackoverflow.com/questions/2400504/
"""
pattern = re.co... | bdaf05f2f9c5de2c0742c12219e2984ed3e7699e | 74,079 |
import six
def sanitise_args(config):
"""
Sanitise command-line configuration.
:param config: Config dictionary (from docopt)
:returns: Config dictionary with all keys stripped of '<' '>' and '--'
"""
sane_conf = {}
for key, value in six.iteritems(config):
if value is not None:
... | 575d8bedf81ba3cf8b0436a9c837e12e6face548 | 74,080 |
def run_benchmark(
benchmark_config: BenchmarkWrapper, result_name: str, fp16=False, training=False
):
"""Run Huggingface's PyTorch benchmarks.
args:
benchmark_config: BenchmarkWrapper
result_name: str = Name prepended (without spaces or special characters) for the saved result
fp16: bool = If ... | 3deae95485478da40c8ec887381cd0260020cf6f | 74,081 |
def find_strings(project_path,outfile, branch, depth, from_date, to_date, regex):
"""
Read the repo. Check the active branch.
If branch args is not specified scan the repo as it is.
Else If active branch !== branch_args; then checkout branch_args.
If depth is not specified; Initialize scan_depth= MA... | 49d71562816ed089f0e22f31ecb7c3b19eec1d09 | 74,082 |
def images_2D(image1, image2, vector_of_euler_changes_2D=None,
max_intensity1=255, max_intensity2=255):
"""
Euler characteristic curve of a pair of 2D images.
This uses the vector of all possible Euler characteristic changes
produced by a pixel insertion in 2D images. This is recompu... | 01e5c79b1bdf8e0dfd36faaf2e14fbdefc59da79 | 74,083 |
from functools import reduce
def apply_filter_conditions(df, conditions):
"""
return a function to apply filtering conditions on df
"""
if len(conditions) == 0:
return df
elif len(conditions) == 1:
return df[conditions[0]]
else:
return df[reduce(lambda c1, c2: c1 & c2, ... | 43f218069b535aa29e1c6855befd488449cffc06 | 74,084 |
import requests
def get_client_info(client_ip, dnac_jwt_token):
"""
This function will retrieve all the information from the client with the IP address
:param client_ip: client IPv4 address
:param dnac_jwt_token: DNA C token
:return: client info, or {None} if client does not found
"""
url ... | 2cf92a4ff95549a49524e7df51cb9fa207cde2b3 | 74,085 |
import random
import string
def new_identifier(context):
"""
Create a new identifier or return an existing one.
"""
def random_identifier(length):
random_letter = lambda: random.choice(string.ascii_lowercase)
name = ''.join(random_letter() for _ in xrange(length)) + '_'
return name
if not context.has_names... | 24ce035b486c686c8fdef704db2f77aaf58c5b73 | 74,086 |
def process(json_path, output_format = 'csv'):
"""
Entripoint function.
Parameters:
json_path (string): input path of json file
ouput_format (strint) : csv/json, ouput file format
Returns:
over_weight_count (integer) : number of overweight people count
"""
t... | e0bb62588017521bb19f9be067c30d9660ab99da | 74,087 |
def filter_country(df, countryiso, country_of="originating"):
"""Keep only rows for one country - originating or residing.
A column "Country" with column names of the variable country (residing or originating) is created.
"""
countries_table = evaluate(
"countries"
).get() # evaluate rather... | d9b4523084ea3523305cf1db50a99db1d0296d25 | 74,088 |
def TraceActiveVars():
"""Return a list of active trace variables"""
ret = []
for i in range(TRACE_VAR_CT):
dat = SendCmd(OP_TRACE, [SUBCMD_TRACE_GET_VARID, i])
var_id = Build16(dat)[0]
var = FindVarByID(var_id)
if var:
ret.append(var)
return ret | c2e9871775d96ff8aae597134adabb55b17ff2ce | 74,089 |
import argparse
def process_command_line(argv=None):
"""
Parse command line arguments
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
Return a Namespace representing the argument list.
"""
# Create the parser
parser = argparse.ArgumentParser(prog='mm_dataprep',
... | 63fe7dae63bac28b0cf17bd91f977bd96429a48d | 74,090 |
import os
def Illumination_correction(im, correction_channel, crop_limits=None,
all_channels=_allowed_colors, single_im_size=_image_size,
cropped_profile=None, correction_folder=_correction_folder,
profile_dtype=np.float, image_dtyp... | fcdf4e251ad8b69b314ecc321b3b30ca48cb5c18 | 74,091 |
import argparse
def get_args():
"""
--mode train/test/deploy
--cores 1/2/3/4/5/6/7/8
--load_model <path_to_model>
### only for train mode ###
--save_top 1/2/3/4/5/6
--batch_size
--epochs
--learning_rate
###########################
... | a508679f14943afd801b40562c0d9182326d5e44 | 74,092 |
from io import StringIO
def create_current_save_file():
"""
:return: a string that looks like a current, valid save file, whatever we are using
"""
persistor = PickleFilePersistor(
persist_root=None, save_file_name="current_pickle", testing=True,
)
buffer = StringIO()
persistor.wri... | 2b86de15d1d18c4183e58307c25a3949793a375e | 74,093 |
def getter_generator(field_name, short_description):
"""
Generate get_'field name' method for field field_name.
"""
def get_translation_field(self, language_id_or_code=None, fallback=False):
try:
return getattr(self.get_translation(language_id_or_code,
... | c8773b46f527ad99c40f3003a7ab35cd05062ac2 | 74,094 |
import argparse
def process_arguments(args):
"""Process the system arguments using argparser"""
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="input file to check URL links")
parser.add_argument(
"-v",
"--version",
help="display program name and versi... | 2ab8abdc1176aa56c6aebcf30bcdbc436737a9ef | 74,095 |
from typing import Sequence
from typing import Any
from typing import Optional
def create_POUCT(
actions: Sequence[Action],
sim: Simulator,
num_sims: int,
init_stats: Any = None,
leaf_eval: Optional[Evaluation] = None,
ucb_constant: float = 1,
horizon: int = 100,
rollout_depth: int = 1... | b1ce2a3178caf336921af23970bc247f03757986 | 74,096 |
def find_serial_devices(serial_matcher="ED"):
"""
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
"""
objWMIService = win32com.client... | ab89435b379b004ec4cd075fb0157059df3a4fd7 | 74,097 |
def GetOutputFileUrl(test_run, attempt, file_path: str = '') -> str:
"""Get URL for a command attempt's output file.
Args:
test_run: test run
attempt: command attempt
file_path: optional file path
Returns:
attempt's output URL
"""
return GetAppStorageUrl(
[test_run.output_path, attempt.... | c28743e379d13e89c4f75fc29cef213708c4bbe4 | 74,098 |
from typing import Dict
from pathlib import Path
from typing import Optional
import csv
def write_results(
result_dict: Dict[str, Dict[str, str]],
trans_dict: Dict[str, str],
input_filepath: Path,
output_filepath: Path,
write_csv: Optional[bool] = False,
) -> Dict[str, Dict[str, str]]:
"""
... | a791f47c9d16b451db14cd599cf2f15f04f0637c | 74,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.