content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_add_many_columns_function(row_function, data_types):
"""Returns a function which adds several columns to a row based on given row function"""
def add_many_columns(row):
result = row_function(row)
data = []
for i, data_type in enumerate(data_types):
try:
... | 72bb0edae6ddd109beae118f691fc387b6bfdce7 | 21,808 |
import torch
def sumlike_wrap(fun_name):
"""Handle torch.sum and torch.mean"""
# Define appropriate torch function, the rest of the logic is the same
assert fun_name in ['sum', 'mean']
torch_fun = getattr(torch, fun_name)
@wraps(torch_fun)
def sumlike_fun(input, dim=None, keepdim=False):
... | 3aa0247b965dbbf5038e4b0f4f00b0ead9855270 | 21,810 |
def __crossover(n: int, g: np.matrix, m_list: np.array, f_list: np.array) -> np.matrix:
"""
:param n: half of g.shape[0]
:param g: bin mat of genes
:param m_list: male nums
:param f_list: female nums
:return: crossed-over bin mat of genes
"""
cros = np.random.randint(low=0, high=g.shape[1], size=n)
g_cros = n... | 93fbd5138bdf2e293fe0515a0096ab643fbf1953 | 21,811 |
def setup_system():
"""
Galacitic center potential and Arches cluster
position from Kruijssen 2014
"""
potential = static_potentials.Galactic_Center_Potential_Kruijssen()
cluster = Particle()
# At time 2.05 in KDL15
cluster.position = [-17.55767, -53.26560, -9.39921] | units.par... | 9713feaa51bfb0430394a8e8171bdecd3590d5e2 | 21,812 |
from typing import Iterable
from typing import List
def collect_dynamic_libs(name: str, dest: str = ".", dependencies: bool = True,
excludes: Iterable[str] = None) -> List:
"""
Collect DLLs for distribution **name**.
Arguments:
name:
The distribution's project... | 5e4ed9f9d412c6e071d85fcb34091fbed0722258 | 21,814 |
import pickle
def make_agreements(file) -> pd.DataFrame:
"""In some of the human conditions, we hold out questions. Each randomly generated agent is
given our test and then asked it's opinion on every hold out question.
agreements.pkl is a Dict[Experiment, Tuple(ndarray, ndarray)] where each array elemen... | e9cb9e45aa1c2ff5b694f6712da2892c6f44fd99 | 21,815 |
def column_as_html(column, table):
"""Return column as an HTML row."""
markup = "<tr>"
markup += "<td class='field'>{0}</td>".format(column.name, column.comment)
markup += "<td>{0}</td>".format(column.formattedType)
# Check for Primary Key
if table.isPrimaryKeyColumn(column):
markup += ... | 0c6ed56cd686a4359776022407b023d5733198c9 | 21,816 |
def covariation(x, y):
"""
Covariation of X and Y.
:param list or tuple x: 1st array.
:param list or tuple y: 2nd array.
:return: covariation.
:rtype: float
:raise ValueError: when x or y is empty
"""
if x and y:
m_x = mean(x)
m_y = mean(y)
dev_x = [i - m_x f... | dd42467a453978edb5970b79653724f77c07beb7 | 21,817 |
def stripped_spaces_around(converter):
"""Make converter that strippes leading and trailing spaces.
``converter`` is called to further convert non-``None`` values.
"""
def stripped_text_converter(value):
if value is None:
return None
return converter(value.strip())
ret... | b92f38d3eb8d191f615488bbd11503bae56ef6de | 21,818 |
from typing import Union
from typing import Literal
from typing import Any
def ootf_inverse(
value: FloatingOrArrayLike,
function: Union[
Literal["ITU-R BT.2100 HLG", "ITU-R BT.2100 PQ"], str
] = "ITU-R BT.2100 PQ",
**kwargs: Any
) -> FloatingOrNDArray:
"""
Maps relative display linear... | 65c7aa374d1daa086828b87a4f30802f63b4a3b7 | 21,819 |
def modified_query(benchmark, model_spec, run_index: int, epochs=108, stop_halfway=False):
"""
NOTE:
Copied from https://github.com/google-research/nasbench/blob/b94247037ee470418a3e56dcb83814e9be83f3a8/nasbench/api.py#L204-L263 # noqa
We changed the function in such a way that we now can specified the... | 21ccbafb230da1d984f53f36f41c6e9ceb0d7f18 | 21,821 |
def gauss(x, mu=0, sigma=1):
"""
Unnormalized Gaussian distribution.
Parameters
----------
Returns
-------
y : type(x)
Gaussian evaluated at x.
Notes
-----
Some people use alpha (1/e point)
instead of the sigma (standard deviation)
to define the width of the Gaussian.
They are r... | 24e5c5b9e42cc6b84e6d2c4aa9f2a26b44793112 | 21,822 |
def GetSpd(ea):
"""
Get current delta for the stack pointer
@param ea: end address of the instruction
i.e.the last address of the instruction+1
@return: The difference between the original SP upon
entering the function and SP for the specified address
"""
func = ida... | 84c00ac2bb722e51d27813a35f55c8c59fdac579 | 21,823 |
def is_fugashi_ipadic_available():
"""
Check if the library is available.
This function checks if sentencepiece is available in your environment
and returns the result as a bool value.
Returns
-------
_fugashi_ipadic_available : bool
If True, fugashi wiht ipadic is available in you... | cc3b80718691b2914f57c950452f2fbb253100d1 | 21,824 |
import torch
def pad_to_sidelength(schematic, labels=None, nothing_id=0, sidelength=32):
"""Add padding to schematics to sidelength"""
szs = list(schematic.size())
szs = np.add(szs, -sidelength)
pad = []
# this is all backwards bc pytorch pad semantics :(
for s in szs:
if s >= 0:
... | 81a7bb8deb2474106715720f79e0d3ee8937557b | 21,825 |
def segmentation_gaussian_measurement_batch(
y_true,
y_pred,
gaussian_sigma=3,
measurement=segmentation_losses.binary_crossentropy):
""" Apply metric or loss measurement to a batch of data incorporating a 2D gaussian.
Only works with batch size 1.
Loop and call this ... | de88b6ee1175612f7fa8e41c98dc6e1b3287a034 | 21,826 |
def save_image(img: Image, img_format=None, quality=85):
""" Сохранить картинку из потока в переменную для дальнейшей отправки по сети
"""
if img_format is None:
img_format = img.format
output_stream = BytesIO()
output_stream.name = 'image.jpeg'
# на Ubuntu почему-то нет jpg, но есть jpe... | 5696745ad33a2b1b59718f1c4d4eedf0eda7cd46 | 21,827 |
def check_input(args: dict) -> dict:
"""
Check if user entries latitude and longitude are well formated. If ok, retruns a dict with
lat and lng converted as flaots
- args: dict. request.args
"""
lat = args.get("lat")
lng = args.get("lng")
if lat is None:
abort(400, "Latitude... | 078fc0ae5665562d6849746788b1f7a5a88981eb | 21,828 |
def adjust_learning_rate(epoch, total_epochs, only_ce_epochs, learning_rate, optimizer):
"""Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for ... | 94ddbb9fcc7676799f7e032f4ab6658b1b056b32 | 21,829 |
def dummy_nullgeod():
"""
Equatorial Geodesic
"""
return Nulllike(
metric="Kerr",
metric_params=(0.5,),
position=[4., np.pi / 2, 0.],
momentum=[0., 0., 2.],
steps=50,
delta=0.5,
return_cartesian=False,
suppress_warnings=True,
) | fd5af27cebd029fbcbcdab07f154ee4f4dff2575 | 21,830 |
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
C = tensor.size(1)
# new axis order
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
# Transpose: (N, C, D, H, W) ->... | 67a0d89ce98e6695a9d58b1f3ab2f403b09c89ce | 21,832 |
from chiesa_correction import align_gvectors
def compare_scalar_grids(gvecs0, nkm0, gvecs1, nkm1, atol=1e-6):
"""Compare two scalar fields sampled on regular grids
Args:
gvecs0 (np.array): first grid, (npt0, ndim)
nkm0 (np.array): values, (npt0,)
gvecs1 (np.array): second grid, (npt1, ndim), expect n... | 0f75d4387e4c8a5f497a85191df342ac33df1c11 | 21,833 |
def a_dot(t):
"""
Derivative of a, the scale factor
:param t:
:return:
"""
return H0 * ((3 / 2) * H0 * t) ** (-1 / 3) | b5557176f75ed45f6e5b38eb827d655779311e0a | 21,834 |
def frame(x, frame_length, hop_length, axis=-1, name=None):
"""
Slice the N-dimensional (where N >= 1) input into (overlapping) frames.
Args:
x (Tensor): The input data which is a N-dimensional (where N >= 1) Tensor
with shape `[..., seq_length]` or `[seq_length, ...]`.
frame_le... | f43420ceefa8963579776c5234179274688c83d6 | 21,835 |
import functools
def wrapped_partial(func: callable, *args, **kwargs) -> callable:
"""Wrap a function with partial args and kwargs.
Args:
func (callable): The function to be wrapped.
*args (type): Args to be wrapped.
**kwargs (type): Kwargs to be wrapped.
Returns:
callabl... | d8c3eb53e3c74104aa72acce545269c98585cd83 | 21,836 |
import typing
def with_sfw_check(
command: typing.Optional[CommandT] = None,
/,
*,
error_message: typing.Optional[str] = "Command can only be used in SFW channels",
halt_execution: bool = False,
) -> CallbackReturnT[CommandT]:
"""Only let a command run in a channel that's marked as sfw.
P... | 565d4e0f9e5f473a72692511a1ba3896717c9069 | 21,837 |
def algorithm_id_to_generation_class(algorithm_id):
"""
Returns the Generation class corresponding to the
provided algorithm ID (as defined in settings).
"""
return _algorithm_id_to_class_data(algorithm_id)[1] | 5cf4ede818832a57c1c279d5c78c43c2c214b9b5 | 21,838 |
def search(session, **kwargs):
"""
Searches the Discogs API for a release object
Arguments:
session (requests.Session) - API session object
**kwargs (dict) - All kwargs are added as query parameters in the search call
Returns:
dict - The first result returned in the search
Raises:
... | f67646b3060602b743eb4166a4aab5882b8a3c81 | 21,839 |
def _conv_general_precision_config_proto(precision):
"""Convert an integer to an XLA.PrecisionConfig."""
if precision is None:
return None
proto = xla_data_pb2.PrecisionConfig()
proto.operand_precision.append(int(precision))
return proto | 8b43272aadeccd4385ddb74bcf0691f4a779e4c1 | 21,840 |
def list_in_list(a, l):
"""Checks if a list is in a list and returns its index if it is (otherwise
returns -1).
Parameters
----------
a : list()
List to search for.
l : list()
List to search through.
"""
return next((i for i, elem in enumerate(l) if elem == a), -1) | 494d9a880bcd2084a0f50e292102dc8845cbbb16 | 21,842 |
def sent_to_idx(sent, word2idx, sequence_len):
"""
convert sentence to index array
"""
unknown_id = word2idx.get("UNKNOWN", 0)
sent2idx = [word2idx.get(word, unknown_id) for word in sent.split("_")[:sequence_len]]
return sent2idx | ffaa65741d8c24e02d5dfbec4ce84c03058ebeb8 | 21,844 |
from re import T
def expand_sqs_results(settings: Settings, sqs_results: T.Iterable[SQSResult],
timings: T.Optional[TimingDictionary] = None, include=('configuration',),
inplace: bool = False) -> Settings:
"""
Serializes a list of :py:class:`sqsgenerator.public.SQ... | 316e6d66617f6715193502058eff173954214a89 | 21,845 |
def test_files_atlas(test_files):
"""ATLAS files"""
# ssbio/test/test_files/atlas
return op.join(test_files, 'atlas') | 9ab8f55582d85e7f51c301b1cc0c80a5b7233b47 | 21,846 |
from modefit.basics import get_polyfit
def _get_xaxis_polynomial_(xyv, degree=DEGREE, legendre=LEGENDRE,
xmodel=None, clipping = [5,5]):
""" """
x,y,v = xyv
flagin = ((np.nanmean(y) - clipping[0] * np.nanstd(y)) < y) * (y< (np.nanmean(y) + clipping[1] * np.nanstd(y)))
co... | d0b4ebf790339154fe0d979ec720a9960be92da8 | 21,847 |
def generateKey():
"""
Method to generate a encryption key
"""
try:
key = Fernet.generate_key()
updateClipboard(f"export LVMANAGER_PW={str(key)[2:-1]}")
print(f"Key: {key}")
print("Export command copied to clipboard. Save this value!")
return True
except Excep... | a0d197c499d978600c6d95879aab67d595648ffc | 21,848 |
def _zpkbilinear(z, p, k, fs):
""" Return a digital filter from an analog one using a bilinear transform """
z = np.atleast_1d(z)
p = np.atleast_1d(p)
degree = _relative_degree(z, p)
fs2 = 2.0 * fs
# Bilinear transform the poles and zeros
z_z = (fs2 + z) / (fs2 - z)
p_z = (fs2 + p) / (fs... | ef7e50ae81023edc599fb56e3c1e20a4579f8389 | 21,849 |
def so3exp(w):
"""
Maps so(3) --> SO(3) group with closed form expression.
"""
theta = np.linalg.norm(w)
if theta < _EPS * 3:
return np.eye(3)
else:
w_hat = S03_hat_operator(w)
R = np.eye(3) + (np.sin(theta) / theta) * w_hat + ((1 - np.cos(theta)) / theta**2) * np.dot... | 434168c7652311a850dbcb700343e445ac808c57 | 21,850 |
def bin2ppm(nproc_old, model_tags, region, npts, nproc,
old_mesh_dir, old_model_dir, output_dir):
"""
convert the bin files to the ppm model.
"""
result = ""
julia_path = get_julia("specfem_gll.jl/src/program/get_ppm_model.jl")
latnproc, lonnproc = map(int, nproc.split("/"))
npro... | 2e8f8be993ca7d164faf2cfce4e1539a16764ad4 | 21,851 |
def st_sdata(obs, cols):
"""return string data in given observation numbers as a list of lists,
one sub-list for each row; obs should be int or iterable of int;
cols should be a single str or int or iterable of str or int
"""
obs, cols, _ = _parseObsColsVals(obs, cols)
if not all(st_i... | 7e08168a42043b7de379f7f513f25b6e88a89847 | 21,852 |
def list_data(args, data):
"""List all servers and files associated with this project."""
if len(data["remotes"]) > 0:
print("Servers:")
for server in data["remotes"]:
if server["name"] == server["location"]:
print(server["user"] + "@" + server["location"])
... | 6a005b6e605d81985fca85ca54fd9b29b28128f5 | 21,853 |
def vecInt(xx, vv, p, interpolation = 'weighted'):
"""
Interpolates the field around this position.
call signature:
vecInt(xx, vv, p, interpolation = 'weighted')
Keyword arguments:
*xx*:
Position vector around which will be interpolated.
*vv*:
Vector ... | c93572205e1d5a3c00ef21f1780a5184c695d988 | 21,854 |
def anchor_inside_flags(flat_anchors, valid_flags, img_shape,
allowed_border=0, device='cuda'):
"""Anchor inside flags.
:param flat_anchors: flat anchors
:param valid_flags: valid flags
:param img_shape: image meta info
:param allowed_border: if allow border
:return: ins... | 500fe39f51cbf52bd3417b14e7ab7dcb4ec2f9cc | 21,855 |
def notinLRG_mask(primary=None, rflux=None, zflux=None, w1flux=None,
rflux_snr=None, zflux_snr=None, w1flux_snr=None):
"""See :func:`~desitarget.sv1.sv1_cuts.isLRG` for details.
Returns
-------
:class:`array_like`
``True`` if and only if the object is NOT masked for poor quali... | a89a02d017140f1321905695bbbcb34789b2e535 | 21,856 |
def get_theta_def(pos_balle:tuple, cote:str):
"""
Retourne les deux angles theta (voir les explications) pour que le goal soit aligné avec la balle.
Ceux-ci sont calculés en fonction des deux poteaux pour avoir les deux "extrémités" pour être correctement alignées.
Paramètres:
- pos_balle : tuple - conti... | 0fdde277c4c63b593c5c40c595c7181539eb0fd1 | 21,857 |
def public_doc():
"""Documentation for this api."""
return auto.html(groups=['public'], title='Ocean App Web Service Public Documentation') | 37d343ca4159566f4191a9f8608378dea7ce1bb5 | 21,858 |
def getAllTeams():
"""
returns the entire list of teams
"""
return Team.objects.order_by('name').all() | 8e06518e417657d3a24d4261a71d9b0bda31af22 | 21,859 |
def parse_lamp_flags(flags):
"""Parses flags and returns a dict that represents the lamp states."""
# flags: [0123]{8}
values = _swap_key_and_value(_LAMP_STATES) # {value: state}
states = dict([
(color, values[flags[digit]]) for color, digit in _LAMP_DIGITS.items()
])
return {'lamps': s... | 5a2416ebca980fd9d3ae717aaa4da3b008d76e95 | 21,860 |
def user_owns_item(function):
""" Decorator that checks that the item was created by current user. """
@wraps(function)
def wrapper(category_name, item_name, *args, **kwargs):
category = db_session.query(Category
).filter_by(name=category_name).one()
user_... | 912c93408b6297c338be6dc48414f3b4bb57aea3 | 21,861 |
def generate_bit_byte_overview(inputstring, number_of_indent_spaces=4, show_reverse_bitnumbering=False):
"""Generate a nice overview of a CAN frame.
Args:
inputstring (str): String that should be printed. Should be 64 characters long.
number_of_indent_spaces (int): Size of indentation
... | 325eafc0ca9a8d91e3774cc6bc8b91052b01d261 | 21,862 |
def return_list_of_file_paths(folder_path):
"""Returns a list of file paths
Args:
folder_path: The folder path were the files are in
Returns:
file_info: List of full file paths
"""
file_info = []
list_of_file_names = [fileName for fileName in listdir(folder_path) if isfile(joi... | 7bc67a17b028d68d3ef99fc82cd03e21c34ec803 | 21,863 |
import numpy
def artificial_signal( frequencys, sampling_frequency=16000, duration=0.025 ):
"""
Concatonates a sequence of sinusoids of frequency f in frequencies
"""
sins = map( lambda f : sinusoid(f, sampling_frequency, duration), frequencys)
return numpy.concatenate( tuple(sins) ) | ef67e5ca9b66da8c003108e2fe5eb4ba43d7a564 | 21,864 |
def _sources():
"""Return the subdir name and extension of each of the contact prediction types.
:return: Contact prediction types and location.
:rtype: dict [list [str]]
"""
sources = _sourcenames()
confiledir = ["deepmetapsicov", "deepmetapsicov", "deepmetapsicov"]
confilesuffix = ["psic... | f03b6059a106a5fe5619b2b673eb88d9b352e70f | 21,865 |
def pdns_forward(hostname):
"""Get the IP addresses to which the given host has resolved."""
response = get(BASE_API_URL + "pdns/forward/{}".format(hostname))
return response | 3022190035bc6acc0ff1d16da7616703ca339c53 | 21,866 |
def make_conv(in_channels, out_channels, conv_type="normal", kernel_size=3, mask_activation=None, version=2, mask_init_bias=0, depth_multiplier=1, **kwargs):
"""Create a convolution layer. Options: deformable, separable, or normal convolution
"""
assert conv_type in ("deformable", "separable", "normal")
... | 515e0544aae6464c966612b3c32e23e878a9260d | 21,867 |
import requests
from selenium import webdriver
from time import sleep
from typing import Callable
def url_to_html_func(kind="requests") -> Callable:
"""Get a url_to_html function of a given kind."""
url_to_html = None
if kind == "requests":
def url_to_html(url):
r = requests.get(url)
... | f19643f1d49212e643fc0fe50ce69f5f4a444c09 | 21,868 |
def head(filename, format=None, **kwargs):
"""
Returns the header of a file. Reads the information about the content of the file
without actually loading the data. Returns either an Header class or an Archive
accordingly if the file contains a single object or it is an archive, respectively.
Parame... | f7e0bb98f95b378bd582801b00a26c72aef0b677 | 21,871 |
def uncomment_magic(
source, language="python", global_escape_flag=True, explicitly_code=True
):
"""Unescape Jupyter magics"""
parser = StringParser(language)
next_is_magic = False
for pos, line in enumerate(source):
if not parser.is_quoted() and (
next_is_magic
or is... | 4d3444844e51c4821f151a3ce9813c8475fa6bd7 | 21,872 |
from re import T
import logging
def clean_nice_ionice_parameters(value):
"""Verify that the passed parameters are not exploits"""
if value:
parser = ErrorCatchingArgumentParser()
# Nice parameters
parser.add_argument("-n", "--adjustment", type=int)
# Ionice parameters, not su... | 9bbde29a4a8c19441d4c1510c29870c87d928142 | 21,873 |
def rand_alnum(length=0):
"""
Create a random string with random length
:return: A random string of with length > 10 and length < 30.
"""
jibber = ''.join([letters, digits])
return ''.join(choice(jibber) for _ in xrange(length or randint(10, 30))) | 7a095aabcec5428ea991220ae46c252c47b3436a | 21,874 |
def _GenerateGstorageLink(c, p, b):
"""Generate Google storage link given channel, platform, and build."""
return 'gs://chromeos-releases/%s-channel/%s/%s/' % (c, p, b) | e5e4a0eb9e27b0f2d74b28289c8f02dc0454f438 | 21,875 |
def parse_decl(inputtype, flags):
"""
Parse type declaration
@param inputtype: file name or C declarations (depending on the flags)
@param flags: combination of PT_... constants or 0
@return: None on failure or (name, type, fields) tuple
"""
if len(inputtype) != 0 and inputtype[-1] != ';':... | a5cf042256a35cface8afd024d5d31ae5eccbe72 | 21,876 |
def post_attention(h, attn_vec, d_model, n_head, d_head, dropout, is_training,
kernel_initializer, residual=True):
"""Post-attention processing."""
monitor_dict = {}
# post-attention projection (back to `d_model`)
proj_o = tf.get_variable("o/kernel", [d_model, n_head, d_head],
... | d48157d3759ab273b78a45dd2d150e15f66b44bf | 21,877 |
def get_recursively(in_dict, search_pattern):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in in_dict.items():
if key == search_pattern:
fields_found.append(value)
elif ... | 3c9011894c24c25a05d24f8b3b5369c9334dc2c7 | 21,878 |
def neals_funnel(ndims = 10,
name = 'neals_funnel'):
"""Creates a funnel-shaped distribution.
This distribution was first described in [1]. The distribution is constructed
by transforming a N-D gaussian with scale [3, 1, ...] by scaling all but the
first dimensions by `exp(x0 / 2)` where `x0`... | 99719ce2e192034472bf8082c918c39a6ab1a96f | 21,879 |
def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_co... | 4cac23303e2b80e855e800a7d55b7826fabd9992 | 21,880 |
def colon(mac):
""" aa:aa:aa:aa:aa:aa """
return _reformat(mac, separator=':', digit_grouping=2) | 7930fdb449f99aa99a2c052be4eee24a8e4605ab | 21,881 |
import requests
from bs4 import BeautifulSoup
import re
def create_strings_from_wikipedia(minimum_length, count, lang):
"""
Create all string by randomly picking Wikipedia articles and taking sentences from them.
"""
sentences = []
while len(sentences) < count:
# We fetch a random pag... | 92cc09a081a257d61530e3ddaf8f8215412e5b0d | 21,882 |
def computeHashCheck(ringInputString, ringSize):
"""Calculate the knot hash check.
Args:
ringInputString (str): The list of ints to be hashed as a comma-separated list.
ringSize (int): The size of the ring to be \"knotted\".
Returns:
int: Value of the hash check.
"""
ringI... | 75dce4aacdd4ae03fa34532471a21a43a81fbd13 | 21,883 |
from masci_tools.util.xml.xml_setters_basic import xml_delete_tag
from masci_tools.util.xml.common_functions import check_complex_xpath
from typing import Union
from typing import Iterable
from typing import Any
def delete_tag(xmltree: Union[etree._Element, etree._ElementTree],
schema_dict: 'fleur_sche... | 2e4d9276ecc8d42c0890e81aa0afa61adf23c178 | 21,884 |
def cart2pol_vectorised(x, y):
"""
A vectorised version of the cartesian to polar conversion.
:param x:
:param y:
:return:
"""
r = np.sqrt(np.add(np.power(x, 2), np.power(y, 2)))
th = np.arctan2(y, x)
return r, th | dbef7d4663990a9e3c775e53649ab30e0dc8767a | 21,885 |
def encryption(text):
"""
encryption function for saving ideas
:param text:
:return:
"""
return AES.new(cipher_key, AES.MODE_CBC, cipher_IV456).encrypt(text * 16) | c321dd2e0c95f15c9a4b04f1b13471a1f1a7aceb | 21,886 |
def _concat(to_stack):
""" function to stack (or concatentate) depending on dimensions """
if np.asarray(to_stack[0]).ndim >= 2:
return np.concatenate(to_stack)
else:
return np.hstack(to_stack) | 1b4ab755aed3e1823629301e83d070433d918c7c | 21,888 |
import math
def make_orthonormal_matrix(n):
"""
Makes a square matrix which is orthonormal by concatenating
random Householder transformations
Note: May not distribute uniformly in the O(n) manifold.
Note: Naively using ortho_group, special_ortho_group in scipy will result in unbearable computin... | ec7f39eba0d471f377519db86cee85a0b640593b | 21,889 |
from typing import Dict
from typing import Tuple
def build_synthetic_dataset_cae(window_size:int, **kwargs:Dict)->Tuple[SingleGapWindowsSequence, SingleGapWindowsSequence]:
"""Return SingleGapWindowsSequence for training and testing.
Parameters
--------------------------
window_size: int,
Win... | 9ab09aadf9578a3475a2e9bbaa7cfa75a3adacdf | 21,891 |
import random
def montecarlo_2048(game, simulations_per_move, steps, count_zeros=False, print_averages=True, return_scores=False):
"""
Test each possible move, run montecarlo simulations and return a dictionary of average scores,
one score for each possible move
"""
# Retrieve game score at the c... | 1bfd9beb78e6f832105b61d28af2218b6a86eb1a | 21,892 |
def getAggregation(name, local=False, minOnly=False, maxOnly=False):
"""
Get aggregation.
"""
toReturn = STATISTICS[name].getStatistic()
if local:
return STATISTICS[name].getLocalValue()
elif minOnly and "min" in toReturn:
return toReturn["min"]
elif maxOnly and "max" in toRe... | 2f009c4db871fe56a8c26ee75728259e33b53280 | 21,893 |
def get_gene_symbol(row):
"""Extracts gene name from annotation
Args:
row (pandas.Series): annotation info (str) at 'annotation' index
Returns:
gene_symbol (str): gene name(s)
"""
pd.options.mode.chained_assignment = None
lst = row["annotation"].split(",")
genes = [token.sp... | d564266fa6a814b4c7cfce9f7f2fb8d5e1c1024f | 21,894 |
from datetime import datetime
def session_login():
"""
Session login
:return:
"""
print("Session Login")
# Get the ID token sent by the client
# id_token = request.headers.get('csfToken')
id_token = request.values.get('idToken')
# Set session expiration to 5 days.
expires_in = ... | 6c5c27d50c4c62e3f62b67433f4161835f2a6478 | 21,895 |
from django.core.cache import get_cache
def get_cache_factory(cache_type):
"""
Helper to only return a single instance of a cache
As of django 1.7, may not be needed.
"""
if cache_type is None:
cache_type = 'default'
if not cache_type in cache_factory:
cache_factory[c... | 89da971b92395c4e604d51d66148688f2ab4f362 | 21,896 |
import six
import pickle
def ruleset_from_pickle(file):
""" Read a pickled ruleset from disk
This can be either pickled Rules or Ryu Rules.
file: The readable binary file-like object, or the name of the input file
return: A ruleset, a list of Rules
"""
if six.PY3:
ruleset... | f68e005ece3697126dd0528952e1610695054332 | 21,897 |
def delayed_read_band_data(fpar_dataset_name, qc_dataset_name):
"""Read band data from a HDF4 file.
Assumes the first dimensions have a size 1.
FparLai_QC.
Bit no. 5-7 3-4 2 1 0
Acceptable values:
000 00 0 0 0
001 01 0 0 0
Unacceptable mask:
110 10 1 1... | cda95533b07101d58883c0f5fa32870c48c09e2a | 21,899 |
def _aggregate_pop_simplified_comix(
pop: pd.Series, target: pd.DataFrame
) -> pd.DataFrame:
"""
Aggregates the population matrix based on the CoMix table.
:param pop: 1-year based population
:param target: target dataframe we will want to multiply or divide with
:return: Retuns a dataframe tha... | 11ddfb103c95416b1a93577f90e12aa6159123eb | 21,900 |
def authenticate():
"""
Uses HTTP basic authentication to generate an authentication token.
Any resource that requires authentication can use either basic auth or this token.
"""
token = serialize_token(basic_auth.current_user())
response = {'token': token.decode('ascii')}
return jsonify(response) | adfd4d80bb08c6a0c3175495b4b2ab1aa0b898c6 | 21,901 |
import torch
def split_image(image, N):
"""
image: (B, C, W, H)
"""
batches = []
for i in list(torch.split(image, N, dim=2)):
batches.extend(list(torch.split(i, N, dim=3)))
return batches | da51c3520dfee740a36d5e0241f3fd46a07f2752 | 21,902 |
def _upsample_add(x, y):
"""Upsample and add two feature maps.
Args:
x: (Variable) top feature map to be upsampled.
y: (Variable) lateral feature map.
Returns:
(Variable) added feature map.
Note in PyTorch, when input size is odd, the upsampled feature map
with `F.upsample(..., sca... | facac22b50906509138a479074a7744b737d554d | 21,903 |
def get_eta_and_mu(alpha):
"""Get the value of eta and mu. See (4.46) of the PhD thesis of J.-M. Battini.
Parameters
----------
alpha: float
the angle of the rotation.
Returns
-------
The first coefficient eta: float.
The second coefficient mu: float.
"""
if alpha == 0... | 4f1a215a52deda250827d4ad3d06f8731c69dc9d | 21,904 |
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to fi... | 3d1c1ab7b2f346dab0fe3f01a262983c880eda34 | 21,905 |
def write_error_row(rowNum, errInfo):
"""Google Sheets API Code.
Writes all team news link data from RSS feed to the NFL Team Articles speadsheet.
https://docs.google.com/spreadsheets/d/1XiOZWw3S__3l20Fo0LzpMmnro9NYDulJtMko09KsZJQ/edit#gid=0
"""
credentials = get_credentials()
http = credential... | 5a3d071d78656f6991103cac72c7ce46f025d689 | 21,906 |
import json
def get_last_transaction():
""" return last transaction form blockchain """
try:
transaction = w3.eth.get_transaction_by_block(w3.eth.blockNumber, 0)
tx_dict = dict(transaction)
tx_json = json.dumps(tx_dict, cls=HexJsonEncoder)
return tx_json
except Exception as... | 89a70c474670b6e691fde8424ffc78b739ee415e | 21,907 |
def get_tp_model() -> TargetPlatformModel:
"""
A method that generates a default target platform model, with base 8-bit quantization configuration and 8, 4, 2
bits configuration list for mixed-precision quantization.
NOTE: in order to generate a target platform model with different configurations but wi... | 5a501f18a090927f7aeba9883f3676ede595944c | 21,908 |
from typing import Optional
def check_sparv_version() -> Optional[bool]:
"""Check if the Sparv data dir is outdated.
Returns:
True if up to date, False if outdated, None if version file is missing.
"""
data_dir = paths.get_data_path()
version_file = (data_dir / VERSION_FILE)
if versio... | 2c2ebeee0ad0c8a08c841b594ca45676a22407d7 | 21,910 |
def grav_n(expt_name, num_samples, num_particles, T_max, dt, srate, noise_std, seed):
"""2-body gravitational problem"""
##### ENERGY #####
def potential_energy(state):
'''U=sum_i,j>i G m_i m_j / r_ij'''
tot_energy = np.zeros((1, 1, state.shape[2]))
for i in range(state.shape[0]):
... | 05f8aa5f6b864440a8a69be35f23d3938114e133 | 21,911 |
def fit_spline_linear_extrapolation(cumul_observations, smoothing_fun=simple_mirroring, smoothed_dat=[],
plotf=False, smoothep=True, smooth=0.5, ns=3, H=7):
"""
Linear extrapolation by splines on log daily cases
Input:
cumul_observations: cumulative observations,
... | 62c0feacf87096a3889e63a2193bc93092b9dc02 | 21,912 |
def compute_dl_target(location):
"""
When the location is empty, set the location path to
/usr/sys/inst.images
return:
return code : 0 - OK
1 - if error
dl_target value or msg in case of error
"""
if not location or not location.strip():
loc = "... | 419b9fcad59ca12b54ad981a9f3b265620a22ab1 | 21,913 |
def hz_to_angstrom(frequency):
"""Convert a frequency in Hz to a wavelength in Angstroms.
Parameters
----------
frequency: float
The frequency in Hz.
Returns
-------
The wavelength in Angstroms.
"""
return C / frequency / ANGSTROM | 9fed63f7933c6d957a35de7244464d0303abf3ce | 21,914 |
from re import T
def is_literal(token):
"""
リテラル判定(文字列・数値)
"""
return token.ttype in T.Literal | 46527a24660f8544951b999ec556a4cf12204087 | 21,915 |
def PutObject(*, session, bucket, key, content, type_="application/octet-stream"):
"""Saves data to S3 under specified filename and bucketname
:param session: The session to use for AWS connection
:type session: boto3.session.Session
:param bucket: Name of bucket
:type bucket: str
:param key: Name of file
... | 908581b7d61c3cce9a976b03a0bf7d3ed8c691ca | 21,916 |
from io import StringIO
def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
p... | d81167b49f2e375f17a227d708d5115af5d18549 | 21,917 |
from azure.cli.core.azclierror import CLIInternalError
def billing_invoice_download(client,
account_name=None,
invoice_name=None,
download_token=None,
download_urls=None):
"""
Get URL to downloa... | a75326953188e0aaf0145ceeaa791460ec0c0823 | 21,918 |
import re
def find_classes(text):
"""
find line that contains a top-level open brace
then look for class { in that line
"""
nest_level = 0
brace_re = re.compile("[\{\}]")
classname_re = "[\w\<\>\:]+"
class_re = re.compile(
"(?:class|struct)\s*(\w+)\s*(?:\:\s*public\s*"
... | 126bc091a809e152c3d447ffdd103c764bc6c9ac | 21,919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.