content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import OrderedDict
def unzip(zipped):
"""
Pull parameters from Theano shared variables
"""
new_params = OrderedDict()
for kk, vv in zipped.items():
new_params[kk] = vv.get_value()
return new_params | 44c3a60ba9401a7784ff7966a4d72d2731bf2952 | 68,000 |
from typing import Union
from typing import Callable
def divisible_shape(divisor: AxesLike, axes: AxesLike = None, padding_values: Union[AxesParams, Callable] = 0,
ratio: AxesParams = 0.5):
"""
Pads an incoming array to be divisible by ``divisor`` along the ``axes``. Afterwards the padding... | aba98b6bb298934df54bce73db7472516138088d | 68,001 |
def dQHIIdz(y, z,a,b,c,d): # specify the initial time point t0=0
""" Gives differential eq. for QHII """
theta=(a,b,c,d)
trec = 3.19e2*(1+z)**(-3.) * (3./hz.Ch2)#ch2=3
H0m1 = 9.77*hz.h**(-1) #9.77*h^-1 Gyr
dtdz = -H0m1*1./(1+z)*(hz.Om*(1+z)*... | 00f7ef76a8acb539db157c960ee7dac67b110302 | 68,002 |
def linear(z):
"""The linear activation function"""
return z | da2eaf35354f221461451dc343e37e5e59bad51b | 68,003 |
import torch
def sequence_mask(lens: torch.Tensor, max_len: int = None) -> torch.ByteTensor:
"""
Compute sequence mask.
Parameters
----------
lens : torch.Tensor
Tensor of sequence lengths ``[batch_size]``.
max_len : int, optional (default: None)
The maximum length (optional)... | 084a3e25026e1ea862ab5b6190a4fcc63ede8284 | 68,004 |
def pack_bin(in1):
"""
Pack binary arrary.
Data will be packed with little endian for NVIDIA GPU compatibility.
Parameters
----------
in1 : ndarray
The ndarray to be pack at binary.
Returns
-------
out : ndarray
An 1-dimensional array containing packed binary data.
... | a1bc15d18c51231c2bd34455219023ec3415702a | 68,005 |
def boltzman_average_bond_order(bond_orders):
"""
Calculate the Boltzmann weighted bond order average.
Parameters
----------
bond_orders: Dictionary of bond orders. The key is the energy of the molecule.
Returns
-------
bond_order_arrays: Dictionary of Boltzmann weighted bond orders.
... | 84d71bedc39492c0d59f2d2eef672fbe40fdeee5 | 68,006 |
def compare_mssim(x_true, x_pred, data_range, multidimension, detail=False):
"""
:param x_true:
:param x_pred:
:param data_range:
:param multidimension:
:return:
"""
mssim = [structural_similarity(x_true[:, :, i], x_pred[:, :, i], data_range=data_range, multidimension=multidimension)
... | ccedbe5404463d8eb20eea85a0414de888a5cad1 | 68,007 |
def get_slave_exception_by_error(error: HTTPError) -> SlaveResponseException:
"""
Overview:
Auto transform http error object to slave response exception object.
Arguments:
- error (:obj:`HTTPError`): Http error object
Returns:
- exception (:obj:`SlaveResponseException`): Slave re... | 1923001590fd1a76b055b10faeb68921940cb9b3 | 68,008 |
def model_run(config_data):
"""ModelRun built from config
"""
return ModelRun.from_dict(config_data) | d2705240adf9ddc58cfb43ab42c2de7144692a88 | 68,009 |
def post_user_stats(user_info): # noqa: E501
"""updates current user statistics count
# noqa: E501
:param user_info: Which os and platform is the user on.
:type user_info: dict | bytes
:rtype: None
"""
if user_info is not None:
(stat_id, windowsCount, macosCount, otherCount, isD... | 94db218445abbf1df729731a370389dfcea99bd0 | 68,010 |
def check_game_finish(board, mark):
"""Return boolean value is the game finished or not."""
if win_check(board, mark):
print(f'The player with the mark "{mark}" wins!')
return True
if full_board_check(PLAY_BOARD):
print('The game ended in a draw.')
return True
return Fa... | 3f9bb46ec7f72d63ebcadb2154b2789d0a69ffce | 68,011 |
from operator import inv
def generate_position_field(
affine,
velocity_fields,
velocity_field_resolution,
template_shape,
template_resolution,
target_shape,
target_resolution,
deform_to="template",
):
"""
Integrate velocity_fields and apply affine to produce a position field.
... | dde1ac017fc8d3a0eed804974e16ff949d09212e | 68,012 |
import random
def unique_random_string(model, field, length=16):
""" Generates a random alphanumeric string, unique in code field from a django class model
:param length: Length of the generated string.
:param model: Model class, it has a code field.
:param field: field name to be sure is unique.
... | 9e86acc92a2cfecbd14a37cea54698a1606dcfc4 | 68,013 |
def async_pipe(*args, **kwargs):
"""A processor that asynchronously extracts sub-elements from an item.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'path'. May
... | bc1bcdd44ad5dd4d9f78fd9f14909aeb2bcaecde | 68,014 |
def nature_cnn_lite(scaled_images, **kwargs):
"""
CNN from Nature paper.
:param scaled_images: (TensorFlow Tensor) Image input placeholder
:param kwargs: (dict) Extra keywords parameters for the convolutional layers of the CNN
:return: (TensorFlow Tensor) The CNN output layer
"""
activ = tf.... | b8282282d4ed0a91f7c3f022f41721fb65142cab | 68,015 |
def extractValue(value, attrVal, attrLang, ttlList):
"""
Helper for getAttributes. It decides which characters are added to the value.
For data properties: ""; for object properties: <>; for language tags: ""@<lang>
"""
if 'acdhi:' in value:
ttlList.append(' '.join([attrVal, value]))
eli... | 99607624d284918369061c8525f331e76b5c46a0 | 68,016 |
import os
import tempfile
def run_tiling(ds_or_path, **kwargs):
"""
Run the tiling process
:param ds_or_path: The :class:`gdal.Dataset` or a path to a file on disk to be tiled
:type ds_or_path: :class:`gdal.Dataset` or str
:param kwargs: Optional arguments.
:return: Creates the tiles in the g... | 1fd7af82cd606e0c8c321502dc2814d401c0b65e | 68,017 |
import os
import gzip
def getSTRINGMapping(source="BLAST_UniProt_AC", download=True, db="STRING"):
"""
Parses database (db) and extracts relationships between identifiers to order databases (source).
:param str url: link to download database raw file.
:param str source: name of the source database fo... | 6df91c15d81773907165da466cd56768e647ced0 | 68,018 |
def modify_instance_or_cluster_for_verify(database, sg_ids):
"""Modify an RDS Instance or Cluster to allow connections.
Args:
database (:class:`dbsnap.database.Database`): the database or cluster
to modify to allow access for verification routines.
sg_ids (list): Security group ids t... | 0f78e064b19b8d1bb2b032eaa13016608852d1b0 | 68,019 |
def time_between_shutdowns(loglines):
"""TODO 2:
Extract shutdown events ("Shutdown initiated") from loglines and
calculate the timedelta between the first and last one.
Return this datetime.timedelta object.
"""
shutdowns = [line for line in loglines if 'Shutdown initiated' in line]
... | 379e8e9b63f94c4f9feeb3fadddc577a5c996411 | 68,020 |
def numerordinatio_descendentibus(
numerordinatio: str, collectio: list, ordo_maximo: int = None) -> list:
"""numerordinatio_descendentibus _summary_
Trivia:
- collēctiō, s, f, , nominativus
- dēscendentibus, pl, m/f/n, , dativus,
https://en.wiktionary.org/wiki/descendens#Latin
- ō... | 8df7dbd5d24d51ffabf1f853e4aaa21adfcb474b | 68,021 |
from math import cos, sin
def general_rotation(x, y, z, a, b, c, u, v, w, angle):
""" Rotation about an arbitrary line
x,y,z : point to rotate
a,b,c : line through point
u,v,w : direction vector of the line (normalized)
angle : rotation angle in radians when looked down
the rotation ax... | bcf9f70556ca5c8123e9e83f0bb8215919151838 | 68,022 |
def get_option_block_info(block):
"""."""
os_name = sys_info.get_os_name()
block_info = {'names': []}
heads = get_heads(block)
item_blocks = get_blocks_by_heads(block, heads)
for item_block in item_blocks:
head = get_heads(item_block)[0]
item_block = remove_block_head(item_block... | b23112480429b869f2d8280fc28d463130516e1e | 68,023 |
def read_fasta(filepath, to_df = False):
"""
Read data from a fasta file.
Arguments
---------
filename : str, the path to a file in fasta format.
to_df : bool, should the function return a pandas dataframe
instead of a list of dicts? (default is False)
Returns
---------
out : list, a list of sequence... | 302c0940ea34a2817bfe7d6885fd0ebb30ffab7f | 68,024 |
import pbsmrtpipe.pb_io as IO
import itertools
import copy
import os
import uuid
def add_gather_to_completed_task_chunks(bg, chunk_operators_d, registered_tasks_d, tasks_root_dir):
"""Create the gathered.chunk.json by gathering the Chunked Task Instances.
1. Find all scattered task nodes
2. Find all the ... | 5c831e24dba299781989dab89b6bb87b43b387eb | 68,025 |
def pca_localized_set(patient_id):
"""Simplified API for setting clinical PCa localized status w/o FHIR
Requires simple JSON doc to set PCaLocalized diagnosis: '{"value": true}'
Raises 401 if logged-in user lacks permission to edit requested
patient.
---
operationId: setPCaLocalized
tags:... | 82cd55c265f5d18a253d0f840055240c8dd7ce2b | 68,026 |
def compute_min_altitude(height, field_of_regard):
"""
Fast computation of minimum altitude angle required to observe a point.
Args:
height (float): Height (meters) above surface of the observation.
field_of_regard (float): Angular width (degrees) of observation.
Returns:
float... | 69a47d85d42bb2f18a944e8ed7496e05394b6f08 | 68,027 |
import pickle
def load_params():
"""
Load parameters from file
"""
return pickle.load(open('params.p', mode='rb')) | 510b3663c0395a43e607cd46318af85719d3cbb7 | 68,028 |
import time
import calendar
def get_certificates(params, node, server):
"""Convert XML Certificates metric to ZabbixMetric
Return Zabbix packet elements.
"""
if params is None or node is None or server is None:
return None
p = []
try:
name = node.find('./m:name', NS).text
... | a7af2477bc6f37a58fd547e987a0519ff2b89b97 | 68,029 |
def parse_request_headers(headers):
"""
@param headers:
@return:
"""
request_headers_keys = set(headers.keys(lower=True))
request_meta_keys = set(XHEADERS_TO_ARGS_DICT.keys())
data_headers_keys = request_headers_keys.intersection(request_meta_keys)
return dict(([XHEADERS_TO_ARGS_DICT[key... | 860bc148273592374aa516867f2c149915aa33f6 | 68,030 |
def insertion_sort(arr):
"""Performs insertion sort of given IntsToSort"""
if len(arr) < 2:
return arr
if len(arr) > 1:
i = 1
while i < len(arr):
curr_val = arr[i]
j = i - 1
# Start with curr val and compare to all previous values
whil... | 0e8da20d1e5e958f8df73dc5e9e83a7bdf6d235b | 68,031 |
from datetime import datetime
def get_latest_news(channel, top=None, show_Body=False):
"""
获取即时新闻
Parameters
-------
channel: str, 待获取的新闻所在频道(id或名称)
top: int, 最多获取多少条新闻,默认None全获取
show_body: bool, 是否返回新闻正文,默认False不返回
Result
-------
pandas.DataFrame, 包括如下列:
... | 8fd63e151eafbd61919c3bea021a180196ace8ed | 68,032 |
def cartesian2spherical(m):
"""Convert from cartesian to spherical"""
# nC = int(len(m)/3)
x = m[:, 0]
y = m[:, 1]
z = m[:, 2]
a = (x**2.0 + y**2.0 + z**2.0) ** 0.5
t = np.zeros_like(x)
t[a > 0] = np.arcsin(z[a > 0] / a[a > 0])
p = np.zeros_like(x)
p[a > 0] = np.arctan2(y[a ... | ce9401177b5dc9ab4a7808c3153007bdc1e6c849 | 68,033 |
import unittest
def nightly_gpu():
"""
Nightly GPU tests.
Runs on CircleCI nightly, and when [gpu] or [long] appears in a commit string.
"""
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests/nightly/gpu')
test_suite = _circleci_parallelism(test_suite)
return... | c3fcbd224df17f6004b2281080a0fea2383a36c8 | 68,034 |
def robot_x_fn(state, u = None, dt=1.0):
"""
State update for nonlinear system
Computes next state using the non-linear dynamics
"""
x = state.value[0][0]
y = state.value[1][0]
theta = state.value[2][0]
v = state.value[3][0]
w = state.value[4][0]
x += v * cos(theta)*dt
y +=... | 7f08c22495947a26103973aa3401b4557aa0fd34 | 68,035 |
def default_resolution():
"""Note that this and the number of ts objects created below are fine tuned
for these tests to create just over a week of data, and changing them might
cause the tests to fail. See docstrings of tests for info"""
return 20 | eacfdecb06665c52930f959ea9ee0adfde2775c3 | 68,036 |
def dataframe_to_panel_by_colgroup(df,keylist,prefix='',surfix=''):
"""
transfer a dataframe into panel by separating the columns into different
groups by keywords.
Parameters:
-----------
keylist: a list of strings indicating the keylists used to group the
columns.
"""
if n... | ce3dd00c5b3ba6cdb59d7afa3e38eec258831f31 | 68,037 |
import torch
def embedding_similarity(
batch: torch.Tensor,
similarity: str = 'cosine',
reduction: str = 'none',
zero_diagonal: bool = True
) -> torch.Tensor:
"""
Computes representation similarity
Example:
>>> from pytorch_lightning.metrics.functional import embedding_similarity
... | dda82b8fa4dc4f3760a5c7ec329c77b980f3860c | 68,038 |
def non_independent_joint(a, operation, b):
"""非独立联合事件"""
if operation == 'and' or operation == MathSymbols.intersection:
return a * non_independent_joint(b, MathSymbols.condition, a) | b2bbd7968abc7066db16b7c3cf9aba340adcb83e | 68,039 |
def read_annotation_from_dataset(dataset: (list, tuple, dict), label_key):
"""reads the annotation from dataset. Basically reverting annotate.
Args:
dataset:
label_key:
Returns: annotation
>>> dataset = [{'timestamp': 0., 'audio_length': 1.}, {'timestamp': 2., 'audio_length': 5.}, {'t... | 099b6d288c46cae7ea984b51d6dde48d54983a32 | 68,040 |
def get_plots_figure(should_show_plots, should_write_movie):
"""
:param should_show_plots: Indicates whether the animation of SLAM should be plotted, in real time.
:param should_write_movie: Indicates whether the animation of SLAM should be written to a movie file.
:return: A figure if the plots should ... | 40498845559b794e4ad5def0012cb5af73d3f3b3 | 68,041 |
import requests
import tqdm
def stock_jgdy_tj_em(date: str = "20220101") -> pd.DataFrame:
"""
东方财富网-数据中心-特色数据-机构调研-机构调研统计
http://data.eastmoney.com/jgdy/tj.html
:param date: 开始时间
:type date: str
:return: 机构调研统计
:rtype: pandas.DataFrame
"""
url = "http://datacenter-web.eastmoney.com... | 21b567fa6a3a54f01217c9ed6751528a1eb7111a | 68,042 |
from typing import List
from typing import Dict
from typing import Any
def venue_author_representation(
venues: List[str], published_papers: List[Dict[str, Any]]
) -> np.ndarray:
"""Create an author vector representation based on the venues an author has published at.
The returned vector is N-dimensional... | 86191a749e97334b41b2be64c86efba93d57b723 | 68,043 |
def reconstruct_parallel2d(img, basis, ncores=8, algo=reconstruct_1Dmagic):
"""A simple wrapper to reconstruct 2D images assuming the lines are independent.
Careful, this wrapper consider the lines as independent reconstructions to be
performed.
Args:
- img (numpy 2d matrix mxN): input compressed m... | 3ea09038a5488a4e0a2c05db138ba470d2ea03a8 | 68,044 |
from typing import List
from typing import Dict
from typing import Any
import logging
import json
def entity2tag(token_list: List[str], entities: List[Dict[str, Any]]):
""" 将实体 entity 格式转为 tag 格式,若标注过程中有重叠标注,则会自动将靠后的
实体忽略、删除。针对单条处理,不支持批量处理。
Args:
token_list(List[str]): token 化的文本的 list
en... | 79c0d228da642013dfcbfa59aa2e317185e413c2 | 68,045 |
def results(domain):
"""."""
xn = XNTwist()
results = xn.twist(domain, simple=True)
return render_template('results.html', domain=domain, possible_squats=results['possible_squats'], count=results['count']) | 1d9119c5d845eff8ca94243b1bf65b90f3cf2746 | 68,046 |
import logging
import csv
def write_to_csv(incidents, fields_dict, filename, max_count=None, filter=None, in_log=None):
"""
Write incidents to a CSV file according to the field definition.
This function is factorized out intentionally for better unit test.
:param incidents: list of incidents in... | be8e2aabe1b0257ef6ca65d2e3107c046d02357b | 68,047 |
def add_cell_to_compute_node(compute_node, cell_name):
"""Fix compute_node attributes that should be unique. Allows
API cell to query the 'id' by cell@id.
"""
# NOTE(sbauza): As compute_node is a ComputeNode object, we need to wrap it
# for adding the cell_path information
compute_proxy = Compu... | 4821946a17c0104532c11cbcc1206ded691eb64e | 68,048 |
def im_detect_keypoints_scale(model, im, scale, max_size, boxes, hflip=False):
"""Computes keypoint predictions at the given scale."""
# Store the original scale
orig_scales = cfg.TEST.SCALES
orig_max_size = cfg.TEST.MAX_SIZE
# Perform detection at the given scale
cfg.TEST.SCALES = (scale, )
... | a1065619ec5f26dd488e80f8fcebf3806c376268 | 68,049 |
def bundle_archive(request, tmp_path):
"""
Prepare tar file from dir without using bundle packer
"""
return _pack_bundle(request.param, tmp_path) | 62639e6e1710bd525584168cc16631db2b92b19c | 68,050 |
import sys
def loadingFinder(load):
"""
"""
_load = str(load).lower()
_load = _load.replace(' ','')
_load = _load.replace('-','')
_load = _load.replace('_','')
_load = _load.strip()
#
_static = ['static']
_dyamic = ['dynamic']
#
if _load in _static : _type = 'static'
... | 7bf6cc738932f1b04dc0d7532302f7402437eaf1 | 68,051 |
def lmap(*args, **kwargs):
"""Take map generator and make a list for Python 3 work"""
return list(map(*args, **kwargs)) | 8c68edb2d4f26de6583b4bd8ae95722e2f911578 | 68,052 |
import os
def get_run_directory() -> str:
"""Returns the run directory for the current rank.
Returns:
str: The run directory.
"""
run_dir = os.path.join(get_node_run_directory(), f"rank_{dist.get_global_rank()}")
os.makedirs(run_dir, exist_ok=True)
return run_dir | 6af08b6b498fa21f8913fe021c3866e2033ea684 | 68,053 |
from typing import Optional
from typing import Union
def eckart(
vibfreq: float,
delta_forward: float,
delta_backward: Optional[float] = None,
temperature: Union[float, np.ndarray] = 298.15,
) -> Union[float, np.ndarray]:
"""Calculate the Eckart correction to quantum tunneling.
References are... | be808c3c5992b186834c806ccc9098c241faacd1 | 68,054 |
import json
from typing import OrderedDict
def _handle_response(response, feature_names, feature_names_accu):
"""Parse an elasticsearch response from requests into a feature vector.
Parameters
----------
response : dict
msearch responses
feature_names : list
feature names
feat... | 244c5e7d23f6978ac76bd9fa2a7fca48a05f37bb | 68,055 |
def is_space_element(level_element: LevelElement) -> bool:
"""Determines whether the object is a `Space` level element or not."""
return isinstance(level_element, Space) | ec37c917206b1a0b423f43421c5c325363f770ec | 68,056 |
import os
def decide_verifier(file, szexe=None):
"""
Decide which verifier function to use.
:param file: Filename.
:type file: str
:param szexe: Path to 7z executable, if needed.
:type szexe: str
"""
print("VERIFYING: {0}".format(file))
if file.endswith(".7z") and szexe is not No... | 56fdf039d15bac3df29ba8c0320940f7fc600b29 | 68,057 |
def fib(n):
"""
Computing the nth of Fib series
Implemetation focusing on 1 time running of fib.
"""
memoire = [0] * 100
def rec_fib(n):
if n == 1 or n == 2:
memoire[n-1] = 1
return 1
else:
if memoire[n - 1] == 0:
mem... | dfeae222af315c55a1010ce73857a8925f20d837 | 68,058 |
def cfg_get(cfgfile,item,delimiter,detail=False, config=None):
"""Get value of a config item.
"""
if not config: config = loadconfig(cfgfile,delimiter,detail=detail)
if config.has_key(item):
return config[item]
else:
return None | 871026fe9896e111f7985ef6d212d0706ef8b72e | 68,059 |
def Find(string1, string2):
"""Looks for a substring inside a specified string."""
return NexRun("Find", locals()) | 79a1712b09953b73eb7bd83f359d993971e640d6 | 68,060 |
def sort_tables(tables, skip_fn=None, extra_dependencies=None):
"""sort a collection of Table objects in order of
their foreign-key dependency."""
tables = list(tables)
tuples = []
if extra_dependencies is not None:
tuples.extend(extra_dependencies)
def visit_foreign_key(fk... | 3a6e3328ff38cb30b68a2d401834ded009f1ef39 | 68,061 |
def RNA_to_AA(numeric_columns):
"""
Translate an RNA codon to its corresponding amino acid
"""
return translation[codon] | 2cc58c83c0caee1f35487d0e6130e689320461e8 | 68,062 |
def remove_stopwords(text, swords=None):
"""Remove stopwords
"""
if swords is None:
swords = stopwords.words('english')
words = wordpunct_tokenize(text)
words = [w for w in words if w not in swords]
text = ' '.join(words)
return text | 797174c38c6acb58e298e37e6681f34188af6be2 | 68,063 |
def u2_(U1, h=1., z1=2., z2=10.): # pragma: no cover
"""
:param xU1: measurement at one height
:param xh: canopy height (m)
:param xz: measurement height (m)
:return u2: wind at another height
"""
zo = zo_(h)
d = d_(h)
return U1*(log((z2 - d) / zo))/(log((z1 - d) / zo)) | c551962b912fa2f173a1c3087baf6342c47c57fe | 68,064 |
def build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate:
"""Fail for edges with citations whose references are one of the given PubMed identifiers.
:param pmids: A PubMed identifier or list of PubMed identifiers to filter against
"""
return invert_edge_predicate(build_pmid_inclusion_filter(pmi... | 719f185c4f1982152e4f89fce7f08df467c47867 | 68,065 |
def onboarding_ml_app_patterns_get(): # noqa: E501
"""Get list of all MLApp patterns
# noqa: E501
:rtype: List[MLAppPattern]
"""
return 'do some magic!' | 25be7fd2797eb7a3e8fd7d5cb41e88dd7c607a7d | 68,066 |
def extractMask(video_masks, frame_time):
"""
Extract one mask from a group of videomasks given the frame_time
:param video_masks:
:param frame_time: time or frame number
:return:
"""
extract_time_tuple = tool_set.getMilliSecondsAndFrameCount(frame_time, defaultValue=(0, 1))
timeManager... | bc37d1dc576e3e0e0a290dfa8d77831f9d820ca6 | 68,067 |
import tempfile
import os
import subprocess
def run_c_source(src, cflags):
"""
Compile and run C source code
:param src: the c language code to run
:param cflags: additional cflags passing to compiler
:return:
"""
binname = tempfile.mktemp(prefix="mbedtls")
fd, srcname = tempfile.mkste... | 26275e219e07c48ddb7649ca9618b70f2eb10b0e | 68,068 |
def FormatArguments(*args, **kwargs):
"""Format function call arguments in a human-readable way for logging."""
def _FormatArg(arg):
return FormatLogArgument(arg)
# Truncate arguments.
args = [_FormatArg(arg) for arg in args]
kwargs = {key: _FormatArg(value) for key, value in kwargs.items()}
return "(... | 3a9b2e84b717db75a9502f73553ba85dfbc7933f | 68,069 |
def _fetchUnicodes(glif):
"""
Get a list of unicodes listed in glif.
"""
parser = _FetchUnicodesParser()
parser.parse(glif)
return parser.unicodes | 271a84f979d8725845ee82dcd13a752010da2851 | 68,070 |
from datetime import datetime
def login_user():
"""
Function to check the user credentials. If they are correct, then generate a valid JWT token
and return it.
:return: status of the request or the user token
"""
# if the request doesn't have a Basic Authentication header, then discard it
... | b5404905f916c869e3b8a5d0fc0a8b6fe7830fc6 | 68,071 |
def plot3d(*args, **kwargs):
""" Create a 3D surface plot of the specified 2D array (matrix).
Plot3D image(surface): surface is a 2D array (matrix).
Plot3D image(x, y, surface): surface is a 2D array (matrix); x and y are matrices of the same size that provide the x and y coordinates.
x and y are expect... | d8e1a1262867981f21e671e8914938e8373486a0 | 68,072 |
def run_county(fips):
"""
Run the R_t inference for each county in a state.
Parameters
----------
fips: str
County fips to run against
"""
if not fips:
return None
df = RtInferenceEngine.run_for_fips(fips)
county_output_file = get_run_artifact_path(fips, RunArtifact... | 7124b9ee9f78d0267141d437971c3770b2999ce3 | 68,073 |
def parse_test_names( filedoc ):
"""
Determine the test name and check for validity. If this XML file is not
an "rtest" then returns None. Otherwise returns a list of test names.
"""
if filedoc == None or filedoc.getName() != "rtest":
return []
# determine the test name
name = fi... | 461a1f81db109a8527f4e91e1925242ea073b309 | 68,074 |
def get_files(path, keywords = ["features_ OR msd_"]):
"""
Takes in a path and list of keywords. Returns a list of filenames
that are within the path that contain one of the keyword in the list.
Set keyword to "" to get all files in the path.
Parameters
----------
path : string
file... | 7f6ad0d2785c5646426bc8c17fdb3ea09762a4db | 68,075 |
def EndOfBatches() -> Data:
"""Construct a 'end of batches' marker."""
return Data(graph_ids=[], data=None, end_of_batches=True) | 50003d6ae1a379ce55a931d9843e488fa2bf7bfe | 68,076 |
def GetClientInstance(release_track=base.ReleaseTrack.GA, use_http=True):
"""Returns an instance of the Cloud Build client.
Args:
release_track: The desired value of the enum
googlecloudsdk.calliope.base.ReleaseTrack.
use_http: bool, True to create an http object for this client.
Returns:
base... | 95b156e8de65a8c51f851f204553f419c9d86eac | 68,077 |
def driver_fixture(client, controller_state):
"""Return a driver instance with a supporting client."""
return Driver(client, controller_state) | 8e706ba9e9704b9ea9803355f8e5d36f18db2b9b | 68,078 |
import math
def project_onto_ball(positions, head_position, radius):
"""
params: positions: 3-d numpy array, the original positions collected from unity
params: head_position: 3-d numpy array, the center of fitting sphere
params: radius: float, radius of the sphere
return:
"""
new_position... | 87ee065a30f434def3a742614fd5588d68a31720 | 68,079 |
def authorize_twitter():
"""Authorize a user's Twitter account."""
TWITTER_REDIRECT_URL = url_for("get_twitter_token", _external=True)
twitter_oauth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,
TWITTER_CONSUMER_SECRET,
TWITTER_RE... | 22ab6ccf2c28a45d30b5c4446468c4b16e429102 | 68,080 |
import warnings
def preprocess_dataset(X, y = None):
"""
Performs feature scaling, one-hot encoding of labels and shuffles the data if labels are provided.
Assumes original dataset is sorted by labels.
Parameters
----------
X : ndarray
Dataset array c... | e3da84cbb8779350858d193c97fea418a2a3bdf2 | 68,081 |
def tenant_user_admin(db) -> TenantUser:
"""Returns Admin User instance."""
with schema_context('public'):
return TenantUser.objects.create_superuser(
_USER_PASS,
email='super@user.com',
) | 602b6eff13587f56d38ef5982d0a391fd20c42d7 | 68,082 |
def ht_is_filled(x, y, intensity):
"""Returns 1 if halftone pixel is black, 0 if white"""
return bayer_4x4[x&3][y&3] > intensity | eaa7781b5d7e8728dc3a17314e683901aea0c129 | 68,083 |
from typing import OrderedDict
def _raw_at_zoom(config, zooms):
"""Return parameter dictionary per zoom level."""
params_per_zoom = OrderedDict()
for zoom in zooms:
params = OrderedDict()
for name, element in config.items():
if name not in _RESERVED_PARAMETERS:
... | c4af99390f0994637f80130767c2caa5395d9d63 | 68,084 |
import itertools
def get_adj_list(cities_file):
"""Return a list of adjacencies (assuming all city-to-city edges are
feasible) along with the length of each edge (in km).
"""
cities = load_cities(cities_file)
return itertools.combinations(cities, 2) | 876b84fde5b715e2ba6d74312c35430261f82719 | 68,085 |
from typing import Set
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction:
"""Convert a floating point number to a Fraction with a small
denominator.
Args:
flt: A floating point number
denominators: Collection of standard denominators. Default is
... | 78182602c0892efb7b4b4b5fd17e0f348c0c8e19 | 68,086 |
import json
import types
def async_transcribe(id):
"""
Transcribe the given audio file asynchronously and output the word time
offsets.
"""
file_metadata = json.loads(get_file_metadata(id))
client = speech.SpeechClient()
audio = types.RecognitionAudio(uri=file_metadata['uri'])
config ... | fbd6837ce08e375bb9a79ac4439e8e11f8769cbc | 68,087 |
def filtermed_image(data, border=10, filter_size=2):
"""Process image by removing the borders
and filtering it via a median filter
Input
-----
data: 2d array
Array to be processed
border: int
Number of pixels to remove at each edge
filter_size: float
Size of the... | 968e5e618ee38e7d8d34c080b8a122387d0d91ed | 68,088 |
def has_deco(deconames, tree, userlambdas=[]):
"""Return whether a FunctionDef or a decorated lambda has any given deco applied.
deconames: list of decorator names to test.
userlambdas: list of ``id(some_tree)``; when detecting a lambda,
only consider it if its id matches one of those in the list.
... | d4473c568609f9f6fa74331a06fc33652bc7d2b5 | 68,089 |
from io import StringIO
import csv
import requests
def show_redbull_history_csv(message):
"""RedBullの月単位の消費履歴をCSVに出力する
:param message: slackbotの各種パラメータを保持したclass
"""
s = Session()
consume_hisotry = (s.query(RedbullHistory)
.filter(RedbullHistory.delta < 0)
... | b14f71ae30aae80fda05c03231b46b298433d783 | 68,090 |
from typing import List
def find_closest_indices(values: List[float], target_values: List[float]) -> List[int]:
"""
Finds the indices in ``values`` that result in values closest to ``target_values``.
"""
closest_indices = [(np.abs(values - target_value)).argmin() for target_value in target_values]
... | 3ada38e221cfa6ad0e9bdc10c413657066d0552c | 68,091 |
def shades(name: str):
"""Create motorized shades with given name."""
return {
"name": name,
"type": DeviceType.MOTORIZED_SHADES,
"actions": ["Open", "Close", "Hold"],
} | 87785cc24988c4b7cea7c2d2bfa1da891a56a48a | 68,092 |
def count_comparison(combined_df):
"""
Provides a DataFrame that compares counts of growthcleanr categories between runs.
Parameters:
combined_df: A DataFrame in the format provided by prepare_for_comparison
Returns:
A DataFrame where the categories are the index and the columns are the run names.
"""
... | 1bbbec1cf0bc1710a53bd504eb094ff8fbc99db0 | 68,093 |
def get_decimalized_value(fact_a, fact_b, xule_context):
"""Adjust 2 fact values based on accuracy.
:param fact_a: First fact
:type fact_a: ModelFact
:param fact_b: Second fact
:type fact_b: ModelFact
:returns: A tuple of the rounded fact values and the new decimals value for each
:rtyp... | f93b206bf6a9f2fe105f5f7bce84d40beed858d7 | 68,094 |
def max_minimum_allocation_for_families(instance, families) -> AllocationToFamilies:
"""
Find the max-minimum (aka Egalitarian) allocation.
:param agents: a matrix v in which each row represents an agent, each column represents an object, and v[i][j] is the value of agent i to object j.
:param families:... | 15659845a7b6779e58b25daf8b877edb3e9112dd | 68,095 |
def _get_matching_coords(coords, params, shape):
"""
Get the matching coords across a number of broadcast operands.
Parameters
----------
coords : list[numpy.ndarray]
The input coordinates.
params : list[Union[bool, none]]
The broadcast parameters.
Returns
-------
nu... | a9c6618c5d7846af006be53f00ab2193c5318fab | 68,096 |
def decode(daq_path, dataset):
"""
Converts char array into readible strings from the daq.
Inputs:
dataset (str): '/' seperated directory path to to_dataset
Returns:
list of strings contained in the dataset
"""
with h5py.File(daq_path, 'r') as f:
try:
strs =... | c194ad3d2c08b30f1493474da647055c1f421650 | 68,097 |
def run_process(cmd_args, cwd=None):
"""Runs the given process and returns its output and exit code.
"""
try:
return subprocess.check_output(cmd_args, stderr=subprocess.STDOUT, cwd=cwd), 0
except subprocess.CalledProcessError, e:
return e.output, e.returncode | 67b696732afbabf1ec7ff0dc387684bdba3ddbb1 | 68,098 |
from operator import inv
def generate_normals(m,P):
"""
Generate a Gaussian sample
with mean m and precision P
Parameters
----------
m array of shape n: the mean vector
P array of shape (n,n): the precision matrix
Returns
-------
ng : array of shape(n): a draw from th... | 67176faa04e260f238b1dd3ab36a6f455cf49b68 | 68,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.