content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def binary_accuracy(*, logits, labels):
"""Accuracy of binary classifier, from logits."""
p = jax.nn.sigmoid(logits)
return jnp.mean(labels == (p > 0.5)) | f7795c8d7a945e5e5e97475888cf9e5b65aa1415 | 19,700 |
from re import DEBUG
def create_app(app_name=None, blueprints=None, config=None):
"""
Diffy application factory
:param config:
:param app_name:
:param blueprints:
:return:
"""
if not blueprints:
blueprints = DEFAULT_BLUEPRINTS
else:
blueprints = blueprints + DEFAUL... | 8bde6cbe8e01abeca10f6d1d1d2da5f20fcb6789 | 19,701 |
def extract_tag(inventory, url):
"""
extract data from sphinx inventory.
The extracted datas come from a C++ project
documented using Breathe. The structure of the inventory
is a dictionary with the following keys
- cpp:class (class names)
- cpp:function (functions or class methods)... | dcda1869fb6a44bea3b17f1d427fe279ebdc3a11 | 19,702 |
def strip_parens(s):
"""Strip parentheses around string"""
if not s:
return s
if s[0] == "(" and s[-1] == ")":
return strip_parens(s[1:-1])
else:
return s | ee4c9ce6ee769a86a2e2e39159aa9eaa5fd422c6 | 19,703 |
import ast
def custom_eval(node, value_map=None):
"""
for safely using `eval`
"""
if isinstance(node, ast.Call):
values = [custom_eval(v) for v in node.args]
func_name = node.func.id
if func_name in {"AVG", "IF"}:
return FUNCTIONS_MAP[func_name](*values)
eli... | a9ff29455ee90a83f5c54197633153d5b9d0fdbc | 19,704 |
def validate_dict(input,validate):
"""
This function returns true or false if the dictionaries pass regexp
validation.
Validate format:
{
keyname: {
substrname: "^\w{5,10}$",
subintname: "^[0-9]+$"
}
}
Validates that keyname exists, and that it contains a substrname
that is 5-10 word characters, an... | 0a221f5586f4464f4279ab4ce3d22019e247659b | 19,705 |
def build_windows_and_pods_from_events(backpressure_events, window_width_in_hours=1) -> (list, list):
"""
Generate barchart-friendly time windows with counts of backpressuring durations within each window.
:param backpressure_events: a list of BackpressureEvents to be broken up into time windows
:param... | 78adebe54d883a7251c04e250f7c14e47043d40e | 19,706 |
import requests
import json
def package_search(api_url, org_id=None, params=None, start_index=0, rows=100, logger=None, out=None):
"""
package_search: run the package_search CKAN API query, filtering by org_id, iterating by 100, starting with 'start_index'
perform package_search by owner_org:
https://... | 642a869931d45fe441a146cb8e931dc530170c37 | 19,707 |
def voigt_fit(prefix,x,slice,c,vary):
"""
This function fits a voigt to a spectral slice. Center value can be set to constant or floated, everything else is floated.
Parameters:
prefix: prefix for lmfit to distinguish variables during multiple fits
x: x values to use in fit
slice: slice to be f... | 034810cb6a0ac8efb311182df3d65cf0bd6002d9 | 19,708 |
from typing import List
def turn_coordinates_into_list_of_distances(list_of_coordinates: List[tuple]):
"""
Function to calculate the distance between coordinates in a list. Using the
'great_circle' for measuring here, since it is much faster (but less precise
than 'geodesic').
Parameters
----... | 5fdc0198b533604ec3d935224c7b2b634670083e | 19,709 |
import json
def getPileupDatasetSizes(datasets, phedexUrl):
"""
Given a list of datasets, find all their blocks with replicas
available, i.e., blocks that have valid files to be processed,
and calculate the total dataset size
:param datasets: list of dataset names
:param phedexUrl: a string wi... | 48d77aa47998204ff99df188ef830cae647ac9b9 | 19,710 |
def convertpo(inputpofile, outputpotfile, template, reverse=False):
"""reads in inputpofile, removes the header, writes to outputpotfile."""
inputpo = po.pofile(inputpofile)
templatepo = po.pofile(template)
if reverse:
swapdir(inputpo)
templatepo.makeindex()
header = inputpo.header()
... | 6954354db5ca9c660e326eeae23906853743eb57 | 19,711 |
def do_fk5(l, b, jde):
"""[summary]
Parameters
----------
l : float
longitude
b : float
latitude
jde : float
Julian Day of the ephemeris
Returns
-------
tuple
tuple(l,b)
"""
T = (jde - JD_J2000) / CENTURY
lda = l - deg2rad(1.397)*T - deg2... | 2ccc96aab8ddfcbe93d7534a01b0f262c0330053 | 19,712 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.8 ** (epoch // 1))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | ce4b5a3aa70ab07791af3bd41e14758e568fb1cc | 19,713 |
import yaml
def get_defaults(module, *args):
"""
Find an internal defaults data file, load it using YAML, and return the resulting
dictionary.
Takes the dot-separated module path (e.g. "abscal.wfc3.reduce_grism_extract"), splits
off the last item (e.g. ["abscal.wfc3", "reduce_grism_extract"... | a92e37f75c4f967c2b23391a817fb14118b89a8f | 19,714 |
import shlex
def get(using=None):
"""Return a browser launcher instance appropriate for the environment."""
if _tryorder is None:
with _lock:
if _tryorder is None:
register_standard_browsers()
if using is not None:
alternatives = [using]
else:
altern... | 12c2ca5fdd93964527330a0694d69a8d4e84ee12 | 19,715 |
import binascii
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16) | 54b50ffea715bf127eabd7e82aada36e4717c288 | 19,716 |
def update_book(username, book_id, data):
"""Update book data"""
cursor, conn = db_sql.connect('books.db')
keys = list(data.keys())
sql = ("UPDATE " + username + " SET " + " = ?, ".join(keys) +
" = ? WHERE _id = ?")
temp_list = []
for key in keys:
temp_list.append(data[key])
... | 2dcc2970cec8f53c90c72f341092f7cb7c7d6232 | 19,717 |
def score_retrievals(label, retrievals):
"""
Evaluating the current retrieval experiment
Args:
-----
label: string
label corresponding to the query
retrivals: list
list of strings containing the ranked labels corresponding to the retrievals
tot_labels: integer
number ... | c9a3a24c2c6e5a2986387db88710da43984bd862 | 19,718 |
def default_add_one_res_2_all_res(one_res: list, all_res: list) -> list:
"""
默认函数1: one_res 增加到all_res
:param one_res:
:param all_res:
:return:
"""
for i in one_res:
for j in i:
all_res.append(j)
return all_res | 9c2e83ffaa7c67759f8b3d7cf30354d7cf7ca030 | 19,719 |
from typing import Iterable
import re
def search_gene(search_string: str, **kwargs) -> Iterable[Gene]:
""" Symbols have been separated into search_gene_symbol - this returns Gene objects """
CONSORTIUM_REGEX = {
r"(ENSG\d+)": AnnotationConsortium.ENSEMBL,
r"Gene:(\d+)": AnnotationConsortium.R... | 768c6ac712b6660b78b2bead3be6f0000541696f | 19,720 |
import os
def get_steam_libraries():
"""Returns list of found Steam library folders."""
found_libraries = []
if os.path.isdir(STEAM_INSTALL_DIR + '/steamapps/common'):
found_libraries.append(STEAM_INSTALL_DIR)
libraries_config = {}
if LIBRARY_FOLDERS_FILE:
libraries_config = vdf.l... | 2a2e0460929dd0b8801a5caa2ebde055f14b2317 | 19,721 |
import logging
def detect_wings_simple(img, pixel_size=1,
ds=2, layers=2, thresh_window=1.8e3,
minarea=0.5e6, maxarea=2e6, minsolidity=.6,
minaspect=.3, plot=False, threshold_fun=None):
"""
simple wing detection via adaptive thresholding ... | 84c625ce35bb920d893f766c900d3172f658f905 | 19,722 |
def check_logged(request):
"""Check if user is logged and have the permission."""
permission = request.GET.get('permission', '')
if permission:
has_perm = request.user.has_perm(permission)
if not has_perm:
msg = (
"User does not have permission to exectute this ac... | 2cf03f7336b7c8814fd380aae5209b0b8fe6dca9 | 19,723 |
def _deprecated_configs(agentConfig):
""" Warn about deprecated configs
"""
deprecated_checks = {}
deprecated_configs_enabled = [v for k, v in OLD_STYLE_PARAMETERS if len([l for l in agentConfig if l.startswith(k)]) > 0]
for deprecated_config in deprecated_configs_enabled:
msg = "Configuring... | e47a47a1a7dd40d04a21927730479500f934a1d1 | 19,724 |
def check_number_of_calls(object_with_method, method_name, maximum_calls, minimum_calls=1, stack_depth=2):
"""
Instruments the given method on the given object to verify the number of calls to the method is
less than or equal to the expected maximum_calls and greater than or equal to the expected minimum_ca... | 64bdc512753b159128e34aa7c95d60a741745fce | 19,725 |
def strict_transport_security(reqs: dict, expectation='hsts-implemented-max-age-at-least-six-months') -> dict:
"""
:param reqs: dictionary containing all the request and response objects
:param expectation: test expectation
hsts-implemented-max-age-at-least-six-months: HSTS implemented with a max ag... | 55c588cf1c7e214862aae4ace5c7c8a5feb9dabc | 19,726 |
def _get_span(succ, name, resultidx=0, matchidx=0, silent_fail=False):
"""
Helper method to return the span for the given result index and name, or None.
Args:
succ: success instance
name: name of the match info, if None, uses the entire span of the result
resultidx: index of the re... | 1fc6208f1aa7289a53e4e64c041abb71498a2eeb | 19,727 |
import random
def gen_k_arr(K, n):
"""
Arguments:
K {int} -- [apa numbers]
n {int} -- [trial numbers]
"""
def random_sel(K, trial=200):
count_index = 0
pool = np.arange(K)
last = None
while count_index < trial:
count_index += 1
r... | c66084faa8903455835973226ea6ca570239a1ec | 19,728 |
def tau_data(spc_dct_i,
spc_mod_dct_i,
run_prefix, save_prefix, saddle=False):
""" Read the filesystem to get information for TAU
"""
# Set up all the filesystem objects using models and levels
pf_filesystems = filesys.models.pf_filesys(
spc_dct_i, spc_mod_dct_i, run_p... | d27742140929d79dd4bb7a36094b5e5caf7173e2 | 19,729 |
def get_atten(log, atten_obj):
"""Get attenuator current attenuation value.
Args:
log: log object.
atten_obj: attenuator object.
Returns:
Current attenuation value.
"""
return atten_obj.get_atten() | 22d69d326846105491b1fa90f319eb9e0da69a20 | 19,730 |
def lfs_hsm_remove(log, fpath, host=None):
"""
HSM remove
"""
command = ("lfs hsm_remove %s" % (fpath))
extra_string = ""
if host is None:
retval = utils.run(command)
else:
retval = host.sh_run(log, command)
extra_string = ("on host [%s]" % host.sh_hostname)
if re... | ddca4a626786dfecfef231737761924527d136d5 | 19,731 |
def area_under_curve_score(table,scoring_function):
"""Takes a run and produces the total area under the curve until the end of the run.
mean_area_under_curve_score is probably more informative."""
assert_run(table)
scores = get_scores(table,scoring_function)
return np.trapz(scores) | f84fd0a2adede09c17aa6254906bee36a2738983 | 19,732 |
def read_key_value(file):
"""支持注释,支持中文"""
return_dict = {}
lines = readlines(file)
for line in lines:
line = line.strip().split(':')
if line[0][0] == '#':
continue
key = line[0].strip()
value = line[1].strip()
return_dict[key] = value
return return... | 9fdac43783c066872a05cbd59488add7a2dc54c0 | 19,733 |
def binarize_image(image):
"""Binarize image pixel values to 0 and 255."""
unique_values = np.unique(image)
if len(unique_values) == 2:
if (unique_values == np.array([0., 255.])).all():
return image
mean = image.mean()
image[image > mean] = 255
image[image <= mean] = 0
r... | 6e4a621b0a2ff06d6a6bf5c0eb45f1028e6d526f | 19,734 |
from typing import Type
def LineMatcher_fixture(request: FixtureRequest) -> Type["LineMatcher"]:
"""A reference to the :class: `LineMatcher`.
This is instantiable with a list of lines (without their trailing newlines).
This is useful for testing large texts, such as the output of commands.
"""
re... | 86c05df8f099ba66e62ae0bb071b2999cbb4f082 | 19,735 |
def Delay(opts, args):
"""Sleeps for a while
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the duration
the sleep
@rtype: int
@return: the desired exit code
"""
delay = float(args[0])
op = opcodes.OpTestDelay(duration=... | c9ecd6cb3dbdcd5ae48c527f2f6769789b05664d | 19,736 |
def logout():
""" Simply loading the logout page while logged in will log the user out """
logout_user()
return render_template(f"{app_name}/logout.html") | 33191c6870a0aac8fcdebb0349b93196e2ed0ba8 | 19,737 |
from typing import Dict
from typing import Any
def identify_larger_definition(
one: ObjectDefinition,
two: ObjectDefinition
) -> Dict[str, Any]:
"""Return the larger (in dimensions) of the two given definitions."""
if not one:
return two
if not two:
return one
# TODO Handle if ... | 0ba3815ced847de278b503f10a55a718ee00cd81 | 19,738 |
def duration_to_timedelta(obj):
"""Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600)
"""
matches = DURATION_PATTERN.search(obj)
matches = matches.groupdict(default="0")
matches = {k: int(v) for k, v in matches.items()}
return timedelta(**matc... | fcfa67e6667b232a6647cb71fff543a45a6d3475 | 19,739 |
async def create_mock_hlk_sw16_connection(fail):
"""Create a mock HLK-SW16 client."""
client = MockSW16Client(fail)
await client.setup()
return client | 14589398e268a76637994f2883f2cd824a14a81b | 19,740 |
def inv_dist_weight(distances, b):
"""Inverse distance weight
Parameters
----------
distances : numpy.array of floats
Distances to point of interest
b : float
The parameter of the inverse distance weight. The higher, the
higher the influence of closeby stations... | c7e857bba312277b193ce5eda7467b8b0bf8bd75 | 19,741 |
import pytz
def load_inferred_fishing(table, id_list, project_id, threshold=True):
"""Load inferred data and generate comparison data
"""
query_template = """
SELECT vessel_id, start_time, end_time, nnet_score FROM
TABLE_DATE_RANGE([{table}],
TIMESTAMP('{year}-01-01'), TIMESTAMP(... | fba7e007b38d141e91c0608cbd609a2d3b474b4b | 19,742 |
from typing import Any
def is_optional(value: Any) -> CheckerReturn:
"""
It is a rather special validator because it never returns False and emits an exception
signal when the value is correct instead of returning True.
Its user should catch the signal to short-circuit the validation chain.
"""
... | 25e45617ca5584dc2470d9e76ef884596c465917 | 19,743 |
from typing import Union
from typing import Tuple
from typing import List
def approximate_bounding_box_dyn_obstacles(obj: list, time_step=0) -> Union[
Tuple[list], None]:
"""
Compute bounding box of dynamic obstacles at time step
:param obj: All possible objects. DynamicObstacles are filtered.
:re... | 3a8fc28c2a47b50b9d0acc49f0818031e357fffa | 19,744 |
from koala import KOALA_RSS # TODO: currently importing like this for workaround of circular imports
def sky_spectrum_from_fibres_using_file(
rss_file,
fibre_list=[],
win_sky=151,
n_sky=0,
skyflat="",
apply_throughput=True,
correct_ccd_defects=False,
fix_wavelengths=False,
sol=[0,... | e227a72f710c910685cad6941382dd44c7aacbe1 | 19,745 |
def binary_class_accuracy_score(y_pred, data):
"""LightGBM binary class accuracy-score function.
Parameters
----------
y_pred
LightGBM predictions.
data
LightGBM ``'Dataset'``.
Returns
-------
(eval_name, eval_result, is_higher_better)
``'eval_name'`` : string
... | 53f68931a96e3d32bed622dae09239ee2b96d762 | 19,746 |
import win32clipboard
def win32_clipboard_get():
""" Get the current clipboard's text on Windows.
Requires Mark Hammond's pywin32 extensions.
"""
try:
except ImportError:
message = ("Getting text from the clipboard requires the pywin32 "
"extensions: http://sourceforge.... | 9d4f95a46893c2a93ae0b1c48e5b7db72a2352a8 | 19,747 |
def is_prime(n):
"""Given an integer n, return True if n is prime and False if not.
"""
return True | 17d2d7bdf95a9d3e037e911a3271688013413fb7 | 19,748 |
import os
def path_to_newname(path, name_level=1):
"""
Takes one path and returns a new name, combining the directory structure
with the filename.
Parameters
----------
path : String
name_level : Integer
Form the name using items this far back in the path. E.g. if
path = ... | e0d8fc09a8809bf8dfee26e208570b0e3c5a4d02 | 19,749 |
import os
def load_model_from_json(model_path=None, weights_path=None):
"""
load dataset and weights from file
input:
model_path path to the model file, should be json format
weights_path path to the weights file, should be HDF5 format
output:
Keras model
"""
# default model pat... | 615a5a51704ee64bf7a45ca1da091278cb0d4453 | 19,750 |
import sys
def update_parameters(parameters,grads,learning_rate,optimizer,beta1=0.9,beta2=0.999, epsilon=1e-8):
"""
Description:
Updates the neural networks parameters (weights, biases) based on the optomizer selected
Arguments:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "... | f9985935d214072340169d3b83958842efb6b838 | 19,751 |
import logging
def get_request_file():
"""
Method to implement REST API call of GET on address /file
"""
try:
content_file = open("html/file_get.html", "r")
content = content_file.read()
except:
logging.info("Could not load source HTML file '%s'")
raise
return ... | 7a084d5455b1797d851388ac40de23c5c35fb381 | 19,752 |
from collections import Counter
from typing import Iterable
def sock_merchant(arr: Iterable[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5])
6
"""
count = Counter(arr).values()
ret = sum(n // 2 ... | 1b3b8d37ccb3494ed774e26a41ebba32c87a632c | 19,753 |
def new_user_registration(email: str) -> dict:
"""Alert the CIDC admin mailing list to a new user registration."""
subject = "New User Registration"
html_content = (
f"A new user, {email}, has registered for the CIMAC-CIDC Data Portal ({ENV}). If you are a CIDC Admin, "
"please visit the a... | ee4c57e45d15b8e65bd8e702633d527bc2f6db1f | 19,754 |
def article_detail():
"""文章详情"""
id = request.form.get('id')
if id is None:
raise Exception('ARTICLE_NOT_EXIST')
article = Article.find(id)
if article is None:
raise Exception('ARTICLE_NOT_EXIST')
# 获取标签
if article.tags is None:
article.tags = []
else:
al... | 534cb77384b65cb4b88bedd1a82daeb93766714a | 19,755 |
def add_state_names_column(my_df):
"""
Add a column of corresponding state names to a dataframe
Params (my_df) a DataFrame with a column called "abbrev" that has state abbreviations.
Return a copy of the original dataframe, but with an extra column.
"""
new_df = my_df.copy()
names_map ... | 4a9eb49ef2cda11d8135eb33ec43d99422e067b6 | 19,756 |
import glob
def list_subdir_paths(directory):
"""
Generates a list of subdirectory paths
:param directory: str pathname of target parent directory
:return: list of paths for each subdirectory in the target parent
directory
"""
subdir_paths = glob("{}/*/".format(directory))
return ... | df8ec80096b900ad8ceac3bc013fe47b21b4fd54 | 19,757 |
import math
def logic_method_with_bkg(plots_per_cycle, cycle_time, sigma_s=160, m=3, n=4):
"""
:param plots_per_cycle:
:param cycle_time:
:param sigma_s:
:param m:
:param n:
:return:
"""
N = plots_per_cycle.shape[0] # number of cycles
tracks = [] # ret
track_cnt = 0
... | a77e8a9d116187dce674c33ca098012bb6b22363 | 19,758 |
from typing import Union
def bias_scan(
data: pd.DataFrame,
observations: pd.Series,
expectations: Union[pd.Series, pd.DataFrame] = None,
favorable_value: Union[str, float] = None,
overpredicted: bool = True,
scoring: Union[str, ScoringFunction] = "Bernoulli",
num_iters: int = 10,
pena... | 735ccc6c3054e981a7aee9681d892e226316ed41 | 19,759 |
def int_from_bin_list(lst):
"""Convert a list of 0s and 1s into an integer
Args:
lst (list or numpy.array): list of 0s and 1s
Returns:
int: resulting integer
"""
return int("".join(str(x) for x in lst), 2) | a41b2578780019ed1266442d76462fb89ba2a0fb | 19,760 |
def validate_array_input(arr, dtype, arr_name):
"""Check if array has correct type and is numerical.
This function checks if the input is either a list, numpy.ndarray or
pandas.Series of numerical values, converts it to a numpy.ndarray and
throws an error in case of incorrect data.
Args:
a... | 72829dad46aa6e5054cd0d49ff0206083781bddd | 19,761 |
from sklearn.manifold import TSNE
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
def ClassifyBehavior(data, bp_1="snout",bp_2="ear_L", bp_3="ear_R", bp_4="tail", dimensions = 2,distance=28,**kwargs):
"""
Returns an array with the cluster by frame, an array... | 002e11bd0b6050fcfa8b50df0f0b24a3cc36bed7 | 19,762 |
def grab_inputs(board):
"""
Asks for inputs and returns a row, col. Also updates the board state.
"""
keepasking = True
while keepasking:
try:
row = int(input("Input row"))
col = int(input("Input column "))
except (EOFError, KeyboardInterrupt):
pri... | 0fb840348ff645d9f2a48e1c028d99bff0bf31fe | 19,763 |
def start_session():
""" This function is what initializes the application."""
welcome_msg = render_template('welcome')
return question(welcome_msg) | ce666a48f078e49a0df98b5087c71cb1e548e905 | 19,764 |
def solve(filename):
"""
Run a sample, do the analysis and store a program to apply to a test case
"""
arc = Arc(filename)
arc.print_training_outputs()
return arc.solve() | 2a23021bb31508fd67c4be178684bb2da7d1d7c9 | 19,765 |
from typing import Sequence
def extract_item(item, prefix=None, entry=None):
"""a helper function to extract sequence, will extract values from
a dicom sequence depending on the type.
Parameters
==========
item: an item from a sequence.
"""
# First call, we define entry to be a lookup dic... | a4c8c99bcd54baefdbaa95469bb3a289c2811cfc | 19,766 |
def route_counts(session, origin_code, dest_code):
""" Get count of flight routes between origin and dest. """
routes = session.tables["Flight Route"]
# airports = session.tables["Reporting Airport"]
# origin = airports["Reporting Airport"] == origin_code
origin = SelectorClause(
"Reporting ... | ad35a36b6874bcf45107d7217acdb6bae097b305 | 19,767 |
from pathlib import Path
def generate_master_bias(
science_frame : CCDData,
bias_path : Path,
use_cache : bool=True
) -> CCDData:
"""
"""
cache_path = generate_cache_path(science_frame, bias_path) / 'bias'
cache_file = cache_path / 'master.fits'
if use_cache and cache_... | 207ca95109694d16e154088c7e3a12880f01d037 | 19,768 |
def RetryOnException(retry_checker,
max_retries,
sleep_multiplier=0,
retry_backoff_factor=1):
"""Decorater which retries the function call if |retry_checker| returns true.
Args:
retry_checker: A callback function which should take an except... | a721e14c7d5d98e2151f4108dcff18cb0de225e3 | 19,769 |
import csv
import itertools
def ParseCsvFile(fp):
"""Parse dstat results file in csv format.
Args:
file: string. Name of the file.
Returns:
A tuple of list of dstat labels and ndarray containing parsed data.
"""
reader = csv.reader(fp)
headers = list(itertools.islice(reader, 5))
if len(headers... | 39381d0f9eaab1ab139d4d660257aeaec6e765ca | 19,770 |
def uid_to_device_name(uid):
"""
Turn UID into its corresponding device name.
"""
return device_id_to_name(uid_to_device_id(uid)) | e4ec879bb1619fd1e215c94084117b3ce6b237bc | 19,771 |
def zonal_convergence(u, h, dx, dy, dy_u, ocean_u):
"""Compute convergence of zonal flow.
Returns -(hu)_x taking account of the curvature of the grid.
"""
res = create_var(u.shape)
for j in range(u.shape[-2]):
for i in range(u.shape[-1]):
res[j, i] = (-1) * (
h[j... | 42a0ee78e0c4d8f78a600a9dd72aa03aa104f560 | 19,772 |
def filterPoints(solutions, corners):
"""Remove solutions if they are not whithin the perimeter.
This function use shapely as the mathematical computaions for non rectangular
shapes are quite heavy.
Args:
solutions: A list of candidate points.
corners: The perimeter of the garden (lis... | 55c6e824d46e934eb30c6ecca45f516f09f0bff2 | 19,773 |
from typing import Set
def get_migrations_from_old_config_key_startswith(old_config_key_start: str) -> Set[AbstractPropertyMigration]:
"""
Get all migrations where old_config_key starts with given value
"""
ret = set()
for migration in get_history():
if isinstance(migration, AbstractProper... | c8224af6e9a675ed940bf61de984a8dd01f634d5 | 19,774 |
def bbox_mapping(bboxes,
img_shape,
scale_factor,
flip,
flip_direction, # ='horizontal',
tile_offset):
"""Map bboxes from the original image scale to testing scale."""
new_bboxes = bboxes * bboxes.new_tensor(scale_factor)
... | a5fb8283eb6c379ef516db3a72c50d34c58ea8e6 | 19,775 |
import os
def getRNA_X(sample_list, DATAPATH, ctype, lab_type):
"""
Get X for RNA. The required columns are retained and all other rows and
columns dropped. This function also labels the data for building models.
Parameters
----------
sample_list : list
List of tumour samples to be r... | e1ea6b4472f0f899db0fbeeb1ed150208dbb7888 | 19,776 |
import torch
def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):
"""Convert 3x4 rotation matrix to 4d quaternion vector
This algorithm is based on algorithm described in
https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201
Args:
rotation_matrix (Te... | 3198dcd9f7a058a54be0d607cc66f543ea8e46f8 | 19,777 |
import calendar
from datetime import datetime
def get_first_day_and_last_day_by_month(months=0):
"""获取某月份的第一天的日期和最后一天的日期
:param months: int, 负数表示过去的月数,正数表示未来的
:return tuple: (某月第一天日期, 某月最后一天日期)
"""
day = get_today() + relativedelta(months=months)
year = day.year
month = day.month
# ... | 1aea5aa0c1abcc8382212315f0e34cf0f33968b9 | 19,778 |
def kmeans(X, C):
"""The Loyd's algorithm for the k-centers problems.
X : data matrix
C : initial centers
"""
C = C.copy()
V = np.zeros(C.shape[0])
for x in X:
idx = np.argmin(((C - x)**2).sum(1))
V[idx] += 1
eta = 1.0 / V[idx]
C[idx] = (1.0 - eta) * C[idx] + ... | 3006c10bf9091a39f4808781e4b484fc24f2ae3f | 19,779 |
from re import DEBUG
def gap_init(points, D, d, C, L=None, st=None, K=None, minimize_K=True,
find_optimal_seeds=True,
seed_method="cones",
seed_edge_weight_type='EUC_2D',
use_adaptive_L_constraint_weights=True,
increase_K_on_failure=False):
... | 110ee76668283efdf91716c3235de4b5719b81f3 | 19,780 |
def data_block(block_str):
""" Parses all of the NASA polynomials in the species block of the
mechanism file and subsequently pulls all of the species names
and thermochemical properties.
:param block_str: string for thermo block
:type block_str: str
:return data_block: all ... | bfcf457e164002cd4ab8c6c852117ebe24f437ab | 19,781 |
from functools import reduce
from re import S
def risch_norman(f, x, rewrite=False):
"""Computes indefinite integral using extended Risch-Norman algorithm,
also known as parallel Risch. This is a simplified version of full
recursive Risch algorithm. It is designed for integrating various
clas... | 12dd2cbd724566344d73bff48ed46b33d2b84730 | 19,782 |
from .model_store import download_model
import os
def get_vgg(blocks,
bias=True,
use_bn=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create VGG model with specific parameters.
Pa... | ac7cf08fd3faf386edd896672519dbd96e82953f | 19,783 |
import os
import logging
def configure_logger():
"""
Declare and validate existence of log directory; create and configure logger object
:return: instance of configured logger object
"""
log_dir = os.path.join(os.getcwd(), 'log')
create_directory_if_not_exists(None, log_dir)
configure_lo... | 301fd676a3a680a08b14a16ea4dcc6c41fb2af9b | 19,784 |
def preprocess_spectra(fluxes, interpolated_sn, sn_array, y_offset_array):
"""preprocesses a batch of spectra, adding noise according to specified sn profile, and applies continuum error
INPUTS
fluxes: length n 2D array with flux values for a spectrum
interpolated_sn: length n 1D array with relative sn ... | 552d42b3835f3bc60930ae6f05f1544c924e940b | 19,785 |
import json
def read_config(path=None):
"""
Function for reading in the config.json file
"""
#create the filepath
if path:
if "config.json" in path:
file_path = path
else:
file_path = f"{path}/config.json"
else:
file_path = "config.json"
... | 3e3612879645509acb74f184085f7e584afbf822 | 19,786 |
import json
def ema_incentive(ds):
"""
Parse stream name 'incentive--org.md2k.ema_scheduler--phone'. Convert json column to multiple columns.
Args:
ds: Windowed/grouped DataStream object
Returns:
ds: Windowed/grouped DataStream object.
"""
schema = StructType([
Struct... | ad6d6a08906dc5aab5a1ea2d0895eb84eac44f44 | 19,787 |
def read_fingerprint(finger_name: str) -> np.ndarray:
"""
Given the file "x_y_z" name this function returns a vector with
the fingerprint data.
:param finger_name: A string with the format "x_y_z".
:return: A vector (1x256) containing the fingerprint data.
"""
base_path = "rawData/QFM16_"
... | 21b88afffdb016699ad6a0ed635931096ebe8bc1 | 19,788 |
import matplotlib.pyplot as plt
def plot_tree(T, res=None, title=None, cmap_id="Pastel2"):
"""Plots a given tree, containing hierarchical segmentation.
Parameters
----------
T: mir_eval.segment.tree
A tree object containing the hierarchical segmentation.
res: float
Frame-rate reso... | 40baf9a5f62ee139ddc905e840bc982b67166bb8 | 19,789 |
def read_data(data_path):
"""This function reads in the histogram data from the provided path
and returns a pandas dataframe
"""
histogram_df = None # Your code goes here
return histogram_df | 5b927246c9298743c22d8a9fc497175aa9600c24 | 19,790 |
def _interpolate_face_to_bar(nodes, eid, eid_new, nid_new, mid, area, J, fbdf,
inid1, inid2, inid3,
xyz1_local, xyz2_local, xyz3_local,
xyz1_global, xyz2_global, xyz3_global,
nodal_result,
... | 4b35195feb6d41176f0e1daa02c90008a05a75b0 | 19,791 |
def get_number_of_tickets():
"""Get number of tickets to enter from user"""
num_tickets = 0
while num_tickets == 0:
try:
num_tickets = int(input('How many tickets do you want to get?\n'))
except:
print ("Invalid entry for number of tickets.")
return num_tickets | 3703a4ed64867a9884328c09f0fd32e763265e95 | 19,792 |
def scrape(file):
""" scrapes rankings, counts from agg.txt file"""
D={}
G={}
with open(file,'r') as f:
for line in f:
L = line.split(' ')
qid = L[1][4:]
if qid not in D:
D[qid]=[]
G[qid]=[]
#ground truth
... | cad6525a9ae43f8366ae7e0efec14dd8b2921d27 | 19,793 |
import hashlib
import binascii
def private_key_to_WIF(private_key):
"""
Convert the hex private key into Wallet Import Format for easier wallet
importing. This function is only called if a wallet with a balance is
found. Because that event is rare, this function is not significant to the
main pipeline of the ... | 20e7a767fdfb689f586fc566a94ec37f86a88e52 | 19,794 |
def woodbury_solve_vec(C, v, p):
""" Vectorzed woodbury solve --- overkill
Computes the matrix vector product (Sigma)^{-1} p
where
Sigma = CCt + diag(exp(a))
C = D x r real valued matrix
v = D dimensional real valued vector
The point of this function is that you never h... | 875ab6709b82cd8865a4396b88cbd10a2847e608 | 19,795 |
def subsample(inputs, factor, scope=None):
"""Subsamples the input along the spatial dimensions.
Args:
inputs: A `Tensor` of size [batch, height_in, width_in, channels].
factor: The subsampling factor.
scope: Optional variable_scope.
Returns:
output: A `Tensor` of size [batch, height_out, width_ou... | 7e0cbcd5d709405b32ba79c93cbf1ef6e98195f6 | 19,796 |
def pvfactors_engine_run(data, pvarray_parameters, parallel=0, mode='full'):
"""My wrapper function to launch the pvfactors engine in parallel. It is mostly for Windows use.
In Linux you can directly call run_parallel_engine. It uses MyReportBuilder to generate the output.
Args:
data (pandas Da... | 1118838fed39e19e31997db9102fdba70283bed8 | 19,797 |
def get_service_button(button_text, service, element="#bottom_right_div"):
""" Generate a button that calls the std_srvs/Empty service when pressed """
print "Adding a service button!"
return str(render.service_button(button_text, service, element)) | ce8e2a0ec029762c4e19210c9986aef7e78b55d9 | 19,798 |
def create_train_test_set(data, labels, test_size):
"""
Splits dataframe into train/test set
Inputs:
data: encoded dataframe containing encoded name chars
labels: encoded label dataframe
test_size: percentage of input data set to use for test set
Returns:
data_train: Su... | ffeedf0cf4b7b8b1ffa552f0573d33263d216d99 | 19,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.