content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _find_nearest_idx(a, a0):
"""Element idx in nd array `a` closest to the scalar value `a0`."""
if isinstance(a, list):
a = np.array(a)
idx = np.abs(a - a0).argmin()
return idx | c681b96ee8d3629daacd15650428a36041189739 | 12,000 |
def build_argument_parser():
"""
Builds the argument parser
:return: the argument parser
:rtype: ArgumentParser
"""
opts = ArgumentParser()
opts.add_argument(dest='filename', help='Filename or release name to guess', nargs='*')
naming_opts = opts.add_argument_group("Naming")
naming_... | c4194d065ac1751e723e1be6e6968712e6e3cb4f | 12,001 |
def does_user_have_product(product, username):
"""Return True/False if a user has the specified product."""
try:
instance = adobe_api.AdobeAPIObject(username)
except adobe_api.AdobeAPINoUserException:
return False
return instance.has_product(product) | eda5a4a983fac8fa089c575788982685836b4b87 | 12,002 |
from datetime import datetime
def items_for_result(cl, result, form):
"""
Generate the actual list of data.
"""
def link_in_col(is_first, field_name, cl):
if cl.list_display_links is None:
return False
if is_first and not cl.list_display_links:
return True
... | 99ec81a16f833d095de880f459dcd97dce056ccd | 12,003 |
def system_to_ntp_time(timestamp):
"""Convert a system time to a NTP time.
Parameters:
timestamp -- timestamp in system time
Returns:
corresponding NTP time
"""
return timestamp + NTP_DELTA | 2f0081e6c473b05302a5c08dc1818cea0c500caa | 12,004 |
def bcewithlogits_loss(weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None):
"""Creates a criterion that combines a `Sigmoid` layer and the `BCELoss` in one single
class
Arguments:
weights(Tensor, optional) : A manual rescaling weight given to the loss of each batch eleme... | 57c125abb1df39d6e8b77bc741b31aa9bbaba9fc | 12,005 |
from typing import Optional
def transition_matrix(
adata: AnnData,
vkey: str = "velocity",
backward: bool = False,
weight_connectivities: Optional[float] = None,
sigma_corr: Optional[float] = None,
scale_by_variances: bool = False,
var_key: Optional[str] = "velocity_graph_uncertainties",
... | fde82fe71e6e63a5842cf041de60afa10316442d | 12,006 |
from typing import Union
from typing import Any
from datetime import datetime
def create_access_token(
subject: Union[str, Any], expires_delta: timedelta = None, is_superuser: bool = False
) -> str:
"""
generate jwt token
:param subject: subject need to save in token
:param expires_delta: expi... | b07c94ae32311f71737daec6e168ef9deb12ef38 | 12,007 |
import numpy
def transparency(wavelength):
"""Returns the sky transparency in [0, 1] for wavelength in [m]"""
wavelength = wavelength / 10**-9
idx = numpy.argmin(numpy.abs(
data_transparency['wavelength'] * 1000 - wavelength))
return data_transparency['fraction'][idx] | 168691af8b8772203493df146b4b9629100e1002 | 12,008 |
import re
import glob
import os
def split_fortran_files(source_dir, subroutines=None):
"""Split each file in `source_dir` into separate files per subroutine.
Parameters
----------
source_dir : str
Full path to directory in which sources to be split are located.
subroutines : list of str, ... | aa709fcd2b73921b19c8d1e3235a30867112f2ea | 12,009 |
def parse_all_moves(moves_string):
""" Parse a move string """
moves = []
if not moves_string:
raise ValueError("No Moves Given")
moves_strings = moves_string.split(" ")
for move_string in moves_strings:
move = CubeMove.parse(move_string)
moves.append(move)
return moves | ddc063574b8cfe5a2a7bb604033976e505f85df2 | 12,010 |
import itertools
def merge_samples(samples, nchannels, weight_table=None):
"""
Merges two samples
:param samples: the samples, must have the same sample rate and channel count
:param nchannels: the number of channels
:param weight_table: adds a specific weight to each sample when merging the sound... | dcae84c506ea13cc130c3846cbe250d59b6f5115 | 12,011 |
def get_spam_info(msg: Message, max_score=None) -> (bool, str):
"""parse SpamAssassin header to detect whether a message is classified as spam.
Return (is spam, spam status detail)
The header format is
```X-Spam-Status: No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID,
DKIM_VALID_AU,RC... | e11f806a8b8007d25898545b9b16f9ec2207fa89 | 12,012 |
def _check(isamAppliance, id=None):
"""
Check if the last created user has the exact same id or id exists
:param isamAppliance:
:param comment:
:return:
"""
ret_obj = get_all(isamAppliance)
if id != None:
for users in ret_obj['data']:
if users['id'] == id:
... | 36ccb79bf303a6cf0c3eb7a33e7b2c8c1d1090d7 | 12,013 |
import calendar
from datetime import datetime
def plot_week_timeseries(time, value, normalise=True,
label=None, h=0.85, value2=None,
label2=None, daynames=None,
xfmt="%1.0f", ax=None):
"""
Shows a timeseries dispatched by days as bars.... | 051ba850567e56f69d45e6cb33c7148cb5faba31 | 12,014 |
def plot_boxes_on_image(image, boxes, color=(0,255,255), thickness=2):
"""
Plot the boxes onto the image.
For the boxes a center, size representation is expected: [cx, cy, w, h].
:param image: The image onto which to draw.
:param boxes: The boxes which shall be plotted.
:return: An image with ... | 9bd58bb72e8b37b446f342eb145203af50175732 | 12,015 |
import re
def get_text(markup: str) -> str:
"""Remove html tags, URLs and spaces using regexp"""
text = re.sub(r"<.*?>", "", markup)
url_pattern = r"(http|ftp)s?://(?:[a-zA-Z]|[0-9]|[$-_@.&#+]|[!*\(\),]|\
(?:%[0-9a-fA-F][0-9a-fA-F]))+"
text = re.sub(url_pattern, "", text)
text =... | 76b1c86cd852f82fecaa6011aa5e828bae0b4b45 | 12,016 |
def intercept_channel(channel, *interceptors):
"""Intercepts a channel through a set of interceptors.
This is an EXPERIMENTAL API.
Args:
channel: A Channel.
interceptors: Zero or more objects of type
UnaryUnaryClientInterceptor,
UnaryStreamClientInterceptor,
StreamUnary... | 0f56be58125afcad9afd7aefd5ba55c6ca3b2970 | 12,017 |
def create_static_ip(compute, project, region, name):
"""Create global static IP
:param compute: GCE compute resource object using googleapiclient.discovery
:param project: string, GCE Project Id
:param region: string, GCE region
:param name: string, Static IP name
:return: Operation informatio... | 9f2f608ab3878c1534b3af47421866411d1ca523 | 12,018 |
import torch
def ctc_loss(encoder_outputs, labels, frame_lens, label_lens, reduction, device):
"""
All sorts of stupid restrictions from documentation:
In order to use CuDNN, the following must be satisfied:
1. targets must be in concatenated format,
2. all input_lengths must be T.
3. blank=0... | 9907e1890669da7843efea080f5da51f64a82c1a | 12,019 |
import re
def expand_parameters(host, params):
"""Expand parameters in hostname.
Examples:
* "target{N}" => "target1"
* "{host}.{domain} => "host01.example.com"
"""
pattern = r"\{(.*?)\}"
def repl(match):
param_name = match.group(1)
return params[param_name]
return ... | 04f62924fdc77b02f3a393e5cc0c5382d1d4279a | 12,020 |
import math
import time
def search_s1(saturation, size, startTime):
"""
First stage for sequential adsorption.
Returns list of circles, current saturation, list of times and list
of saturations.
Keyword arguments:
size -- radius of single circle
saturation -- max saturation
start... | 386909b285a5504a075f496edeb6e45bb41b6bc3 | 12,021 |
def draw_labeled_bounding_boxes(img, labeled_frame, num_objects):
"""
Starting from labeled regions, draw enclosing rectangles in the original color frame.
"""
# Iterate through all detected cars
for car_number in range(1, num_objects + 1):
# Find pixels with each car_number label value
... | 3eeacafb08a15a98ec70567361c2b7d807af156c | 12,022 |
import re
def _skip_comments_and_whitespace(lines, idx):
###############################################################################
"""
Starting at idx, return next valid idx of lines that contains real data
"""
if (idx == len(lines)):
return idx
comment_re = re.compile(r'^[#!]')
... | b2b794681859eaa22dfc1807211bf050423cd107 | 12,023 |
def named_payload(name, parser_fn):
"""Wraps a parser result in a dictionary under given name."""
return lambda obj: {name: parser_fn(obj)} | 259525b93d056e045b0f8d5355d4028d67bfac45 | 12,024 |
def _SoftmaxCrossEntropyWithLogitsGrad(op, grad_loss, grad_grad):
"""Gradient function for SoftmaxCrossEntropyWithLogits."""
# grad_loss is the backprop for cost, and we multiply it with the gradients
# (which is output[1])
# grad_grad is the backprop for softmax gradient.
#
# Second derivative is just soft... | c5e82b224aa427e1898f037e0be9a42261ef0505 | 12,025 |
def prod_finished(job):
"""Check if prod stage is finished."""
try:
step = "prod" + str(job.doc.prod_replicates_done - 1)
except (KeyError, AttributeError):
step = "prod" + "0"
run_file = job.ws + "/run.{}".format(step)
if job.isfile("run.{}".format(step)):
with open(run_fil... | 4ce509bb6656555a26384f733ccc91b974636d5f | 12,026 |
def PrimaryCaps(layer_input, name, dim_capsule, channels, kernel_size=9, strides=2, padding='valid'):
""" PrimaryCaps layer can be seen as a convolutional layer with a different
activation function (squashing)
:param layer_input
:param name
:param dim_capsule
:param channel... | 41bb066e6b2fdac74f3002ae63055096228bd386 | 12,027 |
def get_font(args):
"""
Gets a font.
:param args: Arguments (ttf and ttfsize).
:return: Font.
"""
try:
return ImageFont.truetype(args.ttf, args.ttfsize)
except:
return ImageFont.load_default() | aee4761c93ef177f26b1bfd81ad5149186e32d47 | 12,028 |
def zeros(shape):
"""
Creates and returns a new array with the given shape which is filled with zeros.
"""
mat = empty(shape)
return fill(mat, 0.0) | 7cbe68c9928094e3588560643b8029867fa51ab7 | 12,029 |
def unpack_puzzle_input(dir_file: str) -> tuple[list, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
bingo numbers and bingo cards in list format
"""
with open(dir_file, "r") as file:
content = file.read().splitlines()
bingo_number... | 47ea8846233aabf1bc8e07f22e9993b7a5a328e1 | 12,030 |
def blank_response():
"""Fixture that constructs a response with a blank body."""
return build_response(data="") | 5ffe8c5b0b775db68c626f1e9cce8a83c66978ff | 12,031 |
import torch
def dense_image_warp(image:torch.Tensor, flow:torch.Tensor) -> torch.Tensor:
"""Image warping using per-pixel flow vectors.
See [1] for the original reference (Note that the tensor shape is different, etc.).
[1] https://www.tensorflow.org/addons/api_docs/python/tfa/image/dense_image_warp
... | 324be2c28dceeeb8079b4a89d94908e1a208c0a1 | 12,032 |
def validateRange(rangeStr : str) -> bool:
"""Validates the range argument"""
# type cast and compare
try:
# get range indices
ranges = rangeStr.split(",", 1)
rangeFrom = 0 if ranges[0] == "" else int(ranges[0])
rangeTo = 0 if ranges[1] == "" else int(ranges[1])
# ... | 375d80ef61c429a4e22df7321d223fe18939f597 | 12,033 |
from operator import add
def update_log_ip_dict_per_ingress_egress_point(flow_ingress_asn, flow_ip, origin_asn, ip_prefix, country_code, flow_bytes, flow_packets, d_ipsrc_level_analysis_perpoint):
"""
Account for unique IPAddresses, BGP prefixes, origin_asn per ingress/egress points.
:param flow_ingress_a... | ad6ccefd62b11f3cf1a7b5e452789ddf22fcad55 | 12,034 |
import yaml
def _config_from_file(configfile):
"""Return a dict containing all of the config values found in the given
configfile.
"""
conf = {}
# set from config if possible
if configfile:
with open(configfile, 'r') as fp:
config_yaml = yaml.load(fp)
conf = con... | 2ab4d779fd18c13054e3c40ae411106856fae9ae | 12,035 |
def odr_planar_fit(points, rand_3_estimate=False):
"""
Fit a plane to 3d points.
Orthogonal distance regression is performed using the odrpack.
Parameters
----------
points : list of [x, y, z] points
rand_3_estimate : bool, optional
First estimation of the plane using 3 random poin... | d4b542f1527fc89937be92e3ff1ffc827cb5cced | 12,036 |
def adjust_learning_rate_lrstep(epoch, opt):
"""Sets the learning rate to the initial LR decayed by decay rate every steep step"""
steps = np.sum(epoch > np.asarray(opt.lr_decay_epochs))
if steps > 0:
new_lr = opt.lr_init * (opt.lr_decay_rate ** steps)
return new_lr
return opt.lr_init | e3af0a5e654595f309a2a202d0620b57e5968530 | 12,037 |
def subplot(n, m, k):
"""
Create a subplot command
Example::
import numpy as np
x = np.linspace(-5, 5, 1000)
figure(1)
subplot(2, 1, 1)
plot(x, np.sin(x), "r+")
subplot(2, 1, 2)
plot(x, np.cos(x), "g-")
show()
"""
global _current_... | d7793d099a57ad8d825e16e737dc72f28dd0456c | 12,038 |
from typing import Any
from typing import cast
def _create_gdcm_image(src: bytes, **kwargs: Any) -> "gdcm.Image":
"""Return a gdcm.Image from the `src`.
Parameters
----------
src : bytes
The raw image frame data to be encoded.
**kwargs
Required parameters:
* `rows`: int
... | d0844d92d3b0c6b62164019c56864cc498c51334 | 12,039 |
def _4_graphlet_contains_3star(adj_mat):
"""Check if a given graphlet of size 4 contains a 3-star"""
return (4 in [a.sum() for a in adj_mat]) | 307f03707d1a7032df0ccb4f7951eec0c75832fe | 12,040 |
import re
import subprocess
import os
def _one_day(args):
"""Prompts for index file update
`_need_to_index` has already filtered jpg preferred over other
formats, that is, if there is a duplicate name, it will list the
jpg, not the arw, pcd, etc. in the index.
Args:
args (list): files to... | 408d75736d1bf891cae2ffd38b204ba18a9bc265 | 12,041 |
from pathlib import Path
def af4_path() -> Path:
"""Return the abspath of Go bio-target-rna-fusion binary. Builds the binary if necessary"""
global AF4_PATH
if not AF4_PATH:
af4_label = "//go/src/github.com/grailbio/bio/cmd/bio-fusion"
build([af4_label])
AF4_PATH = go_executable(af... | f70b97661bf17eb4e3b67af20c5437ebd6123266 | 12,042 |
def get_sentence_content(sentence_token):
"""Extrac sentence string from list of token in present in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
str: setence string
"""
sentence_content = ''
for word in sente... | 4f6f1bb557bb508e823704fc645c2901e5f8f03f | 12,043 |
import os
def _parse_filename(filename):
"""Parse meta-information from given filename.
Parameters
----------
filename : str
A Market 1501 image filename.
Returns
-------
(int, int, str, str) | NoneType
Returns a tuple with the following entries:
* Unique ID of t... | 61d8b721a594a802de8abc1c30a316fd1995a14e | 12,044 |
def sequence_generator(data, look_back = 50):
"""\
Description:
------------
Input data for LSTM: Convert to user trajectory (maximum length: look back)
"""
train,test, valid = [],[],[]
unique_users = set(data[:,0])
items_per_user = {int(user):[0 for i in range(look_back)] for user... | 688e572edf1b6d2dea2f069742b01c10ec36f928 | 12,045 |
def prefit_clf__svm(gamma: float = 0.001) -> base.ClassifierMixin:
"""Returns an unfitted SVM classifier object.
:param gamma: ...
:return:
"""
return svm.SVC(gamma=gamma) | 481409fdd7b2970d3595a7f60e411e71ebb00ac0 | 12,046 |
def option_not_exist_msg(option_name, existing_options):
""" Someone is referencing an option that is not available in the current package
options
"""
result = ["'options.%s' doesn't exist" % option_name]
result.append("Possible options are %s" % existing_options or "none")
return "\n".join(resu... | 7ffa0afa81483d78a1ed0d40d68831e09710b7e1 | 12,047 |
def elslib_CylinderD2(*args):
"""
:param U:
:type U: float
:param V:
:type V: float
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param P:
:type P: gp_Pnt
:param Vu:
:type Vu: gp_Vec
:param Vv:
:type Vv: gp_Vec
:param Vuu:
:type Vuu: ... | af11eee7a0a429ead43d40ed678f932abd2313f7 | 12,048 |
def get_version_message(version: str):
"""Get the message for the zygrader version from the changelog"""
changelog = load_changelog()
msg = [f"zygrader version {version}", ""]
version_index = 0
for line in changelog:
if line == version:
version_index = changelog.index(line) + 1... | 8530180c9d2dc413a1057c2ca255aa0e3dddd72c | 12,049 |
def get_arity(p, b_addr):
"""
Retrieves the arity by inspecting a funciton call
:param p: angr project
:param b_addr: basic block address
:return: arity of the function
"""
return len(get_ord_arguments_call(p, b_addr)) | 47b7721421a226d969aada8d873c43f8f58810e9 | 12,050 |
def draw_des3_plot():
"""
This function is to draw the plot of DES 3.
"""
objects = ('Singapore', 'Uruguay', 'Chile', 'Belgium', 'Denmark', 'Qatar', 'Portugal', 'Canada', 'Spain', 'Ireland')
y_pos = np.arange(len(objects))
performance = [71, 69, 68, 66, 65, 65, 64, 63, 63, 62]
plt.xkcd()
... | 6cc1bb3331e9eed57a700596d133d2bf00c3398e | 12,051 |
def get_pi_id(rc):
"""
Gets the database id of the group PI
Parameters
----------
rc: runcontrol object
The runcontrol object. It must contain the 'groups' and 'people'
collections in the needed databases
Returns
-------
The database '_id' of the group PI
"""
grou... | 12a1e9c0805e8549be7861247b97f52defd576d9 | 12,052 |
def gather_from_processes(chunk, split_sizes, displacements, comm=MPI.COMM_WORLD):
"""Gather data chunks on rank zero
:param chunk: Data chunks, living on ranks 0, 1, ..., comm.size-1
:type chunk: np.ndarray
:param split_sizes: Chunk lenghts on individual ranks
:type split_sizes: np.ndarray
:pa... | 8f696241e0dc61bbb5dd9867f307e29e8358d69e | 12,053 |
import os
from pathlib import Path
async def publish_file_as_upload(
background_tasks: BackgroundTasks, file_data: UploadFile = File(...)
) -> tp.Union[IpfsPublishResponse, GenericResponse]:
"""
Publish file to IPFS using local node (if enabled by config) and / or pin to Pinata pinning cloud (if enabled b... | 4e4f931e61257d86233c07ddd476d9ea548dc0ac | 12,054 |
import json
def edit_collab() :
"""
Endpoint to edit a specified collaboration's member variables. This endpoint requires the requesting user to be an
authenticated user to properly function.
Request Body Parameters:
id: string, JSON, required
owner: string, JSON, optional
siz... | f205302c6f1368542c870f3ab89bbde374e0957b | 12,055 |
def create_lkas_ui(packer, main_on, enabled, steer_alert, defog, ahbc, ahbcramping, config, noipma, stats, persipma, dasdsply, x30, daschime, lines):
"""Creates a CAN message for the Ford Steer Ui."""
values = {
"PersIndexIpma_D_Actl": persipma,
"DasStats_D_Dsply": dasdsply,
"Set_Me_X30": x30,
"Lin... | b9c855b6210b34fde8943eaa8293d691ee291527 | 12,056 |
import torch
def _contextual_loss(x, y, reduction='mean'):
"""Contextual loss
"""
loss = -torch.log(_contextual_similarity(x, y))
if reduction == 'mean':
loss = loss.mean()
return loss | 3dee81131c0b1468e822cdc36f1817204ec9eba3 | 12,057 |
def _actual_center(pos, angle):
"""
Calculate the position of the geometric center of the agent
The value of self.cur_pos is the center of rotation.
"""
dir_vec = get_dir_vec(angle)
return pos + (CAMERA_FORWARD_DIST - (ROBOT_LENGTH / 2)) * dir_vec | bd354e1ef64cd14132944da9e436df2a4696d0fe | 12,058 |
def load_one_batch_mnist(batch_size=64, shuffle=True):
"""Return a single batch (inputs, labels) of MNIST data."""
dataloader = get_mnist_dataloder(batch_size, shuffle)
X, y = next(iter(dataloader))
return X, y | 2a2036a72cecf957fd7c8a5344c85a59935fb442 | 12,059 |
import re
def replace_math_functions(input_string):
""" FIXME: Temporarily replace std:: invocations of math functions with non-std:: versions to prevent linker errors
NOTE: This can lead to correctness issues when running tests, since the correct version of the math function (exp/expf) might not get call... | 09562b7bb173e44877e18368b0283b3c3f590004 | 12,060 |
def KmeansInterCompare(k, data, nbTests):
"""Réalisation d'un nombre donné de classification Kmeans.
Le meilleur résultat selon le critère d'inertie inter-groupe est affiché"""
KmeansResults = []
for i in range(0, nbTests):
KmeansResults.append(Kmeans(k, data))
# on maximise l'inertie inter... | 42d8d900ad5e7d6e80bbd16736178fe5a14f878c | 12,061 |
from bs4 import BeautifulSoup
def get_all_reports_url(url_1,url_2, headers=None):
""" Returns all reports URLs on a single 'url' """
if headers == None:
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
els... | 705047c4d21167f9ecde23f163e383e9f6aa00b2 | 12,062 |
import os
def generate_url_with_signature(endpoint, signature):
"""Generate a url for an endpoint with a signature.
Args:
endpoint: An endpoint referencing a method in the backend.
signature: A signature serialized with releant data and the secret
salt.
Returns:
url for ... | 491b3ef932bd9fd6e68d21112282e1f660a56a0f | 12,063 |
def left_shift(k, n=32):
"""
Returns the n*n matrix corresponding to the operation
lambda v: vec_from_int(int_from_vec(v) << k, n)
>>> print_mat(left_shift(2, 6))
000000
000000
100000
010000
001000
000100
>>> int_from_vec(left_shift(2) * vec_from_int(42)) == 42 << 2
... | 216011184a8b6a02675524fd2906f092553396c6 | 12,064 |
from typing import List
from datetime import datetime
def get_tensorboard_logger(
trainer: Engine, evaluators: ThreeEvaluators, metric_names: List[str]
) -> TensorboardLogger:
"""
creates a ``tensorboard`` logger which read metrics from given evaluators and attaches it to a given trainer
:param train... | 30a920c056cf10df4656cbda2a1e92fb28388f06 | 12,065 |
def get_vocabs(datasets):
"""Build vocabulary from an iteration of dataset objects
Args:
dataset: a list of dataset objects
Returns:
two sets of all the words and tags respectively in the dataset
"""
print("Building vocabulary...")
vocab_words = set()
vocab_tags = set()
... | 1fce7fe7b9dbdd3216802d0816ac5fabc542b859 | 12,066 |
def check_row_uniqueness(board: list) -> bool:
"""
Return True if each row has no repeated digits.
Return False otherwise.
>>> check_row_uniqueness([\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****",\
" 9 5 ",\
" 6 83 *",\
"3 1 **",\
" 8 2***",\
" 2 ****"\
])
True
>... | b4d937f14de0da90e694621fb2c70e9a59e80f0a | 12,067 |
def calculate_distance_to_divide(
grid, longest_path=True, add_to_grid=False, clobber=False
):
"""Calculate the along flow distance from drainage divide to point.
This utility calculates the along flow distance based on the results of
running flow accumulation on the grid. It will use the connectivity
... | 99afc09e88aee3ea7486a9dfddc45d98358d0bd7 | 12,068 |
import matplotlib.pyplot as plt
import textwrap
import os
import time
def run_example(device_id, do_plot=False):
"""
Run the example: Connect to a Zurich Instruments UHF Lock-in Amplifier or
UHFAWG, UHFQA, upload and run a basic AWG sequence program. It then demonstrates
how to upload (replace) a wave... | 925954c576cc21c32ed94386d62a3e4dcfebdfe3 | 12,069 |
def string_unquote(value: str):
"""
Method to unquote a string
Args:
value: the value to unquote
Returns:
unquoted string
"""
if not isinstance(value, str):
return value
return value.replace('"', "").replace("'", "") | e062c012fc43f9b41a224f168de31732d885b21f | 12,070 |
def translate(tx, ty, tz):
"""Translate."""
return affine(t=[tx, ty, tz]) | f3b11f6bcf0f77b39423d8aac3d34149ae8b93a7 | 12,071 |
import torch
def randomized_svd_gpu(M, n_components, n_oversamples=10, n_iter='auto',
transpose='auto', random_state=0, lib='pytorch',tocpu=True):
"""Computes a truncated randomized SVD on GPU. Adapted from Sklearn.
Parameters
----------
M : ndarray or sparse matrix
Mat... | 31483d2f83b66d8cd4bc15a929ecf657c67d0af2 | 12,072 |
import re
def clean_column_names(df: pd.DataFrame) -> pd.DataFrame:
"""Cleans the column names of the given dataframe by applying the following steps
after using the janitor `clean_names` function:
* strips any 'unnamed' field, for example 'Unnamed: 0'
* replaces the first missing name with... | 37c41b02846cacab1e412d402b50d94e18e1e20e | 12,073 |
def cos(x):
"""Return the cosine.
INPUTS
x (Variable object or real number)
RETURNS
if x is a Variable, then return a Variable with val and der.
if x is a real number, then return the value of np.cos(x).
EXAMPLES
>>> x = Variable(0, name='x')
>>> t = cos(x)
>>> print(t.val, t.der['x'])
1.0 0.0
"""
t... | 472bfb53345c14545a8f1bf75deb5679fe1916f8 | 12,074 |
def _get_regions(connection):
""" Get list of regions in database excluding GB. If no regions are found,
a ValueError is raised.
"""
query_regions = connection.execute(
db.select([models.Region.code]).where(models.Region.code != "GB")
)
regions = [r[0] for r in query_regions]
if... | ffb58c5c695a8dd669497f8dccdf5ef8202e5a21 | 12,075 |
def word_embedding_forward(x, W):
"""
Forward pass for word embeddings. We operate on minibatches of size N where
each sequence has length T. We assume a vocabulary of V words, assigning each
to a vector of dimension D.
Inputs:
- x: Integer array of shape (N, T) giving indices of words. Each element idx
... | 232096cc2c90a16fdc1c428d98ebe2db184df368 | 12,076 |
def retrieve_from_stream(iden, interval=60):
"""
Return messages from a stream.
:param iden: Identifier of the stream.
:param interval: defaults to messages of last 60 seconds.
"""
return stm_str.get_messages(str(UID), str(TOKEN), interval, iden) | 166918258ff3bc8ff972164027df4bf93b4a280e | 12,077 |
def train_op(tot_loss, lr, var_opt, name):
"""
When only the discriminator is trained, the learning rate is set to be 0.0008
When the generator model is also trained, the learning rate is set to be 0.0004
Since there are batch_normalization layers in the model, we need to use update_op for keeping train... | 52dc967b9adac561f210fe4305d69b8724841607 | 12,078 |
import math
def logadd(x, y):
"""Adds two log values.
Ensures accuracy even when the difference between values is large.
"""
if x < y:
temp = x
x = y
y = temp
z = math.exp(y - x)
logProb = x + math.log(1.0 + z)
if logProb < _MinLogExp:
return _Min... | d1993f9e3d9fd5f44938509df12d818fb5eb7f3d | 12,079 |
def getResourceNameString(ro_config, rname, base=None):
"""
Returns a string value corresoponding to a URI indicated by the supplied parameter.
Relative references are assumed to be paths relative to the supplied base URI or,
if no rbase is supplied, relative to the current directory.
"""
rsplit... | f5840a7effb4ac91a77810531f10d323a03490ce | 12,080 |
import os
def NMFcomponents(ref, ref_err = None, n_components = None, maxiters = 1e3, oneByOne = False, path_save = None):
"""Returns the NMF components, where the rows contain the information.
Input: ref and ref_err should be (N * p) where n is the number of references, p is the number of pixels in each refe... | ca986498797a635a3b4a85ba6ac432a4ce2954d3 | 12,081 |
import argparse
def parse_args():
"""
Parses arguments provided through the command line.
"""
# Initialize
parser = argparse.ArgumentParser()
# Arguments
parser.add_argument("meme_file", metavar="motifs.meme")
parser.add_argument("tomtom_file", metavar="tomtom.txt")
parser.add_ar... | cc2e38e563ef5e94009f171e757454a3b59d8588 | 12,082 |
def get_mean_from_protobin(filename):
"""Get image mean from protobinary and return ndarray with skimage format.
"""
img = read_caffe_protobin(filename)
size = (img.channels, img.height, img.width)
img = caffe.io.blobproto_to_array(img).reshape(size)
img = img.transpose([1, 2, 0])
return img | ba03cdeb534d00885c1c6bee22bee15af3880a85 | 12,083 |
def has_key(key):
"""
Check if key is in the minion datastore
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' data.has_key <mykey>
"""
store = load()
return key in store | 7d551773da4c7d98f090d7ff9b489bcbecbec32e | 12,084 |
def __create_setting(ingest):
"""Creates the setting for a particular family"""
signer, addresser, auth_keys, threshold = ingest
settings = Settings(
auth_list=','.join(auth_keys),
threshold=threshold)
return (
signer,
addresser,
SettingPayload(
action... | a74d7c5a109555de591d26f5e123c31a5d0b4a7a | 12,085 |
def paser_bs(sent):
"""Convert compacted bs span to triple list
Ex:
"""
sent=sent.strip('<sos_b>').strip('<eos_b>')
sent = sent.split()
belief_state = []
domain_idx = [idx for idx,token in enumerate(sent) if token in all_domain]
for i,d_idx in enumerate(domain_idx):
next_d_... | b517d58e7a7958b9186c7f9216cb33e506c148f7 | 12,086 |
def app_factory(global_conf, **local_conf):
"""paste.deploy app factory for creating WSGI container server apps."""
conf = global_conf.copy()
conf.update(local_conf)
return ContainerController(conf) | d493112d714e0303b807304b8be11d0d8b8c5b37 | 12,087 |
import traceback
def retrieve_succinct_traceback() -> str:
"""
A utility that retrive succint traceback digest from a complete traceback string.
"""
tb = traceback.format_exc()
return "\n".join(pg.splitlines()[-1] for pg in split_paragraphs(tb)) | 882e190138fd51be807d37f014c22aead57f88ba | 12,088 |
def get_canonical_format_name(format_name):
"""
Get the canonical format name for a possible abbreviation
Args:
format_name (str): Format name or abbreviation
Returns:
The canonical name from CANONICAL_FORMATS, or None if the format is
not recognized.
"""
try:
r... | ae95d0321e2f8880ccbd7710e48666991208a470 | 12,089 |
def build_protoc_args(
ctx,
plugin,
proto_infos,
out_arg,
extra_options = [],
extra_protoc_args = [],
short_paths = False,
resolve_tools = True):
"""
Build the args for a protoc invocation.
This does not include the paths to the .proto files, ... | 24796ea7d817dd3a11ec2c1b54de23573c6da275 | 12,090 |
def cycle_left(state):
"""Rotates the probabilityfunction, translating each discrete left by one site.
The outcome is the same as if the probabilityfunction was fully local, with n_discretes
indices, and the indices were permuted with (1, 2, ..., n_discretes-1, 0).
Args:
state: The probabilityfunction to ... | 37f6f3626abe66682b339e9a74fb439917cba9ce | 12,091 |
def make_rare_deleterious_variants_filter(sample_ids_list=None):
""" Function for retrieving rare, deleterious variants """
and_list = [
{
"$or":
[
{"cadd.esp.af": {"$lt": 0.051}},
... | 2a97e5a0aa96b2a221c32639dde20fcf8de09bce | 12,092 |
def PluginCompleter(unused_self, event_object):
"""Completer function that returns a list of available plugins."""
ret_list = []
if not IsLoaded():
return ret_list
if not '-h' in event_object.line:
ret_list.append('-h')
plugins_list = parsers_manager.ParsersManager.GetWindowsRegistryPlugins()
fo... | c03b765ed39c1e43d3b67aaf9486c0f015b7bc4e | 12,093 |
def train_model(item_user_data) -> []:
""""Returns trained model"""
model = implicit.als.AlternatingLeastSquares(factors=50)
model.fit(item_user_data)
return model | d3917cb422707bebdd519bab04b9332c1056ec7a | 12,094 |
def refresh_blind_balances(wallet, balances, storeback=True):
""" Given a list of (supposedly) unspent balances, iterate over each one
and verify it's status on the blockchain. Each balance failing
this verification updates own status in the database (if storeback is True).
Returns a list of... | 2d468827ae32d359b323921d5933796ada22d627 | 12,095 |
import argparse
from typing import Union
def command_up(
stairlight: StairLight, args: argparse.Namespace
) -> Union[dict, "list[dict]"]:
"""Execute up command
Args:
stairlight (StairLight): Stairlight class
args (argparse.Namespace): CLI arguments
Returns:
Union[dict, list]:... | 042214e94a95b998a0f416ab51c973338eba34ba | 12,096 |
def hull_area(par, llhs, above_min=1):
"""Estimate projected area of llh minimum for single parameter
Parameters
----------
par : np.ndarray
the parameter values
llhs : np.ndarray
the llh values
Returns
-------
float
"""
min_llh = llhs.min()
try:
Hul... | 3284a9742dfd9889fff67fd6f68ab9435858a521 | 12,097 |
def assemble_chain(leaf, store):
"""Assemble the trust chain.
This assembly method uses the certificates subject and issuer common name and
should be used for informational purposes only. It does *not*
cryptographically verify the chain!
:param OpenSSL.crypto.X509 leaf: The leaf certificate from which to bu... | c59025ddcbb777f4f5358f8d89e05191c22eb780 | 12,098 |
import os
def hcp_mg_relax_cell() -> tuple:
"""
HCP Mg relax cell, wyckoff='c'.
"""
aiida_twinpy_dir = os.path.dirname(
os.path.dirname(aiida_twinpy.__file__))
filename = os.path.join(aiida_twinpy_dir,
'tests',
'data',
... | 54c3e169be518aa2cba39954eb5d8115f400634e | 12,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.