content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def value_iteration(model, maxiter=100):
"""
Solves the supplied environment with value iteration.
Parameters
----------
model : python object
Holds information about the environment to solve
such as the reward structure and the transition dynamics.
maxiter : int
The ma... | e04ffc27be47470f466832a14f9ecf9910d18f27 | 15,125 |
from typing import Callable
import inspect
import abc
def node(function: Callable):
"""A decorator that registers a function to execute when a node runs"""
sig = inspect.signature(function)
args = []
for (name, param) in sig.parameters.items():
value = param.default
if value is inspe... | 65ed2c383e1354a0663daef98b78b73382ea65ea | 15,126 |
def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index.
Args:
m: Tuple of the complex refractive indices of the media.
mix: Tuple of the volume fractions of the media, len(mix)==len(m)
(if sum(mix)!=1, these are taken relative to sum(mix))
Returns:
The ... | 57712b6abd9b6a5a642767fa91b6212729b697dc | 15,127 |
def locateObjLocation(data, questionDict, questionIdict):
"""
Locate the object of where questions.
Very naive heuristic: take the noun immediately after "where".
"""
where = questionDict['where']
for t in range(data.shape[0] - 1):
if data[t, 0] == where:
for u in range(t + 1... | 4b0b8ff892e7d6fdbd9b1cf9d7a9ce7a50ba90c2 | 15,128 |
from typing import Union
from typing import List
def mkshex(shapes: Union[CSVShape, List[CSVShape]]) -> Schema:
"""Convert list of csv2shape Shapes to ShExJSG Schema object."""
# pylint: disable=invalid-name
# One- and two-letter variable names do not conform to snake-case naming style
if isinstance... | 3cc83d3a23ca982f30c6b4b64553801e404ef1b3 | 15,130 |
def get_unsigned_js_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get unsigned remaped joystick value in reverse range
(For example if the limit is 2000, and the input valueis also 2000,
the value returned will be 1. And with the same limit, if the input value
is 1, the output value wwill ... | 6e77d76423ffeef756291924d00cbdbb2c03cc07 | 15,131 |
def to_xyz(struct, extended_xyz: bool = True, print_stds: bool = False,
print_forces: bool = False, print_max_stds: bool = False,
print_energies: bool = False, predict_energy=None,
dft_forces=None, dft_energy=None, timestep=-1,
write_file: str = '', append: bool = False, labe... | 729a5429d2c6b4cc0c63462577b91a582bf197ed | 15,132 |
def load_file(filename: str):
"""Load the .xls file and return as a dataframe object."""
df = pd.read_csv(filename, delimiter='\t')
return df | 09a7f6abc67bf80651dffe5d7698798f5dfc5be8 | 15,133 |
def loadRegexList(regexListFile):
"""Returns regexList, registries, internetSources"""
regexList = []
registries = set()
internetSourceTypes = set()
libLF.log('Loading regexes from {}'.format(regexListFile))
with open(regexListFile, 'r') as inStream:
for line in inStream:
line = line.strip()
... | 7a3fe4c269aa4c868684384417f3c1d0229fcad8 | 15,134 |
def _decode_and_center_crop(image_bytes, image_size, resize_method=None):
"""Crops to center of image with padding then scales image_size."""
shape = tf.shape(image_bytes)
image_height = shape[0]
image_width = shape[1]
padded_center_crop_size = tf.cast(
((image_size / (image_size + CROP_PADDING)) *
... | 933bfb91a84f9fe403adf9cbfc9efeb57d1e50f0 | 15,135 |
import typing
import numpy
def match_beacons_translate_only(
sensor_a_beacons: typing.Set[typing.Tuple[int, int, int]],
sensor_b_beacons: numpy.ndarray,
min_matching: int,
) -> typing.Optional[numpy.ndarray]:
"""
Search for matching beacons between `sensor_a_beacons` and `sensor_b_beac... | 0fd12c05d9ee159e301c7bad9d1ddcaa3009a960 | 15,136 |
def txm_log():
"""
Return the logger.
"""
return __log__ | 3b03daf2075549dc4d333e5a47d8e9a1cef21152 | 15,137 |
def remove_list_by_name(listslist, name):
"""
Finds a list in a lists of lists by it's name, removes and returns it.
:param listslist: A list of Twitter lists.
:param name: The name of the list to be found.
:return: The list with the name, if it was found. None otherwise.
"""
for i in range(... | 356a7d12f3b2af9951327984ac6d55ccb844bf72 | 15,138 |
import math
def song_clicks_metric(ranking):
"""
Spotify p
:param ranking:
:return:
"""
if 1 in ranking:
first_idx = ranking.index(1)
return math.floor(first_idx / 10)
return 51
@staticmethod
def print_subtest_results(sub_test_names, metric_names, results):
... | ec6400e7929a2ab0f7f691fffa0ecb3be039b012 | 15,139 |
import copy
def merge_reports(master: dict, report: dict):
"""
Merge classification reports into a master list
"""
keys = master.keys()
ret = copy.deepcopy(master)
for key in keys:
scores = report[key]
for score, value in scores.items():
ret[key][score] += [value]
... | 3ac633c38a8bb73a57841138cba8cbb80091cf04 | 15,140 |
def multi_layer_images():
"""
Returns complex images (with sizes) for push and pull testing.
"""
# Note: order is from base layer down to leaf.
layer1_bytes = layer_bytes_for_contents(
"layer 1 contents", mode="", other_files={"file1": "from-layer-1",}
)
layer2_bytes = layer_bytes_f... | 08b35fa4202a7d25ec415ed3b6d1ae6a9f37fd9c | 15,142 |
from typing import Iterable
def user_teams(config: Config, email: str) -> Iterable[Team]:
"""Return the teams a user member is expected to be a member of.
Only the teams in which the user is a direct member are return. The
ancestors of these teams are not returned.
"""
names = config.by_member.ge... | 669ec82b68e8e530dafeee4e272c85743bde7db1 | 15,143 |
import torch
def se3_transform(g, a, normals=None):
""" Applies the SE3 transform
Args:
g: SE3 transformation matrix of size ([1,] 3/4, 4) or (B, 3/4, 4)
a: Points to be transformed (N, 3) or (B, N, 3)
normals: (Optional). If provided, normals will be transformed
Returns:
... | 9d8ca31dd6df6382e6a45fb80f30b61e9902da5c | 15,144 |
def summarize_single_OLS(regression, col_dict, name, is_regularized=False):
"""Return dataframe aggregating over-all stats from a dictionary-like object containing OLS result objects."""
reg = regression
try:
col_dict['rsquared'][name] = reg.rsquared
except AttributeError:
col_dict['rsq... | b7dd8dfac6cf1b743491ae4e1abfc20fb73e8f31 | 15,145 |
def simplify(polynom):
"""Simplifies a function with binary variables
"""
polynom = Poly(polynom)
new_polynom = 0
variables = list(polynom.free_symbols)
for var_i in variables:
coefficient_i = polynom.as_expr().coeff(var_i)/2
coefficient_i += polynom.as_expr().coeff(var_i ** 2)
... | 62647c9a7530df8b73644e7af96b77b06bfb5285 | 15,146 |
def process_login():
"""Log user into site.
Find the user's login credentials located in the 'request',
look up the user, and store them in the session.
"""
user_login = request.get_json()
if crud.get_user_by_email(user_login['email']):
current_user = crud.get_user_by_email(user_l... | 39e0498370e06ca3203c1212552ce435b1d047e0 | 15,147 |
def is_int(var):
"""
is this an integer (ie, not a float)?
"""
return isinstance(var, int) | 09924c6ea036fc7ee1add6ccbefc3fb0c9696345 | 15,148 |
def returnstringpacket(pkt):
"""Returns a packet as hex string"""
myString = ""
for c in pkt:
myString += "%02x" % c
return myString | 866ef7c69f522d4a2332798bdf97a966740ea0e4 | 15,149 |
def GetIndicesMappingFromTree( tree ):
"""
GetIndicesMappingFromTree
=========================
reuse bill's idea to gives the indexes of all nodes (may they be
a sub tree or a single leaf) gives a list of indices of every sublist.
To do that, I add one thing: the last element of an index is the ... | d18e85943273a1f4a75951f3f3fda176853b06e0 | 15,150 |
import random
def generate_pairwise(params, n_comparisons=10):
"""Generate pairwise comparisons from a Bradley--Terry model.
This function samples comparisons pairs independently and uniformly at
random over the ``len(params)`` choose 2 possibilities, and samples the
corresponding comparison outcomes... | 96bea4a192d81eaf9a43f8ae493187d826dcdb21 | 15,153 |
def render_json(fun):
"""
Decorator for views which return a dictionary that encodes the dictionary
into a JSON string and sets the mimetype of the response to
application/json.
"""
@wraps(fun)
def wrapper(request, *args, **kwargs):
response = fun(request, *args, **kwargs)
tr... | 15984f0fe7a6a5fbc5a6c9b360bb2780854868b4 | 15,154 |
from typing import List
def count_smileys_concise(arr: List[str]) -> int:
"""
Another person's implementation. Turns the list into an string,
then uses findall() on that string.
Turning the result into a list makes it possible to return the length of that list.
So this version is more concise, but... | 8fbd353422cbac9840294af3d0a6022d8a45e4e1 | 15,155 |
def transform_dead_op_vars(graph, translator=None):
"""Remove dead operations and variables that are passed over a link
but not used in the target block. Input is a graph."""
return transform_dead_op_vars_in_blocks(list(graph.iterblocks()),
[graph], translator) | c10fde9cca58732bf6bd17018e963ee629a1796d | 15,156 |
import torch
def test_reconstruction_torch():
"""Test that input reconstruction via backprop has decreasing loss."""
if skip_all:
return None if run_without_pytest else pytest.skip()
if cant_import('torch'):
return None if run_without_pytest else pytest.skip()
device = 'cuda' if torch.... | 070e7e52ce44c2a875a7ad418ffb985a1827d8c6 | 15,157 |
def to_pixels(Hinv, loc):
"""
Given H^-1 and (x, y, z) in world coordinates, returns (c, r) in image
pixel indices.
"""
loc = to_image_frame(Hinv, loc).astype(int)
return (loc[1], loc[0]) | 09dff4d2045c64d753aa8229f44f049f1a6936c3 | 15,158 |
def calc_distance_between_points_two_vectors_2d(v1, v2):
"""calc_distance_between_points_two_vectors_2d [pairwise distance between vectors points]
Arguments:
v1 {[np.array]} -- [description]
v2 {[type]} -- [description]
Raises:
ValueError -- [description]
ValueError... | 75d00fae9dbe8353e1b53d12428de054e267a528 | 15,161 |
import heapq
import random
def get_nearest_list_index(node_list, guide_node):
"""
Finds nearest nodes among node_list, using the metric given by weighted_norm
and chooses one of them at random.
Parameters
----------
node_list : list
list of nodes corresponding to one of the two search trees growing towards ... | 7d8a373a589e87dc04f72150424685c088b535fb | 15,162 |
def get_extensions_from_dir(path: str) -> list[str]:
"""Gets all files that end with ``.py`` in a directory and returns a python dotpath."""
dirdotpath = ".".join(path.split(sep)[1:]) # we ignore the first part because we don't want to add the ``./``.
return [f"{dirdotpath}.{file}" for file in listdir(path... | c5a12241270f970733c055493534c7f5e8548fd2 | 15,163 |
def to_normalized_exacta_dividends(x,scr=-1):
""" Convert 2-d representation of probabilities to dividends
:param x:
:param scr:
:return:
"""
fx = to_normalized_dividends( to_flat_exacta(x), scr=scr )
return from_flat_exacta(fx, diag_value=scr) | 1c216908752326333185da7d21e7657f722e20f1 | 15,164 |
def CSVcreation():
"""This functions allows to access to page for the creation of csv"""
if "logged_in" in session and session["logged_in"] == True:
print("User login", session["username"])
try:
count1 = managedb.getCountLoginDB(session["username"])
if count1 == 0:
... | 33af7221ab77d8d0d40b60d220ce8e59ba728f0f | 15,165 |
import types
def generate_copies(func, phis):
"""
Emit stores to stack variables in predecessor blocks.
"""
builder = Builder(func)
vars = {}
loads = {}
# Allocate a stack variable for each phi
builder.position_at_beginning(func.startblock)
for block in phis:
for phi in ph... | 5ee76907970dea569c34d3bd4a5f57456bed7eb4 | 15,167 |
from typing import Sequence
def calculate_dv(wave: Sequence):
"""
Given a wavelength array, calculate the minimum ``dv`` of the array.
Parameters
----------
wave : array-like
The wavelength array
Returns
-------
float
delta-v in units of km/s
"""
return C.c_km... | 8e29af2644a97948330a4a5fcaaeb2e49ddad831 | 15,168 |
def check_link_errors(*args, visit=(), user="user", **kwargs):
"""
Craw site starting from the given base URL and raise an error if the
resulting error dictionary is not empty.
Notes:
Accept the same arguments of the :func:`crawl` function.
"""
errors, visited = crawl(*args, **kwargs)
... | 571b03e555894560128530c6e751c50a4aed0e21 | 15,169 |
def cart3_to_polar2(xyz_array):
"""
Convert 3D cartesian coordinates into 2D polar coordinates.
This is a simple routine for converting a set of 3D cartesian vectors into
spherical coordinates, where the position (0, 0) lies along the x-direction.
Parameters
----------
xyz_array : ndarray ... | 37220bd026ae48bf5a9914117075a10a51efba5a | 15,170 |
import requests
def deploy_release(rel_id, env_id):
"""deploy_release will start deploying a release to a given environment"""
uri = config.OCTOPUS_URI + "/api/deployments"
r = requests.post(uri, headers=config.OCTOPUS_HEADERS, verify=False,
json={'ReleaseId': rel_id, 'EnvironmentId'... | 08eae9366a3233704f65a6f952801cdd3ffbe867 | 15,171 |
def create_static_route(dut, next_hop=None, static_ip=None, shell="vtysh", family='ipv4', interface = None, vrf = None):
"""
To create static route
Author: Prudvi Mangadu ([email protected])
:param dut:
:param next_hop:
:param static_ip:
:param shell: sonic|vtysh
:param family... | 9097f016eaeb85e9b84351d50cac71d88779b1c1 | 15,172 |
def _markfoundfiles(arg, initargs, foundflags):
"""Mark file flags as found."""
try:
pos = initargs.index(arg) - 1
except ValueError:
pos = initargs.index("../" + arg) - 1
# In cases where there is a single input file as the first parameter. This
# should cover cases such as:
... | e27ca91de403a6364cbebc8ee4ee835a9335dccc | 15,173 |
def part_a(puzzle_input):
"""
Calculate the answer for part_a.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_a.
"""
recipes_to_make = int(''.join(puzzle_input))
elf_index_1 = 0
elf_index_2 = 1
recip... | 50e1cf923184a15747322528a47bad248c03dfa2 | 15,174 |
def _CompareFields(field, other_field):
"""Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC mess... | d6ce0b7f7caafd17dff188679800dee2dbe8e791 | 15,175 |
def loadtxt_rows(filename, rows, single_precision=False):
"""
Load only certain rows
"""
# Open the file
f = open(filename, "r")
# Storage
results = {}
# Row number
i = 0
# Number of columns
ncol = None
while(True):
# Read the line and split by commas
... | 9393cf7df8f24910a81e7d55128164a9bb467d91 | 15,177 |
def create_signal(frequencies, amplitudes, number_of_samples, sample_rate):
"""Create a signal of given frequencies and their amplitudes.
"""
timesamples = arange(number_of_samples) / sample_rate
signal = zeros(len(timesamples))
for frequency, amplitude in zip(frequencies, amplitudes):
signa... | 58876fd45e96d221220ccc4ad0129cf48912d691 | 15,178 |
import logging
import requests
from datetime import datetime
def serp_goog(q, cx, key, c2coff=None, cr=None,
dateRestrict=None, exactTerms=None, excludeTerms=None,
fileType=None, filter=None, gl=None, highRange=None,
hl=None, hq=None, imgColorType=None, imgDominantColor=None,... | ca1b32d2795c035aab8578f0dc36f4a8dd503bec | 15,179 |
def get_wiki_modal_data(term):
"""
runs the wikiperdia helper functions and created the
wikipedia data ready for the modal
"""
return_data = False
summary_data = get_wiki_summary(term=term)
related_terms = get_similar_search(term=term)
if summary_data:
return_data = {
... | 2d19c8ac1b3d261b3866b69a6a70d78ddac0ad0c | 15,181 |
def format_taxa_to_js(otu_coords, lineages, prevalence, min_taxon_radius=0.5,
max_taxon_radius=5, radius=1.0):
"""Write a string representing the taxa in a PCoA plot as javascript
Parameters
----------
otu_coords : array_like
Numpy array where the taxa is positioned
li... | 46052620ee7d4092761e728d78d6ab7b6abb6b45 | 15,182 |
def compute_heading(mag_read):
""" Computes the compass heading from the magnetometer X and Y.
Returns a float in degrees between 0 and 360.
"""
return ((atan2(mag_read[1], mag_read[0]) * 180) / pi) + 180 | c160e7a69aa0d4bdfe232f45094e863d0d8dd478 | 15,184 |
def ConvertTrieToFlatPaths(trie, prefix=None):
"""Flattens the trie of paths, prepending a prefix to each."""
result = {}
for name, data in trie.items():
if prefix:
name = prefix + '/' + name
if len(data) != 0 and not 'results' in data:
result.update(ConvertTrieToFlatPaths(data, name))
el... | c226f3c9d72ca04d5dfe3267a92888bc6255d649 | 15,185 |
from typing import List
from pathlib import Path
def get_root_version_for_subset_version(root_dataset_path: str,
sub_dataset_version: str,
sub_dataset_path: MetadataPath
) -> List[str]:
"""
... | b77da6b9f35e50e463dfba8cd2d710c357615d36 | 15,186 |
def subject() -> JsonCommandTranslator:
"""Get a JsonCommandTranslator test subject."""
return JsonCommandTranslator() | eed4b66f06a0257b2070e17b7cffa9f9005b6b0d | 15,187 |
import torch
def accuracy(output, target, cuda_enabled=True):
"""
Compute accuracy.
Args:
output: [batch_size, 10, 16, 1] The output from DigitCaps layer.
target: [batch_size] Labels for dataset.
Returns:
accuracy (float): The accuracy for a batch.
"""
batch_size = ta... | fc795bf54bfccfeea6bb3e8f1f81aa7282499d39 | 15,188 |
import sqlite3
def save_message(my_dict):
"""
Saves a message if it is not a duplicate.
"""
conn = sqlite3.connect(DB_STRING)
# Create a query cursor on the db connection
queryCurs = conn.cursor()
if my_dict.get('message_status') == None:
my_dict['message_status'] = "Unconfirmed"
... | 57f65f949c731b8120dec1b0f1b77b3d29505497 | 15,189 |
from typing import List
def getKFolds(train_df: pd.DataFrame,
seeds: List[str]) -> List[List[List[int]]]:
"""Generates len(seeds) folds for train_df
Usage:
# 5 folds
folds = getKFolds(train_df, [42, 99, 420, 120, 222])
for fold, (train_idx, valid_idx, test_idx) in enumer... | adc25fad4530bf0f134033d95a1d936fb7eb2653 | 15,190 |
def redownload_window() -> str:
"""The number of days for which the performance data will be redownloaded"""
return '30' | d5cc816f426f26586870def4797b91a05e37825a | 15,191 |
def clean_flight_probs(flight_probs: np.ndarray, rng: np.random.Generator) -> np.ndarray:
"""
Round off probabilities in flight_probs to 0 or 1 with random bias of the current probability
:param flight_probs: a vector of inclusion probabilities after the landing phase
:param rng: a random number genera... | f7127433781df86dabe699575be740f775310194 | 15,192 |
async def question(session: AskSession):
"""
Ask user for his answer on which LeetCode problem
he whats to anticipate.
"""
return await session.prompt(
message="Enter the problem URL from LeetCode site: ",
validator=LeetCodeUrlValidator(session)
) | a4ac5fd194736d2850e70ee5ac89e3569abf4410 | 15,193 |
import copy
def mongo_instance(instance_dict, ts_dt):
"""An instance as a model."""
dict_copy = copy.deepcopy(instance_dict)
dict_copy["status_info"]["heartbeat"] = ts_dt
return Instance(**dict_copy) | 32b0547cad0d84400a879814790eed6219ddb84a | 15,194 |
def get_conversion_option(shape_records):
"""Prompts user for conversion options"""
print("1 - Convert to a single zone")
print("2 - Convert to one zone per shape (%d zones) (this can take a while)" % (len(shape_records)))
import_option = int(input("Enter your conversion selection: "))
return import... | 7608c588960eb3678970e0d4467c67ff9f17a331 | 15,196 |
def base_conditional(Kmn, Lm, Knn, f, *, full_cov=False, q_sqrt=None, white=False):
"""
Given a g1 and g2, and distribution p and q such that
p(g2) = N(g2;0,Kmm)
p(g1) = N(g1;0,Knn)
p(g1|g2) = N(g1;0,Knm)
And
q(g2) = N(g2;f,q_sqrt*q_sqrt^T)
This method computes the mean and (co)v... | a6ddc7d2904836d7fa83557057dc42e25a8b8a9b | 15,197 |
def find_shortest_dijkstra_route(graph, journey):
"""
all_pairs_dijkstra_path() and all_pairs_dijkstra_path_length both return
a generator, hense the use of dict().
"""
all_paths = dict(nx.all_pairs_dijkstra_path(graph))
all_lengths = dict(nx.all_pairs_dijkstra_path_length(graph))
if len(a... | 49689cc3f4b03fa6589369bf0d085ee2dbe64d5d | 15,198 |
from functools import reduce
import operator
def product_consec_digits(number, consecutive):
"""
Returns the largest product of "consecutive"
consecutive digits from number
"""
digits = [int(dig) for dig in str(number)]
max_start = len(digits) - consecutive
return [reduce(operator.mul, dig... | 2df16f7445e6d579b632e86904b77ec93e52a1f3 | 15,199 |
def WeightedCrossEntropyLoss(alpha=0.5):
"""
Calculates the Weighted Cross-Entropy Loss, which applies a factor alpha, allowing one to
trade off recall and precision by up- or down-weighting the cost of a positive error relative
to a negative error.
A value alpha > 1 decreases the false negative co... | 5746bab38e39dd6f688ea648f29e7c30d7827466 | 15,201 |
def expand_stylesheet(abbr: str, config: Config):
"""
Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for
stylesheet languages like CSS, SASS etc.) and outputs it according to options
provided in config
"""
return stringify_stylesheet(stylesheet_abbreviation(abbr, ... | 17a65d1d6f6f2205a71e6e0ab653ef723672d756 | 15,202 |
def generate_legacy_dir(ctx, config, manifest, layers):
"""Generate a intermediate legacy directory from the image represented by the given layers and config to /image_runfiles.
Args:
ctx: the execution context
config: the image config file
manifest: the image manifest file
layers: the ... | 6001820e63ac3586625f7ca29311d717cc1e4c07 | 15,203 |
def workflow_key(workflow):
"""Return text search key for workflow"""
# I wish tags were in the manifest :(
elements = [workflow['name']]
elements.extend(workflow['tags'])
elements.extend(workflow['categories'])
elements.append(workflow['author'])
return ' '.join(elements) | 57347705b605e68a286dd953de5bb157ac50628e | 15,204 |
def get_logits(input_ids,mems,input_mask,target_mask):
"""Builds the graph for calculating the final logits"""
is_training = False
cutoffs = []
train_bin_sizes = []
eval_bin_sizes = []
proj_share_all_but_first = True
n_token = FLAGS.n_token
batch_size = FLAGS.batch_size
features =... | 4719104fdbb693411a9614e8a4048cbf6b932d1f | 15,205 |
def _api_get_scripts(name, output, kwargs):
""" API: accepts output """
return report(output, keyword="scripts", data=list_scripts()) | 88f002646cdec6911a76aa16cec2939b32cffd33 | 15,207 |
import requests
def get_children(key):
"""
Lists all direct child usages for a name usage
:return: list of species
"""
api_url = 'http://api.gbif.org/v1/species/{key}/children'.format(
key=key
)
try:
response = requests.get(api_url)
json_response = response.json()
... | 8d4a4ca4c1231ca2c7d98f7c0cede5ecdac003d5 | 15,208 |
def _extend(obj, *args):
"""
adapted from underscore-py
Extend a given object with all the properties in
passed-in object(s).
"""
args = list(args)
for src in args:
obj.update(src)
for k, v in src.items():
if v is None:
del obj[k]
return obj | 9fe1bffcd05ac44a3587b53a71f592c462975482 | 15,209 |
from asgiref.sync import async_to_sync
import functools
def async_test(func):
"""
Wrap async_to_sync with another function because Pytest complains about
collecting the resulting callable object as a test because it's not a true
function:
PytestCollectionWarning: cannot collect 'test_foo' because... | 10127bd083230404a7bb79d764502e6354f44b5a | 15,210 |
import logging
def get_logger(lname, logfile):
"""logging setup
logging config - to be moved to file at some point
"""
logger = logging.getLogger(lname)
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {... | 0a4795f383077b52b84afb882f090e0f9140fd0f | 15,211 |
def get_percentiles(data, percentiles, integer_valued=True):
"""Returns a dict of percentiles of the data.
Args:
data: An unsorted list of datapoints.
percentiles: A list of ints or floats in the range [0, 100] representing the
percentiles to compute.
integer_valued: Whether or not the values are... | 763c0c1a724b55ac4bb5b83a6831fa5aa44993fd | 15,212 |
def estimate_poster_dedpul(diff, alpha=None, quantile=0.05, alpha_as_mean_poster=False, max_it=100, **kwargs):
"""
Estimates posteriors and priors alpha (if not provided) of N in U with dedpul method
:param diff: difference of densities f_p / f_u for the sample U, np.array (n,), output of estimate_diff()
... | 5d7fe900e379418f38f6097ac8024984fc2e66fa | 15,213 |
def get_short_topic_name(test_run_name):
"""Returns the collection name for the DLQ.
Keyword arguments:
test_run_name -- the unique id for this test run
"""
return test_run_name[3:] if test_run_name.startswith("db.") else test_run_name | 6901ecd14b9cde9e0d8b7b62d11cf3c04b3b4a2e | 15,214 |
from shapely.geometry import Point, LineString
def cut_in_two(line):
"""
Cuts input line into two lines of equal length
Parameters
----------
line : shapely.LineString
input line
Returns
----------
list (LineString, LineString, Point)
... | 95df9b6b3995a930b6772a5137db3a14f10b4b26 | 15,215 |
def get_processor(aid):
"""
Return the processor module for a given achievement.
Args:
aid: the achievement id
Returns:
The processor module
"""
try:
path = get_achievement(aid)["processor"]
base_path = api.config.get_settings()["achievements"]["processor_base_p... | 941e998e0e3ee81a6e22903976959e7696dd11ef | 15,216 |
import locale
import re
def parse_price(price):
"""
Convert string price to numbers
"""
if not price:
return 0
price = price.replace(',', '')
return locale.atoi(re.sub('[^0-9,]', "", price)) | bb90aa90b38e66adc73220665bb5e6458bfe5374 | 15,217 |
def render_content(template, context={}, request=None):
"""Renderiza el contenido para un email a partir de la plantilla y el contexto.
Deben existir las versiones ".html" y ".txt" de la plantilla.
Adicionalmente, si se recibe el request, se utilizará para el renderizado.
"""
if request:
context_class = Re... | 0ef06bb3d42f737e9ae112a852460595b8bb1824 | 15,218 |
def calculate_psi(expected, actual, buckettype="bins", breakpoints=None, buckets=10, axis=0):
"""Calculate the PSI (population stability index) across all variables
Args:
expected: numpy matrix of original values
actual: numpy matrix of new values
buckettype: type of strategy for creat... | d5250a93e784ce13cc24a1d16a88929d33426c1c | 15,219 |
import requests
def get_sid(token):
"""
Obtain the sid from a given token, returns None if failed connection or other error preventing success
Do not use manually
"""
r = requests.get(url=str(URL + "app"), headers={'Accept': 'text/plain',
'author... | eaa26681f988b8c27fecf489bbf1bb1d5c460810 | 15,221 |
def generer_lien(mots, commande="http://www.lextutor.ca/cgi-bin/conc/wwwassocwords.pl?lingo=French&KeyWordFormat=&Maximum=10003&LineWidth=100&Gaps=no_gaps&store_dic=&is_refire=true&Fam_or_Word=&Source=http%3A%2F%2Fwww.lextutor.ca%2Fconc%2Ffr%2F&unframed=true&SearchType=equals&SearchStr={0}&Corpus=Fr_le_monde.txt&ColloS... | 0a646603fb538468a4ae29b102cb8250479fedce | 15,222 |
import numpy
def ring_forming_scission_grid(zrxn, zma, npoints=(7,)):
""" Build forward WD grid for a ring forming scission reaction
# the following allows for a 2-d grid search in the initial ts_search
# for now try 1-d grid and see if it is effective
"""
# Obtain the scan coordinate
... | de6e521ae28603b5afea5148f98a65f578e7b349 | 15,223 |
import re
def parse_proj(lines):
""" parse a project file, looking for section definitions """
section_regex_start = re.compile(
'\s*([0-9A-F]+) /\* ([^*]+) \*/ = {$', re.I)
section_regex_end = re.compile('\s*};$')
children_regex = re.compile('\s*([0-9A-F]+) /\* ([^*]+) \*/,', re.I)
children_regex_start = ... | 28e979a6a3c82f5669704375e8a6104f406af33f | 15,224 |
import torch
def mot_decode(heat,
wh,
reg=None,
cat_spec_wh=False,
K=100):
"""
多目标检测结果解析
"""
batch, cat, height, width = heat.size() # N×C×H×W
# heat = torch.sigmoid(heat)
# perform nms on heatmaps
heat = _nms(heat) # 默认应用3×3ma... | 22d5c8f85bd90936c46faf73ecb6c520466fb6da | 15,225 |
def get_descriptors(smiles):
""" Use RDkit to get molecular descriptors for the given smiles string """
mol = Chem.MolFromSmiles(smiles)
return pd.Series({name: func(mol) for name, func in descList.items()}) | 2107b4e1d13c2a7a02e15392fe38e1448d1772c2 | 15,226 |
def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
... | 87d259d00b073c8728833d8608fed5e4f484a987 | 15,227 |
def ends_with(s, suffix, ignore_case=False):
"""
suffix: str, list, or tuple
"""
if is_str(suffix):
suffix = [suffix]
suffix = list(suffix)
if ignore_case:
for idx, suf in enumerate(suffix):
suffix[idx] = to_lowercase(suf)
s = to_lowercase(s)
suffix = tupl... | 4b92596f95bb482a196bf2b8a07a6a954f526045 | 15,228 |
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
# 学学
version1 = [int(val) for val in version1.split(".")]
version2 = [int(val) for val in version2.split(".")]
if len(version1) > len(version2):
min_version = version2
... | 70ff77595f61620e1dac32d29be510e0906b505b | 15,229 |
import glob
import re
def create_capital():
""" Use fy and p-t-d capital sets and ref sets to make capital datasets """
adopted = glob.glob(conf['temp_data_dir'] \
+ "/FY*_ADOPT_CIP_BUDGET.xlsx")
proposed = glob.glob(conf['temp_data_dir'] \
+ "/FY*_PROP_CIP_BUDGET.xlsx")
t... | 64abc2c73e1455d42b94039cf857534a03075c41 | 15,230 |
def gen_gt_from_quadrilaterals(gt_quadrilaterals, input_gt_class_ids, image_shape, width_stride, box_min_size=3):
"""
从gt 四边形生成,宽度固定的gt boxes
:param gt_quadrilaterals: GT四边形坐标,[n,(x1,y1,x2,y2,x3,y3,x4,y4)]
:param input_gt_class_ids: GT四边形类别,一般就是1 [n]
:param image_shape:
:param width_stride: 分割的步... | 4dfd81bd7a0f20334385bc9e1c9681d371e6f609 | 15,231 |
def monotonic(l: list):
"""Return True is list elements are monotonically increasing or decreasing.
>>> monotonic([1, 2, 4, 20])
True
>>> monotonic([1, 20, 4, 10])
False
>>> monotonic([4, 1, 0, -10])
True
"""
#[SOLUTION]
if l == sorted(l) or l == sorted(l, reverse=True):
retu... | 1f8a34943e288ea9695f040be91f18cfe82a6e48 | 15,232 |
import math
def get_weight(stats):
"""
Return a data point weight for the result.
"""
if stats is None or 'ci_99_a' not in stats or 'ci_99_b' not in stats:
return None
try:
a = stats['ci_99_a']
b = stats['ci_99_b']
if math.isinf(a) or math.isinf(b):
# ... | 7e44032bc9e51e5fe7522c3f51ead5e733d4107a | 15,236 |
import torch
def get_true_posterior(X: Tensor, y: Tensor) -> (Tensor, Tensor, float, float, float):
"""
Get the parameters of the true posterior of a linear regression model fit to the given data.
Args:
X: The features, of shape (n_samples, n_features).
y: The targets, of shape (n_samples... | 3431513d52905ec51bbe7b694af02a8274cbf48e | 15,237 |
def findmax(engine,user,measure,depth):
"""Returns a list of top (user,measure) pairs, sorted by measure, up to a given :depth"""
neighbors = engine.neighbors(user)
d = {v:measure(user,v) for v in neighbors}
ranked = sorted(neighbors,key=lambda v:d[v],reverse=True)
return list((v,d[v]) for v in rank... | ecf6d72f8c689f1b7af78a714e55d8fbfe57f2ad | 15,238 |
from typing import OrderedDict
def cart_update(request, pk):
"""
Add/Remove single product (possible multiple qty of product) to cart
:param request: Django's HTTP Request object,
pk: Primary key of
products to be added to cart
:return: Success message
... | 1673b299a41bdccaf6d0a27b15fbf85a0bb7028f | 15,239 |
def mlp_gradient(x, y, ws, bs, phis, alpha):
"""
Return a list containing the gradient of the cost with respect to z^(k)for each layer.
:param x: a list of lists representing the x matrix.
:param y: a list of lists of output values.
:param ws: a list of weight matrices (one for each layer)
:para... | 0e148d5b3b343a982d9332637c4f51be8b3afa3b | 15,241 |
import torch
def src_one(y: torch.Tensor, D: torch.Tensor, *,
k=None, device=None) -> torch.Tensor:
"""
y = Dx
:param y: image (h*w)
:param D: dict (class_sz, train_im_sz, h*w)
:param k:
:param device: pytorch device
:return: predict tensor(int)
"""
assert y.dim() == 1
... | b779e3313fb707bb6659fe48f59b030b9c9ae7d3 | 15,242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.