content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_completed_exploration_ids(user_id, collection_id):
"""Returns a list of explorations the user has completed within the context
of the provided collection.
Args:
user_id: str. ID of the given user.
collection_id: str. ID of the collection.
Returns:
list(str). A list of e... | 7d3456f8fa0af83d776d7f2daf0edde33c83adb6 | 22,000 |
import re
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\?", " ? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower() | dec81e721fb3a83c8ea372d21dfa805394edc0e3 | 22,001 |
def transitive_closure(graph):
"""
Compute the transitive closure of the graph
:param graph: a graph (list of directed pairs)
:return: the transitive closure of the graph
"""
closure = set(graph)
while True:
new_relations = set((x, w) for x, y in closure for q, w in closure if q == y... | 3bb6567033cf920ccced7565e75f8f789c55c37d | 22,002 |
def call_function(func_name, func_args, params, system):
"""
func_args : list of values (int or string)
return str or None if fail
return ROPChain if success
"""
if( system == Systems.TargetSystem.Linux and curr_arch_type() == ArchType.ARCH_X86 ):
return call_function_linux_x86(func... | ede0b62dfa6d47c2c79ff405b056c26198e5afb5 | 22,003 |
import traceback
def error_handler(update, context):
"""Log Errors caused by Updates."""
log.error(
'with user: "%s (%s)"\nmessage: "%s"\ntraceback: %s',
update.effective_user,
update.effective_user.id,
context.error,
traceback.format_exc()
)
return Conversation... | 45ea22efe64c600ede6de81ee278493ff14dc772 | 22,004 |
def jac(w, centred_img_patches, F, NUM_MODES):
"""
The Jacobian of the numerical search procedure.
Parameters
----------
w : numpy array (floats)
Column vector of model weights, used to construct mapping.
centred_img_patches : numpy array (floats)
The mean-centred {p x NUM_PATCH... | ee780ac6e366f14c1ab7c661db99bcdbdd3cc033 | 22,005 |
def get_session():
"""Entrega uma instancia da session, para manipular o db."""
return Session(engine) | eb528d0de57e704e96ffa502e7504746efac6cbb | 22,006 |
def sdm_ecart(f):
"""
Compute the ecart of ``f``.
This is defined to be the difference of the total degree of `f` and the
total degree of the leading monomial of `f` [SCA, defn 2.3.7].
Invalid if f is zero.
Examples
========
>>> from sympy.polys.distributedmodules import sdm_ecart
... | 00d4e8807eef38326ee8a588a81287a1c9d62d0d | 22,007 |
def draw_gif_frame(image, bbox, frame_no):
"""Draw a rectangle with given bbox info.
Input:
- image: Frame to draw on
- length: Number of info (4 info/box)
- bbox: A list containing rectangles' info to draw -> frame id x y w h
Output: Frame that has been drawn on"""
obj_id = b... | 462773a88179361bc013777405b04f99ac73bd3b | 22,008 |
def build_response(session_attributes, speechlet_response):
""" Build the Alexa response """
# Log
debug_print("build_response")
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} | 87713223e25a39ed29452157dc188e59521e8553 | 22,009 |
def create_host(api_client, orig_host_name, orig_host_uid, cloned_host_name, cloned_host_ip):
"""
Create a new host object with 'new_host_name' as its name and 'new_host_ip_address' as its IP-address.
The new host's color and comments will be copied from the the "orig_host" object.
:param api_client: Ap... | 18fb2f727bae8150c98510a45e69409ff8aa4fe9 | 22,010 |
def parenthesize(x):
"""Return a copy of x surrounded by open and close parentheses"""
cast = type(x)
if cast is deque:
return deque(['('] + list(x) + [')'])
return cast('(') + x + cast(')') | ae76b220fd3bc00d3df99ec97982b44010f36e64 | 22,011 |
def get_logo_color():
"""Return color of logo used in application main menu.
RGB format (0-255, 0-255, 0-255). Orange applied.
"""
return (255, 128, 0) | a6eee63d816a44af31893830ac641d6c0b1b9ba1 | 22,012 |
def DG(p,t,Ep=10):
"""
Entrenamiento por Descenso de Gradiente
"""
# m será igual al número patrones de
# entrenamiento (ejemplos) y n al número
# de elementos del vector de caracteristicas.
m,n = p.shape
a = 0.5
#--- Pesos iniciales ---
w = np.random.uniform(-0.25,0.25,2)
... | d23c5b11432cfb6d7d4e3beb56b917f82809442e | 22,013 |
import matplotlib.patheffects as pe
def plot_tc_errors(rec, legend=True, ax=None, per_stim=False,
ylim=(0, 200)):
"""
Plot tuning curve (TC) sMAPE.
.. WARNING:: Untested!
.. TODO:: Test or remove `plot_tc_errors`.
Parameters
----------
rec : `.GANRecords`
"""
... | 67d2f8ecc1f41ed71c3734acb28ae9d9016e8cde | 22,014 |
def delete_video_db(video_id):
"""Delete a video reference from the database."""
connection = connect_db()
connection.cursor().execute('DELETE FROM Content WHERE contentID=%s',
(video_id,))
connection.commit()
close_db(connection)
return True | c91428f5f60590d7f0219d732900ae24fcc39749 | 22,015 |
import numba
def int_to_float_fn(inputs, out_dtype):
"""Create a Numba function that converts integer and boolean ``ndarray``s to floats."""
if any(i.type.numpy_dtype.kind in "ib" for i in inputs):
args_dtype = np.dtype(f"f{out_dtype.itemsize}")
@numba.njit(inline="always")
def inpu... | f47f9485fa83acb2e7a0237c7ef851d3c23f8fe6 | 22,016 |
from numpy import sqrt
def vel_gradient(**kwargs):
"""
Calculates velocity gradient across surface object in supersonic
flow (from stagnation point) based upon either of two input variable
sets.
First method:
vel_gradient(R_n = Object radius (or equivalent radius, for
shapes that a... | 8ee3ef490c113551e9200743e52378a8206a3666 | 22,017 |
from functools import reduce
def lcm(numbers):
""" Get the least common multiple of a list of numbers
------------------------------------------------------------------------------------
input: numbers [1,2,6] list of integers
output: 6 integer """
return reduce(lambda x, y: int((x * y) / gcd(x, ... | a1c3ce93b0ea4f06c8fb54765110fa85f7517fe5 | 22,018 |
def parseBracketed(idxst,pos):
"""parse an identifier in curly brackets.
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (a,b)= parseBracketed(idxst,pos)
... print(st[a:b])
...
>>> test(r'{abc}',0)
{abc}
>>> test(r'{ab8c}',0)
{ab8c... | d78617fa8a85c234920d0f985566d7a00ebe6b1a | 22,019 |
def compute_agg_tiv(tiv_df, agg_key, bi_tiv_col, loc_num):
""" compute the agg tiv depending on the agg_key"""
agg_tiv_df = (tiv_df.drop_duplicates(agg_key + [loc_num], keep='first')[list(set(agg_key + ['tiv', 'tiv_sum', bi_tiv_col]))]
.groupby(agg_key, observed=True).sum().reset_index())
if 'is_... | 246ea2d61230f3e3bfe365fdf8fdbedbda98f25b | 22,020 |
from typing import List
def convert_configurations_to_array(configs: List[Configuration]) -> np.ndarray:
"""Impute inactive hyperparameters in configurations with their default.
Necessary to apply an EPM to the data.
Parameters
----------
configs : List[Configuration]
List of configurati... | 09b14dc5d5bb5707b059b7a469d93c7288da84cf | 22,021 |
from typing import Optional
from datetime import datetime
import requests
def annual_mean(
start: Optional[datetime] = None,
end: Optional[datetime] = None
) -> dict:
"""Get the annual mean data
----------------------------
Data from March 1958 through April 1974 have been obtained by C. David Ke... | 4fd06301f9f414e08629cdbfeae75adcc6febdcf | 22,022 |
def exception(logger,extraLog=None):
"""
A decorator that wraps the passed in function and logs
exceptions should one occur
@param logger: The logging object
"""
print logger
def decorator(func):
print "call decorator"
def wrapper(*args, **kwargs):
print "call e... | 52a0ca19b738576a5e42da9d720ec5a5118466fe | 22,023 |
def read_external_sources(service_name):
"""
Try to get config from external sources, with the following priority:
1. Credentials file(ibm-credentials.env)
2. Environment variables
3. VCAP Services(Cloud Foundry)
:param service_name: The service name
:return: dict
"""
config = {}
... | a8008efecf6cbc8801022c9a99617480d50ad525 | 22,024 |
import torch
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor)... | 96f67dd8ee1b40af469b5e40dc1f3456250451b3 | 22,025 |
import re
def tokenize(text):
""" tokenize text messages
Input: text messages
Output: list of tokens
"""
# find urls and replace them with 'urlplaceholder'
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
text = re.sub(url_regex, 'urlplaceholder'... | 02c322b01b0af995030c007be634b7d3d1603518 | 22,026 |
import scipy
import copy
def peakFindBottom(x, y, peaks, fig=None, verbose=1):
""" Find the left bottom of a detected peak
Args:
x (array): independent variable data
y (array): signal data
peaks (list): list of detected peaks
fig (None or int): if integer, then plot results
... | dd79a4fd572f69f5db9adeaaf56ab4c8661c0ca1 | 22,027 |
def replacelast(string, old, new, count = 1):
"""Replace the last occurances of a string"""
return new.join(string.rsplit(old,count)) | 6af2cd56cc43e92b0d398e8aad4e25f0c6c34ddd | 22,028 |
import os
def parse_config(config):
"""Parse the config dictionary for common objects.
Currently only parses the following:
* `directories` for relative path names.
Args:
config (dict): Config items.
Returns:
dict: Config items but with objects.
"""
# Prepend the bas... | 696cfb8b2e6ba308310445e451787c8b115d07e0 | 22,029 |
def _safe_read_img(img):
"""
Read in tiff image if a path is given instead of np object.
"""
img = imread(img) if isinstance(img, str) else np.array(img)
return np.nan_to_num(img) | a9a50b5ad76a6ed5833c2c149b1366b318814d6a | 22,030 |
def max_version(*modules: Module) -> str:
"""Maximum version number of a sequence of modules/version strings
See `get_version` for how version numbers are extracted. They are compared
as `packaging.version.Version` objects.
"""
return str(max(get_version(x) for x in modules)) | 34ad9bd27591e3496e6a5a7e75dbf0191a8c077e | 22,031 |
def load_secret(name, default=None):
"""Check for and load a secret value mounted by Docker in /run/secrets."""
try:
with open(f"/run/secrets/{name}") as f:
return f.read().strip()
except Exception:
return default | 1aac980ad6bc039964ef9290827eb5c6d1b1455f | 22,032 |
from operator import sub
def snake_case(x):
"""
Converts a string to snake case
"""
# Disclaimer: This method is annoyingly complex, and i'm sure there is a much better way to do this.
# The idea is to iterate through the characters
# in the string, checking for specific cases and handling... | 133ff68eb42e5e009fe2eee03d1e52f7d015732c | 22,033 |
async def process_manga(data_list: list[dict], image_path: str) -> str:
"""对单张图片进行涂白和嵌字的工序
Args:
data_list (list[dict]): ocr识别的文字再次封装
image_path (str): 图片下载的路径(同时也作为最后保存覆盖的路径)
Returns:
str: 保存的路径
"""
image = Image.open(image_path).convert("RGB")
for i in data_list:
... | 47574e11067c00d3c5ab4110a7dae8100d450a1f | 22,034 |
def padded_nd_indices(is_valid, shuffle=False, seed=None):
"""Pads the invalid entries by valid ones and returns the nd_indices.
For example, when we have a batch_size = 1 and list_size = 3. Only the first 2
entries are valid. We have:
```
is_valid = [[True, True, False]]
nd_indices, mask = padded_nd_indic... | 61a57aa95c1d3151900aba3db07bba0eae542dfd | 22,035 |
def part_two(data: str) -> int:
"""The smallest number leading to an md5 hash with six leading zeros for data."""
return smallest_number_satisfying(data, starts_with_six_zeros) | 57195761f388654f9aa099162f337e8177e56111 | 22,036 |
def showlatesttag(context, mapping):
"""List of strings. The global tags on the most recent globally
tagged ancestor of this changeset. If no such tags exist, the list
consists of the single string "null".
"""
return showlatesttags(context, mapping, None) | e04b03a9dca54a93f450de676ea05c307f157dab | 22,037 |
def list_filters():
"""
List all filters
"""
filters = [_serialize_filter(imgfilter) for imgfilter in FILTERS.values()]
return response_list(filters) | e43da929925872f5eefca5da2659052a1a48d442 | 22,038 |
def len_adecuada(palabra, desde, hasta):
"""
(str, int, int) -> str
Valida si la longitud de la palabra está en el rango deseado
>>> len_adecuada('hola', 0, 100)
'La longitud de hola, está entre 0 y 100'
>>> len_adecuada('hola', 1, 2)
'La longitud de hola, no está entre 1 y 2'
:para... | df217a0159cd04c76f5eb12ca42e651ee62fcd99 | 22,039 |
import warnings
def ECEF_from_ENU(enu, latitude, longitude, altitude):
"""
Calculate ECEF coordinates from local ENU (east, north, up) coordinates.
Args:
enu: numpy array, shape (Npts, 3), with local ENU coordinates
latitude: latitude of center of ENU coordinates in radians
longit... | 13561632731d59e40e4232f8dc2798e8dcd8067f | 22,040 |
def showresults(options=''):
"""
Generate and plot results from a kima run.
The argument `options` should be a string with the same options as for
the kima-showresults script.
"""
# force correct CLI arguments
args = _parse_args(options)
plots = []
if args.rv:
plots.appe... | 0c5c944dc21e0abf808c258d8993f6133a254701 | 22,041 |
import re
def convert_as_number(symbol: str) -> float:
"""
handle cases:
' ' or '' -> 0
'10.95%' -> 10.95
'$404,691,250' -> 404691250
'$8105.52' -> 8105.52
:param symbol: string
:return: float
"""
result = symbol.strip()
if... | cea1d6e894fa380ecf6968d5cb0ef1ce21b73fac | 22,042 |
import pandas as pd
import os
def mgus(path):
"""Monoclonal gammapothy data
Natural history of 241 subjects with monoclonal gammapothy of
undetermined significance (MGUS).
mgus: A data frame with 241 observations on the following 12 variables.
id:
subject id
age:
age in years at the detection of... | 98a6b9ae47657aa8557b5920490d15e8f7005fec | 22,043 |
def smiles_dict():
"""Store SMILES for compounds used in test cases here."""
smiles = {
"ATP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C"
+ "@@H](O)[C@H]1O",
"ADP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)O)[C@@H](O)[C" + "@H]1O",
"meh": "CCC(=O)C(=O)O... | 080373bdfb250f57e20e0e2b89702ac07c430f69 | 22,044 |
def prepare_parser() -> ArgumentParser:
"""Create all CLI parsers/subparsers."""
# Handle core parser args
parser = ArgumentParser(
description="Learning (Hopefully) Safe Agents in Gridworlds"
)
handle_parser_args({"core": parser}, "core", core_parser_configs)
# Handle environment subpa... | c0a42abf56f3c82ae09ef2459aae49fded71e9f0 | 22,045 |
def import_google(authsub_token, user):
"""
Uses the given AuthSub token to retrieve Google Contacts and
import the entries with an email address into the contacts of the
given user.
Returns a tuple of (number imported, total number of entries).
"""
contacts_service = gdata.contact... | 768b900ceac60cc69d1906ef915fdace8b6d0982 | 22,046 |
def getGpsTime(dt):
"""_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime
"""
total = 0
days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc.
total += days*3600*24
total += dt.hour * 3600
total += dt.minute * 60
total += dt.second
return(total) | 30f0fa562cf88ca2986c3346b4111dcb18b1cb34 | 22,047 |
def class_logger(module_logger, attribute = "logger"):
"""
Class decorator to add a class-level Logger object as a class
attribute. This allows control of debugging messages at the class
level rather than just the module level.
This decorator takes the module logger as an argument.
"""
def decorator(cl... | 8eddbca3d112156eca162e0d709dde1ec03d9339 | 22,048 |
from datetime import datetime
def validate_date(date, flash_errors=True):
"""
Validates date string. Format should be YYYY-MM-DD. Flashes errors if
flash_errors is True.
"""
try:
datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
if flash_errors:
flask.flash('Invalid date provid... | ed3e45c3232da8d994f854001a3be852180681e0 | 22,049 |
def generate_error_map(image, losses, box_lenght):
"""
Function to overlap an error map to an image
Args:
image: input image
losses: list of losses, one for each masked part of the flow.
Returs:
error_map: overlapped error_heatmap and image.
"""
box_lenght = int(box_lengh... | b4b8a8207a90226caba0c5f5be4c322dc6181a42 | 22,050 |
def get_order(oid): # noqa: E501
"""Gets an existing order by order id
# noqa: E501
:param oid:
:type oid: str
:rtype: Order
"""
oid = int(oid)
msg = "error retrieving order"
ret_code = 400
if oid in orders:
msg = {"status": f"order retrieved", "order": orders[oid],... | d95051e027994b0bd7837859a3e7fd8106f4a07e | 22,051 |
import operator
def most_recent_assembly(assembly_list):
"""Based on assembly summaries find the one submitted the most recently"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1] | 1d7ecf3a1fa862e421295dda0ba3d89863f33b0f | 22,052 |
import re
def dict_from_xml_text(xml_text, fix_ampersands=False):
"""
Convert an xml string to a dictionary of values
:param xml_text: valid xml string
:param fix_ampersands: additionally replace & to & encoded value before parsing to etree
:return: dictionary of data
"""
if fix_ampers... | fc008f9c9ef23640ed09adef3320eb549506988d | 22,053 |
def find_encryption_key(loop_size, subject_number):
"""Find encryption key from the subject_number and loop_size."""
value = 1
for _ in range(loop_size):
value = transform_value(value, subject_number)
return value | cb9f58d065e4bc227ac034357981eac070834f73 | 22,054 |
import math
def carla_rotation_to_RPY(carla_rotation):
"""
Convert a carla rotation to a roll, pitch, yaw tuple
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the c... | 30f4cd3facd3696d3f0daf25f2723d82541c89f2 | 22,055 |
from bempp.api.integration.triangle_gauss import rule
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import aslinearoperator
def compute_p1_curl_transformation(space, quadrature_order):
"""
Compute the transformation of P1 space coefficients to surface curl values.
Returns two lists, curl_t... | 6ad147c23fb9c153d534b742443c6238c1dc6f33 | 22,056 |
def _get_individual_id(individual) -> str:
"""
Returns a unique identifier as string for the given individual.
:param individual: The individual to get the ID for.
:return: A string representing the ID.
"""
if hasattr(individual, "identifier") and (isinstance(individual.identifier, list) and
... | e606d5eef7bfbcd0d76113c20f450be3c1e6b2ab | 22,057 |
def get_self_url(d):
"""Returns the URL of a Stash resource"""
return d.html_url if isinstance(d, PullRequest) else d["links"]["self"][0]["href"] | b7b88b49a1035ec7d15e4d0f7c864e489dccbf70 | 22,058 |
def shift(arr, *args):
"""
**WARNING**
The ``Si`` arguments can be either a single array containing the shift
parameters for each dimension, or a sequence of up to eight scalar shift
values. For arrays of more than one dimension, the parameter ``Sn`` specifies
the shift applied to the n-th dime... | b70a430039ba369d99a3c2edea920430eb27dfa1 | 22,059 |
def ConvertToMeaningfulConstant(pset):
""" Gets the flux constant, and quotes it above some energy minimum Emin """
# Units: IF TOBS were in yr, it would be smaller, and raw const greater.
# also converts per Mpcs into per Gpc3
units=1e9*365.25
const = (10**pset[7])*units # to cubic Gpc an... | e393f66e72c3a43e91e9975f270ac7dcf577ad3e | 22,060 |
def hw_uint(value):
"""return HW of 16-bit unsigned integer in two's complement"""
bitcount = bin(value).count("1")
return bitcount | 9a9c6017d3d6da34c4e9132a0c89b267aa263ace | 22,061 |
import copy
def clip(x,xmin,xmax) :
""" clip input array so that x<xmin becomes xmin, x>xmax becomes xmax, return clipped array
"""
new=copy.copy(x)
bd=np.where(x<xmin)[0]
new[bd]=xmin
bd=np.where(x>xmax)[0]
new[bd]=xmax
return new | 502d8c5ce0427283bf02ead2d5f5c90c69e14638 | 22,062 |
def profile_from_creds(creds, keychain, cache):
"""Create a profile from an AWS credentials file."""
access_key, secret_key = get_keys_from_file(creds)
arn = security_store(access_key, secret_key, keychain, cache)
return profile_from_arn(arn) | 62923959ce115bef776b32c3ed93a19aef93f9c3 | 22,063 |
import traceback
import traceback
from typing import Tuple
from pathlib import Path
from typing import List
from typing import Iterable
import warnings
def get_files(pp: Paths, glob: str=DEFAULT_GLOB, sort: bool=True) -> Tuple[Path, ...]:
"""
Helper function to avoid boilerplate.
Tuple as return type is ... | b22c36dc1fe4af1f05e5f7fb8f9f226226bbb0f1 | 22,064 |
import torch
def test(model, test_loader, dynamics, fast_init):
"""
Evaluate prediction accuracy of an energy-based model on a given test set.
Args:
model: EnergyBasedModel
test_loader: Dataloader containing the test dataset
dynamics: Dictionary containing the keyword arguments
... | 41c6e20fbcf11e76437a175f7b4662ec24b85773 | 22,065 |
def get_cluster_activite(cluster_path_csv, test, train=None):
"""Get cluster activite csv from patch cluster_path_csv.
Merge cluster with station_id
Parameters
----------
cluster_path_csv : String :
Path to export df_labels DataFrame
test : pandas.DataFrame
train : pandas.DataFrame... | f8dbb1bb2149a58f8617f76cfdf1a4943f500314 | 22,066 |
from typing import Optional
def get_ssl_policy(name: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSSLPolicyResult:
"""
Gets an SSL Policy within GCE from its name, for use with Target HTTPS and Target SSL... | 1b4248a6a8dbbd735a006cc99de5d5e855c195ca | 22,067 |
def getitem(self, item):
"""Select elements at the specific index.
Parameters
----------
item : Union[slice, int, dragon.Tensor]
The index.
Returns
-------
dragon.Tensor
The output tensor.
"""
gather_args = []
if isinstance(item, Tensor):
if item.dtype ... | 0f7a4659a9fc3ac34fcee8f402fada7f622e11f0 | 22,068 |
import torch
def zdot_batch(x1, x2):
"""Finds the complex-valued dot product of two complex-valued multidimensional Tensors, preserving the batch dimension.
Args:
x1 (Tensor): The first multidimensional Tensor.
x2 (Tensor): The second multidimensional Tensor.
Returns:
The dot pro... | 5e57dd7a693c420dd1b0c5c01523eb2f0fb85253 | 22,069 |
from datetime import datetime
def add(request):
"""
Case of UPDATE REQUEST '/server/add/'
対象の更新
POST リクエストにのみレスポンス
"""
request_type = request.method
logger.debug(request_type)
if request_type == 'GET':
raise Http404
elif request_type == 'OPTION' or request_type == 'HEAD':
... | efc4a4dc74356cb68e1c14e24e55cf6d9961b749 | 22,070 |
def gradient_check_numpy_expr(func, x, output_gradient, h=1e-5):
"""
This utility function calculates gradient of the function `func`
at `x`.
:param func:
:param x:
:param output_gradient:
:param h:
:return:
"""
grad = np.zeros_like(x).astype(np.float32)
iter = np.nditer(x, f... | 221c3c75be8dd59f9b004c7ac49c973111ac6fe6 | 22,071 |
def serve_values(name, func, args, kwargs, serving_values, fallback_func, backend_name=None, implemented_funcs=None, supported_kwargs=None,): #249 (line num in coconut source)
"""Determines the parameter value to serve for the given parameter
name and kwargs. First checks for unsupported funcs or kwargs, then
... | 7ad5847df2d3904da7786ab0c77e5a0d9e6380cd | 22,072 |
def find_peaks(sig):
"""
Find hard peaks and soft peaks in a signal, defined as follows:
- Hard peak: a peak that is either /\ or \/.
- Soft peak: a peak that is either /-*\ or \-*/.
In this case we define the middle as the peak.
Parameters
----------
sig : np array
The 1d si... | 486b30d506e3d79dc7df8d2503d3bc626b6791f5 | 22,073 |
def evenly_divides(x, y):
"""Returns if [x] evenly divides [y]."""
return int(y / x) == y / x | dbf8236454e88805e71aabf58d9b7ebd2b2a6393 | 22,074 |
def proxmap_sort(arr: list, key: Function = lambda x: x, reverse: bool = False) -> list:
"""Proxmap sort is a sorting algorithm that works by partitioning an array of data items, or keys, into a number of
"subarrays" (termed buckets, in similar sorts). The name is short for computing a "proximity map," which in... | 9673abbad9320df5d83ebef9658c84ab21b5f021 | 22,075 |
import pathlib
def load_footings_file(file: str):
"""Load footings generated file.
:param str file: The path to the file.
:return: A dict representing the respective file type.
:rtype: dict
.. seealso::
:obj:`footings.testing.load_footings_json_file`
:obj:`footings.testing.load... | 929cf95e631e8be4dcc8f18c36a0b545593fed69 | 22,076 |
def coupler(*, coupling: float = 0.5) -> SDict:
"""a simple coupler model"""
kappa = coupling ** 0.5
tau = (1 - coupling) ** 0.5
sdict = reciprocal(
{
("in0", "out0"): tau,
("in0", "out1"): 1j * kappa,
("in1", "out0"): 1j * kappa,
("in1", "out1"): ... | dfd40ce9a8c61ffe8382b461c41d4034c7342570 | 22,077 |
def new_client(request):
"""
Function that allows a new client to register itself.
:param request: Who has made the request.
:return: Response 200 with user_type, state, message and token, if everything goes smoothly. Response 400 if there
is some kind of request error. Response 403 for forbidden. O... | d05eeb55527cfe355fb237751693749ed707a598 | 22,078 |
from datetime import datetime
def parse_time_interval_seconds(time_str):
""" Convert a given time interval (e.g. '5m') into the number of seconds in that interval
:param time_str: the string to parse
:returns: the number of seconds in the interval
:raises ValueError: if the string could not be parsed... | 6c07ee52b8dd727e96dae8a58f59c1bd043f3627 | 22,079 |
from typing import List
from typing import Dict
def _map_class_names_to_probabilities(probabilities: List[float]) -> Dict[str, float]:
"""Creates a dictionary mapping readable class names to their corresponding probabilites.
Args:
probabilities (List[float]): A List of the probabilities for the best ... | 51096015e4c291b7d3357822ea13de3354b9b12f | 22,080 |
import collections
def order_items(records):
"""Orders records by ASC SHA256"""
return collections.OrderedDict(sorted(records.items(), key=lambda t: t[0])) | a9117282974fcea8d0d99821ea6293df82889b30 | 22,081 |
def G2DListMutatorRealGaussianGradient(genome, **args):
""" A gaussian gradient mutator for G2DList of Real
Accepts the *rangemin* and *rangemax* genome parameters, both optional.
The difference is that this multiplies the gene by gauss(1.0, 0.0333), allowing
for a smooth gradient drift about the value.
... | 52e739fe4c490064dbec5fe0b6a7443570cada0e | 22,082 |
def convert_group_by(response, field):
"""
Convert to key, doc_count dictionary
"""
if not response.hits.hits:
return []
r = response.hits.hits[0]._source.to_dict()
stats = r.get(field)
result = [{"key": key, "doc_count": count} for key, count in stats.items()]
result_sorted = so... | 888321f300d88bd6f150a4bfda9420e920bab510 | 22,083 |
import sys
def get_different_columns(
meta_subset1: pd.DataFrame,
meta_subset2: pd.DataFrame,
common_cols: list) -> list:
"""Find which metadata columns have the
same name but their content differ.
Parameters
----------
meta_subset1 : pd.DataFrame
A metadata table
... | f36d89efb9027e4201dbbbbe579c45b9aec6ea30 | 22,084 |
def _parse_single(argv, args_array, opt_def_dict, opt_val):
"""Function: _parse_single
Description: Processes a single-value argument in command line
arguments. Modifys the args_array by adding a dictionary key and a
value.
NOTE: Used by the arg_parse2() to reduce the complexity ratin... | 5b44a891400b545940c9be3913af9710c37df898 | 22,085 |
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}):
"""
task 0.5.9
comprehension whose value is the intersection of setA and setB
without using the '&' operator
"""
return {x for x in (setA | setB) if x in setA and x in setB} | 2b222d6c171e0170ace64995dd64c352f03aa99b | 22,086 |
def d_beta():
"""
Real Name: b'D BETA'
Original Eqn: b'0.05'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 0.05 | 32aa0e1fbf31761a36657b314a7c4bc4bf99889e | 22,087 |
import csv
def _get_data(filename):
"""
:param filename: name of a comma-separated data file with two columns: eccentricity and some other
quantity x
:return: eccentricities, x
"""
eccentricities = []
x = []
with open(filename) as file:
r = csv.reader(file)
for row... | f8c86f0f1c9bf2ee91108382cd6da6b98445bf1f | 22,088 |
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) > 0:
common = strs[0]
for str in strs[1:]:
while not str.startswith(common):
common = common[:-1]
return common
else:
return '' | a860d46df8dbaeaab90bb3bc69abb68484216b5b | 22,089 |
def analytics_dashboard(request):
"""Main page for analytics related things"""
template = 'analytics/analyzer/dashboard.html'
return render(request, template) | 068913de2f2b1a381f73395e53e2e06db7d02e8e | 22,090 |
def insert(shape, axis=-1):
"""Shape -> shape with one axis inserted"""
return shape[:axis] + (1,) + shape[axis:] | 8c786df81b76cfa5dae78b51d16b2ee302263c53 | 22,091 |
import re
def simplify_text(text):
"""
:param text:
:return:
"""
no_html = re.sub('<[^<]+?>', '', str(text))
stripped = re.sub(r"[^a-zA-Z]+", "", str(no_html))
clean = stripped.lower()
return clean | a867bd08a642843df9d8a2a517f1b0c13ea145b1 | 22,092 |
def is_numpy_convertable(v):
"""
Return whether a value is meaningfully convertable to a numpy array
via 'numpy.array'
"""
return hasattr(v, "__array__") or hasattr(v, "__array_interface__") | 163da2cf50e2172e1fc39ae8afd7c4417b02a852 | 22,093 |
def grower(array):
"""grows masked regions by one pixel
"""
grower = np.array([[0,1,0],[1,1,1],[0,1,0]])
ag = convolve2d(array , grower , mode = "same")
ag = ag != 0
return ag | b6ae0c9eeb96ec13a5f9ef7a282ec428b5d536ad | 22,094 |
def SMAPELossFlat(*args, axis=-1, floatify=True, **kwargs):
"""Same as `smape`, but flattens input and target.
DOES not work yet
"""
return BaseLoss(smape, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | 470e8f34cfd5fd6a867f9991e8babcad25fa03ff | 22,095 |
from datetime import datetime
def get_fake_datetime(now: datetime):
"""Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value."""
class FakeDatetime:
"""Fake datetime.datetime class."""
@classmethod
def now(cls):
"""Return... | f268640c6459f4eb88fd9fbe72acf8c9d806d3bc | 22,096 |
from typing import List
def generate_order_by(fields: List[str], sort_orders: List[str], table_pre: str = '') -> str:
"""Функция генерит ORDER BY запрос для SQL
Args:
fields: список полей для сортировки
sort_orders: список (asc\desc) значений
table_pre: префикс таблицы в запросе
Re... | 863d348d2bd844718e056c6767e1f282405b3edf | 22,097 |
def toUnicode(glyph, isZapfDingbats=False):
"""Convert glyph names to Unicode, such as 'longs_t.oldstyle' --> u'ſt'
If isZapfDingbats is True, the implementation recognizes additional
glyph names (as required by the AGL specification).
"""
# https://github.com/adobe-type-tools/agl-specification#2-the-mapping
#
... | 42bfee52db47f466308dfc4782a609776f6b90b9 | 22,098 |
def list_watchlist_items_command(client, args):
"""
Get specific watchlist item or list of watchlist items.
:param client: (AzureSentinelClient) The Azure Sentinel client to work with.
:param args: (dict) arguments for this command.
"""
# prepare the request
alias = args.get('watchlist_al... | 1567bd56c90e9560fcae583d8360e4299620c266 | 22,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.