content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from commands import wtf
def fixture_wtf():
"""Fixture for wtf tests."""
message = Message()
kwargs = dict(user=message.user,
channel=message.channel,
message=message)
text = wtf.get_def(**kwargs)
return message, text | 1a079a91a85e348c77148a67c93c0f69fc7233ed | 56,154 |
def hamming_w(x, N, ft_compensated=False):
"""
Specific Hamming FT window function.
If ``ft_compensated==True``, multiply the window function by a compensating factor to preserve power in the spectrum.
"""
return gen_hamming_w(x,N,0.54,0.46,ft_compensated=ft_compensated) | ec6ebaba69c4904e4e0fff2a4a8d47ece6b8e58d | 56,155 |
def caculate_matmul_shape(matrix_A_dim, matrix_G_dim, split_dim):
"""get matmul shape"""
split_dimA = split_dim
split_dimG = split_dim
if matrix_A_dim % split_dim == 0:
batch_w = matrix_A_dim // split_dim
else:
if matrix_A_dim < split_dim:
batch_w = 1
split_di... | 54a036103a97b739d00c3bd416e7dc49b1cba9e2 | 56,156 |
def percolation_finder(m, max_num_percolation=6):
"""
Step 3 percolation finder
"""
walks = { 'walk': [] } # Name binding
def redundancy_index(v):
n = len(v)
occurrence_vector = [v.count(i) for i in range(n)]
return max(occurrence_vector) - 1 + occurrence_vector.count(0) * ... | 16f33deb1bbf1e28fab268228e9690c6acad07bc | 56,157 |
def RenderPassStartDependenciesVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartDependenciesVector(builder, numElems) | ff2216b9e80302f2f97aea9ce97a4adf2ee783c1 | 56,158 |
def check_for_ambiguous_sta(db, stalist,
collection='arrival',
verbose=False,
verbose_attributes=None):
"""
Scans db.collection for any station in the list of station codes
defined by the list container stalist. By default ... | 183dbfc58e3333bb814ad51f2751eccfc23265f8 | 56,159 |
def get_response_date():
"""
Date of response to include in responses
:return: the current time, correctly formatted
"""
# return datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
return DateFormat.now() | 939e8c0253cd8d8fa9b9238a6d5c7b2cbd4d086e | 56,160 |
def wrong_sign(qs):
"""Check if instance @qs has a tag indicating that it is a wrong sign.
The 'wrong-sign-tag' is defined in the database and is Signbank-implementation dependent;
The particular value used by a signbank must be specified in [sWrongSignTag] above
"""
# Initialise boolean return
... | b49a9671a138b11046f61bc39f438b4bc09551ae | 56,161 |
def volume_to_length(volume, cell_radius):
"""
get cell length from volume, using the following equation for capsule volume, with V=volume, r=radius,
a=length of cylinder without rounded caps, l=total length:
V = (4/3)*PI*r^3 + PI*r^2*a
l = a + 2*r
"""
pi = np.pi
cylinder_length = (volum... | e355e0799a0072a1bfeb5cb43c347b7b9cdefb66 | 56,162 |
def FindInfo(mnemonic,addressmode, operand):
"""Figure out which opcode to use for this instruction based on
addressing mode. The text doesn't definitively determine the addressing
mode, so use the text along with what is available for that mnemonic to
decide which mode to pick.
"""
if operand ... | 0dd27d5ca512f96c14da8092755248669ea93087 | 56,163 |
import numpy
import tempfile
def train_and_predict(
csv_file_name=_DATA_FILE, training_steps=200, estimator_config=None,
export_directory=None):
"""Train and predict using a custom time series model."""
# Construct an Estimator from our LSTM model.
categorical_column = tf.feature_column.categorical_colu... | 71b3b1cb00e27df062809022630781efbb7a0822 | 56,165 |
import code
def simulate_gen(simobject, Ndet, pixelsize, detz, k=None, settings="double", maximg=_np.inf, detangles=(0, 0), *args, **kwargs):
"""
returns an array of simulated wavefields
parameters:
simobject: a simobject whose get() returns an Nx4 array with atoms in the first and (x,y,z,phase) of ea... | 7ba4314ef50f3825c8ec6ee1a57821e4c6239e90 | 56,166 |
def genDict(linebuffer, titlebuffer, f, original_path, typebuffer, githubUrl):
"""Puts the function info into a dict
Also add pygments and hardcode github url info
"""
lexer = get_lexer_by_name("scheme", stripall=True)
result = highlight(linebuffer, lexer, HtmlFormatter())
url = f.replace(original_path, githubUrl... | b5536ec535bcf2fc7a22150069742613947e14af | 56,168 |
def scorethreshold(source,logit=None):
"""
Check that this variable has the appropriate format and reformat otherwise
----------
source : str
Source of the contact list ("deepmetapsicov" or "psicov")
logit : str, optional
If not none, it activates the logging. The default is None.
... | b56e6e26bdd8b960b25b789cd067257afd489ad8 | 56,169 |
def randint(low: int, high: int, shape: _ShapeType, dtype: mindspore.dtype = mindspore.int8) -> Tensor:
"""Return random integers from `low` (inclusive) to `high` (exclusive)."""
outputs_np = np.random.randint(low, high, size=shape)
outputs = Tensor(outputs_np, dtype=dtype)
return outputs | 7c5c041bc99ff86f7702a9afad88faae4309dc0e | 56,170 |
def states_id(id):
"""
method to render state ids
"""
state_all = storage.all('State')
try:
state_id = state_all[id]
return render_template(
'9-states.html',
state_id=state_id,
condition="state_id")
except:
return render_template('9... | f034e77ea8e83de200939cdcee2a2fd2c580df08 | 56,171 |
import sqlite3
from typing import List
from typing import Any
def get_data(conn: sqlite3.Connection,
table_name: str,
columns: List[str],
start: int = None,
end: int = None,
) -> List[List[Any]]:
"""
Get data from the columns of a table.
All... | 1760f64a63094e14c6bf22c3199a549c02c4bc4e | 56,172 |
import requests
def get_gitlab_tags(proj_id):
"""
obtain tags from Gitlab
:param proj_id: project id in Gitlab
:return: list
"""
result = []
r = requests.get("{}/projects/{}/repository/tags".format(gitlab_api_url, proj_id),
headers={"PRIVATE-TOKEN": gitlab_token})
... | 69b0b8213cfe7e3ea35d0393dfa8ab1f94309b12 | 56,173 |
import json
def compare_reload_data(inid, src_dir, site_dir):
"""Load the original csv and compare to reloading the JSON you wrote out
which = 'edges' or 'data'
"""
csv_path = input_path(inid, ftype='data', src_dir=src_dir)
jsn_path = output_path(inid, ftype='comb', format='json', site_dir=site_d... | 6b6ce47c203fc433f9bd5657802ff8086587b99d | 56,174 |
def _is_integer(value):
"""Check if a value is a Python or NumPy integer instance."""
return isinstance(value, (int, np.integer)) | 67a5bed37ecd41a151eed9210b61e3b9d29b945c | 56,175 |
def getMoreInfoOfCurrentRestaurant(update: Update, context: CallbackContext) -> int:
"""Fetches in-depth details of the current restaurant and shows them to the user."""
verifyChatData(update=update, context=context)
query = update.callback_query
query.answer()
# Getting the current restaurant and... | 690413608c25d0e5d23c07bcd055a9fb87937263 | 56,176 |
def GetBedSwapMessage( PrimaryID1, VisitID1, PrimaryID2, VisitID2 ):
"""
Create a bedswap message (A17) which switches the location of 2 patients.
Parameters:
PrimaryID1 - The first patient's Primary Patient ID that stays with the patient forever
VisitID1 - The first patient... | 03cd50aa8433061ecf8696b69abfecbea06e3b14 | 56,177 |
def spatial_mean(yarray, w=5):
"""
Spatial mean over rows and columns
"""
wh = int(w / 2.0)
yarray = np.pad(yarray.copy(), ((0, 0), (w, w), (w, w)), mode='reflect')
ymean = np.zeros(yarray.shape, dtype='float64')
ymask = np.where(yarray > 0, 1, 0).astype('uint8')
ycount = np.zeros(ya... | dfa9eb93b6307f4af82334c0bdf25a3a0a03ed27 | 56,179 |
def validate_overlap(periods, datetime_range=False):
"""
Receives a list with DateRange or DateTimeRange and returns True
if periods overlap.
This method considers that the end of each period is not inclusive:
If a period ends in 15/5 and another starts in 15/5, they do not overlap.
This is the ... | bae96eb890063e4d27af0914e7fcd1348d1340a7 | 56,181 |
def find_primes_sieve(upper_bound):
"""
Returns all primes up to upper_bound (exclusive) using the sieve of Eratosthenes.
The numbers are returned as a list.
Example: find_primes(7) -> [2, 3, 5]
"""
# 1 marks a potential prime number, 0 marks a non-prime number
# indexes 0 and 1 are not tou... | 236cbd0cdf2eee2cda91ae3d2d240a9548a920dc | 56,182 |
def get_lesson_attachments(lesson_id):
"""
Get attachments for a lesson
"""
# pylint: disable=E1101
lesson_attachments = Attachment.objects.filter(lesson=lesson_id)
result = []
for attachment in lesson_attachments:
url = attachment.attached_file.url
result.append({'title': at... | f4f03675b56d07a545d1d2bbae27493cb7f14279 | 56,183 |
def aggregate_loader(data_path):
"""Load the data from the given hdf5 file"""
# with pd.HDFStore(data_all[0]['analysis_path']) as h:
with pd.HDFStore(data_path) as h:
# get a list of the existing keys
keys = h.keys()
# if it's only one key, just load the file
if len(keys) == ... | 00be112655e71bb6d681f58419606ecb34867465 | 56,184 |
def new_category():
"""
View new group route function that returns a page with a form to create a category
"""
form = CategoryForm()
if form.validate_on_submit():
name = form.name.data
new_category = PitchCategory(name = name)
new_category.save_category()
retur... | 69a90621792ce3c07cf5dd92f09af21fbc196e94 | 56,185 |
from pathlib import Path
def get_dump():
"""Helper for creating and returning a dump Path"""
dump = Path("pyinseq/tests/dump")
if not dump.exists():
dump.mkdir()
return dump | d34d149c6de235e58cbee222067b8023afcf8f93 | 56,186 |
from typing import MutableMapping
import itertools
from typing import Set
from typing import Hashable
def is_adjacency(item: object) -> bool:
"""Returns whether 'item' is an adjacency list.
Args:
item (object): instance to test.
Returns:
bool: whether 'item' is an adjacency list.
... | 792597c0f9678c737e21e8fc690098168e7e7f0f | 56,188 |
import warnings
def drop_duplicate_cols(df: pd.DataFrame, warn: bool = True) -> pd.DataFrame:
"""
Drop duplicate columns from pandas DataFrame
:param df: pandas DataFrame
:param warn: Whether to trigger a warning if duplicate columns are dropped
:return: pandas DataFrame without the duplicates co... | d127e925ac79206a48d5aaac7d9f6d5781a3c23b | 56,189 |
def line_of_sight_integrate(
radial_distances: np.ndarray,
get_emission_func: EmissionFunction,
observer_position: np.ndarray,
earth_position: np.ndarray,
unit_vectors: np.ndarray,
freq: float,
) -> np.ndarray:
"""Returns the integrated Zodiacal emission for a component (Trapezoidal).
P... | 29e0f7397efd7a54547ddfd346b3ecfd2c5188af | 56,190 |
import tempfile
def sv56(x, sr, ndb=-26):
"""Run sv56 gain normalization
Args:
x (array): waveform
sr (int): Sampling rate
ndb (int): Gain level in dB
Return
array: gain-normalized waveform
"""
assert x.dtype == np.int16
with tempfile.TemporaryDirectory() as f... | ad6fc138457bed2be376b7d92ba3d373da46e886 | 56,191 |
import click
def remote_option(help):
"""`REMOTE` is the name of a configured remote. Use ``guild remotes``
to list available remotes.
For information on configuring remotes, see ``guild remotes
--help``.
"""
assert isinstance(help, str), "@remote_option must be called with help"
def wr... | 643ba728e99d81956780e62c09489396476ba341 | 56,192 |
def handle_add_vote(data) -> None:
"""Takes an info dictionary of the form:
{ 'channel': channel_id, 'vote': vote_id, 'option': option_id }
"""
channel_id = data['channel']
vote_id = data['vote']
option_id = data['option']
if not verify_valid_option(channel_id, vote_id, option_id):
... | 18ff788bd121f0032e3cd59c5c8807d2bb46e933 | 56,193 |
def get_edge_between_verts_colour(veering_colours, tetrahedron, v0, v1):
"""returns the veering direction (colour) for the given edge, between v0, v1"""
edge_index = get_edge_between_verts_index( tetrahedron, v0, v1)
return direction_to_col[ veering_colours[edge_index] ] | 84373ac2b9a3d13250cdbe7ea853fc10bd3970c4 | 56,194 |
import copy
def mutually_exclusive_group(group):
"""Decorator function for mutually exclusive :mod:`argparse` arguments.
Args:
group (list of tuples): A list of the standard :mod: `argparse`
arguments which are mutually exclusive. Each argument is
represented as a tuple of its... | c6875840371c9a6fb6060c7148b734248a6f0b41 | 56,195 |
def async_setup(hass, config):
"""Track the state of the sun."""
if config.get(CONF_ELEVATION) is not None:
_LOGGER.warning(
"Elevation is now configured in home assistant core. "
"See https://home-assistant.io/docs/configuration/basic/")
sun = Sun(hass, get_astral_location(... | 27566afd924dcc973ac15eecc403dab642ac5846 | 56,198 |
from .verbose_output import print_to_terminal
def generate_2d_parametermap(self, spectrum_parameter):
"""
Create a 2D map of a given spectral parameter
Parameters
----------
scouseobject : Instance of the scousepy class
"""
map = np.zeros(self.scouseobject.cube.shape[1:])
map[:] = np... | 6aaeb852bb1987040d3e09fe234792853523d749 | 56,199 |
def PIsA (inTL):
""" Tells if the input really is a Python Obit TableList
returns true or false (1,0)
inTL = Python TableList to test
"""
################################################################
# Checks
if not isinstance(inTL, TableList):
return False
#
return Obit... | e119d79895f5f36405d26a5125308249845df25a | 56,200 |
def _GetStepLogViewUrl(build, full_step_name, log_name, partial_match=False):
"""Gets view url of the requested log.
Args:
build (buildbucket_proto.build_pb2.Build proto): Information about a build.
full_step_name (str): Full name of the step.
log_name (str): Type of the log.
partial_match (bool): ... | 7e240e0414c8d83620d701d348d3386cb5054226 | 56,201 |
def downgrade(emap, factor, op=np.mean):
"""Returns enmap "emap" downgraded by the given integer factor
(may be a list for each direction, or just a number) by averaging
inside pixels."""
fact = np.full(2, 1, dtype=int)
fact[:] = factor
tshape = emap.shape[-2:]//fact*fact
res = op(np.reshape(emap[...,:tshape[0],... | 6f4cb34441b371436ebe94b9ce9afb71c19614bf | 56,202 |
def test_config_file_fails_missing_database(monkeypatch, presence, config):
"""Check if test fails with missing database configuration."""
def mock_file_config(self):
return {'algorithm': 'asha'}
monkeypatch.setattr(presence.builder, "fetch_file_config", mock_file_config)
status, msg = presenc... | dd96df036a9e07d5ee207310e21c490e027f7e53 | 56,204 |
import itertools
def pairwise(iterable):
"""
Iterate pairwise through an iterable.
pairwise([1,2,3,4]) -> (1,2),(2,3),(3,4)
"""
val, nextVal = itertools.tee(iterable)
next(nextVal, None)
return zip(val, nextVal) | 495fedbaf2046d66bd791dc78dea8525761e01b1 | 56,205 |
import numpy
def lamb2(v,r):
"""Approximate the Lambert W function.
Approximate the Lambert W function from its upper and lower bounds.
The result replicates the triple point of the (idealized) system
exactly, because lamb2(0,r) = 1.
:arg float v: Modified argument of the function. Must ... | 358907f75de539d3da88935b0d470f72310c3b57 | 56,206 |
def interleave(l1, l2):
"""
Return an interleaving of lists l1 and l2.
If l2 is not a list, broadcast its value.
"""
if isinstance(l2, list):
l2_list = l2
else:
l2_list = [l2] * len(l1)
return list(it.chain.from_iterable(it.zip_longest(l1, l2_list))) | 5101be177cbfcbf8f769ceaacd7ad022bd8625c5 | 56,207 |
from typing import Tuple
from typing import Optional
def collide(left: int, right: int) -> Tuple[Optional[int]]:
"""Return the result of a collision
Returns
tuple of (negative, positive) remaining after collision
"""
small, big = sorted((left, right))
if abs(small) > big:
return (... | 4d75def5df0315f8b8adabb13fef49adf48fbf2d | 56,208 |
def choose(aliases, exprs, mapper, mingain):
"""
Analyze the detected aliases and, after applying a cost model to rule out
the aliases with a bad memory/flops trade-off, inject them into the original
expressions.
"""
aliases = AliasList(aliases)
# `score < m` => discarded
# `score > M` ... | 8028318ec907c69504e721eaffc023a4a857f3bf | 56,210 |
import random
def name() -> str:
"""(TBI) Generates name, unique every time."""
while True:
new_name = "S"
while(new_name[-1] != "E"):
new_name += random.choice(name_next_chars[new_name[-1 - memory:]])
if((new_name not in names) and (len(new_name) > 3)):
break
names.append(new_name)
return new_name[1:... | 2ae4a65732f1c8d40899811d22ce5ad41e83256c | 56,212 |
def check_if_author_relevant(author_id, query):
"""
Check whether the author is relevant to the search query based on their tags.
Parameters:
author_id (string or int)
query (string): The search query used to retrieve this particular author
Returns:
boolean based on the presence of... | 23603688813f39a4d422e9c8ac049e9372042f60 | 56,213 |
def apply_perspective_transform(img):
"""
This function takes in a binary threshold image and retuned a warped bird eyes view of the image
"""
img_size = (img.shape[1], img.shape[0])
# # source points
src = np.float32([[699,462],[1084,img_size[1]],[227,img_size[1]],[585,462]])
# 4 destinat... | 9bca1a2d08b8a875d8f67e0d37700b555c243d74 | 56,214 |
def create_mating_pool(population, fitnesses, norm=True):
"""
Generate a mating pool
This will create a new population proportional to the fitnesses
of the original population. The pool will the be used as the basis
for generating the next generation.
Parameters
----------
population :... | 1ea329c334ffa54527aacf8fba7a33b55c927eb1 | 56,215 |
def active_filesets(filesets):
"""Active filesets are displayed in the listing"""
return filesets.filter(Fileset.deleted.isnot(True)) | fa39a2ff62623828fabf076acd4049dc8062f136 | 56,216 |
from typing import List
def _align_mortgages(periods_a: List[int],
periods_b: List[int],
fees_a: List[int],
fees_b: List[int]) -> (List[int], List[int]):
""" Align periods and fees of two mortgages and compute the exact fee for each period.
:para... | 01c30c3b010c94a5d03c0936377c3551cdb3e5ef | 56,219 |
def two_point(rng, population, fitness, new_individuals, N):
"""Add `N` individuals based on the crossovering two randomly selected individuals by a middle point.
If there are no new individuals, then they crossovering occurs between the individuals in the previous generation.
Parameters
----------
... | a0e149b319391ddc2e6e975954e381bccdc728cf | 56,220 |
import json
def rating(ticker):
"""
Description
----
Gives information about the rating of a company which includes i.a. the company
rating and recommendation as well as ratings based on a variety of ratios.
Input
----
ticker (string)
The company ticker (for example: "... | afd26bc4db16e9f6f6d03217a26ab223f8687ab5 | 56,221 |
import traceback
def testrangepartition(MyAssignment, ratingstablename, n, openconnection, partitionstartindex, ACTUAL_ROWS_IN_INPUT_FILE):
"""
Tests the range partition function for Completness, Disjointness and Reconstruction
:param ratingstablename: Argument for function to be tested
:param n: Argu... | c4d4f945c0f51180964114bda178a2e9bf245281 | 56,222 |
def bpow(a, f):
"""Broken power law. This model assumes that there is a break in the power
spectrum at some given frequency.
Parameters
----------
a : ndarray[3]
* a[0] : the natural logarithm of the normalization constant
* a[1] : the power law index at frequencies lower than t... | 1d42e9ab0c22ba9dbdd0190c09ea7b191ae5d66c | 56,223 |
def sample_dataframe(df, parameters=None):
"""
Sample a dataframe on a given number of cases
Parameters
--------------
df
Dataframe
parameters
Parameters of the algorithm, including:
- Parameters.CASE_ID_KEY
- Parameters.CASE_ID_TO_RETAIN
Returns
-------... | e7e8f203339d671f3e363572a813f4658e189d35 | 56,224 |
def make_row(path1, path2, dt1, dt2, diff_man, diff_euc):
"""Make a list containing all row info.
For Hive and RPi number, just add the two columns later.
header = [...]
"""
# # Get interval duration
# td = (dt2 - dt1)
# dur = td.total_seconds()
# dt_center = dt1 + (td / 2)
# Shor... | 21159e7d109b4019f632c2644354c97f8416a80f | 56,228 |
from pathlib import Path
def elec_demands_dirpath(tmp_path: Path) -> Path:
"""Create a temporary directory of dummy data called 'SM_electricity'.
Args:
tmp_path (Path): see https://docs.pytest.org/en/stable/tmpdir.html
Returns:
Path: Path to a temporary directory of dummy data called 'SM... | 19cd13a7bfd61f211fd900caa43c9355c26ac500 | 56,229 |
def get_operation_subfuncs(entry_info, callgraph):
"""
get reachable functions of each operation
entry_funcs_file: operation entry functions list
callgraph: callgraph of the application, networkx.classes.multidigraph.MultiDiGraph type
"""
OperationNames = list(entry_info.keys())
# callgraph ... | 8fa5bc77dd8ab378d61345d2f9377ed5ffba51c2 | 56,231 |
import re
def StringHits(s: str, ks: [str], excluding=None, regexformat=r"[a-zA-Z0-9]*{}[a-zA-Z0-9]*"):
"""
find tokens in which there is at least one of <ks>
:param excluding: a list of keywords that should not appear in the tokens
"""
ms = []
excluding = [ex.lower() for ex in excluding]
... | 36948be94cf210767ccdeb7a93b80df3a5b5db97 | 56,232 |
def calculate_ms_ssim(predictions, gt_labels, max_val):
"""
ms-ssim calculation
Parameters
----------
predictions : ndarray
the reconstructed results
gt_labels : ndarray
the ground truth
max_val : float
the value range
"""
tf_predictions = tf.placeholder(t... | 671ea748fd2c0c62a145bf3a98231dcf3f807830 | 56,233 |
def rescale(nums, scales, budget=None):
"""
Rescale nums with scales to budget. Budget defaults to sum(nums)
Ex:
nums = [10, 20]
scale = [2, 1]
budget = 30
will return [15, 15]
"""
raw = np.multiply(nums, scales)
if np.sum(raw) == 0:
raise ValueError("Rescaling denominat... | 33f030390f96c04220b25f201138554d9dcf97fb | 56,234 |
from typing import Iterable
from typing import Set
def BCH_words_of_order(n: int,
alphabet: Iterable[BCH_Symbol],
disallowed_end: Set[BCH_Symbol] = set()) \
-> Iterable[BCH_Word]:
"""Generate all possible combinations of symbols in alphabet of length n.
R... | 3a815165fd4bd1d4c99603b55bd3def8193ee6da | 56,235 |
def uCSIsAegeanNumbers(code):
"""Check whether the character is part of AegeanNumbers UCS
Block """
ret = libxml2mod.xmlUCSIsAegeanNumbers(code)
return ret | e2e62a6ce992bc6f38990bdb1f3adf52f78871f8 | 56,236 |
def prettify(elem):
"""
Return a pretty-printed XML string for the Element.
"""
rough_string = ET.tostring(elem, encoding="utf-8", method='xml')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 314db4eba6628be37cac6a239767962a3e677767 | 56,237 |
import resource
def GetVPNServiceClass():
"""Gets the VPNService class.
Args:
Returns:
Implementation class
"""
return resource.GetResourceClass(VPNService) | 614092185f37e10367901848e88363d294f0b7cd | 56,238 |
def get_nn_gp_kernel(kernel_type, nn_type, gp_cts_hps, gp_dscr_hps, tp_comp,
kernel_options):
""" Constructs and returns the kernel hyperparams. """
# pylint: disable=unused-argument
kernel_hyperparams = {}
gp_cts_hps = gp_cts_hps[:] # create a copy of the list
# Extract GP hyper-paramete... | 9d5f6d71f25901bc0a5ac8cba93956981fa1220f | 56,239 |
from typing import Optional
def get_sobol(
search_space: SearchSpace,
seed: Optional[int] = None,
deduplicate: bool = False,
init_position: int = 0,
scramble: bool = True,
) -> RandomModelBridge:
"""Instantiates a Sobol sequence quasi-random generator.
Args:
search_space: Sobol ge... | f5f36fb20c7b8e39ebc8c0de6e5b47b267e1f939 | 56,240 |
def compute_distance(x0,y0,x1,y1):
"""takes two location vectors computes there distance from each element
in the first location to the elements in the second returning the element
from location one that is closet to location 2.
This is done using a kdtree algorithm."""
# Create point arrays
x... | 780101198af3401bbe29634b151c8279ecac5b4e | 56,241 |
def load_model(weights, device):
""" load model and it's weights """
model = YoloV2Net()
if weights:
load_weights(model, weights)
#model.load_state_dict(torch.load(weights))
return model.to(device) | 5b966fff88e1bc2bfb07f68303f5723733dc2fa6 | 56,242 |
def supported_territory_codes():
""" Return a set of recognized territory codes.
"""
return supported_country_codes().union(supported_subdivision_codes()) | 3cbe9fe8070658f8884f309cfeb4d0777b70c0dc | 56,243 |
from typing import Match
def from_paper(match: Match) -> Players:
"""Creates the players information from a Paper server match.
https://github.com/conqp/mcipc/issues/13#issuecomment-726145034
"""
online, max_, names = match.groups()
players = players_from_paper_names(names)
return Players(int... | a4c53b8e0f55ae6342f13f19053b586bd993ea65 | 56,244 |
def get_target_name(label):
"""
Try to extract the target_name from a given PDS label.
Parameters
----------
label : Object
Any type of pds object that can be indexed
Returns
-------
target_name : str
The defined target_name from the label. If this is None a target name... | 7aae704d4590fb44bfb650481a65af870c7c6570 | 56,245 |
def constant_fold(trace, expression):
"""Replace an expression with a constant if possible"""
try:
return Constant(
trace,
expression.value(),
expression.type_(),
expression.signed()
)
except AttributeError:
trace.error("Not a valid exp... | b5a2e0e08a598f8be8d9d6098f474de3ca0f5b7b | 56,246 |
def confirm_update(bot, update, user_data):
"""Handler for a message that begins with Edit, Cancel or Remove.
Confirm what the user want to do when an already tagged sticker was sent.
"""
if update.message.text == "Edit":
update.message.reply_text("Cool, send me the new tags to your sticker\n... | b42accb2e1c4587f1c5e24a66e2d29858f5e816d | 56,247 |
def _get_str_from_bin(src: bytearray) -> str:
"""Join data in list to the string.
:param src: source to process
:type src: bytearray
:return: decoded string
:rtype: str
"""
return src.rstrip().decode(encoding="utf-8", errors="backslashreplace") | a51d562ea06ff80d3a7f7c10622eb599cd9a1e83 | 56,248 |
def most_likely_distance2(atom1, atom2, box):
"""
Same as most_likely_distance, but distance^2 is computed (faster).
:param atom1: pmx.model.Atom
:param atom2: pmx.model.Atom
:param box: a tuple
:return: most likely distance from atom1 to atom2 w.r.t. box
"""
return closest_distance2(ato... | b3bcb4ec3f323843f29a5150f656f6f71ec809cc | 56,249 |
def mean_cost_div_value_and_grad(X, Y):
"""Compute the mean-cost divergence value *and* gradient w.r.t. X.
The cost is assumed to be the squared Euclidean one.
Args:
X: time series, numpy array of shape (size_X, num_dim).
Y: time series, numpy array of shape (size_Y, num_dim).
gamma: regularization ... | 111e386fea7331c4c53765c754a35873d1eb3406 | 56,250 |
from typing import Optional
def get_certificate(name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCertificateResult:
"""
Get information on a certificate. This data source provides the name, type, state,
domains, expiry date, and the sha1 fingerpri... | be8cc3ea0a00b4bed4f001d7a0eaf9a6f7476a7b | 56,251 |
def kth_diag_indices(array, diag_k):
"""Return a tuple of indices for retrieving the k'th diagonal
of matrix a.
:param array: Input matrix.
:type array: :class:`numpy array <numpy.ndarray>`
:param int diag_k: Diagonal to index. 0 is the centre, 1 is the first \
diagonal below the centre... | 0e81dea00f4931f541a2f339ef3425fd1c46010a | 56,254 |
def unique(obj):
"""
Unique with order
"""
temp = set()
return [x for x in obj if x not in temp and not temp.add(x)] | 2d4fc7a5ba39f1fcc84ccebc1f8604c8ca972e8c | 56,255 |
def str_word_count(s: str) -> int:
"""
This function returns word count using RegexpTokenizer
"""
if s:
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(s)
return len(tokens)
else:
return 0 | 0e2d598008ae8dd1c84cea5d05a8bbd1d5b38da9 | 56,256 |
def identity(x):
"""identity: return the argument"""
return x | 12201cf98d8984c1ade07f2048b770c9bad66c8b | 56,257 |
def is_main_process():
"""
Check whether the current process is the main process.
Returns:
bool: Whether the current process is the main process.
"""
return get_rank() == 0 | 968ae6ca845be6df40b396ca93266047a6b062ae | 56,258 |
def aggregate(namespace, user_project, consortium, drs_file_path=None, terra_output_path=None):
"""Run a series of reconciliations."""
def counts_factory():
return {'expected_sample_count': 0, 'actual_sample_count': 0, 'problems': []}
accessions = defaultdict(counts_factory)
assert drs_file_path... | ebda81fa50dd5be83a7e59b88115afe420978d7a | 56,259 |
from datetime import datetime
def get_bookmarks_backup_filename(date=None):
"""Return the default bookmarks filename as it is exported by Firefox at specific date."""
if date is None:
date = datetime.datetime.today()
return 'bookmarks-{year:0>4}-{month:0>2}-{day:0>2}.json'.format(
year=dat... | a09ee7d9dda2cdb15b4c2916bc19d1ceff32e396 | 56,260 |
from datetime import datetime
def get_sandbox_data(request, code):
""" If the proxy is in sandbox_mode, return sandbox data if it's there else 404 for robot, EDR request for others"""
if SANDBOX_MODE:
res = None
if request.authenticated_role == 'robots':
res = get_sandbox_details(r... | 658e9bfa5384f1e572d39eba8e39557eaffd4405 | 56,261 |
def metabase_data_db_name() -> str:
"""The name (in Metabase) of the database that Metabase reads from"""
return 'MyCompany DWH' | 391551068308d842c35e80a8e196f3854259e143 | 56,262 |
def doy_to_datetime(doy, year, zero_based=False):
"""convert a decimal day of year (e.g., 34.58275) to a datetime.
Day is one-based unless zero_based param is True"""
origin = '{}-01-01'.format(year)
o = pd.Timestamp(origin)
if not zero_based:
adjusted_doy = doy - 1
return pd.to_datetime... | 95f4d0d02d80c20e8099b08b2d2d56770685e4ae | 56,263 |
def smiley():
"""Return smiley page of for app."""
if current_app.smiley:
table = current_app.smiley.db.tables.smiley.head(n=10000).to_html()
else:
table = ''
return render_template('smiley.html', table=table) | 527367ebbf113016b7955d2e2da013bf665f911e | 56,264 |
def _h1_chebyshev_sum_ ( h1 , N , **kwargs ) :
"""Make a histogram representation in terms of Chebyshev polynomials
>>> histo = ...
>>> fsum = histo.chebyshev_sum ( 4 )
>>> print fsum
>>> x = ...
>>> print 'FUN(%s) = %s ' % ( x , fsum ( x ) )
"""
##
xmin = max ( kwargs.get( 'xmin... | 02f56aa730639e6474734e312e0000398a39a74d | 56,265 |
from typing import List
from typing import Any
def flatten_list(x: List[Any]) -> List[Any]:
"""
Converts a list of lists into a flat list.
Args:
x: list of lists
Returns:
flat list
As per
http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-o... | b600cce1dc88869c60c80019f3be9ea5245cdda7 | 56,266 |
import copy
def cmap_powerlaw_adjust(cmap, a):
"""
Returns a new colormap based on the one given
but adjusted via power-law, `newcmap = oldcmap**a`.
:param cmap: colormap instance (e.g., cm.jet)
:param a: power
"""
if a < 0.:
return cmap
cdict = copy.copy(cmap._segmentdata)
... | cfbafb772e867c88e35693a5b009b1f6cfbd3c95 | 56,267 |
def buff_eval(params):
"""Builds and evaluates BUFF energy of model in parallelization
Parameters
----------
params: list
Tuple containing the specification to be built, the sequence,
and the parameters for model building.
Returns
-------
model.bude_score: float
BUF... | 84ba0e9632cbcd5052a790fc805493f79c33cad2 | 56,268 |
def st100(x: np.ndarray) -> float:
"""Styblinksitang function with noise 100."""
return _styblinksitang(x, 100) | 650c07b0e60d7cde6d86dc432e5d19dad7ba5521 | 56,269 |
def normalize_year(input_month, input_year=None):
""" This routine is used when we only have month parameters (text planner / stop schedule lookup) and the
year is implied...
RULES:
return last year if we're w/in a few months of the new year, today is in the months of Jan-March and the se... | 1d53f51d092b96f8ac9267c8fc4d9b90c1cebe4f | 56,270 |
def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-rese... | befab1b5434b9f584a7d7a931a81e51c25f6cfed | 56,271 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.