content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pattern():
"""Start a pattern
Expected arguments are: name, delay, pause
"""
if request.args.get('name') is None:
return ''
pattern = request.args.get('name')
delay = float(request.args.get('delay', 0.1))
pause = float(request.args.get('pause', 0.5))
LightsController.start... | 13d1ff59dbd4521b157ab28bae75fed30378f8c5 | 30,881 |
def smow(t):
"""
Density of Standard Mean Ocean Water (Pure Water) using EOS 1980.
Parameters
----------
t : array_like
temperature [℃ (ITS-90)]
Returns
-------
dens(t) : array_like
density [kg m :sup:`3`]
Examples
--------
>>> # Data from UNESCO Tec... | 1f7ae913a1f4c71493d7d94d04bf543e6ffff72b | 30,882 |
from typing import Optional
from typing import Tuple
import torch
def generate_change_image_given_dlatent(
dlatent: np.ndarray,
generator: networks.Generator,
classifier: Optional[MobileNetV1],
class_index: int,
sindex: int,
s_style_min: float,
s_style_max: float,
style_direction_index... | 89ad94dd6f74c175ede27712046d3c46ba43143c | 30,884 |
def _build_square(A, B, C, D):
"""Build a matrix from submatrices
A B
C D
"""
return np.vstack((
np.hstack((A, B)),
np.hstack((C, D))
)) | 510b39f433023339f977a665c055f60abe46a160 | 30,886 |
def DataFrame_to_AsciiDataTable(pandas_data_frame,**options):
"""Converts a pandas.DataFrame to an AsciiDataTable"""
# Set up defaults and pass options
defaults={}
conversion_options={}
for key,value in defaults.items():
conversion_options[key]=value
for key,value in options.items():
... | 2864440528324e00e5d7389b5cc2b04aecbb833b | 30,888 |
def generate_fps_from_reaction_products(reaction_smiles, fp_data_configs):
""" Generates specified fingerprints for the both reactive and non-reactive substructures of the reactant and
product molecules that are the participating in the chemical reaction. """
# Generate the RDKit Mol representations of... | 42c4777dcf9c306cd45f9e94bbf18c0d1768c59b | 30,891 |
import torch
def count_acc(logits, label):
"""The function to calculate the .
Args:
logits: input logits.
label: ground truth labels.
Return:
The output accuracy.
"""
pred = F.softmax(logits, dim=1).argmax(dim=1)
if torch.cuda.is_available():
return (pred == label).ty... | 2f34be0cfb52a438c66b36d1d653ecbd72d559e2 | 30,892 |
def cuda_argmin(a, axis):
""" Location of minimum GPUArray elements.
Parameters:
a (gpu): GPUArray with the elements to find minimum values.
axis (int): The dimension to evaluate through.
Returns:
gpu: Location of minimum values.
Examples:
>>> a = cuda_argmin(cuda_give... | 25231969616e5c14736757a7b13f058ee218b6aa | 30,893 |
def _process_columns(validated_data, context):
"""Process the used_columns field of a serializer.
Verifies if the column is new or not. If not new, it verifies that is
compatible with the columns already existing in the workflow
:param validated_data: Object with the parsed column items
:param con... | cae79dda5e5121d4684e0995034050e9c6c45598 | 30,894 |
def module_of_callable(c):
"""Find name of module where callable is defined
Arguments:
c {Callable} -- Callable to inspect
Returns:
str -- Module name (as for x.__module__ attribute)
"""
# Ordinal function defined with def or lambda:
if type(c).__name__ == 'function':
... | 116e46a3e75fcd138e271a3413c62425a9fcec3b | 30,895 |
def lung_seg(input_shape, num_filters=[16,32,128], padding='same') :
"""Generate CN-Net model to train on CT scan images for lung seg
Arbitrary number of input channels and output classes are supported.
Arguments:
input_shape - (? (number of examples),
input image height (pixe... | 67cf286122c40e7fa2f87fc1e0a2f57e97777e32 | 30,896 |
def set_cluster_status(event, context):
"""Set the status of a cluster, ie active, inactive, maintainance_mode, etc"""
try:
cluster_status = event['queryStringParameters']['cluster_status']
except:
return {
"statusCode": 500,
"body": {"message": f'Must provide a stat... | dbb4215c19b8a241d8d353f3567a19eca32190dc | 30,897 |
import numpy
def rep(x, n):
""" interpolate """
z = numpy.zeros(len(x) * n)
for i in range(len(x)):
for j in range(n):
z[i * n + j] = x[i]
return z | 97c2ba7e48ff365fb6b4cebcee3f753169cd4670 | 30,898 |
def insert_new_datamodel(database: Database, data_model):
"""Insert a new datamodel in the datamodels collection."""
if "_id" in data_model:
del data_model["_id"]
data_model["timestamp"] = iso_timestamp()
return database.datamodels.insert_one(data_model) | b841e9e08e269cda60d261857bc8826b6a614814 | 30,899 |
async def infer_scatter_add(
self,
engine,
input: lib.AbstractArray,
dim: xtype.UInt[64],
index: lib.AbstractArray,
src: lib.AbstractArray,
):
"""Infer the return type of primitive `scatter_add`."""
return input | 1ce75e1e7d79ca89a4b467d96a1eb8c70b75fbee | 30,900 |
def eintr_retry(exc_type, f, *args, **kwargs):
"""Calls a function. If an error of the given exception type with
interrupted system call (EINTR) occurs calls the function again.
"""
while True:
try:
return f(*args, **kwargs)
except exc_type as exc:
if exc.errno !... | a4bf9e6ce3539226c1e963e59cce535ac57ac02c | 30,902 |
def dot2string(dot):
"""Return a string repr of dots."""
return "*" * int(dot) | e2822bfe20dab5702ec4052445718398e66d993e | 30,903 |
from typing import Optional
from typing import Dict
from typing import Any
import random
def generate_visited_place(
user_email: Optional[str] = None,
place_uid: Optional[str] = None,
place_id: Optional[int] = None,
latitude: Optional[float] = None,
longitude: Optional[float] = None,
) -> Dict[str... | e58de94b838512c642ba2a9c23bf87a9e50227bd | 30,904 |
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if ... | 3054b6ffe04c5bef18657dfd8e00e9f798689533 | 30,906 |
def authenticate_key(api_key):
"""
Authenticate an API key against our database
:param api_key:
:return: authenticated username
"""
user_model = Query()
user = db.search(user_model.api_key == api_key)[0]
if user:
return user["username"]
return False | 8d6e129e2e234730d629393b1398003eb7fa8361 | 30,907 |
def verify_ospf3_neighbor_number(device,
expected_interface=None,
expected_number=None,
expected_state=None,
extensive=False,
max_time=60,
... | 6540fa2425553672cd4b34fe0a112da3333d2c46 | 30,908 |
def create_and_clone_vcs_repo(orgname, reponame, tmpdir, testname=None):
"""
Creates a VCS org
Create a repo in that org
Clones that repo into a subdirectory of tmpdir
Returns the cloned repo directory path
"""
if testname == None:
description = "Created by CMS VCS test library"
... | fc6009c8fa4a4d89cc85d14d65178b59cdfe06e0 | 30,909 |
def graph(x, y, xerr=None, yerr=None):
"""Create a ROOT TGraph from array-like input.
Parameters
----------
x, y : float or array-like, shape (n, )
The data positions.
xerr, yerr : float or array-like, shape (n, ), optional
Error bar sizes in the *x* and *y* directions. The default... | 27222a556077e29a0240ae9bbc559639bbe5a041 | 30,910 |
def qUri(x):
"""Resolve URI for librdf."""
return resolve_uri(x, namespaces=RDF_NAMESPACES) | 4a27ebcd57cd9937311b7086d69a5e819704de9b | 30,911 |
def uninstall():
"""Uninstaller for pimessage"""
status = 0
try:
shutil.rmtree(data_dir, ignore_errors=True)
except OSError:
print 'Error in removing ~/.pimessage'
return 1
# Remove daemon from .profile
try:
_profile = os.path.join(utils.get_home_dir(), '.profile... | d4aac428d12304fa72a33ce7634a5b43f52a6ec8 | 30,912 |
import re
def regex(pattern: str) -> Parser:
"""Regex function.
Returns a function that parses the beginning of the
received string with the regular expression pattern.
Parameters
----------
pattern: str
a regular expression string.
Example
-------
>>> from simpleparser ... | 9db2bcff825a8f1a8662c34819796eb07816cd31 | 30,913 |
def get_name_scope_name(name):
"""Returns the input name as a unique `tf.name_scope` name."""
if name and name[-1] == '/':
return name
name = strip_invalid_chars(name)
with tf.name_scope(name) as unique_name:
pass
return unique_name | 4d745839d824646a0c43c8936428e8638dc267b3 | 30,914 |
def read_and_filter_wfdb(filename, length=None):
"""
Reads and filters a signal in Physionet format and returns a numpy array
:param filename: the name of the file
:param length: the length of the file to return or None for max length
:return: the filtered and cut signal as a numpy array
"""
... | d617a9832d2093bc8f1fd41b24920a668fa50287 | 30,915 |
def true_thresholds_out(true_cde, z_delta, expected_prop):
"""
calculates thresholds for the cde to get desired HPD value
Arguments:
----------
true_cde: numpy array (n, d) array of cde values for a range of y values
conditional on a x value (the row value)
z_delta : float, space betwee... | 14eba4fe24ed0e46df4ea0d6986ed870fb084d9e | 30,918 |
def query_disc(nside, lon, lat, radius, **kwargs):
"""
Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
radius : float
The... | fb987b327861acfa684a6ccabec745996d545e5d | 30,920 |
def prepare_audio_file(uploaded_file):
"""
A function to prepare the audio file uploaded by the user.
Input: uploaded file passed by st.file_uploader
Output: float32 numpy
"""
# use pydub to quickly prepare audio segment
a = pydub.AudioSegment.from_file(file=uploaded_file, format=uploa... | 688d326891cc0bfc7628cfcc5c636c181e714ad5 | 30,921 |
def get_item(obj,name):
"""Given a attribute item like 'robots[2].links[4].name', evaluates
the value of the item in the object.
Note: not secure! Uses eval()
"""
loc = {'_w':map(obj)}
result = {}
return eval('_w.'+name,globals(),loc) | a802b4cccda11b9a97be6a8bf0fd62024d636a74 | 30,922 |
def generate_bars_dict(H, neg_bars=False):
"""Generate a ground-truth dictionary W suitable for a std. bars test
Creates H bases vectors with horizontal and vertival bars on a R*R pixel grid,
(wth R = H // 2). The function thus returns a matrix storing H dictionaries of
size D=R*R.
:param H: Numb... | 2d0f0ff96507d7fb826ea37467c81d16af37a768 | 30,923 |
def add_node(uuid, state, manage_boot=True, **attributes):
"""Store information about a node under introspection.
All existing information about this node is dropped.
Empty values are skipped.
:param uuid: Ironic node UUID
:param state: The initial state of the node
:param manage_boot: whether... | 0765177fdc0ec4acc1926fcfcb40f4d8cd96abee | 30,924 |
def read_from_hdf5(hdfFile,label,dof_map=None):
"""
Just grab the array stored in the node with label label and return it
If dof_map is not none, use this to map values in the array
If dof_map is not none, this determines shape of the output array
"""
assert hdfFile is not None, "requires hdf5 f... | 92aa7da786e893d6477c2bcb3c6e3988cbc33558 | 30,925 |
def copy_planning_problem(planning_problem):
"""
Make a copy of a planning problem.
Parameters:
planning_problem (PlanningProblem): A planning problem.
Returns:
(PlanningProblem): A copy of the given planning problem.
"""
copy = PlanningProblem(
initial=planning_proble... | 03773086f067626c69eb44a319a48cd5c05dad27 | 30,926 |
def remove_pc(x, npc=1):
"""
Remove the projection on the principal components
:param x: X[i,:] is a data point
:param npc: number of principal components to remove
:return: XX[i, :] is the data point after removing its projection
"""
pc = compute_pc(x, npc)
if npc == 1:
xx = x -... | 797d538236f108a1710041c25aea3e88cc202c5f | 30,927 |
import json
def invocation_parameter(s) :
"""argparse parameter conversion function for invocation request
parameters, basically these parameters are JSON expressions
"""
try :
expr = json.loads(s)
return expr
except :
return str(s) | cca1a9c3514def152295b10b17ef44480ccca5a9 | 30,928 |
def build_bhp(bhm, dt_bin_edges, num_fissions = None,
pair_is = 'all', type_is = 'all', print_flag = False):
"""
Build the bicorr_hist_plot by selecting events from bhm and applying normalization factor. The normalization factor is only applied if norm_factor is provided. If not, norm_factor remai... | 083a959755b0c81567af236226c7a321fefdb8b9 | 30,929 |
def env_builder(env_name, env_info, **kwargs):
"""
the interface func for creating environment
:param env_name:the name of environment
:param env_info: the config info of environment
:return:environment instance
"""
return Registers.env[env_name](env_info, **kwargs) | ca5f8267bfac46407cd39e3464ff95d765274634 | 30,930 |
def filter_functions(input_set, filter_set):
"""
Keeps only elements in the filter set
:param input_set:
:param filter_set:
:return:
"""
ns = {}
filter_low = {x.lower() for x in filter_set}
for x in input_set:
xl = x.lower()
if xl in filter_low:
ns[x] = in... | cabc321b6730df4a0c7987b83c6a2c3d6fb69c02 | 30,932 |
from .scattering1d.filter_bank import morlet_1d, gauss_1d
from scipy.fft import ifftshift, ifft
def make_jtfs_pair(N, pair='up', xi0=4, sigma0=1.35):
"""Creates a 2D JTFS wavelet. Used in `wavespin.visuals`."""
morl = morlet_1d(N, xi=xi0/N, sigma=sigma0/N).squeeze()
gaus = gauss_1d(N, sigma=sigma0/N).squ... | 9a3e9c5d5a4a81c62f1ac3a5c7b0d5922eefdb78 | 30,933 |
def convert(your_text):
"""
Changes foot-notes into numbered foot-notes
Args:
your_text (str): a certain text
Returns:
str
"""
# print(f"Hello world, I plan to convert the following text: {your_text}")
### Terminology
# Given a four-line text that looks like the (so... | 82f926a3366ff29d65160ac9d09f5e72cf37b8cd | 30,934 |
def categorical(cum_weights):
"""
Sample from a discrete distribution
:param cum_weights: list of cumulative sums of probabilities (should satisfy cum_weights[-1] = 1)
:return: sampled integer from `range(0,len(cum_weights))`
"""
p = _rand.random()
i = 0
while p > cum_weights[i]:
... | c14009b98d5f683fc92cdeed64db0ca8276cd868 | 30,935 |
def floodfill(image, *args, **kwargs):
"""
Performs a floodfill on the given image
:Parameters:
image : `Image` or `numpy.array` or `basestring`
The image object we would like to operate on as a numpy array, url, filepath, or image object
keycolor : `tuple`
The c... | 1f8ce1bd87c3ecbd36b32524676208357ccefa78 | 30,936 |
def get_words_per_sentence(content):
"""
Get words per sentance average
:content: str
:returns: int
"""
words = get_words(content)
sentences = get_sentences(content)
return words / sentences | b3b4e8858f531723fee97d1cc3ba18c85ff16f92 | 30,937 |
def timeout_soft_cmd(cmd, timeout):
"""Same as timeout_cmd buf using SIGTERM on timeout."""
if not timeout:
return cmd
return 'timeout %us stdbuf -o0 -e0 %s' % (timeout, cmd) | 79491bf29a80678381e06ee1e9fe1feda858faf2 | 30,938 |
from typing import List
from typing import Tuple
def get_all_links_and_port_names_of_equipment(
client: SymphonyClient, equipment: Equipment
) -> List[Tuple[Link, str]]:
"""Returns all links and port names in equipment.
Args:
equipment ( `pyinventory.common.data_class.Equipment` ): could ... | a1cbf02744630fa4e7e72799f351e4befdb5737e | 30,939 |
def get_model_input(image):
"""Function to perform the preprocessing required so that it can be passed to the model for prediction
Args:
image (PIL image object): image that has to be transformed
Returns:
tensor (4D torch tensor): transformed image to torch 4D tenso... | cad77ab6c43a486838748cd1e8be39561171ac58 | 30,940 |
def extract_api_tree():
"""
Generates a tree of command group names and function
signatures in leaves from API function names in Master
"""
api_funcs = {}
for i in dir(session['master'])+dir(public_api(None)):
if (i.startswith('api_') or i.startswith('admin_api_') or
i.st... | c5fe7aacf5a4b6aad1e187307662d5d7f8601b98 | 30,941 |
def dataset_names_csv():
"""Returns the expected dataset names included in the tool."""
return resource_loader("dataset_names.csv") | cbb038d08982327a99657e1820136386ed3da4e4 | 30,943 |
def is_subtree(cls_name):
"""Determine whether 'cls_name' is a subtree."""
if cls_name == "SequentialCell":
return True
if cls_name in _ms_common_ns or cls_name in _ms_nn_ns or cls_name in _ms_ops_ns:
return False
return True | 46728b25d9098f6561861fa1f182f53567d5ece9 | 30,944 |
import re
def relevancy_to_adjust(relevancy):
"""
Convert the old test case relevancy into adjust rules
Expects a string or list of strings with relevancy rules.
Returns a list of dictionaries with adjust rules.
"""
rules = list()
rule = dict()
if isinstance(relevancy, list):
... | 960be0ef1fa0cce57dcd039e95fb031383ab25b5 | 30,945 |
def create_bcs(dim, H, Hmin, inlet_velocity, inlet_velocityOil,
V_0, solutes, subdomains_file, WaterOilInlet,
concentration_left,
interface_thickness,
enable_NS, enable_PF, enable_EC,
mesh, boundaries_Facet, contact_angle, **namespace):
"""... | d69db7ec4adbcddbaa3f6ffd95a2cff9333fd647 | 30,946 |
def get_parameter_values(parameter, Grid, selectedmodels, noofind):
"""
Get parameter values from grid
Parameters
----------
parameter : str
Grid, hdf5 object
selectedmodels :
models to return
noofind :
number of parameter values
Returns
-------
x_all : ... | 5e5dbfe3d810cb40e55c9e8cc1b6f33841212584 | 30,947 |
def dumpj(game):
"""Dump a game to json"""
return game.to_json() | bac5480ea2b3136cbd18d0690af27f94e4a2b6a3 | 30,948 |
def __add_statement2issue(statement_uid: int, issue_uid: int) -> StatementToIssue:
"""
Adds a new statement to issue link to the database
:param statement_uid: id of the related statement
:param issue_uid: id of the related issue
:return: New statement to issue object
"""
db_statement2issue... | 415ab377f048a6f0a490606853e38c57b2d00e45 | 30,949 |
def CreateInnerMaskBmapFromOuterMask( srcBmap ) :
"""
Derive the inner mask wxBitmap from the Outer mask wxBitmap.
The srcBmap must be "well behaved" in that a continuous border
must present so that a floodfill to the perimeter area will not reach
into the inner area. The border color must b... | 76b17d0d3d252bf316ba42c77e3b203f8e80a474 | 30,950 |
def generate_fake_example(w: int, h: int, identifier: int):
"""Generate a random COCO example."""
num_objects = 8
return {
'image': np.random.randint(0, 256, size=(w, h, 3), dtype=np.uint8),
'image/filename': f'{identifier:012}.jpg',
'image/id': identifier,
'objects': {
'area': n... | 38256e8de420a1a81875138936331e7fb914e72c | 30,951 |
from ..learn.optim import SGDW
from ..learn.optim import NesterovSGD
from ..learn.optim import NesterovSGDW
from ..learn.optim import AMSGrad
import torch
def get_optim(name: str):
""" get an optimizer by name """
if name.lower() == 'adam':
optimizer = torch.optim.Adam
elif name.lower() == 'adamw'... | 22c77840cffc8f6d5bd89bd190c8b912728cf6fa | 30,952 |
import types
def _get_functions_names(module):
"""Get names of the functions in the current module"""
return [name for name in dir(module) if
isinstance(getattr(module, name, None), types.FunctionType)] | 581384740dc27c15ac9710d66e9b0f897c906b96 | 30,953 |
import ast
def ex_rvalue(name):
"""A variable store expression."""
return ast.Name(name, ast.Load()) | 4afff97283d96fd29740de5b7a97ef64aad66efe | 30,954 |
def roll(input, shifts, dims=None):
"""Roll elements along the given dimension.
:attr:`dims` could be negative or ``None``:
```python
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# A negative dimension is the last-k dimension
print(torch.roll(x, shifts=1, dims=1)) # [[3, 1, 2], [6, 4, 5]]
pr... | 9ad3f85a3313be66fed358894d9fd105aa3c1c32 | 30,955 |
def gsl_eigen_genhermv_free(*args, **kwargs):
"""gsl_eigen_genhermv_free(gsl_eigen_genhermv_workspace w)"""
return _gslwrap.gsl_eigen_genhermv_free(*args, **kwargs) | 738832672277da7d6b8780a501aff36d740e3eba | 30,957 |
def model3():
"""
PyMC configuration with Model 1.
preevac_alpha vs theta[0] + theta[1]*type + theta[2]*eff_wid + theta[3]*tread
"""
# Priors
theta = mc.Uniform('theta',
lower=[-10.0, -10.0],
upper=[ 10.0, 10.0],
... | c79aa2edbd1cff864a48b5476106afaf49d74975 | 30,959 |
def getVTGui():
"""Small wrapper to hide the fact that vtapp object contains gui.
:return: main window object
"""
return vtutils.getVTApp().gui | 08ac978c35a6530cddc154ef1df925ea339559f3 | 30,960 |
def ksd_parametric_custom(ksd_value, alpha, B_parametric):
"""
Compute KSD test using a parametric bootstrap with kernel matrix
inputs: ksd_values: (N,) array consisting of KSD values
for N bandwidths for inputs X and score_X
alpha: real number in (0,1) (level of the test)
... | 4c4cf6ae1edde41cb519bf7459950f1f1dd42c8a | 30,961 |
def freehand(img, depth=10., el=np.pi / 2.2, az=np.pi / 4):
"""
手绘风格图像生成
:param img:
:param depth: 深度,取值在0-100
:param el: 光源的俯视角度,弧度值
:param az: 光源的方位角度,弧度值
:return:
"""
img = rgb2grey(img)
img = img * 255 if np.max(img) <= 1.1 else img
grad = np.gradient(img) # 取图像灰度的梯度值
... | 06874581c622a671ed6e0cbb3a33dfed020902f5 | 30,962 |
def batch_compute_ic(trajs, params, *, weights=None, method="fft"):
"""Compute a batch of integrated correlated matrices.
Parameters
----------
trajs : list of (n_frames[i], n_features) ndarray
List of featurized trajectories.
params : 1d array-like or list of 1d array-like
If a 1d ... | c6a931820eb1d17477143e615b942551e1c6369f | 30,963 |
def genTrainFeatures(dimension=128):
"""
Input:
dimension: desired dimension of the features
Output:
X: n feature vectors of dimensionality d (nxd)
Y: n labels (-1 = girl, +1 = boy) (n)
"""
# Load in the data
Xgirls = name2features("data/girls.train", B=dimension)
... | f5c9838f81caf1cc9641de450e6eb9a844e47ccd | 30,965 |
def stateDiff(start, end):
"""Calculate time difference between two states."""
consumed = (end.getTimestamp() - start.getTimestamp()).total_seconds()
return consumed | 1f76903e2486e2c378f338143461d1d15f7993a6 | 30,966 |
import copy
import random
def staticDepthLimit(max_depth):
"""Implement a static limit on the depth of a GP tree, as defined by Koza
in [Koza1989]. It may be used to decorate both crossover and mutation
operators. When an invalid (too high) child is generated, it is simply
replaced by one of its paren... | cdcb1e58a681b622ced58e9aa36562e1fedb6083 | 30,967 |
def rotate(coor, alpha, beta, gamma):
"""Rotate 'coor' by the angles alpha, beta, gamma.
"""
R1 = getD(alpha)
R2 = getC(beta)
R3 = getD(gamma)
M = R3 * R2 * R1
return np.dot(coor, M) | fc7348dfd65012239841949da82a188299305e97 | 30,968 |
import requests
def get_content(url):
"""get content - cfscrape"""
request = requests.get(url)
content = request.text
if request.status_code == 503:
scraper = cfscrape.create_scraper()
content = scraper.get(url).content
return content | 4f6db08c2cc393f2ac6a1447f6bd9a44535de12a | 30,970 |
import re
def titlecase(string):
"""Turn string of words into titlecased words.
:type string: str
:param string: A string of words.
"""
return re.sub(
r"[A-Za-z]+('[A-Za-z]+)?",
lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),
string,
) | 77976d2ccad5b6b924b76d587a6883cf660497d0 | 30,971 |
import re
from datetime import datetime
def youdao_definition(wrapped_word):
"""
get word meaning from youdao.com, thanks for their great work.
"""
word = wrapped_word[:-2].strip()
url = constants.YOUDAO_URL_PREFIX + word
content = utility.get_content_of_url(url)
soup = bs4.BeautifulSoup(m... | 207a0777122bb1a0945037e18a916217f6c084cb | 30,972 |
from operator import mod
def bahai_from_fixed(date):
"""Return Bahai date [major, cycle, year, month, day] corresponding
to fixed date, date."""
g_year = gregorian_year_from_fixed(date)
start = gregorian_year_from_fixed(BAHAI_EPOCH)
years = (g_year - start -
(1 if (date <= fixed_fr... | bf31da3d961fc00abd764e06bae70094cb81af23 | 30,973 |
def create_or_update_record(tableName, record):
"""
Function to create or update a record in DynamoDB
Params:
tableName::str
The table name to get the record
record::dict
The object to store
Returns:
bool
If the record was inserted or not
... | 4b1fbec40b404d93aefa2da728b5966917b2264a | 30,974 |
import http
import json
def get_service_status(fledge_url):
"""
Return ping status from fledge.
Args:
fledge_url: The URL of Fledge.
Returns:
A json string that contains ping status.
"""
_connection = http.client.HTTPConnection(fledge_url)
_connection.request("GET", '/fledg... | 5c0381acba98dc4ff060f36671ec6f15595e8afb | 30,976 |
def png_to_jpeg(image_bytes: bytes, quality: int = 100) -> np.ndarray:
"""Converts PNG image (bytes or str) to JPEG (bytes)."""
runner = _get_runner()
decode_fn = lambda img: tf.image.decode_png(img, channels=3)
image = runner.run(decode_fn, image_bytes)
fn = lambda img: tf.image.encode_jpeg(img, format='rgb'... | fa9cde555f2f2bba6375ecdb195a42ba6d753497 | 30,977 |
import urllib
def get_object_metadata(sess, bucket_name, blob_name):
"""
get object metadata
"""
url = "https://www.googleapis.com/storage/v1/b/{}/o/{}".format(
bucket_name, urllib.quote(blob_name, safe="")
)
return sess.request(method="GET", url=url) | 37fc44216e61e876c426b66a53054e59847bdbc6 | 30,978 |
def j2_pert(s):
"""Returns the J2 acceleration for a given state.
Args:
s(1x6 numpy array): the state vector [rx,ry,rz,vx,vy,vz]
Returns:
1x3 numpy array: the J2 acceleration [ax,ay,az]
"""
r = np.linalg.norm(s[0:3])
K = -3*mu_Earth*J2*(Re**2)/2/r**5
comp = np.... | fc9561521d55e4f6f300dd9a7cdfc52ba49c9473 | 30,979 |
import scipy
def bootstrap(v):
"""
Constructs Monte Carlo simulated data set using the
Bootstrap algorithm.
Usage:
>>> bootstrap(x)
where x is either an array or a list of arrays. If it is a
list, the code returns the corresponding... | 7d6a194e68ad9833ef0cbef6de0b8ff6f5a7cd62 | 30,980 |
def html_table_header():
"""Return the HTML row with header cells used in all tables."""
markup = ("<tr>" +
"<th>Column name</th>" +
"<th>DataType</th>" +
"<th><abbr title='Primary Key'>PK</abbr></th>" +
"<th><abbr title='Foreign Key'>FK</abbr></th>" +
... | 0fc65ca33cf23594dad007a3b0b16f1244ace62e | 30,981 |
import glob
def load_images(input_files):
"""
Flattens each image in a folder into a 1D numpy array.
Next, each 1D numpy array is stacked into a 2D numpy array,
where each row of the image is the flattened version of the image
"""
imgfiles = glob.glob(input_files)
arr = []
for i, imgfi... | 06894e87f66a25ba195563a7a7ff961c365691db | 30,982 |
def hpat_pandas_series_iloc(self):
"""
Pandas Series operators :attr:`pandas.Series.at`, :attr:`pandas.Series.iat`, :attr:`pandas.Series.iloc`, :attr:`pandas.Series.loc` implementation.
.. only:: developer
Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_iloc2
Parameter... | 56ec60440b540b2b15a38a730aad3f4cba4563f3 | 30,983 |
def checkLoggedIn(session):
"""
checks if any player
has logged in yet
"""
try:
return session["roll"] is not None
except KeyError:
session["roll"] = None
return False | 436f51212abc9fe00abf11266cb90159a7f60bd4 | 30,984 |
import typing
import logging
def push_docker_image_buildah(external_docker_name, push_connection: typing.Optional[Connection]) -> str:
"""
Push the docker image using buildah
:param external_docker_name: external docker image target name, without host
:param push_connection: connection for pushing Do... | 950fd26d65de99f035ea5d39e3f708b0173298f6 | 30,985 |
def _match(patspec, tree):
"""Test if a tree matches the given pattern statement; return the matches
>>> _match(b'f(_)', parse(b'f()'))
>>> _match(b'f(_)', parse(b'f(1)'))
[('func', ('symbol', 'f'), ('symbol', '1')), ('symbol', '1')]
>>> _match(b'f(_)', parse(b'f(1, 2)'))
"""
pattern = _cac... | 1b0fd2ef103bc2e9a6e1ee3df855b736ff24c162 | 30,986 |
from typing import List
def list_methods(client: Client) -> List[str]:
"""Lists the methods which are available on the server.
Args:
client: A client instance.
Returns:
List of method names.
"""
return client._client.ListMethods() | a005113b9142f6de929b6c7accc4b0150041742c | 30,987 |
import re
def MakeLocal(start, end, location, name):
"""
Create a local variable
@param start: start of address range for the local variable
@param end: end of address range for the local variable
@param location: the variable location in the "[bp+xx]" form where xx is
a numb... | 1950cd443bb4a4618638943256ed602412133ca7 | 30,988 |
def accuracy(y, t):
"""
y: baredl.Tensor or np.ndarray (n, c)
n: number of samples
c: number of classes
Assuming it contains probabilities for each class
e.g. [[0.1,0.3,0.6], [0.1,0.8,0.1], ...]
t: baredl.Tensor or np.array (n,)
n: number of samples
Assuming ... | 7f810190ee0a3c36ab3f8f51a2d7869309614a75 | 30,989 |
from typing import Type
def get_config() -> Type[Config]:
"""Get the global spines configuration
Returns
-------
Config
The global configuration settings for the current spines
project.
"""
if _GLOBAL_CONFIG is None:
load_config()
return _GLOBAL_CONFIG.copy() | 628337a2669237df265aafb7ad07746e075690c7 | 30,990 |
from typing import Optional
def prompt_yes_or_no(
question: str,
yes_text: str = 'Yes',
no_text: str = 'No',
has_to_match_case: bool = False,
enter_empty_confirms: bool = True,
default_is_yes: bool = False,
deselected_prefix: str = ' ',
selected_prefix:... | 754659d5ab28715002d1a5d47a80e87a64d3b79f | 30,991 |
import oci.object_storage
import mysqlsh
import re
import threading
def delete_bucket_object(name=None, **kwargs):
"""Deletes an object store bucket objects
Args:
name (str): The name of the object, can include * to match multiple
objects
**kwargs: Additional options
Keyword... | 95e15c98f5c11cb55b6036305ab8fc0b440fcfa0 | 30,992 |
def _create_input_dict(function_graph,
func_arg_placeholders,
initial_value=None):
"""Create a mapping from graph tensor names to function tensor names."""
if initial_value is None:
input_dict = {}
else:
input_dict = dict(initial_value)
for op in function_gr... | 8db84c7ba4cb13c13bf5ef54fe1ecff79b5765fc | 30,993 |
def process(document, rtype=None, api=None):
""" Extracts spelling-corrected tokens in specified format from given texterra-annotated text. """
corrected_tokens = []
if annotationName in document['annotations']:
if rtype == 'annotation':
for token in document['annotations'][annotationNam... | bbd2de604bcf9c280bd2fac8e5e0d0975a905bc9 | 30,994 |
from pathlib import Path
import hashlib
import base64
def get_hashed_path (path: Path, *, algorithm=hashlib.sha256, stretching_count: int=256) -> bytes:
"""
obfuscate a filename.
I recommend this function, if you want to hide from anybody guess a file information from file-name.
"""
p = Path(path)
retur... | 1981477e975465a23f73931d9496a71c8cf26e34 | 30,995 |
def quantile(values, q):
"""
Returns q-th quantile.
"""
values = sorted(values)
size = len(values)
idx = int(round(size * q)) - 1
if idx == 0:
raise ValueError("Sample size too small: %s" % len(values))
return values[idx] | 614f6d9dbdf586b802d6380e2880df3659faa0c2 | 30,996 |
def parse_child_text(parent, selector, parser, index=0):
"""Parse the text content of the child element of parent as specified by the given CSS selector
If index is specified, parse the text content of the matching child element at the specified zero-based index; otherwise, parse the text content of the first matchi... | b10ec463dd572b4e6e256302d8db6e599638b1be | 30,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.