content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Type
from re import T
def load_instance(alfacase_content: DescriptionDocument, class_: Type[T]) -> T:
"""
Create an instance of class_ with the attributes found in alfacase_content.
"""
alfacase_to_case_description = get_case_description_attribute_loader_dict(class_)
case_values... | 5436c17f856461eac54b71018596c86e735c6ab5 | 3,628,300 |
import os
def build_pair_output_path(indices: list, save_dir: str) -> (str, str):
"""
Create directory for saving the paired data
:param indices: indices of the pair, the last one is for label
:param save_dir: directory of output
:return: - save_dir, str, directory for saving the moving/fixed ima... | 2bf8ea4d9ea61d8767e9a128e55e1d4c1cdd1074 | 3,628,301 |
def number_scenarios(scenes):
"""
Add a 'scenario_number' and 'scenario_name' variable to each scenario.
The hash table for each scenario is altered!
"""
count = 0
for scene in scenes:
scene[1]['scenario_name'] = scene[0]
scene[1]['scenario_number'] = count
count += 1
... | 5b3391e2113142bed49d8bcdb7c6fe4b1e0ab8cc | 3,628,302 |
def trimscan_corner_plot(det, element, ranges, chips=range(16)):
"""
"""
pixels = det.get_pixels()
labels = [r'$a_0$', r'$a_1$', r'$a_2$', r'$a_3$', r'$a_4$', r'$a_5$']
data = []
# Loop over pixels and do the analysis
for index in range(len(labels)):
fit_data = []
... | 0e14c703d3d2d7a8160a51845f25db70a14d3f91 | 3,628,303 |
def find_key_value_in_list(listing, key, value):
"""
look for key with value in list and return dict
:param listing:
:param key:
:param value:
:return: dict_found
"""
# for l in listing:
# if key in l.keys():
# if l[key] == value:
# print("l[key = ", v... | 642d8e43cbfbeef9bc014c85085c7027380156e2 | 3,628,304 |
def request_test_suite_started(etos, activity_id):
"""Request test suite started from graphql.
:param etos: Etos Library instance for communicating with ETOS.
:type etos: :obj:`etos_lib.etos.ETOS`
:param activity_id: ID of activity in which the test suites started
:type activity_id: str
:return... | 9bd0f8ba7a0846be440ece1d1d7e4c7335c05dcc | 3,628,305 |
import six
def cast_env(env):
"""Encode all the environment values as the appropriate type.
This assumes that all the data is or can be represented as UTF8"""
return {six.ensure_str(key): six.ensure_str(value) for key, value in env.items()} | b7adfbd20a95f3b2ff24f36f578a869317165c49 | 3,628,306 |
def contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0], norm=True):
"""Return the contingency table for all regions in matched segmentations.
Parameters
----------
seg : np.ndarray, int type, arbitrary shape
A candidate segmentation.
gt : np.ndarray, int type, same shape as `seg`
... | 6eb0835b92e9552d3686271dc00bd136fd873779 | 3,628,307 |
import logging
def create_object_detection_training(
train_object_detection_model_request: TrainImageModel,
):
"""[Train a Object Detection Model in AutoML GCP]
Args:
train_object_detection_model_request (TrainImageModel): [Based on Input Schema]
Raises:
error: [Error]
Returns:
... | 0944b898b9fdf8395ddd17f8f2e9d0c36a559c94 | 3,628,308 |
def jwt_authentication(secret, exc=exceptions.PermissionDenied()):
"""
Provide authentication for a view that must have a valid JWT token for the provided secret key
:param secret: The secret key that validates the jwt token provided in the request headers
:param exc: The exception to throw if the token... | 4e82b8eb4288092f769797571851555e6fcdef77 | 3,628,309 |
def strategy_regret(meta_games, subgame_index, ne=None, subgame_ne=None):
"""
Calculate the strategy regret based on a complete payoff matrix for PSRO.
strategy_regret of player equals to nash_payoff in meta_game - fix opponent nash strategy, player deviates to subgame_nash
Assume all player... | c4514746d523084e8978861af2a5369d9fe2a1e8 | 3,628,310 |
def convert_int_to_form(num: int, form_num: int) -> int:
"""Converts decimal integer to specified form number.
Supports conversion to octal and binary forms.
"""
output = 0
bin_digits = []
while num > 0:
num, r = divmod(num , form_num)
bin_digits.insert(0, r)
num_digits =... | 28a81a277baaefbb8ed27970bee1afb13d3cdde1 | 3,628,311 |
def less_equal(x, y, cond=None):
"""
This OP returns the truth value of :math:`x <= y` elementwise,
which is equivalent function to the overloaded operator `<=`.
"""
helper = MpcLayerHelper("less_equal", **locals())
if cond is None:
cond = helper.create_variable_for_type_inference(dtype... | 37cefd3c85265d73635f1b2de1c8c778dc9ece08 | 3,628,312 |
def _expiration(timeout, time_format=None):
"""
Return an expiration time
:param timeout: When
:param time_format: The format of the returned value
:return: A timeout date
"""
if timeout == "now":
return time_util.instant(time_format)
else:
# validity time should match l... | 174f0395d9a748dd6bc47c4aa836cd4aa402c39e | 3,628,313 |
import os
def get_default_opts(project_name, **aux_opts):
"""
Creates default options using auxiliary options as keyword argument
Use this function if you want to use PyScaffold from another application
in order to generate an option dictionary that can than be passed to
:obj:`create_project`.
... | 4b408cf9e2c8355ea9869dbc4b0f6418d90f37d9 | 3,628,314 |
def get_vgg_model(image_size, num_classes):
"""Get VGG16 model"""
inputs = Input(shape=[*image_size, 3])
model = VGG16(
include_top=False,
weights="imagenet",
classes=num_classes,
input_tensor=inputs,
classifier_activation=None,
)
model.trainable = False
... | 17a6198a2d2186771ba1ee7c8442acc6c552d021 | 3,628,315 |
def random_weights(n_i: int, n_j: int, axis: int = 0, seed: int | None = None) -> ndarray:
"""Generate random weights for producer-injector gains.
Args
----
n_i : int
n_j : int
axis : int, default is 0
seed : int, default is None
Returns
-------
gains_guess: ndarray
"""
... | 67d420db30a703d33174af9238d71fc8f68fd61f | 3,628,316 |
def ensure_session(session=None):
"""If session is None, create a default session and return it. Otherwise return the session passed in"""
if session is None:
session = boto3.session.Session()
return session | 5d53bd3bd6a6d61f75cc3680d0618889fb14394f | 3,628,317 |
def reset(label):
"""
@api {delete} /:label Reset counter
@apiName ResetCounter
@apiGroup Counter
@apiParam {String} label Counter label.
@apiSuccess {Number} counter Zero value.
"""
store.delete(label)
return jsonify(counter=0) | 6834b33246ff8994525cd3781e72602497d1d381 | 3,628,318 |
def remove_duplicates(df, by=["full_text"]):
"""
Remove duplicates from raw data file by specific columns and save results in file with name given.
"""
boolean_mask = df.duplicated(subset=by, keep="first")
df = df[~boolean_mask]
return df | dfe99259a90280b346290dd2c880ab51e443e036 | 3,628,319 |
import gzip
import os
import re
def read_ecmwf_corrections(base_dir, LMAX, months, MMAX=None):
"""
Read atmospheric jump corrections from Fagiolini et al. (2015)
Arguments
---------
base_dir: Working data directory for GRACE/GRACE-FO data
LMAX: Upper bound of Spherical Harmonic Degrees
mo... | 2cd8884748141cc4dc77595ce180c8eefbb7045c | 3,628,320 |
def tex_parenthesis(obj):
"""Return obj with parenthesis if there is a plus or minus sign."""
result = str(obj)
return f"({result})" if "+" in result or "-" in result else result | 356a3886d27d431e90de2a76e6590481ad85f05e | 3,628,321 |
def swap_target_nonterminals(target):
"""
Swap non-terminal tokens.
:param target: List of target tokens
:return: List of target tokens
"""
return ['X_1' if token == 'X_0' else 'X_0' if token == 'X_1' else token for token in target] | 56e91df1a513ee5dad1071337463e039ded57a86 | 3,628,322 |
def validate_nd_array(x):
"""Casts x as a numpy array of the original input shape."""
# Get shape and cast as 1d
x, shape = _get_shape_and_return_1d_array(x)
# Return to original shape
x = x.reshape(shape)
return x | 007ad923f9e1e712a6bdcbd659a8d257a6383cb8 | 3,628,323 |
def _expandaliases(aliases, tree, expanding, cache):
"""Expand aliases in tree, recursively.
'aliases' is a dictionary mapping user defined aliases to
revsetalias objects.
"""
if not isinstance(tree, tuple):
# Do not expand raw strings
return tree
alias = _getalias(aliases, tree... | 4c104aab5c20510f5a87a719139c33db7c23d657 | 3,628,324 |
import os
import stat
def is_executable_file(path):
"""Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits dire... | b9ec4bfa15d0a121ff4958b146d8e1646e6b15ed | 3,628,325 |
def to_svd_numpy(numpy_array, compress_rate):
"""
We transform an image to its SVD representation: U x D x V^T.
We return as output for each channel X, 2 channels with values: U x D, and V^T.
The initial size is n^2, the final size is: 2np
:param numpy_array: the input image
:param compress_rat... | e407ffdb2049c248b2ea51b5ecb240628d94f508 | 3,628,326 |
def _get_login_player_name(html):
"""
指定されたHTMLからログインユーザー名を抽出する。
:param html: 投票ページのHTML
:type html: str
:return: ログインユーザー名
:rtype: str
"""
# ログインユーザー名を返却する
soup = bs4.BeautifulSoup(html, 'html.parser')
player_name_box = soup.find('div', {'class': 'player_name_box'})
if play... | a6aaa72a92ae8dcefacfe4db042148aa69f24443 | 3,628,327 |
from datetime import datetime
def get_max_streak(submissions):
"""
Get the maximum of all streaks
@param submissions (List of tuples): [(DateTime object, count)...]
@return (Tuple): Returns streaks of the user
"""
streak = 0
max_streak = 0
prev = curr = None
total_sub... | f021647e028475e66c548773fc9d1571e6f3b251 | 3,628,328 |
import requests
def check_node_reachable(context):
"""
Returns whether the specified node IP is reachable and informs user
"""
chat_id = context.job.context['chat_id']
user_data = context.job.context['user_data']
if 'is_node_reachable' not in user_data:
user_data['is_node_reachable']... | f8ab268d38cbd98cb8de017bd944d26f5ba746be | 3,628,329 |
def padZeros(numberString, numZeros, insertSide):
"""Return a string padded with zeros on the left or right side."""
if insertSide == 'left':
return '0' * numZeros + numberString
elif insertSide == 'right':
return numberString + '0' * numZeros | d0c2d08a392e4792b13a64d076c8fb6aff1572cb | 3,628,330 |
def stations():
""" Return a JSON list of stations from the dataset."""
# Create our session (link) from Python to the DB
session = Session(engine)
station_list = session.query(Measurement.station, Station.name, func.count(Measurement.station)).\
filter(Measurement.station == St... | adda327b3fba5dacfedde07fd14f1fca1955f945 | 3,628,331 |
def eval_sot_accuracy_robustness(results,
annotations,
burnin=10,
ignore_unknown=True,
videos_wh=None):
"""Calculate accuracy and robustness over all tracking sequences.
Args:
... | e5aeb63919ecab3d82c60688066b434a65b7442c | 3,628,332 |
def spares_kdt_compute_mean_std_v2(res_dicts, spaces, arch_key='eval_arch', perf_key='eval_perf', use_hash=False, sort_best_model_fn=None):
""" Just compute the average sKdT
Parameters
----------
res_dicts : list
dict of running, multiple seed run contains inside
arch_key : str, optional
... | bacb3b8283ed9a54268d9d5b0fea78b410bd90e6 | 3,628,333 |
def roi_proposal(rpn_cls_prob_reshape, rpn_bbox_pred, H, W, ANCHOR_PER_GRID, ANCHOR_BOX, TOP_N_DETECTION, NMS_THRESH, IM_H, IM_W):
"""
clip the predict results fron rpn output
appply nms
proposal topN results as final layer output, no backward operation need here
"""
box_probs = np.reshape(rpn_c... | 871c5d81f047ecaa8fd5d08ec3bbd22f83059062 | 3,628,334 |
def mi_gg(x, y, biascorrect=True, demeaned=False):
"""Mutual information (MI) between two Gaussian variables in bits
I = mi_gg(x,y) returns the MI between two (possibly multidimensional)
Gassian variables, x and y, with bias correction.
If x and/or y are multivariate columns must correspond to sampl... | 2e2614f233c42e27d2b53d6761c1069d04c66f39 | 3,628,335 |
def reverse_path(dict_, root, child_to_parents):
"""
CommandLine:
python -m utool.util_graph --exec-reverse_path --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> child_to_parents = {
>>> 'chip': ['... | f27a248e800d73e895b0553856b3e7ba55684eb8 | 3,628,336 |
import math
def build_lifegame_model(n, **kwargs):
""" build a MIP model for a stable game of life configuration
chessboard is (n+1) x (n+1)
:param n:
:return:
"""
assert n >= 2
assert Model.supports_logical_constraints(), "This model requires logical constraints cplex.version must be 1... | 74c615639d8a45bf6ff6ab055f0e7189ace1be07 | 3,628,337 |
def get_wofs_values(landsat_dataset):
"""classifies a landsat scene using the wofs algorithm
:param landsat_dataset: xarray with dims 'latitude','longitude' containing data from a landsat scene
:return: xarray dataset containing wofs classification values
"""
# landsat dataset needs dim 'time' for w... | e069da04de9800fe61f3416f981ec386cb8e1f2a | 3,628,338 |
def readdirs(DIR):
"""Implementation of perl readdir in list context"""
result = (DIR[0])[DIR[1]:]
DIR[1] = len(DIR[0])
return result | 98d9b588704ea2820b14ba2c5542ea0a619a02ce | 3,628,339 |
def expandChunk(layout, typesize, shape_json,
chunk_min=CHUNK_MIN, layout_class='H5D_CHUNKED'):
""" Extend the chunk shape until it is above the MIN target.
"""
if shape_json is None or shape_json["class"] == 'H5S_NULL':
return None
if shape_json["class"] == 'H5S_SCALAR':
... | 1d43c21629b77b5cdc0ab6ac35397729f8f96d89 | 3,628,340 |
def remove_domestic(images: pd.DataFrame, reset_index: bool = True) -> pd.DataFrame:
"""
Removes images where the identification corresponds to a domestic
species. See wiutils/_domestic for a list of the genera considered
as domestic.
Parameters
----------
images : DataFrame
DataFra... | a2038a36c6fbd6f0492c1abb8afc34919b6ecc4c | 3,628,341 |
def compute_cyclepoints(sig, fs, f_range, **find_extrema_kwargs):
"""Compute sample indices of cyclepoints.
Parameters
----------
sig : 1d array
Time series.
fs : float
Sampling rate, in Hz.
f_range : tuple of (float, float)
Frequency range, in Hz, to narrowband filter t... | c748b4f52dac249cf1021a9902e533a3cf485c6f | 3,628,342 |
def behav_data_inverted(df):
"""
Flips the dimensions that need inverting
Faster than using is_inverted_dim
"""
# Apparently groupby with categorical dtype is broken
# See https://github.com/pandas-dev/pandas/issues/22512#issuecomment-422422573
df["class_"] = df["class_"].astype(str)
inv... | 69ad0d4cea1a12b2dd8dc256c77b13f1002ae6b8 | 3,628,343 |
def _resample_event_obs(obs, fx, obs_data):
"""
Resample the event observation.
Parameters
----------
obs : datamodel.Observation
The Observation being resampled.
fx : datamodel.EventForecast
The corresponding Forecast.
obs_data : pd.Series
Timeseries data of the eve... | 1c66ae124aaa2e732c7d0ec3e733ae2b5caaa6cb | 3,628,344 |
def project_raw_gw(
raw_waveforms,
sample_params,
waveform_generator,
ifo,
get_snr=False,
noise_psd=None,
):
"""Project a raw gravitational wave onto an intterferometer
Args:
raw_waveforms: the plus and cross polarizations of a list of GWs
sample_params: dictionary of GW... | d7f1d652baae37f402e0ea520600ffe7423fac75 | 3,628,345 |
def threshold(weights, delta_size):
""" Sample for threshold minimizing pixel changes. """
return min((abs(added_pixel_count(weights,i) + delta_size), i)
for i in np.linspace(10**-2,10**-7,40))[1] | 01c00a55938df949c42299384b2574a07de8e3ff | 3,628,346 |
def davenport_matrix(B = None,
covariance_analysis = False,
**attitude_profile_kwargs):
"""Compute the Davenport matrix for a given attitude profile.
Accepts either an attitude profile matrix or the arguments
for the attitude_profile_matrix() funct... | 5cb1e7b2fe81c0a985f1189f4786fa7be42cf378 | 3,628,347 |
def _arg_raw(dvi, delta):
"""Return *delta* without reading anything more from the dvi file"""
return delta | 041cfaaf23c6e229b60d5278e8cf27352e078a65 | 3,628,348 |
from typing import Sequence
import struct
async def write_mapInfoReply(maps: Sequence[BeatmapInfo]) -> bytearray:
""" Write `maps` into bytes (osu! map info). """
ret = bytearray(len(maps).to_bytes(4, 'little'))
# Write files
for m in maps:
ret.extend(struct.pack('<hiiiBbbbb',
m.i... | f601c7898acd7c94890fb26679d1814ecdd5cce2 | 3,628,349 |
def getPolarPoints2(x, y, center):
"""Convert list of cartesian points to polar points
The returned points are not rounded to the nearest point. User must do that by hand if desired.
Parameters
----------
x : (N,) :class:`numpy.ndarray`
List of cartesian x points to convert to polar domain... | f6f3ebed82eac397c26f2c20ce23a4e8cf19e3b1 | 3,628,350 |
def to_bytes(binary_string: str) -> bytes:
"""Change a string, like "00000011" to a bytestring
:param str binary_string: The string
:returns: The bytestring
:rtype: bytes
"""
if len(binary_string) % 8 != 0:
binary_string += "0" * (
8 - len(binary_string) % 8
) # fill... | 83dda243e27d7f7988d520c0455e43d1937d5447 | 3,628,351 |
def choose_best_assembly_name(assembly_names):
"""
Given a list of reference genome names returns the best according to the
following criteria:
1) Prefer Ensembl reference names to UCSC
2) Prefer reference names with higher numbers in them.
Parameters
----------
assembly_names :... | fc111677f5dfc0e3b10e14e74ac096fd0f22dbfb | 3,628,352 |
def user_follow(request):
"""
This one is VERY similar to the <image_like> func in app-image/views.
There are only two options after all (well, true for some cases) :D
"""
user_id = request.POST.get('id')
action = request.POST.get('action')
if user_id and action:
... | 7b4956ec002aea512758ba34a260b24bfd5622d8 | 3,628,353 |
def module_patch_twin(connectionId, twin): # noqa: E501
"""Updates the device twin
# noqa: E501
:param connectionId: Id for the connection
:type connectionId: str
:param twin:
:type twin: dict | bytes
:rtype: None
"""
if connexion.request.is_json:
twin = Twin.from_dict(... | 1b712264c5723a44a2fa0328ac7621cf090585b7 | 3,628,354 |
def rgbToHsv(r, g, b):
"""
Converts an RGB color value to HSV. Conversion formula
adapted from http://en.wikipedia.org/wiki/HSV_color_space.
Args:
r, g, b (int): red, green, and blue values between 0 and 255 inclusive
Returns:
Array [hue, saturation, value]
hue between 0 and 36... | 5d7e40dc8f5deba686bcca29da3b5ea2d7d9f37c | 3,628,355 |
def assign_from_checkpoint(model_path, var_list):
"""Creates an operation to assign specific variables from a checkpoint.
Args:
model_path: The full path to the model checkpoint. To get latest checkpoint
use `model_path = tf.train.latest_checkpoint(checkpoint_dir)`
var_list: A list of (possibly par... | f318ee5cc923ef147e5c937b74d44c3af101a405 | 3,628,356 |
def _read_tmpfd(fil):
"""Read from a temporary file object
Call this method only when nothing more will be written to the temporary
file - i.e., all the writing has already been done.
"""
fil.seek(0)
return fil.read() | 08648325e7e0e9bcd543d3238cb4630ac284f6ed | 3,628,357 |
def eigenvalues_and_eigenvectors(a: Matrix, epsilon=eps, max_iterations=1000) \
-> (TransposedVectorView, Matrix):
"""Eigenvalues|vectors with QR factorization"""
assert is_symmetric(a)
a_k = a.copy()
v_k = Matrix.identity(a.size()[0])
for i in range(max_iterations):
if almost_upper_... | 987d65f65bc95dd6acad1dc86061e2b036437a4c | 3,628,358 |
def evens(input):
"""
Returns a list with only the even elements of data
Example: evens([0, 1, 2, 3, 4]) returns [0,2,4]
Parameter input: The data to process
Precondition: input an iterable, each element an int
"""
result = []
for x in input:
if x % 2 == 0:
result.a... | 8a219f8815d95a18bea148eaae117f3356a77d4b | 3,628,359 |
def _setup_output_skip_keys(args):
"""reduce tensors pulled from data files to save time/space
"""
if (args.subcommand_name == "dmim") or (args.subcommand_name == "synergy"):
skip_keys = []
elif (args.subcommand_name == "mutatemotifs"):
skip_keys = [
DataKeys.ORIG_SEQ_PWM_HIT... | 20a5d95f8ee811aeba4dea47eb58339264241a5e | 3,628,360 |
from typing import List
def create_example(speakers: List[List[nparr]]) -> nparr:
"""
:param speakers: a list of speakers where each item is a list of microphones where each contains
a sound file padded to a consistent length
:return: matrix of size [features(freq),file_len(time),(mic_num-1)*2] which ... | 21c81d8f0f60e24ace3eca4f3a205604da98b3df | 3,628,361 |
def todo_detail(request, pk):
"""API endpoint to get single todo or update its last exec date
GET: Displays single ToDo
PUT: Updates last exec date
"""
todo = get_object_or_404(ToDo, pk=pk)
if request.method == 'GET':
serializer = ToDoSerializer(todo)
return Response(data=seria... | 74d89ed578220304efc2148024922b5baeb3b566 | 3,628,362 |
def SaveNumSummary(doc:NexDoc, filename):
"""Saves the summary of numerical results to a text file with the specified name."""
return NexRun("SaveNumSummary", locals()) | b51924a149d96043d4c8e9397063b8ff419db11f | 3,628,363 |
def get_binary_balanced_purity_ranges(preds, class_labels, bin_size, total_class_counts):
"""
Get balanced purity for each class, for each range of probabilities, for binary classifier.
Return dict. of class names to balanced purity at each prob threshold (10 thresholds)
:param preds: List of Numpy row... | 5389e44f3605ca344572483c6cbbc1f40a8b3ef7 | 3,628,364 |
def bond_symmetry_numbers(xgr, frm_bnd_key, brk_bnd_key):
""" symmetry numbers, by bond
the (approximate) symmetry number of the torsional potential for this bond,
based on the hydrogen counts for each atom
It is reduced to 1 if one of the H atoms in the torsional bond is a neighbor to the
special ... | 931a147e690ea5d2aa7564a353f9a18aa2be5a43 | 3,628,365 |
import subprocess
import os
def compile_catalog(locale_dir, domain, locale):
"""
Compile `*.po` files into `*.mo` files and saved them next to the
original po files found.
Parameters
----------
output_dir: str
FIXME:
domain: str
FIXME:
locale: str, optional
FIX... | 57eacdf96810d0243c03d8d5ac7568ce5771d3ff | 3,628,366 |
import logging
import json
def get_last_end_time(project_id, bucket_name):
""" Get the end_time as a string value from a JSON object in GCS.
This file is used to remember the last end_time in case one isn't provided
"""
last_end_time_str = ""
file_name = '{}.{}'.format(project_id, config.LAST... | 0c3c78fb10613fd2a9910b120bef0422764a29d8 | 3,628,367 |
import html
def make_header_layout():
"""The html layout for the dashboard's header view."""
return html.Div(
id="header",
className="header",
children=[
html.Div(id="title", className="header--project", children="rubicon-ml"),
html.Div(
id="lin... | 3dfd4587242c305ebeb1239b976556952f6c5601 | 3,628,368 |
def quimbify(data, qtype=None, normalized=False, chopped=False,
sparse=None, stype=None, dtype=complex):
"""Converts data to 'quantum' i.e. complex matrices, kets being columns.
Parameters
----------
data : dense or sparse array_like
Array describing vector or operator.
qtype :... | 7392d51f35b2728e3f475de2e4180b2c4fd586b1 | 3,628,369 |
def _check_insert_data(obj, datatype, name):
""" Checks validity of an object """
if obj is None:
return False
if not isinstance(obj, datatype):
raise TypeError("{} must be {}; got {}".format(
name, datatype.__name__, type(obj).__name__))
return True | 057d0124db3f304e7efd4093510c663f5383af63 | 3,628,370 |
def create_importance_sampling(
baddr: GBAPOMDPThroughAugmentedState, num_samples: int, minimal_sample_size: float
) -> belief_types.BeliefUpdate:
"""Creates importance sampling
Returns a rejection sampling belief update that tracks ``num_samples``
particles in the ``baddr``. Basically glue between
... | c13e4f921e9d0ac32561b43d2a4b445e7633b2e9 | 3,628,371 |
import csv
def maps():
""" VALUES TO EDIT: """
name_to_open_file = "act_comercial.csv"
""" END OF VALUES TO EDIT """
full_path_to_open_file = "static/databases/" + name_to_open_file
with open(full_path_to_open_file) as csv_file:
reader = csv.DictReader(csv_file)
all_commercial_... | 1c01b46f72ff32a8fb083b6973464388e1b270c7 | 3,628,372 |
from typing import Optional
def improved_land_choice(context: Context) -> Optional[int]:
"""
Play untapped land if needed, then ramp, then draw, then randomly choose a playable card
"""
hand = context.zones["hand"]
mana = context.mana
gold = context.gold
playable_cards = context.playable_c... | 343b283d8c6938f00ce36a1077c244734016ef8d | 3,628,373 |
def _ParsePath(path):
"""Parses a path into a bucket name and an object name."""
if not path:
return '', ''
parts = path.split(_PATH_DELIMITER, 1)
bucket = parts[0] if parts[0] else None
object_name = parts[1] if 1 < len(parts) else None
return bucket, object_name | f059eabe500164a92ae7c32bbae4ca4bc30c0eac | 3,628,374 |
def instance ():
"""
Get single instance of cache. If not setup already, the cache will be set up by default parameters.
"""
global _CacheInstance
if _CacheInstance != None:
return _CacheInstance
else:
return setup () | 117248d9519e1f745a7a6b368425ea2a0759aedc | 3,628,375 |
def bboxes_iou(boxes1,boxes2):
"""
Argument:
bboxes:dim = (num_box,4), 4 : [x_min,y_min,x_max,y_max]
Retiurn:
a np.array,dim = (num_box,1)
"""
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[...,2] - boxes1[...,0]) * (boxes1[...,3] - boxes1[...,1])
... | 6ab80cbab148280331f5e25e5455b01894034eb0 | 3,628,376 |
import os
def dir_exists(foldername):
""" Return True if folder exists, else False
"""
return os.path.isdir(foldername) | edf3bc0dcdb16e816f48134ede420b758aa53d16 | 3,628,377 |
def normalizeListVec(v):
"""Normalizes a vector list."""
length = v[0] ** 2 + v[1] ** 2 + v[2] ** 2
if length <= 0:
length = 1
v = [val / np.sqrt(length) for val in v]
return v | 8ee0f960011c79e8e9f8c666aa198c4a72002fe4 | 3,628,378 |
import itertools
def sim_1x5bits(K, kappa, num_sim):
"""
Compute simulation scalar products and
return a list of ranks and intersection values for several simulations.
Parameters:
K -- string
kappa -- string
num_sim -- integer
Return:
rank_wr_list -- list of tuples
"""
# Length of signal part
n ... | 2b5fb3f48b4841fc9b4c1824b7afd91ee15d7a75 | 3,628,379 |
import http
from typing import Optional
def athenaupload_start(
request: http.HttpRequest,
pk: int,
workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
"""Load a data frame using an Athena connection.
The parameters are obtained and if valid, an operation is scheduled for
exec... | 0fd167b85220c32dcab2dfcc59db96cfcddd0106 | 3,628,380 |
def dasum(x):
"""
Compute the sum of the absolute values of the entries in {x}
"""
# compute and return the result
return gsl.blas_dasum(x.data) | 78a09a0f23b88facba04361e2bd222777e769eea | 3,628,381 |
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port, ready_check_path, mappath):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs)... | b502f9776f6f6475e060c0bf919597222cf5f30f | 3,628,382 |
def get_datasets(filename):
"""
Get the names of datasets in an HDF5 file.
Parameters
----------
filename : str
Name of an HDF5 file visible to the arkouda server
Returns
-------
list of str
Names of the datasets in the file
See Also
--------
ls_hdf
... | c844c072501116b505dfcee93236633b8c915de2 | 3,628,383 |
def stats_particle(difference):
""""
Returns the relevant statistics metrics about the distribution of the reative energy difference, as the mean,
standard deviation, standard error and an appropriate label.
:parameter difference: array containing the difference between true energy and the predicted en... | ad5a886cf5167cd7b82deef2700f42eddb517163 | 3,628,384 |
import pprint
def oxe_set_flex(host, token, flex_ip_address, flex_port):
"""Summary
Args:
host (TYPE): Description
token (TYPE): Description
flex_ip_address (TYPE): Description
flex_port (TYPE): Description
Returns:
TYPE: Description
"""
packages.u... | 9933bebc905e463abb523f3c94b2812cd00888be | 3,628,385 |
import requests
from bs4 import BeautifulSoup
import copy
import re
def process_advisory(url):
"""Process an advisory URL."""
global rule_number, RULE_TEMPLATE
logger.debug('process_advisory({0})'.format(url))
html = requests.get(url).text
soup = BeautifulSoup(html, 'html5lib')
rule = copy.deepcopy(RULE_TEMP... | e8e8908ecf2cc1db2a4c1cb28f677159b154d9d8 | 3,628,386 |
async def rest_handler(request):
"""Defines a GET handler for the '/rest' endpoint.
Users make requests of this handler with a query string containing the following arguments:
cmd: The command c to execute | c E {find, stats}
params: A list of key-value parameters corresponding to the commands ... | 4bfdaa44f1a0189614447780ae6223db3646b32c | 3,628,387 |
def if_true(value, replace_with=None):
"""Replaces the value with the passed if the value is true."""
if not value:
return ''
if replace_with is None:
return value
return Template(replace_with).safe_substitute(value=value) | 968fac956801317454a9fec8a27c53107ed31881 | 3,628,388 |
import os
def scenepath(scene):
"""Generate path for scene directory"""
return os.path.join(basedir, name(scene)) | cf78e6c0ff9674e48261d9cbdedafb3f33449bd6 | 3,628,389 |
async def quineables(ctx) -> None:
"""
Displays a list of files printable with
the quine command
"""
table = PrettyTable()
table.align = "c"
table.field_names = ["File Name", "File Path"]
for f, p in _generate_valid_files().items():
table.add_row([f, p])
return await ctx.send... | 01cbef961c5e1383c23ca0055c81fd2167211263 | 3,628,390 |
def piece_not(piece: str) -> str:
"""
helper function to return the other game piece that is not the current game piece
Preconditions:
- piece in {'x', 'o'}
>>> piece_not('x')
'o'
>>> piece_not('o')
'x'
"""
return 'x' if piece == 'o' else 'o' | 18bb3b45accf98d4f914e3f50372c4c083c1db4d | 3,628,391 |
def util(cpu='all', state='user', mode='avg1', host_os=detect_host_os()):
"""
Returns average percentage of time spent by cpu in a state over a period
of time
:raises: WrongArgumentError if unknown cpu is supplied
:raises: WrongArgumentError if unknown state is supplied
:raises: WrongArgumentEr... | 3a754200320a55211ce4d9e2470beb88b12eac57 | 3,628,392 |
import scipy
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y, angle)
the gaussian parameters of a 2D distribution found by a fit"""
params = moments(data)
errorfunction = lambda p: np.ravel(gaussian(*p)(*np.indices(data.shape)) - data)
p, success = scipy.optimize.leastsq(errorfun... | c7aa83c280a471f7191ea70e81e442320dcff76e | 3,628,393 |
def retina_debug():
"""
Return a dictionary with parameters for the retina suitable for debugging.
"""
params = retina_default()
params.update({'description' : 'debug retina','N': 8})
return params | 27321a835417f9022dfc57f75ea19a517e76012f | 3,628,394 |
def argsum(*args):
"""sum of all arguments"""
return sum(args) | 2445ef4f3fc321b3eae1997a8c44c628cd72d70a | 3,628,395 |
import multiprocessing
def fit_data_multi_files(dir_path, file_prefix, param, start_i, end_i, interpath="entry/instrument/detector/data"):
"""
Fitting for multiple files with Multiprocessing.
Parameters
----------
dir_path : str
file_prefix : str
param : dict
start_i : int
sta... | 3633054ff8238895e1c6a4fa68be4530d2ea1b22 | 3,628,396 |
def mark_up_series(
issues: pd.DataFrame, series: str, area_of_testing: str, patterns: str
) -> pd.DataFrame:
""" Appends binarized series to df.
Parameters:
----------
issues:
Bug reports.
series:
df series name.
area_of_testing:
area of testing.
patterns:
... | fdfba7b11fe1bb40d7a6cac171af33be2fce1152 | 3,628,397 |
def get_exp_parameters():
"""
Defines the default values for the hyper-parameters of the experiment.
:return: A dictionnary with values of the hyper-parameters
:rtype: dict
"""
parser = ArgumentParser(add_help=False)
parser.add_argument('--use_optuna', type=bool, default=False)
parse... | f24240aa14c9bf28c81684a6afedf6ab30796932 | 3,628,398 |
from typing import List
from typing import Dict
from typing import Tuple
from typing import Callable
def enum_options(values: List[Dict]) -> Tuple[List[str], int, Callable]:
"""Enumerate options of a enum parameter for display in a select box.
Returns a 3-tuple containing a list of option value, the list inde... | c1214f319847b40705f425e529420a5916debe6e | 3,628,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.