content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def polinomsuzIntegralHesapla(veriler):
"""
Gelen verileri kullanarak integral hesaplar.
:param veriler: İntegrali hesaplanacak veriler. Liste tipinde olmalı.
"""
a,b=5,len(veriler)
deltax = 1
integral = 0
n = int((b - a) / deltax)
for i in range(n-1):
integral += deltax * (v... | 468e02da8ff077b04456f71f0af6d77bf5a47d68 | 3,646,013 |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return... | 009233e381e2015ff4d919338225057d94d40a82 | 3,646,014 |
from typing import Dict
def make_all_rules(
schema: "BaseOpenAPISchema", bundles: Dict[str, CaseInsensitiveDict], connections: EndpointConnections
) -> Dict[str, Rule]:
"""Create rules for all endpoints, based on the provided connections."""
return {
f"rule {endpoint.verbose_name}": make_rule(
... | 3b92fdea984b5bfbe2b869640b978398106f098b | 3,646,015 |
def audio_to_magnitude_db_and_phase(n_fft, hop_length_fft, audio):
"""This function takes an audio and convert into spectrogram,
it returns the magnitude in dB and the phase"""
stftaudio = librosa.stft(audio, n_fft=n_fft, hop_length=hop_length_fft)
stftaudio_magnitude, stftaudio_phase = librosa.magp... | b9927f11bc353610fe7edbee9b710bd78fc13899 | 3,646,016 |
def has_rc_object(rc_file, name):
"""
Read keys and values corresponding to one settings location
to the qutiprc file.
Parameters
----------
rc_file : str
String specifying file location.
section : str
Tags for the saved data.
"""
config = ConfigParser()
try:
... | e7edd4ba8545257d7d489a7ac8f6e9595b4f087d | 3,646,018 |
import torch
def apply_transform_test(batch_size, image_data_dir, tensor_data_dir, limited_num = None, shuffle_seed = 123, dataset = None):
"""
"""
std = [1.0, 1.0, 1.0]
mean = [0.0, 0.0, 0.0]
# if dataset is None:
# std = [1.0, 1.0, 1.0]
# mean = [0.0, 0.0, 0.0]
# elif dataset... | 664e9fadeb4897aee7ef26abeec9c128ec7cef56 | 3,646,019 |
def take_t(n):
"""
Transformation for Sequence.take
:param n: number to take
:return: transformation
"""
return Transformation(
"take({0})".format(n), lambda sequence: islice(sequence, 0, n), None
) | 1e485cc59160dbec8d2fa3f358f51055115eafdd | 3,646,021 |
def metric_fn(loss):
"""Evaluation metric Fn which runs on CPU."""
perplexity = tf.exp(tf.reduce_mean(loss))
return {
"eval/loss": tf.metrics.mean(loss),
"eval/perplexity": tf.metrics.mean(perplexity),
} | 3614ed0ccc3e390aeaf4036805dfeff351d4d150 | 3,646,022 |
def gensig_choi(distsmat, minlength=1, maxlength=None, rank=0):
""" The two dimensional sigma function for the c99 splitting """
if rank:
distsmat = rankify(distsmat, rank)
def sigma(a, b):
length = (b - a)
beta = distsmat[a:b, a:b].sum()
alpha = (b - a)**2
if minlen... | 75568f854eff9c3bbc13b4a46be8b1a2b9651b9b | 3,646,023 |
from typing import Optional
def check_ie_v3(base, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
s = sum((w * int(c) for w, c in zip(range(8, 1, -1), base)),
9 * (ord(add) - ord('@'))) # 'A' - 'I' -> 1 - 9
i = s % 23
return _IE_CC_MAP[i] | 19fd495db8301ed7193881cc637e3ce1b75e368c | 3,646,024 |
def filter_experiment_model(faultgroup, faultmodel, interestlist=None):
"""
Filter for a specific fault model. If interestlist is given only experiments
in this list will be analysed.
0 set 0
1 set 1
2 Toggle
"""
if not isinstance(faultmodel, int):
if "set0" in faultmodel:
... | 7594f7f5a410c3bf9231996989259d1267ed250b | 3,646,025 |
import inspect
def _default_command(cmds, argv):
"""Evaluate the default command, handling ``**kwargs`` case.
`argparse` and `argh` do not understand ``**kwargs``, i.e. pass through command.
There's a case (`pykern.pkcli.pytest`) that requires pass through so we wrap
the command and clear `argv` in t... | aecaaba610ec473b41f1cd546cb5c551541d9fab | 3,646,027 |
def nameable_op(node_factory_function): # type: (Callable) -> Callable
"""Set the name to the ngraph operator returned by the wrapped function."""
@wraps(node_factory_function)
def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Node
node = node_factory_function(*args, **kwargs)
node = ... | 0230c96e40b91772dc06a0b2c9cf358d1e0b08c7 | 3,646,029 |
import re
def by_pattern(finding: finding.Entry, ignore: ignore_list.Entry) -> bool:
"""Process a regex ignore list entry."""
# Short circuit if no pattern is set.
if not ignore.pattern:
return False
# If there's a match on the path, check whether the ignore is for the same module.
if re.... | bbeb7d8ab740273bd21c120ca7bc42dc205e4a2b | 3,646,031 |
def hex2int(s: str):
"""Convert a hex-octets (a sequence of octets) to an integer"""
return int(s, 16) | ecdb3152f8c661c944edd2811d016fce225c3d51 | 3,646,032 |
from operator import index
def into_two(lhs, ctx):
"""Element I
(num) -> push a spaces
(str) -> equivlaent to `qp`
(lst) -> split a list into two halves
"""
ts = vy_type(lhs, simple=True)
return {
NUMBER_TYPE: lambda: " " * int(lhs),
str: lambda: quotify(lhs, ctx) + lhs,
... | 6fae5eb7c5ae58a0e7faef6e46334201ccc6df10 | 3,646,033 |
def find_renter_choice(par,sol,t,i_beta,i_ht_lag,i_p,a_lag,
inv_v,inv_mu,v,mu,p,valid,do_mu=True):
""" find renter choice - used in both solution and simulation """
v_agg = np.zeros(2)
p_agg = np.zeros(2)
# a. x
iota_lag = -1
i_h_lag = -1
LTV_lag = np.nan
_m... | f6cffb4ce6ed3ddaa98edefefdb6962536fbffb8 | 3,646,034 |
def met_zhengkl_gh(p, rx, cond_source, n, r):
"""
Zheng 2000 test implemented with Gauss Hermite quadrature.
"""
X, Y = sample_xy(rx, cond_source, n, r)
rate = (cond_source.dx() + cond_source.dy()) * 4./5
# start timing
with util.ContextTimer() as t:
# the test
zheng_gh = cgo... | 41bef090ccc515be895bd08eda451864c330327e | 3,646,035 |
from typing import Optional
from typing import Sequence
def get_domains(admin_managed: Optional[bool] = None,
include_unverified: Optional[bool] = None,
only_default: Optional[bool] = None,
only_initial: Optional[bool] = None,
only_root: Optional[bool] =... | e7cb3a42ec7be45153c67d860b4802669f8043e5 | 3,646,036 |
import six
def get_writer(Writer=None, fast_writer=True, **kwargs):
"""
Initialize a table writer allowing for common customizations. Most of the
default behavior for various parameters is determined by the Writer class.
Parameters
----------
Writer : ``Writer``
Writer class (DEPRECA... | 0e51b930d90585905b37ddd585cdfd53de111aa9 | 3,646,037 |
def find_last_service(obj):
"""Identify last service event for instrument"""
return Service.objects.filter(equipment=obj).order_by('-date').first() | 5c7c74b376568fc57268e8fe7c1970c03d61ad2c | 3,646,038 |
def SectionsMenu(base_title=_("Sections"), section_items_key="all", ignore_options=True):
"""
displays the menu for all sections
:return:
"""
items = get_all_items("sections")
return dig_tree(SubFolderObjectContainer(title2=_("Sections"), no_cache=True, no_history=True), items, None,
... | ea3766d923337e1dffc07dec5e5d042e2c85050c | 3,646,039 |
def perform_save_or_create_role(is_professor, created_user, req_main, is_creating):
"""Performs update or create Student or Professor for user"""
response_verb = 'created' if is_creating else 'updated'
if is_professor is True:
professor_data = None
if 'professor' in req_main.keys():
... | 6161aaf886b31209a8387426f812cda73b739df2 | 3,646,040 |
def ecg_rsp(ecg_rate, sampling_rate=1000, method="vangent2019"):
"""Extract ECG Derived Respiration (EDR).
This implementation is far from being complete, as the information in the related papers
prevents me from getting a full understanding of the procedure. Help is required!
Parameters
---------... | ec4ecdbf4489216124ef82399c548461968ca45b | 3,646,041 |
def bootstrap(request):
"""Concatenates bootstrap.js files from all installed Hue apps."""
# Has some None's for apps that don't have bootsraps.
all_bootstraps = [(app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name)]
# Iterator ov... | 94be21562c383ad93c7a0530810bb08f41f3eb26 | 3,646,042 |
def get_selection(selection):
"""Return a valid model selection."""
if not isinstance(selection, str) and not isinstance(selection, list):
raise TypeError('The selection setting must be a string or a list.')
if isinstance(selection, str):
if selection.lower() == 'all' or selection == '':
... | 996d0af844e7c1660bcc67e24b33c31861296d93 | 3,646,043 |
def getAllImageFilesInHierarchy(path):
"""
Returns a list of file paths relative to 'path' for all images under the given directory,
recursively looking in subdirectories
"""
return [f for f in scan_tree(path)] | 821147ac2def3f04cb9ecc7050afca85d54b6543 | 3,646,044 |
def list_package(connection, args):
"""List information about package contents"""
package = sap.adt.Package(connection, args.name)
for pkg, subpackages, objects in sap.adt.package.walk(package):
basedir = '/'.join(pkg)
if basedir:
basedir += '/'
if not args.recursive:
... | 7c8e0cb8a6d5e80a95ae216ad2b85309f0b4d45c | 3,646,045 |
def calc_hebrew_bias(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: gender bias in corpus
"""
bias = 0
for idx in range(0, len(probs), 16):
bias -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
bias += probs[idx + 2] +... | 565be51b51d857c671ee44e090c5243e4d207942 | 3,646,046 |
import pickle
def load_wiki(size = 128, validate = True):
"""
Return malaya pretrained wikipedia ELMO size N.
Parameters
----------
size: int, (default=128)
validate: bool, (default=True)
Returns
-------
dictionary: dictionary of dictionary, reverse dictionary and vectors
"""... | 6daaa592000f8cb4ac54632729bda60c7325548d | 3,646,047 |
def generate_pibindex_rois_fs(aparc_aseg):
""" given an aparc aseg in pet space:
generate wm, gm and pibindex rois
make sure they are non-overlapping
return 3 rois"""
wm = mask_from_aseg(aparc_aseg, wm_aseg())
gm = mask_from_aseg(aparc_aseg, gm_aseg())
pibi = mask_from_aseg(aparc_aseg, pibi... | 35023b9084bb90f6b74f3f39b8fd79f03eb825d9 | 3,646,048 |
import logging
def rescale(img, mask, factor):
"""Rescale image and mask."""
logging.info('Scaling: %s', array_info(img))
info = img.info
img = ndimage.interpolation.zoom(img, factor + (1,), order=0)
info['spacing'] = [s/f for s, f in zip(info['spacing'], factor)]
mask = rescale_mask(mask, fac... | 9f8676a34e58eec258227d8ba41891f4bab7e895 | 3,646,051 |
def get_data_all(path):
"""
Get all data of Nest and reorder them.
:param path: the path of the Nest folder
:return:
"""
nb = count_number_of_label(path+ 'labels.csv')
data_pop = {}
for i in range(nb):
label, type = get_label_and_type(path + 'labels.csv', i)
field, data =... | 94409d671b287ce213088817a4ad41be86126508 | 3,646,052 |
def from_tfrecord_parse(
record,
pre_process_func=None,
jpeg_encoded=False):
"""
This function is made to work with the prepare_data.TFRecordWriter class.
It parses a single tf.Example records.
Arguments:
record : the tf.Example record with the features of
... | 2e32accfe7485058fa4aff7c683265b939184c94 | 3,646,053 |
import json
import re
def reader_json_totals(list_filenames):
"""
This reads the json files with totals and returns them as a list of dicts.
It will verify that the name of the file starts with totals.json to read it.
This way, we can just send to the function all the files in the directory and it wil... | 57f27dbb3eabee014a23449b7975295b088b5e72 | 3,646,056 |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | c039c0535823edda2f66c3e445a5800a9890f155 | 3,646,057 |
def index_of_first_signal(evt_index, d, qsets, MAXT3):
""" Check the evt_index of the last signal triplet (MC truth).
Args:
Returns:
"""
first_index = -1
k = 0
for tset in qsets:
for ind in tset: # Pick first of alternatives and break
#[HERE ADD THE OPTION TO CHOOSE ... | cd156faceaf3cf3261b2ba217cda5a6c0e3ce4b8 | 3,646,058 |
import numpy
def readcrd(filename, REAL):
"""
It reads the crd file, file that contains the charges information.
Arguments
----------
filename : name of the file that contains the surface information.
REAL : data type.
Returns
-------
pos : (Nqx3) array, positions of the... | efafc2e53eebeacbe6a1a5b1e346d0e121fa7a62 | 3,646,059 |
def load_and_initialize_hub_module(module_path, signature='default'):
"""Loads graph of a TF-Hub module and initializes it into a session.
Args:
module_path: string Path to TF-Hub module.
signature: string Signature to use when creating the apply graph.
Return:
graph: tf.Graph Graph of the module.
... | b04b5f77c7e0207d314ebb5910ec1c5e61f4755c | 3,646,060 |
def get_mention_token_dist(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1.tokens[0].doc_index < m2.tokens[0].doc_index
first = m1 if succ else m2
second = m2 if succ else m1
return max(0, second.tokens[0].doc_index - first.tokens[-1].doc_index) | 84052f805193b1d653bf8cc22f5d37b6f8de66f4 | 3,646,061 |
def shlcar3x3(x,y,z, ps):
"""
This subroutine returns the shielding field for the earth's dipole, represented by
2x3x3=18 "cartesian" harmonics, tilted with respect to the z=0 plane (nb#4, p.74)
:param x,y,z: GSM coordinates in Re (1 Re = 6371.2 km)
:param ps: geo-dipole tilt angle in radius.
... | 5729e0999ddefaf2ee39ad9588009cc58f983130 | 3,646,062 |
def raan2ltan(date, raan, type="mean"):
"""Conversion to True Local Time at Ascending Node (LTAN)
Args:
date (Date) : Date of the conversion
raan (float) : RAAN in radians, in EME2000
type (str) : either "mean" or "true"
Return:
float : LTAN in hours
"""
if type == ... | 90956203d7b5787f5d49941f89b7871d021e5e74 | 3,646,063 |
def _extract_bbox_annotation(prediction, b, obj_i):
"""Constructs COCO format bounding box annotation."""
height = prediction['eval_height'][b]
width = prediction['eval_width'][b]
bbox = _denormalize_to_coco_bbox(
prediction['groundtruth_boxes'][b][obj_i, :], height, width)
if 'groundtruth_area' in pred... | c79a066b719e33704d50128f4d01420af0be27ce | 3,646,064 |
def value_and_entropy(emax, F, bw, grid_size=1000):
"""
Compute the value function and entropy levels for a θ path
increasing until it reaches the specified target entropy value.
Parameters
==========
emax: scalar
The target entropy value
F: array_like
The policy function t... | c9b215d91c6a0affbb4ad8f344614a1f2b6b9a13 | 3,646,065 |
def _biorthogonal_window_loopy(analysis_window, shift):
"""
This version of the synthesis calculation is as close as possible to the
Matlab implementation in terms of variable names.
The results are equal.
The implementation follows equation A.92 in
Krueger, A. Modellbasierte Merkmalsverbesser... | 5fc5dd23cb0b01af93a02812210d3b44b2fe84ab | 3,646,067 |
def depthwise(data, N, H, W, CI, k_ch, KH, KW, PAD_H, PAD_W, SH, SW, block_size, use_bias=False):
"""
Depthwise 5-D convolutions,every channel has its filter-kernel
Args:
data (list):a list,the size is 3 if use_bias else the size is 2;
data[0] tvm.tensor.Tensor of type float16 ,shape ... | c47ef1cc929ecc9b26550f1eabe1e52073b82028 | 3,646,068 |
def FindDescendantComponents(config, component_def):
"""Return a list of all nested components under the given component."""
path_plus_delim = component_def.path.lower() + '>'
return [cd for cd in config.component_defs
if cd.path.lower().startswith(path_plus_delim)] | f9734442bbe3a01460970b3521827dda4846f448 | 3,646,070 |
def _get_source(loader, fullname):
"""
This method is here as a replacement for SourceLoader.get_source. That
method returns unicode, but we prefer bytes.
"""
path = loader.get_filename(fullname)
try:
return loader.get_data(path)
except OSError:
raise ImportError('source not ... | af43b79fa1d90abbbdb66d7d1e3ead480e27cdd1 | 3,646,071 |
from pathlib import Path
def get_source_files(sf: Path) -> list:
"""
Search for files ending in .FLAC/.flac and add them to a list.
Args:
sf (str/pathlib.Path): Folder location to search for files.
Returns:
list: List of file locations found to match .FLAC/.fladc.
"""
return ... | 3828d81528b144367c3d5a74ee212caf2a01b111 | 3,646,072 |
import io
def extract_features(clip):
"""
Feature extraction from an audio clip
Args:
clip ():
Returns: A list of feature vectors
"""
sr, clip_array = wav_read(io.BytesIO(clip))
if clip_array.ndim > 1:
clip_array = clip_array[:, 0]
segments = frame_breaker.get_frames(... | 13c6c18be92067847eaabada17952a0dab142a3f | 3,646,073 |
def comparison_func(target: TwoQubitWeylDecomposition,
basis: TwoQubitBasisDecomposer,
base_fid: float,
comp_method: str):
"""
Decompose traces for arbitrary angle rotations.
This assumes that the tq angles go from highest to lowest.
... | a222138a8c3a01aaf6c3657c6bbbaca284332b76 | 3,646,074 |
from bs4 import BeautifulSoup
def create_bs4_obj(connection):
"""Creates a beautiful Soup object"""
soup = BeautifulSoup(connection, 'html.parser')
return soup | b3956b13756e29cd57a0e12457a2d665959fb03d | 3,646,075 |
def __create_dataframe_from_cassandra(query,con):
"""
Function to query into Cassandra and Create Pandas DataFrame
Parameter
---------
query : String - Cassandra Query
con : cassandra connection object
Return
------
df : pd.DataFrame - DataFrame created using the ... | af839ce372af100b4a496350ed6e21ae12b82444 | 3,646,076 |
from typing import List
from typing import Tuple
from typing import Optional
import ssl
from typing import Iterable
from typing import Union
async def post(
url: str,
content: bytes,
*,
headers: List[Tuple[bytes, bytes]] = None,
loop: Optional[AbstractEventLoop] = None,
... | 8aa95bb43f3937ea09ffa0a55b107bf367ffa5bc | 3,646,078 |
import toml
def parse_config_file(path):
"""Parse TOML config file and return dictionary"""
try:
with open(path, 'r') as f:
return toml.loads(f.read())
except:
open(path,'a').close()
return {} | 599164f023c0db5bffa0b6c4de07654daae1b995 | 3,646,079 |
def wordnet_pos(tag):
"""
Transforms nltk part-of-speech tag strings to wordnet part-of-speech tag string.
:param tag: nltk part-of-speech tag string
:type: str
:return: the corresponding wordnet tag
:type: wordnet part-of-speech tag string
"""
return getattr(nltk_wordnet_pos_dict, tag[0... | 66b915cb63036553d765af5474d690ea4e0f3859 | 3,646,080 |
import requests
def call_telegram_api(function: str, data: dict):
"""Make a raw call to Telegram API."""
return requests.post(
f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/{function}', data=data) | 547626545942b290dc64cd4f1d75277205751eaf | 3,646,081 |
def test_POMDP(POMDP, policy, test_data, status):
"""simulation"""
# Basic settings
p = POMDP
ind_iter = 0
horizon = len(test_data)
state = status
action = p.actions[0]
belief = p.init_belief
reward = 0
state_set = [state]
action_set = []
observation_set = ["null"]
al... | 0f2dfe7c18d254ca0b2953b11aaac2386d4fe920 | 3,646,082 |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
... | eb0fe7271497fb8c5429360d37741d20f691ff3c | 3,646,084 |
def _merge_GlyphOrders(font, lst, values_lst=None, default=None):
"""Takes font and list of glyph lists (must be sorted by glyph id), and returns
two things:
- Combined glyph list,
- If values_lst is None, return input glyph lists, but padded with None when a glyph
was missing in a list. Otherwise, return value... | cc671625bcaa2016cb8562c5727d7afa624699a9 | 3,646,085 |
def sig_for_ops(opname):
"""sig_for_ops(opname : str) -> List[str]
Returns signatures for operator special functions (__add__ etc.)"""
# we have to do this by hand, because they are hand-bound in Python
assert opname.endswith('__') and opname.startswith('__'), "Unexpected op {}".format(opname)
n... | 7f5850c5719ed631d4aabc22b757969d1161eee2 | 3,646,086 |
def lstm2(hidden_nodes, steps_in=5, steps_out=1, features=1):
"""
A custom LSTM model.
:param hidden_nodes: number of hidden nodes
:param steps_in: number of (look back) time steps for each sample input
:param steps_out: number of (look front) time steps for each sample output
:param features: ... | c84c1d4a3cb31ca74fd3d135a9c48c72f5f6c715 | 3,646,088 |
def build_carousel_scroller(items):
"""
Usage:
item_layout = widgets.Layout(height='120px', min_width='40px')
items = [pn.Row(a_widget, layout=item_layout, margin=0, background='black') for a_widget in single_pf_output_panels]
# items = [widgets.Button(layout=item_layout, description=st... | 2c48ef11de7647320833c74e5dc155365c0ae847 | 3,646,089 |
def base_round(x, base):
"""
This function takes in a value 'x' and rounds it to the nearest multiple
of the value 'base'.
Parameters
----------
x : int
Value to be rounded
base : int
Tase for x to be rounded to
Returns
-------
int
The rounded value
... | e5b1a1b81c7baf990b7921fe27a20075c0305935 | 3,646,091 |
def _update_schema_1_to_2(table_metadata, table_path):
"""
Given a `table_metadata` of version 1, update it to version 2.
:param table_metadata: Table Metadata
:param table_path: [String, ...]
:return: Table Metadata
"""
table_metadata['path'] = tuple(table_path)
table_metadata['schema... | 6b0c8bc72100cceeb1b9da5552e53bc3c9bad3fa | 3,646,092 |
def train_cnn_7layer(data, file_name, params, num_epochs=10, batch_size=256, train_temp=1, init=None, lr=0.01, decay=1e-5, momentum=0.9, activation="relu", optimizer_name="sgd"):
"""
Train a 7-layer cnn network for MNIST and CIFAR (same as the cnn model in Clever)
mnist: 32 32 64 64 200 200
cifar: 64 6... | c2d020b4390aca6bb18de6f7e83c801475ac1a03 | 3,646,093 |
def validate():
"""
Goes over all season, make sure they are all there, and they should have length 52, except last one
"""
input_file = processedDatafileName
clusters_file = 'data/SeasonClustersFinal'
seasonDic = {}
allSeasons = {}
for line in open(clusters_file):
... | 883d21b656730c3e26a94ba8581107f359b337b4 | 3,646,094 |
def get_registry(): # noqa: E501
"""Get registry information
Get information about the registry # noqa: E501
:rtype: Registry
"""
try:
res = Registry(
name="Challenge Registry",
description="A great challenge registry",
user_count=DbUser.objects.count(... | 7798da55bee2ad1d6edce37f7c00e4597412491d | 3,646,095 |
def get_fraction_vaccinated(model, trajectories, area=None, include_recovered=True):
"""Get fraction of individuals that are vaccinated or immune (by area) by
state.
Parameters
----------
model : amici.model
Amici model which should be evaluated.
trajectories : pd.DataFrame
Tra... | f11cbeb737c8592528441293b9fd25fed4bee37f | 3,646,096 |
def test_function(client: Client) -> str:
"""
Performs test connectivity by valid http response
:param client: client object which is used to get response from api
:return: raise ValueError if any error occurred during connection
"""
client.http_request(method='GET', url_suffix=URL_SUFFIX['TEST... | 8c773fd9a87a45270157f682cb3229b83ba4a9e0 | 3,646,097 |
import pkgutil
import doctest
def load_tests(loader, tests, ignore):
"""Create tests from all docstrings by walking the package hierarchy."""
modules = pkgutil.walk_packages(rowan.__path__, rowan.__name__ + ".")
for _, module_name, _ in modules:
tests.addTests(doctest.DocTestSuite(module_name, glo... | d8495b32c6cb95a94857f611700f07b9183a9b63 | 3,646,098 |
def k_hot_array_from_string_list(context,
typename,
entity_names):
"""Create a numpy array encoding a k-hot set.
Args:
context: a NeuralExpressionContext
typename: type of entity_names
entity_names: list of names of type typename
Retu... | 66c987f7c5d1e3af2b419d0db301ad811a8df5b7 | 3,646,099 |
from typing import List
from typing import Tuple
def get_validation_data_iter(data_loader: RawParallelDatasetLoader,
validation_sources: List[str],
validation_target: str,
buckets: List[Tuple[int, int]],
... | 826b5847fb55e61ba3a0b416643fbbc356a23b07 | 3,646,100 |
def _serialize_property(
target_expr: str, value_expr: str, a_property: mapry.Property,
auto_id: _AutoID, cpp: mapry.Cpp) -> str:
"""
Generate the code to serialize the property.
The value as the property is given as ``value_expr`` and serialized
into the ``target_expr``.
:param ta... | 3a5a7d7795dd771224d1fd5de8304844cd260fad | 3,646,101 |
def read_raw_data(pattern):
""":return X"""
if isinstance(pattern, basestring):
fpaths = glob.glob(pattern)
elif isinstance(pattern, list):
fpaths = pattern
X = []
for fpath in fpaths:
print 'loading file {} ... ' . format(fpath)
X.extend(loadtxt(fpath))
return X | ae3f503db4b7f31a043dc4b611d9bf2393d7a352 | 3,646,102 |
def warp_affine_rio(src: np.ndarray,
dst: np.ndarray,
A: Affine,
resampling: Resampling,
src_nodata: Nodata = None,
dst_nodata: Nodata = None,
**kwargs) -> np.ndarray:
"""
Perform Affine warp ... | 4843ce222535a93b1fa7d0fee10161dadaba290b | 3,646,103 |
def encode_integer_leb128(value: int) -> bytes:
"""Encode an integer with signed LEB128 encoding.
:param int value: The value to encode.
:return: ``value`` encoded as a variable-length integer in LEB128 format.
:rtype: bytes
"""
if value == 0:
return b"\0"
# Calculate the number o... | b74832115a58248f4a45a880f657de6dd38b0d8d | 3,646,104 |
def google_sen_new(text_content):
"""
Analyzing Entity Sentiment in a String
Args:
text_content The text content to analyze
"""
# text_content = 'Grapes are good. Bananas are bad.' Available types: PLAIN_TEXT, HTML
client = language_v1.LanguageServiceClient()
type_ = enums.Document.Ty... | 57c4020f35a344d7f264453571e3f8825e00206f | 3,646,105 |
def simplify_polygon_by(points, is_higher, should_stop, refresh_node):
"""
Simplify the given polygon by greedily removing vertices using a given priority.
This is generalized from Visvalingam's algorithm, which is described well here:
http://bost.ocks.org/mike/simplify/
is_higher = functio... | b9ae05b2d146e78dbed36cc48df6cbd24c33fcbc | 3,646,107 |
def get_builder(slug):
"""
Get the Builder object for a given slug name.
Args:
slug - The slug name of the installable software
"""
for builder in Index().index:
if builder.slug == slug:
return builder
return False | d6013fb55d11be7a153b7a9e9f2bdd991b2a6304 | 3,646,108 |
def get_contact_lookup_list():
"""get contact lookup list"""
try:
return jsonify(Contact.get_contact_choices())
except Exception as e:
return e.message | e8d3a8f813366a16e86cf2eadf5acb7e235218de | 3,646,110 |
def argmax(X, axis=None):
"""
Return tuple (values, indices) of the maximum entries of matrix
:param:`X` along axis :param:`axis`. Row major order.
:param X: Target matrix.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil,
dia or :class:`numpy.matrix`
:param axis: Speci... | b97cb16798e0d726fc21a76a2a3c6a02d284e313 | 3,646,111 |
import hashlib
from re import T
from re import A
def posts():
"""
Function accessed by AJAX to handle a Series of Posts
"""
try:
series_id = request.args[0]
except:
raise HTTP(400)
try:
recent = request.args[1]
except:
recent = 5
table = s3db.cms_... | dc5b43016c3e50c52969c91505856941c951911b | 3,646,112 |
def resolve_game_object_y_collision(moving, static):
"""Resolves a collision by moving an object along the y axis.
Args:
moving (:obj:`engine.game_object.PhysicalGameObject`):
The object to move along the y axis.
static (:obj:`engine.game_object.PhysicalGameObject`):
The... | 24d63b4fd9e4a37d22aceee01e6accc2a74e8ee4 | 3,646,113 |
def filter_all(fn, *l):
"""
Runs the filter function on all items in a list of lists
:param fn: Filter function
:param l: list of lists to filter
:return: list of filtered lists
>>> filter_all(lambda x: x != "", ['a'], ['b'], [""], ["d"])
[['a'], ['b'], [], ['d']]
"""
return [filter... | 114b7b9bf9b22d55bd891a654318d4a49e30be51 | 3,646,114 |
def get_test_runners(args):
""" Get Test Runners """
res = list()
qitest_jsons = args.qitest_jsons or list()
# first case: qitest.json in current working directory
test_runner = get_test_runner(args)
if test_runner:
res.append(test_runner)
# second case: qitest.json specified with --... | 73d9b4e73935cd2c41c24bd1376ade9ea274f23d | 3,646,115 |
def get_preselected_facets(params, all_categories):
""" Resolve all facets that have been determined by the GET parameters.
Args:
params: Contains the categories/facets
all_categories:
Returns:
dict: Contains all sorted facets
"""
ret_arr = {}
iso_cat = params.get("isoC... | 878f3ef05aaaa643782c6d50c6796bc503c0f8e6 | 3,646,116 |
def has_joined(*args: list, **kwargs) -> str:
"""
Validates the user's joining the channel after being required to join.
:param args: *[0] -> first name
:param kwargs:
:return: Generated validation message
"""
first_name = args[0]
text = f"{_star_struck}{_smiling_face_with_heart} بسیار خ... | d446da88a362c3821e25d0bee0e110ec0a906423 | 3,646,117 |
def depth_residual_regresssion_subnet(x, flg, regular, subnet_num):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
... | 2c5d2cb03f60acc92f981d108b791a0e1215f5f6 | 3,646,118 |
def dist2(x, c):
"""
Calculates squared distance between two sets of points.
Parameters
----------
x: numpy.ndarray
Data of shape `(ndata, dimx)`
c: numpy.ndarray
Centers of shape `(ncenters, dimc)`
Returns
-------
n2: numpy.ndarray
Squared distances between... | 24a1b9a368d2086a923cd656923dc799726ed7f0 | 3,646,119 |
def process_name(i: int, of: int) -> str:
"""Return e.g. '| | 2 |': an n-track name with track `i` (here i=2) marked.
This makes it easy to follow each process's log messages, because you just
go down the line until you encounter the same number again.
Example: The interleaved log of four processes th... | bc3e0d06544b61249a583b6fa0a010ec917c0428 | 3,646,120 |
def cards_db(db):
"""
CardsDB object that's empty.
"""
db.delete_all()
return db | 9649b309990325eca38ed89c6e9d499b41786dab | 3,646,121 |
def _geo_connected(geo, rxn):
""" Assess if geometry is connected. Right now only works for
minima
"""
# Determine connectivity (only for minima)
if rxn is not None:
gra = automol.geom.graph(geo)
conns = automol.graph.connected_components(gra)
lconns = len(conns)
els... | d5993b7083703746214e70d6d100857da99c6c02 | 3,646,122 |
def scale_to_range(image, dest_range=(0,1)):
""" Scale an image to the given range.
"""
return np.interp(image, xp=(image.min(), image.max()), fp=dest_range) | a225b44dc05d71d8ccc380d26fb61d96116414da | 3,646,123 |
def files():
"""Hypothesis strategy for generating objects pyswagger can use as file
handles to populate `file` format parameters.
Generated values take the format: `dict('data': <file object>)`"""
return file_objects().map(lambda x: {"data": x}) | 04e787502a043ffba08912724c9e29f84a6a416c | 3,646,124 |
from typing import Optional
from typing import Generator
def get_histograms(
query: Optional[str] = None, delta: Optional[bool] = None
) -> Generator[dict, dict, list[Histogram]]:
"""Get Chrome histograms.
Parameters
----------
query: Optional[str]
Requested substring in name. Only hi... | 059792d045bdea84ff636a27de9a1d9812ae4c24 | 3,646,125 |
def energy_decay_curve_chu_lundeby(
data,
sampling_rate,
freq='broadband',
noise_level='auto',
is_energy=False,
time_shift=True,
channel_independent=False,
normalize=True,
plot=False):
""" This function combines Chu's and Lundeby's methods:
... | 3e9711fbc47442a27fc339b3fb18ad6f21a44c91 | 3,646,126 |
def sinkhorn(
p, q, metric="euclidean",
):
"""
Returns the earth mover's distance between two point clouds
Parameters
----------
cloud1 : 2-D array
First point cloud
cloud2 : 2-D array
Second point cloud
Returns
-------
distance : float
The distance betwee... | 93a4eb2383cfc4a2f462daf1b984d773c339aee7 | 3,646,127 |
def generate_s3_events(cluster_name, cluster_dict, config):
"""Add the S3 Events module to the Terraform cluster dict.
Args:
cluster_name (str): The name of the currently generating cluster
cluster_dict (defaultdict): The dict containing all Terraform config for a given cluster.
config ... | 93af74bcd9b0c16fdfd1a3495bb709d84edb10a6 | 3,646,128 |
def cluster_seg(bt, seg_list, radius):
"""
Fetch segments which align themself for a given tolerance.
"""
cluster, seen_ix = [], set()
for i, seg in enumerate(seg_list):
if i not in seen_ix:
sim_seg_ix = list(bt.query_radius([seg], radius)[0])
seen_ix |= set(sim_se... | 37308331b41cd7d1e1b8717bf4c0d5a4ced55385 | 3,646,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.