content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def zoom_api_call(user, verb, url, *args, **kwargs):
"""
Perform an API call to Zoom with various checks.
If the call returns a token expired event,
refresh the token and try the call one more time.
"""
if not settings.SOCIAL_AUTH_ZOOM_OAUTH2_KEY:
raise DRFValidationEr... | 5c359a4a7acd69a942aedcb78fc156b8218ab239 | 10,725 |
def addHtmlImgTagExtension(notionPyRendererCls):
"""A decorator that add the image tag extension to the argument list. The
decorator pattern allows us to chain multiple extensions. For example, we
can create a renderer with extension A, B, C by writing:
addAExtension(addBExtension(addCExtension(noti... | 914d2395cdf9c5f52f94eef80e3f7469a70eb0ae | 10,727 |
def get_symmetry_projectors(character_table, conjugacy_classes, print_results=False):
"""
:param character_table: each row gives the characters of a different irreducible rep. Each column
corresponds to a different conjugacy classes
:param conjugacy_classes: List of lists of conjugacy class elements
... | 8780ef1a9ebb3f6e6960d04d07677e323e7565b9 | 10,729 |
from typing import List
def is_permutation_matrix(matrix: List[List[bool]]) -> bool:
"""Returns whether the given boolean matrix is a permutation matrix."""
return (all(sum(v) == 1 for v in matrix) and
sum(any(v) for v in matrix) == len(matrix)) | b53d6f4ba6e8e1ba445783350de831b614aa187e | 10,730 |
import torch
def DPT_Hybrid(pretrained=True, **kwargs):
""" # This docstring shows up in hub.help()
MiDaS DPT-Hybrid model for monocular depth estimation
pretrained (bool): load pretrained weights into model
"""
model = DPTDepthModel(
path=None,
backbone="vitb_rn50_384",
n... | 0a5cb661e9e0f08daae73b8c49ba8324e0cfb3e9 | 10,731 |
def show_counts(input_dict):
"""Format dictionary count information into a string
Args:
input_dict (dictionary): input keys and their counts
Return:
string: formatted output string
"""
out_s = ''
in_dict_sorted = {k: v for k, v in sorted(input_dict.items(), key=lambda item... | 078d1f7599b22741f474c0e6d1b02f44edfc1f9b | 10,732 |
def encipher_railfence(message,rails):
"""
Performs Railfence Encryption on plaintext and returns ciphertext
Examples
========
>>> from sympy.crypto.crypto import encipher_railfence
>>> message = "hello world"
>>> encipher_railfence(message,3)
'horel ollwd'
Parameters
========... | b1a56cdb255065b18caa4ba6da1fa11759f87152 | 10,733 |
import inspect
def format_signature(name: str, signature: inspect.Signature) -> str:
"""Formats a function signature as if it were source code.
Does not yet handle / and * markers.
"""
params = ', '.join(
format_parameter(arg) for arg in signature.parameters.values())
if signature.return_... | a14fde11850d420d15d2f9d7f3ac4cbe9aee03cc | 10,734 |
def extract_ratios_from_ddf(ddf):
"""The same as the df version, but works with
dask dataframes instead."""
# we basicaly abuse map_partition's ability to expand indexes for lack of a working
# groupby(level) in dask
return ddf.map_partitions(extract_ratios_from_df, meta={'path': str, 'ratio': str, ... | fcb816677d3d0816b2327d458a3fdd1b820bac9e | 10,735 |
def check_if_prime(number):
"""checks if number is prime
Args:
number (int):
Raises:
TypeError: if number of type float
Returns:
[bool]: if number prime returns ,True else returns False
"""
if type(number) == float:
raise TypeError("TypeError: entered float ty... | 0a15a4f133b12898b32b1f52a317939cf5e30d34 | 10,736 |
import inspect
def get_signatures() -> {}:
"""
Helper method used to identify the valid arguments that can be passed
to any of the pandas IO functions used by the program
:return: Returns a dictionary containing the available arguments for each pandas IO method
"""
# Creates an empty dictionar... | 243b798e1c4c57a89749fff1d33be660ab4e973b | 10,737 |
from typing import List
def batch_answer_same_context(questions: List[str], context: str) -> List[str]:
"""Answers the questions with the given context.
:param questions: The questions to answer.
:type questions: List[str]
:param context: The context to answer the questions with.
:type context: s... | b58df72f1252427ea3e58e2f8379b8e77ea55273 | 10,740 |
import typing
def dynamic_embedding_lookup(keys: tf.Tensor,
config: de_config_pb2.DynamicEmbeddingConfig,
var_name: typing.Text,
service_address: typing.Text = "",
skip_gradient_update: bool = False,
... | c1d69548e60ff00e55ab04fe83607cae31b6558c | 10,742 |
def register_unary_op(registered_name, operation):
"""Creates a `Transform` that wraps a unary tensorflow operation.
If `registered_name` is specified, the `Transform` is registered as a member
function of `Series`.
Args:
registered_name: the name of the member function of `Series` corresponding
to ... | c0fb56a8e93936a4c45e199e28889ccef67d19de | 10,743 |
def add_climatology(data, clim):
"""Add 12-month climatology to a data array with more times.
Suppose you have anomalies data and you want to add back its
climatology to it. In this sense, this function does the opposite
of `get_anomalies`. Though in this case there is no way to obtain
the climatol... | 28845fc1455bc317d158b503ed07a7d0c1af5655 | 10,744 |
from typing import List
def already_exists(statement: str, lines: List[str]) -> bool:
"""
Check if statement is in lines
"""
return any(statement in line.strip() for line in lines) | 194d8c6c48609f5a2accacdb2ed0857815d48d1d | 10,745 |
import random
def uniform(lower_list, upper_list, dimensions):
"""Fill array """
if hasattr(lower_list, '__iter__'):
return [random.uniform(lower, upper)
for lower, upper in zip(lower_list, upper_list)]
else:
return [random.uniform(lower_list, upper_list)
fo... | 59bcb124f0d71fd6e5890cd1d6c200319ab5910e | 10,746 |
import torch
def prepare_data(files, voxel_size, device='cuda'):
"""
Loads the data and prepares the input for the pairwise registration demo.
Args:
files (list): paths to the point cloud files
"""
feats = []
xyz = []
coords = []
n_pts = []
for pc_file in files:
... | 1c11444d4f6ca66396651bb49b8c655bedf6b8fa | 10,747 |
def reshape(box, new_size):
"""
box: (N, 4) in y1x1y2x2 format
new_size: (N, 2) stack of (h, w)
"""
box[:, :2] = new_size * box[:, :2]
box[:, 2:] = new_size * box[:, 2:]
return box | 56fbeac7c785bd81c7964d7585686e11864ff034 | 10,748 |
import json
def sort_actions(request):
"""Sorts actions after drag 'n drop.
"""
action_list = request.POST.get("objs", "").split('&')
if len(action_list) > 0:
pos = 10
for action_str in action_list:
action_id = action_str.split('=')[1]
action_obj = Action.object... | 80f2042858f7a0ecad3663ae4bf50ad73935be3b | 10,749 |
def fetch_file(parsed_url, config):
"""
Fetch a file from Github.
"""
if parsed_url.scheme != 'github':
raise ValueError(f'URL scheme must be "github" but is "{parsed_url.github}"')
ghcfg = config.get('github')
if not ghcfg:
raise BuildRunnerConfigurationError('Missing configur... | c688a68aeaa4efa0cda21f3b58a94075e4555004 | 10,750 |
import calendar
def number_of_days(year: int, month: int) -> int:
"""
Gets the number of days in a given year and month
:param year:
:type year:
:param month:
:type month:
:return:
:rtype:
"""
assert isinstance(year, int) and 0 <= year
assert isinstance(month, int) and 0 < ... | d585f037292eef36ecc753fbf702035577513a15 | 10,751 |
from functools import reduce
def medstddev(data, mask=None, medi=False, axis=0):
"""
This function computes the stddev of an n-dimensional ndarray with
respect to the median along a given axis.
Parameters:
-----------
data: ndarray
A n dimensional array frmo wich caculate the median s... | bbab9eede714d7c64344af271f8b6e817723d837 | 10,753 |
def load_npz(filename: FileLike) -> JaggedArray:
""" Load a jagged array in numpy's `npz` format from disk.
Args:
filename: The file to read.
See Also:
save_npz
"""
with np.load(filename) as f:
try:
data = f["data"]
shape = f["shape"]
re... | 640add32dab0b7bd12784a7a29331b59521a0f8a | 10,754 |
import re
def _egg_link_name(raw_name: str) -> str:
"""
Convert a Name metadata value to a .egg-link name, by applying
the same substitution as pkg_resources's safe_name function.
Note: we cannot use canonicalize_name because it has a different logic.
"""
return re.sub("[^A-Za-z0-9.]+", "-", r... | 923ff815b600b95ccb5750a8c1772ee9156e53b2 | 10,755 |
def my_view(request):
"""Displays info details from nabuco user"""
owner, c = User.objects.get_or_create(username='nabuco')
# Owner of the object has full permissions, otherwise check RBAC
if request.user != owner:
# Get roles
roles = get_user_roles(request.user, owner)
# Get ... | 55c3443f24d56b6ea22e02c9685d6057dfc79c7e | 10,756 |
def handler500(request):
"""
Custom 500 view
:param request:
:return:
"""
return server_error(request, template_name='base/500.html') | 91db9daeaac6f7f6b2207a3c8be7fa09f932b50f | 10,757 |
def get_badpixel_mask(shape, bins):
"""Get the mask of bad pixels and columns.
Args:
shape (tuple): Shape of image.
bins (tuple): CCD bins.
Returns:
:class:`numpy.ndarray`: 2D binary mask, where bad pixels are marked with
*True*, others *False*.
The bad pixels are foun... | 2e636aef86d2462815683a975ef99fbcdeeaee19 | 10,758 |
import six
import yaml
def maybe_load_yaml(item):
"""Parses `item` only if it is a string. If `item` is a dictionary
it is returned as-is.
Args:
item:
Returns: A dictionary.
Raises:
ValueError: if unknown type of `item`.
"""
if isinstance(item, six.string_types):
... | 9288012f0368e2b087c9ef9cd9ffaca483b4f11b | 10,760 |
def histeq(im,nbr_bins=256):
"""histogram equalize an image"""
#get image histogram
im = np.abs(im)
imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True)
cdf = imhist.cumsum() #cumulative distribution function
cdf = 255 * cdf / cdf[-1] #normalize
#use linear interpolation of cdf to ... | bbb0e758e519a7cfcc866e3193cd1ff26bf5efbc | 10,761 |
def txgamma(v, t, gamma, H0):
"""
Takes in:
v = values at z=0;
t = list of redshifts to integrate over;
gamma = interaction term.
Returns a function f = [dt/dz, d(a)/dz,
d(e'_m)/dz, d(e'_de)/dz,
d(... | a1506ea0b54f468fd63cd2a8bd96e8a9c46a92f3 | 10,762 |
def text_pb(tag, data, description=None):
"""Create a text tf.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A Python bytestring (of type bytes), a Unicode string, or a numpy data
array of those types.
description: Optional long-form description for this summary, ... | 43d652ebb9ab1d52c0514407a3c47d56816cbb65 | 10,763 |
def sanitize_input(args: dict) -> dict:
"""
Gets a dictionary for url params and makes sure it doesn't contain any illegal keywords.
:param args:
:return:
"""
if "mode" in args:
del args["mode"] # the mode should always be detailed
trans = str.maketrans(ILLEGAL_CHARS, ' ' * len(ILL... | 063d314cb3800d24606b56480ce63b7dda3e8e51 | 10,764 |
def sum_to(containers, goal, values_in_goal=0):
"""
Find all sets of containers which sum to goal, store the number of
containers used to reach the goal in the sizes variable.
"""
if len(containers) == 0:
return 0
first = containers[0]
remain = containers[1:]
if first > goal:
... | db5297929332a05606dec033318ca0d7c9661b1d | 10,765 |
def rt2add_enc_v1(rt, grid):
"""
:param rt: n, k, 2 | log[d, tau] for each ped (n,) to each vic (k,)
modifies rt during clipping to grid
:param grid: (lx, ly, dx, dy, nx, ny)
lx, ly | lower bounds for x and y coordinates of the n*k (2,) in rt
dx, dy | step sizes of the regular grid
... | 3af0b8e15fdcc4d9bbeb604faffbd45cf013e86b | 10,766 |
import heapq
def draw_with_replacement(heap):
"""Return ticket drawn with replacement from given heap of tickets.
Args:
heap (list): an array of Tickets, arranged into a heap using heapq.
Such a heap is also known as a 'priority queue'.
Returns:
the Ticket with the least tick... | 06eb982ecf32090da51f02356a6996429773e233 | 10,767 |
def get_string(entry):
"""
This function ...
:param entry:
:return:
"""
value = entry.split(" / ")[0].rstrip()
return value | 38a1dc41fd06b49aa8724cc783466b485c9017fb | 10,769 |
import collections
def get_top_words(words):
"""
Получить список наиболее часто встречающихся слов, с указанием частоты
:param words: список слов для анализа
:return: [(слово1, количество повторений слова1), ..]
"""
return collections.Counter(words).most_common() | 632317f57e734a93b6f3f20dfef001028b40c6b3 | 10,771 |
def get_slope(x, y, L):
"""
Funcao que retorna o slope da serie temporal dos dados
"""
try:
x=np.array(x).reshape(-1, 1)
y=np.array(y).reshape(-1, 1)
lr=LinearRegression()
lr.fit (x[:L],y[:L])
return lr.coef_[0][0]
except:
return 0 | 23f3419049ee1372d5963823e2f52b895bc766e8 | 10,772 |
from typing import Dict
from typing import Any
def _minimize_price(price: Dict[str, Any]) -> Price:
"""
Return only the keys and values of a price the end user would be interested in.
"""
keys = ['id', 'recurring', 'type', 'currency', 'unit_amount', 'unit_amount_decimal', 'nickname',
'prod... | 7414e0f3e5ae11f55b5781a679e593294122aed2 | 10,773 |
def project(signals, q_matrix):
"""
Project the given signals on the given space.
Parameters
----------
signals : array_like
Matrix with the signals in its rows
q_matrix : array_like
Matrix with an orthonormal basis of the space in its rows
Returns
-------
proj_sig... | 0d6aa780d0d424260df5f8391821c806e12c81e5 | 10,774 |
def all_movies():
"""
Returns all movie in the database for Movies
service
"""
movies = ut.get_movies()
if len(movies) == 0:
abort(404)
return make_response(jsonify({"movies":movies}),200) | d8b2e3a66adf52830d7027953c22071449d2b29a | 10,775 |
def format_map(mapping, st):
"""
Format string st with given map.
"""
return st.format_map(mapping) | 462e0a744177d125db50739eac1f2e7a62128010 | 10,776 |
def communities_greedy_modularity(G,f):
"""
Adds a column to the dataframe f with the community of each node.
The communitys are detected using greedy modularity.
G: a networkx graph.
f: a pandas dataframe.
It works with networkx vesion: '2.4rc1.dev_20190610203526'
"""
if not(set(f.name... | cfca6ef66730f3a6ef467f1c51c66c5d46296351 | 10,777 |
import json
def load_loglin_stats(infile_path):
"""read in data in json format"""
# convert all 'stats' to pandas data frames
with open(infile_path) as infile:
data = json.load(infile)
new_data = {}
for position_set in data:
try:
new_key = eval(position_set)
ex... | c307ff2cf4e07bbb7843971cceaf74744422276c | 10,778 |
def _simple_logistic_regression(x,y,beta_start=None,verbose=False,
CONV_THRESH=1.e-3,MAXIT=500):
"""
Faster than logistic_regression when there is only one predictor.
"""
if len(x) != len(y):
raise ValueError, "x and y should be the same length!"
if beta_start is ... | c37190b167e634df31127f79163aaeb56bac217e | 10,779 |
def preemphasis(signal,coeff=0.95):
"""perform preemphasis on the input signal.
:param signal: The signal to filter.
:param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95.
:returns: the filtered signal.
"""
return np.append(signal[0],signal[1:]-coeff*signal[:-1]) | c5173708e7b349decd34ac886493103eaadb023d | 10,780 |
from sacremoses import MosesTokenizer
from sacremoses import MosesPunctNormalizer
def build_moses_tokenizer(tokenizer: MosesTokenizerSpans,
normalizer: MosesPunctNormalizer = None) -> Callable[[str], List[Token]]:
"""
Wrap Spacy model to build a tokenizer for the Sentence class.
... | 0dee31ab9030e387dd6907efad60c188eb0241b2 | 10,781 |
from typing import Callable
from typing import Hashable
from typing import Union
def horizontal_block_reduce(
obj: T_DataArray_or_Dataset,
coarsening_factor: int,
reduction_function: Callable,
x_dim: Hashable = "xaxis_1",
y_dim: Hashable = "yaxis_1",
coord_func: Union[str, CoordFunc] = coarsen... | 07fc497ae8c5cd90699bc73bfbeab705c13ed0c6 | 10,782 |
def statements_api(context, request):
"""List all the statements for a period."""
dbsession = request.dbsession
owner = request.owner
owner_id = owner.id
period = context.period
inc_case = case([(AccountEntry.delta > 0, AccountEntry.delta)], else_=None)
dec_case = case([(AccountEntry.delta ... | 87a1ec3e5fc5730eda30367a5f9f34aef6cf7339 | 10,783 |
def fp(x):
"""Function used in **v(a, b, th, nu, dimh, k)** for **analytic_solution_slope()**
:param x: real number
:type x: list
:return: fp value
:rtype: list
"""
rx = np.sqrt(x * 2 / np.pi)
s_fresnel, c_fresnel = sp.fresnel(rx)
return - 2 * 1j * np.sqrt(x) * np.exp(-1j * x) * np.s... | 202000557fb239e589ffd4d7b9709b60678ab784 | 10,784 |
def get_truck_locations(given_address):
"""
Get the location of the food trucks in Boston TODAY within 1 mile
of a given_address
:param given_address: a pair of coordinates
:return: a list of features with unique food truck locations
"""
formatted_address = '{x_coordinate}, {y_coordinate}'.... | f1d5e290c5c46e1587a2f98c2e82edee3890fc05 | 10,785 |
import inspect
import warnings
def _getRelevantKwds(method, kwds):
"""return kwd args for the given method, and remove them from the given kwds"""
argspec = inspect.getargspec(method)
d = dict()
for a in kwds:
if a not in argspec.args:
warnings.warn("Unrecognized kwd: {!r}".format(... | bca410b99e750f233a5e4476413e6bacfa52dcb9 | 10,786 |
import requests
def find_overview_details(park_code):
""" Find overview details from park code """
global API_KEY
fields = "&fields=images,entranceFees,entrancePasses,operatingHours,exceptions"
url = "https://developer.nps.gov/api/v1/parks?parkCode=" + park_code + "&api_key=" + API_KEY + fields
... | 95cf281828154c45eae1e239f33d2de8bcf9e7fa | 10,787 |
import torch
def embed_nomenclature(
D,
embedding_dimension,
loss="rank",
n_steps=1000,
lr=10,
momentum=0.9,
weight_decay=1e-4,
ignore_index=None,
):
"""
Embed a finite metric into a target embedding space
Args:
D (tensor): 2D-cost matrix of the finite metric
... | 1e9ca98dec0c3e42af0af483b6e9ef9efa11b225 | 10,788 |
def raw_env():
"""
To support the AEC API, the raw_env() function just uses the from_parallel
function to convert from a ParallelEnv to an AEC env
"""
env = parallel_env()
env = parallel_to_aec(env)
return env | dcb491c2beb50f73ba0fdab96bcd069916ce9b6d | 10,789 |
def cmd_line(preprocessor: Preprocessor, args: str) -> str:
"""the line command - prints the current line number"""
if args.strip() != "":
preprocessor.send_warning("extra-arguments", "the line command takes no arguments")
context = preprocessor.context.top
pos = context.true_position(preprocessor.current_positio... | 061bcf2ced6c22c77d81bb30ec00a5c1964c3624 | 10,790 |
from xml.dom import expatbuilder
from xml.dom import pulldom
def parse(file, parser=None, bufsize=None):
"""Parse a file into a DOM by filename or file object."""
if parser is None and not bufsize:
return expatbuilder.parse(file)
else:
return _do_pulldom_parse(pulldom.parse, (file,),
... | 0d4bc592143ecb7c093eceaf4f5fe0d18869ea9c | 10,792 |
import hashlib
def create_hash256(max_length=None):
"""
Generate a hash that can be used as an application secret
Warning: this is not sufficiently secure for tasks like encription
Currently, this is just meant to create sufficiently random tokens
"""
hash_object = hashlib.sha256(force_bytes(g... | 4856be59c475bcfc07137b62511de4d5c7531eb3 | 10,793 |
from io import StringIO
def assert_content_in_file(file_name, expected_content):
"""
Fabric assertion: Check if some text is in the specified file (result of installing a test product)
Provision dir: PROVISION_ROOT_PATH
:param file_name: File name
:param expected_content: String to be found in fil... | eba68222d39c55902da1c4c4ae7055b7edc170e0 | 10,794 |
import math
import numpy
def _calculate_hwp_storage_fut(
hwp_shapes, base_dataset_uri, c_hwp_uri, bio_hwp_uri, vol_hwp_uri,
yr_cur, yr_fut, process_pool=None):
"""Calculates carbon storage, hwp biomassPerPixel and volumePerPixel due to
harvested wood products in parcels on current landscape.
... | 71b597c62014c120a3deb99ceea14d84612e3b19 | 10,796 |
def wcxf2arrays_symmetrized(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy ... | 6cca03761b9799a3af7b933877ff70d6d68f7644 | 10,799 |
def gather_inputs(headers, test_suites, inputs_class=Inputs):
"""Read the list of inputs to test psa_constant_names with."""
inputs = inputs_class()
for header in headers:
inputs.parse_header(header)
for test_cases in test_suites:
inputs.parse_test_cases(test_cases)
inputs.gather_arg... | 18300cab225f817a7a09f73e4b957713ee45d0c8 | 10,800 |
def key_create(adapter_id):
"""Creates a key using a certain adapter."""
adapter = get_adapter(adapter_id)
if not adapter:
return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)
if not adapter.do_verify(request.headers):
return outp... | ec07091f3bb96f469338643f36b63ade50de3205 | 10,801 |
def is_right(side1, side2, side3):
"""
Takes three side lengths and returns true if triangle is right
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: bool
"""
return False | 2d22bbc7d0d363b360f578002a6380a4ae5f5b63 | 10,802 |
def parser_electron_number(electron_line):
"""
function of parser for electron information
Args:
electron_line (str): line
Returns:
list: electron information
"""
electron_list = parser_split_line_by_length(electron_line.rstrip(), CPF_FORMAT["ELECTRON"]["length"], "int")
return electron_list | 3a444aa0cb062ea5cfaac3e7686ff762e42ebf4c | 10,803 |
def summary(t, rtol=1e-5, atol=1e-8):
"""
Parameters
----------
t
rtol
atol
Returns
-------
"""
deltas = np.diff(t)
if np.allclose(deltas, deltas[0], rtol, atol):
# constant time steps
return deltas[0], deltas, ''
# non-constant time steps!
unq... | 0f1a5a65d832be8db35b8bdf145e6240d6072f71 | 10,804 |
def masked_huber(input, target, lengths):
"""
Always mask the first (non-batch dimension) -> usually time
:param input:
:param target:
:param lengths:
:return:
"""
m = mask(input.shape, lengths, dim=1).float().to(input.device)
return F.smooth_l1_loss(input * m, target * m, reduction... | c4eab136b73ffc92034a217252ac290848f77982 | 10,805 |
def calcProbabilisticResiduals(
coords_actual,
coords_desired,
covariances_actual
):
"""
Calculate the probabilistic residual.
Parameters
----------
coords_actual : `~numpy.ndarray` (N, M)
Actual N coordinates in M dimensions.
coords_desired : `~numpy... | c5bdc4048d9fef2e6b40e3bc48c80e6f6e2fcca7 | 10,806 |
import re
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 elements only"'
the resulting list would be:
['Should', 'give', '3 el... | befb31949d4c52fac96765fd78bc1b9d644282ba | 10,807 |
def scheduler(epoch):
"""Generating learning rate value for a given epoch.
inputs:
epoch = number of current epoch
outputs:
learning_rate = float learning rate value
"""
if epoch < 100:
return 1e-3
elif epoch < 125:
return 1e-4
else:
return 1e-5 | 916cbc12ff76b8d022a96c89083b8bd2a3078c69 | 10,808 |
def external_search(query, feature_type, url):
""" Makes an external search request to a specified URL. The url will have the search
text appended to it. Returns geojson matches with extra data for the geocoder.
"""
logger.info("using external API for feature lookup: %s", url + query)
req = E... | f90ea54dd8036b4237a74dd398cf3f2698ab4d0f | 10,809 |
def joinpath(base, end):
"""Like Path.joinpath(), but ensures the result is inside `base`.
Should be used for user-supplied `end`.
"""
result = (base / end).resolve()
if base not in result.parents:
print(base, end, result)
raise ValueError(end)
return result | 1b4f5afcdca21ceb6e676385602dd07b252db3ad | 10,812 |
def multicolored_line_collection(x, y, z, colors):
""" Color a 2D line based on which state it is in
:param x: data x-axis values
:param y: data y-axis values
:param z: values that determine the color of each (x, y) pair
"""
nstates = colors.shape[0]
# come up with color map and normalizat... | 6d9438a58547d4be253ca2a505e05da259c73118 | 10,813 |
def featurise_distances(diagram):
"""Create feature vector by distance-to-diagonal calculation.
Creates a feature vector by calculating distances to the diagonal
for every point in the diagram and returning a sorted vector. The
representation is *stable* but might not be discriminative.
Parameters... | 9c4f20be1deb2ed5073015939d48615f3b04c21b | 10,815 |
def resize(source, width=None, height=None, filter=None, radius=1,
wrapx=False, wrapy=False):
"""Create a new numpy image with the desired size.
Either width or height can be null, in which case its value
is inferred from the aspect ratio of the source image.
Filter can be HERMITE, TRIANGLE... | 08fdc077dcea013fd8b0be4a195a860e6d5291ec | 10,816 |
def load_and_classify_payload(config, service, entity, raw_record):
"""Return a loaded and classified payload."""
# prepare the payloads
payload = load_stream_payload(service, entity, raw_record)
payload = list(payload.pre_parse())[0]
classifier = StreamClassifier(config=config)
classifier.load... | 1931804b1535ba00b495879061492e25a43f91e8 | 10,817 |
def render_text(self, block: str, block_type: str, y: int) -> int:
"""
:param self: MarkdownRenderer
:param block: string of text
:param block_type: type of the text (e.g. headers, ordered/unordered lists, blockquotes, code etc)
:param y: y-coordinate to start rendering on
:return: y-coordina... | ed3e18d9988d612f911d9f6c647cbdf7dfbf7b07 | 10,818 |
def tvadam_reconstructor(dataset='ellipses', name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:return: TV reconstructor for the specified dataset
"""
try:
params = Params.load('{}_tvadam'.format(dataset))
standard_dataset = load_standard_dataset(dataset)
if name... | 0b69d0ce60f05dc522449af66f70ee655389e13c | 10,819 |
import re
def process_spf_data(res, data):
"""
This function will take the text info of a TXT or SPF record, extract the
IPv4, IPv6 addresses and ranges, request process include records and return
a list of IP Addresses for the records specified in the SPF Record.
"""
# Declare lists that will... | 537a59dd9091df35ac2502e8b03f87e625b74b76 | 10,820 |
def create_knight():
"""
Creates a new knight according to player input.
Checks the knights module for how many points are to spend,
and which attributes are available. It then asks the player
for a name for the knight and to spend their points on the
available attributes.
Returns:
... | 8feed9cd71b68868d14cd1bcfe14ff9291cf2abd | 10,821 |
async def get_bank_name(guild: discord.Guild = None) -> str:
"""Get the current bank name.
Parameters
----------
guild : `discord.Guild`, optional
The guild to get the bank name for (required if bank is
guild-specific).
Returns
-------
str
The bank's name.
Raises
... | 1e0e3f1a1de7925daf5810ac3bcc75508993a642 | 10,822 |
from typing import Optional
from typing import Dict
from typing import Any
import tempfile
def build_cli_lib(to_save_location: Optional[str] = None, render_kwargs: Optional[Dict[str, Any]] = None) -> str:
"""Create project-specific cli.fif lib"""
if not to_save_location:
to_save_location: str = tempf... | 0231433f94b129213de95ac50b406ede88860f23 | 10,823 |
def match(A, S, trueS):
"""Rearranges columns of S to best fit the components they likely represent (maximizes sum of correlations)"""
cov = np.cov(trueS, S)
k = S.shape[0]
corr = np.zeros([k, k])
for i in range(k):
for j in range(k):
corr[i][j] = cov[i + k][j] / np.sqrt(cov[i + ... | a0ec70ec768a1dfc610e8a5050d190a94266b307 | 10,824 |
def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the f... | f209cbc9ae9aa18fd22e320fdc96ba97690f8a7d | 10,825 |
def posts_completed(scraped_posts, limit):
"""Returns true if the amount of posts scraped from
profile has reached its limit.
"""
if len(scraped_posts) == limit:
return True
else:
return False | ff72474349a32f326b63b95070927c4b379be800 | 10,826 |
def mag(x):
"""Returns the absolute value squared of the input"""
return np.abs(x)**2 | bd081775a0b99e050287160cf3369faa819e20cf | 10,827 |
def get_zero_columns(matrix):
""" Returns a list of the columns which are all 0 """
rows = matrix.shape[0]
columns = matrix.shape[1]
result = []
for j in range(columns):
is_zero_column = True
for i in range(rows):
is_zero_column = is_zero_column and matrix[i, j] == 0.0
... | 35694592f4155f710e5ed3c2148a138591cd683f | 10,828 |
def traditional_constants_icr_equation_empty_fixed(fixed_params, X_col):
""" Traditional ICR equation with constants from ACE consensus """
a = 450
tdd = X_col[0]
return a / tdd | 2931e4b3592a94690d98b0cb4cb90f712ff4a449 | 10,829 |
def sort_completions_key(completion):
"""
sort completions according to their type
Args:
completion (jedi.api.classes.Completion): completion
Returns:
int: sorting order
"""
if completion.type == "function":
return 2
elif completion.type == "instance":
retur... | 7bf767d908c83c11dafa5e0fd694bbb31a98c404 | 10,830 |
def _is_git_url_mismatch(mismatch_item):
"""Returns whether the given mismatch item is for a GitHub URL."""
_, (required, _) = mismatch_item
return required.startswith('git') | b1c3cec3d8cf3c7d3ffa5c405522b1a08754223b | 10,831 |
def from_url(url, output_path=None, options=None):
"""
Convert file of files from URLs to PDF document
:param url: URL or list of URLs to be saved
:param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string
:param options: (optional) dict to configure pyp... | 8543410dcfba9d44adc8939f3dc8be702f5e922b | 10,832 |
def parse_identifier(stream: TokenStream) -> expression.Identifier:
"""Read an identifier from the token stream.
<ident>.<ident>
<ident>["<ident>"]
<ident>["<ident>"].<ident>
<ident>[<ident --> int/str>]
<ident>[<ident>.<ident --> int/str>]
<ident>[<int>]
<ident>[<int>].<ident>
"""
... | 0679a112a841d90d51806d83cd381aad7632c77b | 10,834 |
from typing import List
def cubemap_projection_matrices(from_point: Vector3D, far_plane: float) -> List[np.ndarray]:
"""
Create the required Cubemap projection matrices.
This method is suitable for generating a Shadow Map.
Simply speaking, this method generates 6 different camera matrices from the c... | e576aceec831df8267bff1c4de3cb7f0a58c3be7 | 10,835 |
from win32com.shell import shellcon, shell
def loadOptionsFile():
"""Find the .buildbot/FILENAME file. Crawl from the current directory up
towards the root, and also look in ~/.buildbot . The first directory
that's owned by the user and has the file we're looking for wins. Windows
skips the owned-by-u... | 2674c6e37de32f673e4fb9aeb6bb11981bee23d0 | 10,836 |
def get_high_accuracy_voronoi_nodes(structure, rad_dict, probe_rad=0.1):
"""
Analyze the void space in the input structure using high accuracy
voronoi decomposition.
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictio... | 2f671f9c8a357bd82f364f767cd387fae2661979 | 10,837 |
def setUpBlobDetector():
"""
Configure parameters for a cv2 blob detector, and returns the detector.
"""
params = cv2.SimpleBlobDetector_Params()
params.minThreshold = 0
params.maxThreshold = 255
params.filterByArea = True
params.minArea = 1500
params.maxArea = 25000
params.f... | d311f46d9b87d759edae0f15583c66dc31f80602 | 10,838 |
def raise_keymap():
"""
! @ # $ % || ^ & * ( )
DEL ESC || PGDN PGUP PSCR
CAPS volup ENT reset || UP
voldn super shift space bspc|| alt ent LEFT DOWN RGHT
"""
lef... | 94beda8275f65f16353b12b22809138d0342f512 | 10,839 |
import click
from typing import cast
def sample_cmd() -> Command:
"""Useful for testing constraints against a variety of parameter kinds.
Parameters have names that should make easy to remember their "kind"
without the need for looking up this code."""
@cloup.command()
# Optional arguments
@cl... | c5a8ed369d910872e52ef080707c8f0ae7436487 | 10,840 |
import inspect
def get_linenos(obj):
"""Get an object’s line numbers in its source code file"""
try:
lines, start = inspect.getsourcelines(obj)
except TypeError: # obj is an attribute or None
return None, None
except OSError: # obj listing cannot be found
# This happens for m... | 248ad7e377995e03969d3f7e1ded88670d8b08ea | 10,841 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.