content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def list_alias():
"""
List all registered aliases.
Returns:
An array of dictionary containing the alias and the command that it points to.
"""
alias_table = get_alias_table()
output = []
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
... | e0548b3c539bc5dd2bd5903282ab8a4a098f4f87 | 74,366 |
from re import S
def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
"""
Chop off tiny real or complex parts.
"""
if value is S.ComplexInfinity:
return value
re, im, re_acc, im_acc = value
# Method 1: chop based on absolute value
if re and re not in _infs_nan and (fastlog(re) < -... | 62836413ad0771edaf8414ec80b8f374b65157c5 | 74,367 |
def pearson_r(x, y):
"""Compute Pearson correlation coefficient between two arrays."""
# Compute correlation matrix: corr_mat
corr_mat = np.corrcoef(x, y)
# Return entry [0,1]
return corr_mat[0,1] | e872d48eb5648cbd35eb0e38ad44427e93fae897 | 74,368 |
from typing import List
from typing import Tuple
def sampling_expectation(hamiltonians: List[PauliSum],
bitstrings: List[np.array]) -> Tuple:
"""Mapped wrapper around ``sampling_expectation_z_base``.
A function that computes expectation values of a list of hamiltonians
w.r.t a li... | b034a8cbef798f0ce3cf8663ca7d252a8b24db1d | 74,369 |
def size(b):
"""
Returns the size in bytes of the first netstring in the provided bytes object.
WARNING: This function doesn't check for netstring validity.
THROWS:
ValueError if cannot determine size
"""
try:
slen = b[:b.find(b':')].decode('ascii')
return 2 + len(slen) + int(slen)
e... | 2b50a555e29c6d7cbdc419d3dfb336d60f907d0c | 74,370 |
def cbcloud_api_mock(monkeypatch, cbc_cloud_api):
"""Mocks CBCloudAPI for unit tests"""
cbcloud_api_mock = CBCloudAPIMock(monkeypatch, cbc_cloud_api)
hashes = [
"405f03534be8b45185695f68deb47d4daf04dcd6df9d351ca6831d3721b1efc4",
"0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf7041930... | 953a19d162f4b8926211803c7ea1b84ee2ccbad2 | 74,371 |
from typing import Optional
from typing import Union
from typing import Tuple
import numpy
import io
def _tile(
z: int,
x: int,
y: int,
scale: int = 1,
ext: str = None,
url: str = None,
indexes: Optional[Union[str, Tuple]] = None,
expr: Optional[str] = None,
nodata: Optional[Union[... | 955ad4e662e2d577fbf033538a6e0126c998e3b5 | 74,373 |
def dnlsim(system, u, t=None, x0=None):
"""Simulate output of a discrete-time nonlinear system.
Calculate the output and the states of a nonlinear state-space model.
x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t))
y(t) = C x(t) + D u(t) + F eta(x(t),u(t))
where zeta and eta are polynomials w... | d93646167f8fc99a83bf23eb0fb6e7a27d06333e | 74,375 |
def person_search(value, type=None):
""" Search for People & Groups which match a search term """
# Shortcuts
groups = s3db.pr_group
persons = s3db.pr_person
items = []
# We want to do case-insensitive searches
# (default anyway on MySQL/SQLite, but not PostgreSQL)
value = value.lower... | a67e7f300aa40389f5e3445d4df45ce30cbefbd0 | 74,376 |
import torch
def get_output_size(model, input_shape=(1, 3, 224, 224), device="cpu", dtype='float32'):
"""
Returns the shape of the convolutional features in output to the model.
Parameters
----------
model pytorch model,
neural network model.
input_shape: tuple of int,
shape o... | f9c4e79e2c38a424c723cfed6fc73fc63ddc3142 | 74,377 |
def checkPrecision(hp,pCentroids,pMeasure,optimisationIteration,distrib,m,directions,precisionCheck,structureCheck,newMeasure,lastMeasure,indexMin):
"""Deprecated - might not work"""
if not precisionCheck:
if newMeasure > lastMeasure :
print('Error: new Distortion bigger than at previous ite... | cb82a552b18f77f51553ceef41797a90496bc288 | 74,378 |
from typing import Union
def mwdx(candles: np.ndarray, factor: float = 0.2, source_type: str = "close", sequential: bool = False) -> Union[
float, np.ndarray]:
"""
MWDX Average
:param candles: np.ndarray
:param factor: float - default: 0.2
:param source_type: str - default: "close"
:param... | 955d062ef364ab2d577f9789ba8e07a4cc0c1264 | 74,380 |
def str_function(connectable) -> str:
"""__str__ function for OutputBase and InputBase."""
infos = []
if connectable.owner:
infos.append('owner: %s' % connectable.owner)
if connectable.connected:
infos.append('connected')
else:
infos.append('not connected')
return '%s(%... | 5ed2ba8575314c0fdf9046988f3977ab262ff0af | 74,381 |
def find_subtracted_fits_fieldprojectidccd(
dirlist,
field,
projectid,
ccd,
subtracttype='reverse',
photreftype='oneframe',
kernelspec='b/4;i/4;d=4/4',
nworkers=8,
maxworkertasks=1000):
"""This searches for all subtracted FITS files matching th... | 78df223605e304569ace3535c0c0a26fa7d46468 | 74,382 |
def cinv(z):
"""Computes the reciprocal of a complex `z`.
Args:
z (:class:`~taichi.math.vec2`): The input.
Example::
>>> @ti.kernel
>>> def test():
>>> z = ti.math.vec2(1, 1)
>>> w = ti.math.cinv(z) # [0.5, -0.5]
Returns:
:class:`~taichi.math.... | a91147855999a60d8252e558eff47e0f17f2403e | 74,383 |
from scipy.ndimage.interpolation import affine_transform
import numpy
def scale_and_rotate_image(im, angle=0.0, scale=None, order=5):
""" Scale and then rotate and image in x, y axes
Applies scale then rotates
:param im: Image
:param angle: Angle in radians
:param scale: Scale [scale_x, scale_y]... | ab91bd3059add848a77aec225227c8a646c06912 | 74,384 |
def _in_exception_handler(identifier, on_conflict):
"""Returns a matcher for a node in the nearest ancestor `except` & binds `identifier`.
Args:
identifier: Name of variable to bind the identifier in the nearest ancestor
exception handler to
on_conflict: BindConflict strategy for binding the identifi... | cd5b9192b4e0ee140c24f1bc54931b7be5adb3d8 | 74,385 |
def reduced(f, G, *gens, **args):
"""
Reduces a polynomial ``f`` modulo a set of polynomials ``G``.
Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
such that ``f = q_1*g_1 + ... + q_n*g_n + r``, w... | e2972af73c4d067458aa1e15017393d898d271e3 | 74,386 |
import requests
def save_running_config(host: str=HOST, username: str=USERNAME,
password: str=PASSWORD, port: str=PORT) -> tuple:
"""GET RESTCONF function to save current running config
Args:
host (str): hostname or ip of device
username (str): API username for authent... | 6398c154a480b9616c433d90b4c6e4ec58be4fb9 | 74,387 |
def _delta_derivative_double_gamma_hrf(delta, t_r=1.0, dur=60.0, onset=0.0):
""" Double Gamma HRF model.
Parameters
----------
delta : float, temporal dilation to pilot the HRF inflation
t_r : float, Time of Repetition, fMRI acquisition parameter, the temporal
resolution
dur : float, (d... | a39fd9ecb1e01d4e779eb7be5a481d1df5514c0e | 74,388 |
def archive_thumbnails(request, inst, proposal):
"""Generate the page listing all archived images in the database
for a certain proposal
Parameters
----------
request : HttpRequest object
Incoming request from the webpage
inst : str
Name of JWST instrument
proposal : str
... | eaddad50cf2395d6919f29f800b5b3cb24c8b8c7 | 74,389 |
import ssl
def get_ssl_context():
"""Create an SSL context."""
context = ssl.SSLContext()
context.verify_mode = ssl.CERT_NONE
return context | 182b18996632f335b1cdf4d73e8dd502881b0f73 | 74,392 |
def annotate_bmp( img, ellipses=None, old_pts=None, thickness=params.ellipse_thickness, windowsize=None, zoomaxes=None ):
"""Draw stuff on image."""
# draw ellipses
(bmp,resize,img_size) = draw_ellipses_bmp( img, ellipses, thickness=thickness,
windowsize=windo... | 4935e8a34b26d131867e0c1203de43f0a8d87dc3 | 74,393 |
def b36encode(number: int) -> str:
"""Convert the number to base36."""
alphabet, base36 = ["0123456789abcdefghijklmnopqrstuvwxyz", ""]
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0] | 54046b8b0246eac6f08f7dea8b918f512f5e23d8 | 74,394 |
def change_id(id, num_samples=7):
"""
automatically change object id, mapping given class to a class with similar size
returns list of changed ids for object replacement, of max size [num_samples]
"""
obj_pool = [75, 58, 127, 165, 159, 129, 116, 57, 35, 3, 20, 6, 9] # animals, people, chairs, etc
vehicle_po... | 141f75cef738b8ce140121609e2003bf1e2fd49d | 74,395 |
def split_order_book(order_book_id: str):
"""
对合约拆分成品种和年份俩个部分
:param order_book_id:
:return:
"""
return order_book_id[:-4], order_book_id[-4:] | 4692e95eb814de50f9effe7ed289f94712e265d6 | 74,396 |
def pro_avfid_superoperator_compsubspace_phasecorrected(U,L1,phases):
"""
Average process (gate) fidelity in the qubit computational subspace for two qutrits
Leakage has to be taken into account, see Woods & Gambetta
The phase is corrected with Z rotations considering both transmons as qubits
"""
... | 8dc731c8bd18133497b08b8a6dc0ccc68df8e4ac | 74,397 |
from typing import Tuple
from typing import List
import base64
def prepare_hw_encryption_attrs(hw_session: HwSessionInfo, label: str) -> \
Tuple[int, int, List[int], bytes, bytes, bytes]:
"""
:param hw_session:
:param label:
:return: 0: protocol id
1: hw type id (see below)
... | 8a868c72d9a0960cd918b6b345dfef114875b0cd | 74,398 |
def find_list(item_list, func, with_index=False):
"""
Find an object from the list that matches the conditions
:param with_index:
:param item_list:
:param func:
:return:
"""
if with_index is True:
return _find_list_with_index(item_list, func)
for item in item_list:
i... | b09762da3d8afa246c715153aecb9dac51342a81 | 74,399 |
def formater (string, props):
""" This function does a regular substitution 'str%(dict)' with a
little difference. It takes care of the escaped percentage chars,
so strings can be replaced an arbitrary number of times."""
s2 = ''
n = 0
while n < len(string):
if n<len(string)-1 and stri... | 8ec2d52d3b26f54dc5d5b86fc7f5def1cfe77360 | 74,400 |
def flatten_complex_to_real(dataset, lazy=False):
"""
Stacks the real values followed by the imaginary values in the last dimension of the given N dimensional matrix.
Thus a complex matrix of shape (2, 3, 5) will turn into a matrix of shape (2, 3, 10)
Parameters
----------
dataset : array-like ... | 0dadd932917cdcce5f9f990bc8ce975499e55ad8 | 74,401 |
def get_template_from_path(path: str) -> str:
"""Convert a normal path back to its template representation."""
# replace all path parts with the template tags
path = path.replace("\\", "/")
return path | 1a62acca2c0531563fb4493bc06708671a601cda | 74,402 |
from typing import Union
from typing import Pattern
from typing import List
import re
from pathlib import Path
import fnmatch
def parse_simple_index_links(
text: str,
url=None,
url_regex: Union[str, Pattern] = "^https?://|^ftp://",
ignore_regex: Union[str, Pattern] = "\/\?C=.;O=.",
fileglob: str =... | d3958f682f4b9a94c6dfea73823b17d278dddf1f | 74,403 |
def compute_mean_average_precision(statistic_list):
"""
Compute the mean average precision:
(https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Mean_average_precision)
We define average precision as Area under Curve AUC)
https://medium.com/@jonathan_hui/map-me... | 81cac2d3dc38962f27ce87648455d5fa989e237a | 74,404 |
import re
def check_email(email):
"""
Checks an email format against the RFC 5322 specification.
"""
# RFC 5322 Specification as Regex
regex = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0... | 522547471730c6975246c301492f5b7676032c75 | 74,405 |
import templateflow.api as tf
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.cifti import GenerateCifti
from niworkflows.interfaces.utility import KeySelect
def init_bold_grayords_wf(
grayord_density, mem_gb, repetition_time, name="bold_grayords_wf"
):
"""
... | 349bb5ce7c8bede76d4e73733f76dafde3e4f00a | 74,406 |
from typing import Dict
from typing import Union
def reverse_endianness(string: str) -> str:
"""Convert hex string to hex string with opposite endianness.
E.g.
Little endian -> Big endian,
Big endian -> Little endian
Result for non hex string is undefined, no validation is done.
Args:
... | 3edd879711e1fe2b302e765fe6009da66c621969 | 74,407 |
import ast
def block_view(A, block=(3, 3)):
"""Provide a 2D block view to 2D array. No error checking made.
Therefore meaningful (as implemented) only for blocks strictly
compatible with the shape of A."""
# simple shape and strides computations may seem at first strange
# unless one is able to re... | 7f5bdbdfd1fe5fe113ae1a72de00b996c85b902f | 74,409 |
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags,
beam_size, batch_size):
"""Given sequences and scores, will gather the top k=beam size sequences.
This function is used to grow alive, and finished. It takes sequences,
scores, and flags, and returns... | 9b92df677cdf99420d51990e3fdf6cb882017780 | 74,410 |
import inspect
def open(file=None, mode='r', format=None, as_decorator=None, **kwargs):
"""
Open a file and return a file object. This method can be used as a function
or a decorator. When used as a decorator, the function to be decorated
should receive the handler using an argument named ``f``. File ... | e2584afe80ad4aa2f2f762292c0e186c910b7324 | 74,411 |
def sniff_features(**kw):
"""
Look at the source files and return the features for a task generator (mainly cc and cxx)::
snif_features(source=['foo.c', 'foo.cxx'], type='shlib')
# returns ['cxx', 'c', 'cxxshlib', 'cshlib']
:param source: source files to process
:type source: list of string or :py:class:`waf... | 5ba230ab16c3e7e96b913ad6bb31a23181d88b35 | 74,412 |
import pandas
def getCumSumForIntervalData(actualTimeSeries, predictedValuesOnLaggedData, intervalSize=365):
"""
:param actualTimeSeries: Object of DataFrame TimeSeries
:param predictedValuesOnLaggedData: Object of DataFrame TimeSeries
:param intervalSize: Period or Seasonality
:return: Cumulative... | 3bcbca64aff1652239b32f2c2454e897d8968334 | 74,413 |
import re
def extract_intro_and_title(filename, docstring):
"""Extract and clean the first paragraph of module-level docstring."""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
para... | 44b1271f0826f21977e51c0c9a4e3852a47c6678 | 74,414 |
def get_s3_file(s3_uri):
"""Retrieve an S3 file"""
s3_client = boto3.client('s3')
url_object = urlparse(s3_uri)
bucket = url_object.netloc
key = url_object.path.lstrip('/')
response = s3_client.get_object(Bucket=bucket, Key=key)
return response['Body'] | c585ccc59df430b991bec76daa47e17c6102c4a4 | 74,416 |
def duplicate_fraction_getter(doc: Doc, attr: str = "lines_counter") -> float:
"""Calculate the duplicate fraction of a Doc attribute based on a counter object
Args:
doc (Doc): A spaCy Doc
attr (str, optional): The attribute to be extracted.
Defaults to "lines_counter".
Returns... | 977b19e926fbd4e08e683d214ea31c4caad73006 | 74,417 |
def __audioread_load(path, offset, duration, dtype):
"""Load an audio buffer using audioread.
This loads one block at a time, and then concatenates the results.
"""
y = []
with audioread.audio_open(path) as input_file:
sr_native = input_file.samplerate
n_channels = input_file.channe... | 3ae3038e08f371be7b47682351cf25dd1ac416d9 | 74,418 |
def get_aggregate_positions(info=None):
"""Collapses all option orders for a stock into a single dictionary.
:param info: Will data_filter the results to get a specific value.
:type info: Optional[str]
:returns: Returns a list of dictionaries of key/value pairs for each order. If info parameter is prov... | 22a783961a3bd95fe065ea7f3d45d23e43021bb4 | 74,419 |
from unittest.mock import Mock
from unittest.mock import patch
import importlib
def session_indexing_decorator():
"""
Fixture that mocks the reddit object indexer for the test suite by default.
Decorators require some extra work to patch since they are already applied to functions
when a module is lo... | 47b36b8cf82977e3c72179a5eb2260abb2427da7 | 74,420 |
def get_theoretical_resolution_limit(f_central):
"""
Parameters
----------
f_central : float
wavelet central frequency in Hz
Returns
-------
float
"""
return 1 / f_central / 4 * 1000 | 187498a249466eade7774e7df86fd82a1d742577 | 74,421 |
def calc_check_digit(number):
"""Calculate the check digit for the number."""
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cutoff = lambda x: x - 9 if x > 9 else x
s = sum(
cutoff(alphabet.index(n) * 2) if i % 2 == 0 else alphabet.index(n)
for i, n in enumerate(number[::-1]))
re... | 967d9ac7eae3e45b42c6bb4e366345fd34207d0d | 74,422 |
import tqdm
import torch
def gen_waveform(
device, # cpu or cuda
labels, # フルコンテキストラベル
logf0_vuv, # 連続対数基本周波数と有声 / 無声フラグ
wavenet_model, # 学習済み WaveNet
wavenet_in_scaler, # 条件付け特徴量の正規化用 StandardScaler
binary_dict, # 二値特徴量を抽出する正規表現
numeric_dict, # 数値特徴量を抽出する正規表現
tqdm=tqdm, # プログレ... | daa74a7b269d1a781238e1c5de2eee438702f7c8 | 74,423 |
def create_reduced_mechanical_system(M_func, D_func, K_func, f_int_func, f_ext_func, V, W=None, constant_mass=False,
constant_damping=False):
"""
Create a mechanical system from a component where the constraints are applied by a constraint formulation
Parameters
---... | dbd174ebe68e234061ebed00aac50994e6e94c99 | 74,424 |
def load_file(filename: str) -> list:
"""Load the passwords and policies from a file
:param filename: Location of the input file
:return: List of passwords and policies
"""
with open(filename) as f:
entries = f.readlines()
entries = [parse_line(e) for e in entries]
return entries | 6670a23003e8903147a612d3e387673aa88d0da1 | 74,425 |
from sklearn.feature_selection import RFE
def select_features_RFE(X,Y,base_model,kbest=15,dir_result='./'):
"""采用RFE方法选择特征,用户可以指定base_model"""
rfe = RFE(base_model, n_features_to_select=kbest)
fit = rfe.fit(X, Y)
feature_names = X.columns.values.tolist()
# 挑选出的特征
index_selected_features =... | 68347f75fc3f9732d290f3561ce4dc40bf137d57 | 74,426 |
def reg_lnX(lnX, data, masks, F, B, K, H, epsilon):
"""
inputs:
lnX : Log of PSF shared for all data
data : patches of stars
masks: masks containing flaged pixels for each patch
F : list of flux values of the stars in different ... | 5807048c1bcf28f2eb624c2284317cbd17738e0d | 74,428 |
def to_stars(num):
"""
turn feed score to stars
:param num:
:return:
"""
return '★' * int(num / 10)
#return int(num / 10) | 0d89f52554662861d5947f8a9f91ff678554f5cf | 74,429 |
def merge_ngrams(word_list, dict_ngrams, exception_dict):
"""
Merge words to ngrams.
Parameters
----------
word_list : list
List of single words.
dict_ngrams : dictionary
dict_ngrams includes bi, tri, and quangrams.
Each ngram is a list.
exception_dict : list
... | dea7fa127c3cd2c955753081786e57de3082474d | 74,430 |
def get_xy_index_column_name(index_column_elt):
"""
Get the Xylinq name of an index column.
@param IN index_column_elt Index column XML element
@return The name as a string
"""
return _get_xy_name(index_column_elt, "index column") | 0bcca81c35c97bbe4cc2ca5c35190f45e5ccf135 | 74,431 |
def __ge__(self,other) :
"""Return True iff other is an initial substring of self"""
if not isinstance(type(other),bitstrings) :
return NotImplemented;
return self._l >= other._l and self[:other._l] == other; | 36c7473949b6d46e79fe20a6e0c9ac3c3d3c86d1 | 74,432 |
import socket
def is_multicast (address):
"""Return ``True`` iff address is a multicast address.
This function is used to eliminate retransmissions for confirmable
messages sent to multicast addresses.
:param address: A socket address as supported by the Python socket
functions: i.e. a pair ... | 2de5497a422b4b40288f09ea224462bd9956a96c | 74,433 |
from pandas.core import common as com
from pandas import NaT
def na_value_for_dtype(dtype):
"""
Return a dtype compat na value
Parameters
----------
dtype : string / dtype
Returns
-------
dtype compat na value
"""
dtype = pandas_dtype(dtype)
if (com.is_datetime64_dtype(... | 7e7f3041e435a67bdea90e489146d9b86b79340d | 74,434 |
def _get_array_index(array_path):
"""Translates @first @last @1 @-1 expressions into an actual array index.
:param str array_path: Array path in XJ notation.
:rtype: int
:return: Array index.
"""
if not array_path.startswith('@'):
raise XJPathError('Array index must start from @ symbol... | c83b848c1ad793323402f1c99bd3e8839fdb6401 | 74,435 |
def redir(regex, redirect_url, name=None):
"""
A shorter wrapper around RedirectView for 301 redirects.
"""
return re_path(
regex,
RedirectView.as_view(url=redirect_url, permanent=True),
name=name,
) | 730eab46c8f38ebf2c2594eaea48f21c0b75df13 | 74,436 |
def pyreq_dlg_trybuild(httpreq_hdlr: HTTPRequestHandler, project_id: int):
"""
Run trial-build on dialog model for Mix project with ID project_id, by sending requests to
API endpoint with Python 'requests' package.
Please note that the dialog trial build may have result where status is 'SUCCESS' while ... | 46474633ef7996ae0e2fbd18432b7b061235b003 | 74,437 |
def normframe(img: np.ndarray, Clim: tuple) -> np.ndarray:
"""
inputs:
-------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael Hirsch, Ph.D.
"""
Vmin = Clim[0]
Vmax = Clim[1... | 808deb8c3463ff85a43ab4854f350d88acef0637 | 74,438 |
def calcul_positions_virages(coordonnees_du_personnage, orientation_du_personnage, profondeur_vision, liste_plan_du_labyrinthe):
"""
Prends en argument :
- La liste correspondant aux coordonnées du personnage, 'coordonnees_du_personnage';
- La chaîne de caractères correspondant à l'orientation du personnage, ... | 1fd818452750e98b0f24a269a19be324484fe6fc | 74,439 |
def load_embeddings(path = '../../NYT/glove.6B/glove.6B.300d.txt'):
"""
Loads pre-trained embeddings from the specified path.
@return (embeddings as an numpy array, word to index dictionary)
"""
word2idx = {} # Maps a word to the index in the embeddings matrix
embeddings = []
with ope... | 61cebe13602876c682ca35133aedadf69fd0a822 | 74,440 |
from typing import Union
def dL_df(
z: Union[float, np.array], cosmo: FLRW = Planck15
) -> un.Quantity[un.Mpc / un.MHz / littleh]:
"""
Get the factor to convert bandwidth to line-of-sight distance in Mpc/h.
Parameters
----------
z : float
The redshift
"""
return (cosmo.h * cns... | 14f6ce422028087042c7488f539d75a90302a668 | 74,441 |
def TFlt_GetPrcStr(*args):
"""
TFlt_GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args) | 24b6f564b74a37a59316209a58a4adb2bdde3052 | 74,442 |
def unique_filename(name):
"""
Returns unique file name based on "name" argument.
"""
return name | 1145ec89e9bbadf5944bc787ff1fda2805bfde1b | 74,443 |
def plasma_fractal(mapsize, wd):
"""
Generate a heightmap using diamond-square algorithm.
Return square 2d array, side length 'mapsize', of floats in range 0-255.
'mapsize' must be a power of two.
"""
assert (mapsize & (mapsize - 1) == 0)
maparray = np.empty((mapsize, mapsize), dtype=np.floa... | e950b5b71e4377cc5c04af946ba8e2c93833e598 | 74,444 |
import typing
def is_forward_ref(tp):
"""Returns true if `tp` is a typing forward reference."""
if hasattr(typing, 'ForwardRef'):
return isinstance(tp, typing.ForwardRef)
elif hasattr(typing, '_ForwardRef'):
return isinstance(tp, typing._ForwardRef) # pylint: disable=protected-access
else:
return... | 2220794e95e6b6f4333a856380d3cd47470623c9 | 74,445 |
from tqdm import tqdm
def GA(domain,fitness,N=50,nPAR=10,recomb_events=2,pS1=0.2,mut_prob=0.2,generations=1000,domain_gen=None,verbose=True,pop=[]):
""" Runs a Genetic Algorithm
Args:
domain (dict) : A <domain> dictionary
fitness (func) : A fitness function that accepts a sol
... | 16097ee6e22143936a79ce0039e6164b62af8738 | 74,446 |
from typing import Union
from typing import get_args
def smartround(num: Union[Integer, Float], ndigits=1) -> Union[int, float]:
"""Round number only if it's a float"""
if isinstance(num, get_args(Integer)):
return int(num)
else:
num = float(num)
if num.is_integer():
re... | 6ead0241e319e016d634862ef0ac38274b8a2468 | 74,447 |
def _get_previous_url(query, position, size):
"""Return the URL to retrieve the previous chunk of results."""
if position < 2:
return None
prev_pos = position - size if position - size > 0 else 1
url = '{0}?query={1}&position={2}&size={3}'
return url.format(request.base_url, query, prev_pos,... | 7090883f2cd5911577b99458ccc430b4b52360c6 | 74,448 |
def neuroscout_recorder():
""" Sets up client, recorder pair """
neuroscout = Neuroscout()
return betamax.Betamax(neuroscout._session), neuroscout | d9f83ee7d237d406aef3692d28e6e102f1ef6991 | 74,450 |
def sample_with_rotation(x, center, angle,
box_dim,
fill_value=255,
wraparound=True,
stdev_threshold=None,
test_stdev=False):
""" Get a patch from x, with rotation, without having to rotate t... | 4de637879d19124b21cdfbd2d8945ad97dfb60e0 | 74,451 |
def find_limits(pts):
"""
Find the limits which outline the provided list of points
Parameters:
* pts List of points [(z0,y0,x0),(z1,y1,x1),...]
Returns (min,max):
* min array of minimum indices array([zmin,ymin,xmin]
* max array of maximum indices array([zmin,ymin,xmin]
... | 8057e308499ceb930bdf6a7890c52258bc6ab5cf | 74,452 |
import re
def GetGcsSourceFromPath(input_file):
"""Validate a Google Cloud Storage location to read the PDF/TIFF file from.
Args:
input_file: the input file path arg given to the command.
Raises:
GcsSourceError: if the file is not a Google Cloud Storage object.
Returns:
vision_v1_messages.GcsSo... | b8c19ea9257e7287b8f396f2fab5bb931d7a9aed | 74,453 |
def left_child(node, new_node=None):
""" Set left child: left_child(node, new_left_child); Get left node: left_child(node). """
if new_node is not None:
node[1] = new_node
return node[1] | baabfbeb4acb7e8a2846b9a4a45b9d993619a1e4 | 74,454 |
from datetime import datetime
def prettify_timestamp(value: str) -> str:
"""
Returns a pretty version of a timestamp object.
Current format:
- %b short name of month like Mar, Jun
- %d day of the month from 1 to 31
- %Y year in 4 digit format
"""
return datetime.utcfromtimestamp(float(... | 82faefee2f98db33665c81c309e531d6dacab099 | 74,455 |
from typing import List
def find_colors(data: File, column: int) -> List[str]:
"""
Determine all the colors in a dataset.
"""
colors = set()
# Here, we show how to open a File to get a normal file stream.
with data.open() as infile:
for line in infile:
row = line.strip().s... | d9d356812e6be78388643d9edbd5e2e734c50a51 | 74,456 |
def _build_resubst_dict(rename_dict):
"""Build dictionary for later use with `_resubst()`.
**Example**
.. python::
>>> from SConsGnu.GVars import _build_resubst_dict
>>> _build_resubst_dict( {"xxx":"yyy", "vvv":"www", "zzz":"zzz" })
{'vvv': '${www}', 'xxx': '${yyy}'}
:Paramet... | 2eabc8da146cdaf80c4afa7eeac29077a293f8ab | 74,458 |
def getManifest(manifest_name = None):
"""
Download a client manifest.
"""
global MANIFESTS
baseurl = pref("RepoURL") + '/manifests/'
if manifest_name is None:
if 'client_manifest' in MANIFESTS:
return MANIFESTS['client_manifest']
#
# Make a list of the iden... | 2641f3de748f99fa14135e2061874b0854f1f147 | 74,459 |
def z_from_p(p, lat, geo_strf_dyn_height=0, sea_surface_geopotential=0):
"""Calculates height from sea pressure using the computationally-efficient
75-term expression for density in terms of SA, CT and p (Roquet et al.,
2015). Dynamic height anomaly, geo_strf_dyn_height, if provided, must be
computed wi... | 1dd8c16158f0225ca1426206a4ebaca9547446c0 | 74,461 |
def parse_other(lines):
"""Parse a series of lines in the format:
0123456789
a ~~~~~~~~~~
...
j ~~~~~~~~~~
Return a map of [x, y] -> MISS, NEAR_MISS or SUNK"""
parse = {}
for y, line in enumerate(lines[1:]):
for x, c in enumerate(line[2:]):
if c == Board.GUESS:
... | 338d71bfce9c580c9e15859a5913eba84bcc6a92 | 74,462 |
from typing import Optional
from typing import Callable
from typing import List
def cross_validate(
model: ModelBridge, folds: int = -1, test_selector: Optional[Callable] = None
) -> List[CVResult]:
"""Cross validation for model predictions.
Splits the model's training data into train/test folds and make... | b3a9d438fa1ea6fe3c856f63308590173ab2bdeb | 74,463 |
def boxcar(x, x1, x2):
""" DOC """
if hasattr(x, 'size'):
y = 1.0 * np.ones_like(x)
y[x < x1] = 0.0
y[x > x2] = 0.0
return y
if x1 <= x <= x2:
return 1.0
return 0.0 | ba9d81a4309e30a6613de6d5e8dca3ecef8fc96d | 74,464 |
def _extract_instance_parameters(attributes):
"""
Extracts instance parameters. If no name found, replaced with identifier.
:param attributes: dict, with the following structure:
{
"arn": string,
"name": string,
"tags": {
"{tag_name}": string
... | 99e76f5f663798667c8121c1f2c9ac243cf1a67c | 74,466 |
def show(db: Session, filename: str):
"""
:param db:
:param filename:
:return:
"""
file_obj = db.query(FileModel).filter(FileModel.s3_filename == filename).first()
if not file_obj:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"File... | 1de63c2ef93fa415b7e40d13c3495cb641ff6e92 | 74,467 |
def TDictOf(key_type, val_type):
"""Checks a dict type for the type of its key/values.
"""
desc = WithDesc("Dictionary with keys of %s and values of %s" %
(Parens(key_type), Parens(val_type)))
def fn(container):
return (compat.all(key_type(v) for v in container.keys()) and
co... | 91672ef089e8c245d6fac8da8f7018719cfb6dfb | 74,468 |
def heading_html(hl, hd, nodes, attrs, context):
"""Formats a HTML heading."""
return [mkdata("<h{n}>{title}</h{n}>".format(n=clamp(1, hl, 6), title=hd))] | 76f8e8e1c22cd05bae07981a24e41fb6c8d63610 | 74,469 |
def remove_position(lmks, position=None):
"""If `position` is `None`, :func:`remove_position` translates `lmks` such
that :func:`get_position()` of `translated_lmks` is the origin. Else it is
the (:func:`get_position()` of `lmks`) - `position`.
Parameters
----------
lmks : array-like
... | 3dde882e1a1a752ccfde12a0088063e76fbbaffd | 74,470 |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
#funny storytime! initially did not pass because I falsely reme... | 4eff4e8d69e7843e2a4e4043df29139d92ded772 | 74,471 |
def custom_subparser_builder(subparser, subparser_id, description, options_func, runner_func, setup_func, shutdown_func, error_handler_func):
"""
Util to add subparser options
:param options_func: Function that will add args and options to Parser instance F(subparser) -> None
:param runner_func: Functi... | 0d5914646e07be26792fae321c32f3338d6b467b | 74,472 |
from typing import Union
from typing import Iterable
from typing import Any
def flag_nulls(
df: pd.DataFrame,
column_name: str = "null_flag",
columns: Union[str, Iterable[str], Any] = None,
) -> pd.DataFrame:
"""
Creates a new column to indicate whether you have null values in a given
row. If ... | 083da4f596b878a25b70e7f2b2648ac59e335e9c | 74,475 |
def std_dev_classification(data, window_length, threshold):
"""Perform wet/dry classification with Rolling standard deviation method
Parameters
----------
data : iterable of float
Time series of received signal level
window_length : int
Length of the sliding window
threshold ... | 3b2c75f417ec99290f7d41497610c356833f3934 | 74,476 |
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
operand = tf_np.asarray(operand)
start_indices = [0] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
start_indices[axis] = start_index
slice_sizes... | e548384a1f2444716960e955f374a4eb710fbff7 | 74,477 |
def process_achievement(aid, data):
"""
Determines whether or not an achievement has been earned.
Should not be called directly.
Args:
aid: the achievement id
data: additional data dictionary
"""
if data.get("uid", None) is None:
data["uid"] = api.user.get_user()["uid"]... | 82bbc59eb90ef3763c879887b4825d13185c8588 | 74,478 |
def validate(db_ns, db_id):
"""Validate identifier, accepting HGNC name or ID"""
if db_ns == 'HGNC':
if db_id.isdigit():
return validate_id(db_ns, db_id)
else:
return get_hgnc_id(db_id) is not None
else:
return validate_id(db_ns, db_id) | 94ee9b009f4993d64c11b80e5d5ca5a307064b57 | 74,479 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.