content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_board_state(file_name):
"""
o = food / point thing
X = wall
P = pac man
S = ghost spawn
' ' = empty space
"""
board = []
with open(file_name, 'r') as file:
for line in file:
line = line.strip()
board.append(list(line))
return board | 4d3a1822649724407f62abfa7909014562fd6978 | 44,000 |
def dist_version(name):
"""
Returns the version of the installed distribution package,
otherwise returns None.
"""
return metadata.version(name) if name else None | 103bf71e9bd302b19a914a5c9157c17c4768b340 | 44,001 |
import click
def validate_profile(context, param, value):
"""
Validates existance of profile.
Returns the profile name if it exists; otherwise throws BadParameter
"""
if value in context.obj.configuration.profiles():
return value
else:
raise click.BadParameter("\"%s\" was not f... | ac1fd3caa99a510173aa96f4c781abfacb6eed97 | 44,002 |
from typing import Callable
def iterated_smoother_routine(initial_state: MVNormalParameters,
observations: jnp.ndarray,
transition_function: Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray],
transition_covariance: jnp.ndarray,
... | b15c762053c0c6d47bfe384521d493808a92d767 | 44,003 |
def HotellingT2Test(X, robust=True, plot=True):
"""Hotellig T^2 test for abnormallity.
Testing whether the observation is abnormal using Hotellig T^2 test
at confidence level a = 0.01
Parameters
----------
X : array-like
robust : bool, optional
plot : bool, optional
Returns
--... | 7283fdc17e0323428a931e7b3a54bec74b2af2e9 | 44,004 |
def bulk_insert(session, mapper, mappings):
"""Perform a bulk insert into table/statement represented by `mapper`
while utilizing a special syntax that replaces the tradtional
``executemany()`` DBAPI call with a multi-row VALUES clause for a
single INSERT statement.
See :meth:`bulk_insert_many` for... | 0c6023ab3adc6377d62c2f72c70e50c01dd121b3 | 44,005 |
def formatPath(a):
"""Format SVG path data from an array"""
return "".join([cmd + " ".join([str(p) for p in params]) for cmd, params in a]) | f56f62b001bf37696fa3636310fda1c8e26e8ae9 | 44,006 |
import torch
def get_subsequent_mask(seq):
"""For masking out the subsequent info."""
len_s = seq.size(1)
subsequent_mask = 1 - torch.triu(
torch.ones((len_s, len_s), device=seq.device), diagonal=1)
subsequent_mask = subsequent_mask.unsqueeze(0).bool()
return subsequent_mask | 37469e1b99aeb6ac308aa43cbb6879f75caa1ac8 | 44,007 |
def merge_configs(*configs):
"""
Merges dictionaries of dictionaries, by combining top-level dictionaries with last value taking
precedence.
For example:
>>> merge_configs({'a': {'b': 1, 'c': 2}}, {'a': {'b': 2, 'd': 3}})
{'a': {'b': 2, 'c': 2, 'd': 3}}
"""
merged_config = {}
for co... | dbbdff74695233b522cd4381a78ca82e6f8057fd | 44,008 |
def _is_file_uri(uri):
"""Returns True if the passed-in URI is a file:// URI."""
return _FILE_URI_REGEX.match(uri) | 21cf9c7b2475d3402100381b627ea148b42d675d | 44,009 |
def _dup_right_decompose(f, s, K):
"""Helper function for :func:`_dup_decompose`."""
n = len(f) - 1
lc = dup_LC(f, K)
f = dup_to_raw_dict(f)
g = { s: K.one }
r = n // s
for i in range(1, s):
coeff = K.zero
for j in range(0, i):
if not n + j - i in f:
... | 48b334a989d1d5fbc186bbc55cf0e16e89205572 | 44,010 |
def DefineNamedRange(sheet, x0, y0, width, height, name):
"""Defines a new (or replaces an existing) named range on a sheet,
using zero-based absolute coordinates
"""
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
# FIXME: Is there some Python-callable API to turn a ... | e8ccfad686ba121fe1acfc14aaf782c143173934 | 44,011 |
import socket
def find_in_connection_table(addr):
"""Find a peer address *addr* in the connection table, and return the
socket address."""
# Addresses in /proc/net/tcp are network endian printed as machine endian,
# meaning they get byte swapped on little endian. Ports are machine endian
# printed... | f61995e41660dddaad7e8ef5a161bf0351168ecd | 44,012 |
def get_xyz_from_radar(radar):
"""Input radar object, return z from radar (km, 2D)"""
azimuth_1D = radar.azimuth['data']
elevation_1D = radar.elevation['data']
srange_1D = radar.range['data']
sr_2d, az_2d = np.meshgrid(srange_1D, azimuth_1D)
el_2d = np.meshgrid(srange_1D, elevation_1D)[1]
xx... | d66b1e64471b1a6f4e1ac0f138be881ffa5d928a | 44,013 |
import torch
def expected_unique(probabilities, sample_size):
"""Get expected number of unique samples.
This computes the expected number of unique samples for a multinomial
distribution from which we sample a fixed number of times.
"""
vals = 1 - (1 - probabilities) ** sample_size
expectati... | fd9b7ebd35db0d29c32495f50cd7f220e76267ba | 44,014 |
def label_tsne(tsne_results, sample_names, tool_label):
"""
Label tSNE results.
Parameters
----------
tsne_results : np.array
Output from run_tsne.
sample_names : list
List of sample names.
tool_label : str
The tool name to use for adding labels.
Returns
---... | 50422e192e57fb6a019618d46e9a95b9b3c3c768 | 44,015 |
def get_client():
"""
Returns an authenticated CustomerInsights client.
"""
base_url = GLOBAL_CONFIG.get("endpoint", "base_url", None)
if base_url:
logger.info('Using base url: %s', base_url)
return CustomerInsights(base_url) | 36187a1ff9f165b83af95e0fc8a7d1328abf7d1e | 44,016 |
def image_warp(image, flow, interp_method, name='dense_image_warp'):
"""Image warping using per-pixel flow vectors.
Apply a non-linear warp to the image, where the warp is specified by a dense
flow field of offset vectors that define the correspondences of pixel values
in the output image back to locations in t... | 6901b86baec2835e8d83585cde459cc483db943e | 44,017 |
def breadcrumb_scope(parser, token):
"""
Easily allow the breadcrumb to be generated in the admin change templates.
"""
return BreadcrumbScope.parse(parser, token) | daf88c6714ec1b32999fc0b771eeec7757d93ca3 | 44,018 |
def QR_algorithm_shift_Givens_double(A):
"""The QR algorithm with largest value shift for finding eigenvalues.
Using Givens rotations for finding RQ.
:param A: The square matrix to find eigenvalues of.
:type A: :py:class:`numpy.ndarray`
:return: The eigenvalues.
:rtype: list
"""
# Fi... | 474dbb3d7795d58ad43ec25ce62556e095c02270 | 44,019 |
import json
def create_user(client, jwt, project_role='developer'):
"""Create user and return user object.
project_role allowed values: developer, manager, cto
"""
response = _create_user_(client, jwt, project_role=project_role)
user = json.loads(response.data)
return user | ccb5a37a7b84c7eb95b3bddc9deb31fb080d813f | 44,020 |
from typing import List
import json
def load_scc_from_cache(
scc: List[MypyFile],
result: BuildResult,
mapper: genops.Mapper,
ctx: DeserMaps,
) -> ModuleIRs:
"""Load IR for an SCC of modules from the cache.
Arguments and return are as compile_scc_to_ir.
"""
cache_data = {
k.fu... | eb0a2b52e9eb6c487e8fc59b2180db03941c5e43 | 44,021 |
def GetFolderUriPath(folder):
"""Return the URI path of a GCP folder."""
return GetParentUriPath('folders', folder) | f23285d5dd40029efa3dacd414d2cc82b0182af8 | 44,022 |
def ffs(model, df, selected_columns=None, target_column="min_offer", df_to_xy_kwargs=None, cv=3, ravel_target=True, n_jobs=-2, enforced_target_values=None, early_stop=2):
"""
Forward feature selection
"""
if selected_columns is None:
selected_columns = [col for col in df.columns if col != target... | caf01ea5ed1acd781c55844a621002cb95883f82 | 44,023 |
def CreateHDFStudyFile(file_name: str, *ignored_args) -> bool:
"""aux function for mocking salome.myStudy.SaveAs
it ignores arguments for multifile and mode (ascii or binary)
TODO do a type check on the "file_name"? => salome seems to only work with "str"
"""
if not file_name.endswith(".hdf"):
... | aa940f08ec8d7a3c916ae29372180ee7d0613088 | 44,024 |
def diff_list(l1, l2):
"""Returns side by side equality test"""
return [False if i1==i2 else True for (i1, i2) in zip(l1, l2)] | 50a81f3c517168d6b369e11ac874520cf5110656 | 44,025 |
def process_metadata(full_dict):
"""Convert an extended system dictionary, as obtained through __dict__, to a reduced one that can be written to
a file
Parameters
----------
full_dict: dict
"""
reduced_dict = {}
for key, param_obj in full_dict.items():
if key[0] == '_':
... | b9acc52902d780df7e32cf835e0eaaa93db45534 | 44,026 |
import socket
from datetime import datetime
import pytz
import json
def submit(
description,
analysis_mode='analysis',
tool='ace_api',
tool_instance='ace_api:{}'.format(socket.getfqdn()),
type='generic',
company_id=None,
event_time=None,
details={},
observables=[],
tags=[],
... | 6fc0bd4566441af72155faa159a1570ec979157f | 44,027 |
def pack_language(language):
"""Pack language in a two-byte tuple."""
return pack_language_or_region(language, 'a') | 06599ddbd3f0970c12d68234d4fcb513d1da1a9d | 44,028 |
def create(**kwargs):
"""
创建EmailClient实例
:param kwargs:
:param smtp_server: smtp发送邮件服务器
:param msg_from: 发件人邮箱
:param password: 发件人授权码
:param msg_from_format: 发件人格式化显示文案
:param msg_to: 收件人邮箱列表
:param msg_subject: 邮件主题
:param msg_content: 邮件内容
:param attach_file: 邮件附件
:pa... | d84e97c04989f675ffc00c35cecec0bfebfdcc8b | 44,029 |
def infer_with_cpu(frame, network):
"""
Run inference using opencv dnn interface.
:param image: resized frame
:return:
"""
# MobileNetSSD Expects 300x300 resized frames
blob = cv.dnn.blobFromImage(frame, 0.00784, (Config.model_image_height, Config.model_image_width), (127.5, 127.5, 127.5), ... | c7eb397a9a223b0141d1172955b84fbf96a123fa | 44,030 |
def protein_substitution(annotation, score):
"""
Returns an array with the MIN and the MAX value of the given ProteinSubstitutionScore. Empty array if not found.
:type annotation: str
:param annotation: Annotation field
:type score: str
:param score:
:rtype:
:return:
"""
jc = ... | 60581c04b7ecf80c016e964f2e88ca50813c67bf | 44,031 |
def calculate_weights_posterior(designmtx, targets, beta, m0, S0):
"""
Calculates the posterior distribution (multivariate gaussian) for weights
in a linear model.
parameters
----------
designmtx - 2d (N x M) array of inputs (data-matrix or design-matrix) where
N is the number of data-p... | a9c3acfd4701d2009b32d2119ca6241fbff29bc1 | 44,032 |
import math
import operator
def cal_item_sim(user_click, user_click_time):
"""
Args:
user_click:dict ,key userid value [itemid1, itemid2]
Return:
dict, key:itemid_i, value dict, value_key itemid_j, value_value simscore
"""
co_appear = {}
item_user_click_time = {}
for user, ... | 740d5964ebd4a3f51155248b56981ab10df002e6 | 44,033 |
from typing import List
def get_routes(vehicles: List[int], stops: List[int]):
"""
Create dict of vehicles (key) and their routes (value).
:vehicles: list of vehicle identities (same order as demand)
:stops: list of stop numbers (same order as vehicles)
return dict
"""
counts... | 966baf998c0ec22ad381175a5680b4cefd045a6f | 44,034 |
def expand_port_range(port_range):
"""Expands a port range.
From https://cloud.google.com/compute/docs/reference/beta/firewalls, ports
can be of the form "<number>-<number>".
Args:
port_range (string): A string of format "<number_1>-<number_2>".
Returns:
list: A list of string integer... | 5e9ef10a3c47104d49caf94975c6c80f1aecb362 | 44,035 |
def parse_common_header(sff_file):
"""Parse a Common Header section from a binary SFF file.
Keys in the resulting dict are identical to those defined in the
Roche documentation.
As a side effect, sets the position of the file object to the end
of the Common Header section.
"""
h = comm... | bed19b5959464e021ee1cf352dcb219d55b54c16 | 44,036 |
import json
def load_features(features_path):
"""
Reading the features from disk.
:param features_path: Location of feature JSON.
:return features: Feature hash table.
"""
features = json.load(open(features_path))
features = {str(k): [str(val) for val in v] for k, v in features.items()}
... | b19bc868cbaf0fc45e55570589476d2d33eadd9e | 44,037 |
def _geodesic_parcel_centroid(vertices, faces, inds):
"""
Calculates parcel centroids based on surface distance
Parameters
----------
vertices : (N, 3)
Coordinates of vertices defining surface
faces : (F, 3)
Triangular faces defining surface
inds : (R,)
Indices of `v... | a32ff85622eb3b8cccc9f020b4c5ca76294425d6 | 44,038 |
def progress_bar(progress, size = 20):
"""
Returns an ASCII progress bar.
:param progress: A floating point number between 0 and 1 representing the
progress that has been completed already.
:param size: The width of the bar.
.. code-block:: python
>>> ui.progress_bar(0.5, 10)
... | ab3bffd9e2c9c0060001a3058217690e8d30a67d | 44,039 |
def backlog_list_wikis(client: BacklogAPI, project: str):
"""プロジェクト配下のwikiをリストする
:param client: API Client
:type client: BacklogAPI
:param project: プロジェクトIDもくしはプロジェクトキー
:type project: str
"""
return client.wiki.list(
projectIdOrKey=project
) | 9823a5f0af0caf60b5229eaf03c6a1c3f450ef4b | 44,040 |
import json
def model_to_json(model):
"""
Serialize a model to Json:
- model: the model object to serialize.
Return: the json as a string
"""
dictionnary = model_to_dict(model)
return json.dumps(dictionnary, cls=DjangoJSONEncoder) | 45a1b9246d69dbe256f48a54fc4bfdcbc8cf2ce3 | 44,041 |
def print_stepdb(df) -> pd.DataFrame:
"""create summary DataFrame from step info db
Parameters
----------
df : DataFrame
outcome of cal_stepinfo with duration, ap_ptp, ml_ptp, balance, LR
Returns
-------
pd.DataFrame
summary dataframe for one patient
"""
res = pd.D... | c521e111e907283dee7f28f5d3aa4f933b3f70dc | 44,042 |
def get_kmer(record_dict, chromosome, position, k=3, pos='mid'):
"""
Given a dictionary (in memory) of fasta sequences this function will
return a kmer of length k centered about pos at a certain genomic position
in an identified dictionary key i.e. chromosome.
Parameters
----------
record_... | b163961603a6f1ecbd2fa9bc9ef5cf2a488d7bd3 | 44,043 |
def blend_images(img0: NDArrayByte, img1: NDArrayByte, alpha: float = 0.7) -> NDArrayByte:
"""Alpha-blend two images together.
Args:
img0: uint8 array of shape (H,W,3)
img1: uint8 array of shape (H,W,3)
alpha: Alpha blending coefficient.
Returns:
uint8 array of shape (H,W,3... | 646fc6d38bed930710c1fc69fef79b030e5db200 | 44,044 |
def hasblocks(hashlist):
"""Determines which blocks are on this server"""
print("HasBlocks()")
return hashlist | 9bcd481b6c6ec1ecbbcb1978edae0bff86fd5cb7 | 44,045 |
def make_matched_rows(num_records):
"""Make multiple interaction CSV rows that should pass contact matching."""
adviser = AdviserFactory(
first_name='Adviser for',
last_name='Matched interaction',
)
service = random_service()
communication_channel = random_communication_channel()
... | c57f7ecc86a1e9c253899ec6f274d40761fe0ab8 | 44,046 |
import torch
def group(nsample, xyz, points):
"""
Input:
nsample: scalar
xyz: input points position data, [B, N, C]
points: input points data, [B, N, D]
Return:
new_xyz: sampled points position data, [B, 1, C]
new_points: sampled points data, [B, 1, N, C+D]
"""
... | b6e5a008f77d50245ce278c2ed0ae716927e4e67 | 44,047 |
def sample_neuron(samp_num, burnin, sigma_J, S, D_i, ro, thin=0, save_all=True):
""" This function uses the Gibbs sampler to sample from w, gamma and J
:param samp_num: Number of samples to be drawn
:param burnin: Number of samples to burn in
:param sigma_J: variance of the J slab
:param S: Neurons... | d1c425495da30760e1e6e044c5125be02095e7a7 | 44,048 |
import warnings
def lookup_angles(system, angles, temperature):
"""Parse the equilibrium angles and force constants of specified angles
from a openmm.System.
Parameters
----------
system : openmm.System
The system object that contains all potential and constraint definitions.
angles :... | 5a3bd8f3ce106034f3b4805aa3226bf40a65ce2e | 44,049 |
def get_schema_file_name() -> Text:
"""
Returns:
Text: get schema filename
"""
# TODO (Alex): remove hardcoded schema name
SCHEMA_NAME = 'stats.tfdv'
return SCHEMA_NAME | 413382cbab5a8294b71cda1818a94ea56816e408 | 44,050 |
def get_submissions_dir(ds):
"""Return pathobj of directory where all the submission packs live"""
return ds.pathobj / GitRepo.get_git_dir(ds.path) / 'datalad' / 'htc' | bdbf4411bfc7dd64f84f626279ff2430b994f112 | 44,051 |
def read_readme():
"""Load the project readme."""
with open("README.md") as readme:
return readme.read() | 4ae59523b29d5bf218ed9ced11679fc2cadbb21e | 44,052 |
def set_func_trace_options(*args):
"""set_func_trace_options(int options)"""
return _idaapi.set_func_trace_options(*args) | 281f9e55c2291dd22ecf2af94ac1e1e35e01da2c | 44,053 |
def page_not_found(e):
""" Render the 404 error page"""
return flask.render_template("404.html") | 092167c6a9f2d1bb9d29415169a0c030eb1d2410 | 44,054 |
def gam_prophoto(rgb):
"""
Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 to gamma corrected form.
Transfer curve is gamma 1.8 with a small linear portion.
https://en.wikipedia.org/wiki/ProPhoto_RGB_color_space
"""
result = []
for i in rgb:
# Mirror linear nat... | 63b1629e0d8e965bb0b78524d30e54f903b0736b | 44,055 |
import sys
def param_list(cls, m_name, a_type):
"""
Generate the parameter list (no parens) for an a_type accessor
@param cls The class name
@param m_name The member name
@param a_type One of "set" or "get" or TBD
"""
member = of_g.unified[cls]["union"][m_name]
m_type = member["m_type"... | 6223231f4bbe58b9fc4ece7ebe337759d7a9364f | 44,056 |
import torch
def pad_tensor(vec: torch.Tensor, pad: int, dim: int) -> torch.Tensor:
"""
args:
vec - tensor to pad
pad - the size to pad to
dim - dimension to pad
return:
a new tensor padded to 'pad' in dimension 'dim'
"""
if pad - vec.size(dim) == 0: # reach max n... | 6171e792e5f4309721d7d236e96ca27688e4fa28 | 44,057 |
def get_2D_transformation(testSession : Session, refSessions : "list[Session]"):
"""returns a list of possible poses along with their confidence
methods:
1: Cross referencing 2 refenrence images with one test sesison image
2: Matching 2 reference images to retrieve 3D points, then p... | 08c4732e8a1917eb9c103ad12e934d7b22e1ede7 | 44,058 |
def project_to_pointcloud(frame, ri, camera_projection, range_image_pose, calibration):
""" Create a pointcloud in vehicle space from LIDAR range image. """
beam_inclinations = compute_beam_inclinations(calibration, ri.shape[0])
beam_inclinations = np.flip(beam_inclinations)
extrinsic = np.array(calibr... | b1a8ae5e200609ffd847ba49f6243b18f20ca6f2 | 44,059 |
def model_verbose_name_plural(model):
"""
Returns the pluralized verbose name of a model instance or class.
"""
return model_options(model).verbose_name_plural | 23ed2d08406776071d9210ffe6459d7cb7a69475 | 44,060 |
def sample_gmmhmm(gmmhmm, n_sim):
"""
Simulate from a GMMHMM.
Returns
-------
states : ndarray of shape (n_sim,)
The sequence of states
obs : ndarray of shape (n_sim, K)
The generated observations (vectors of length K)
"""
states = []
obs = []
state = np.argm... | c71cc2cc946ffc96bb411b1f004f09b7cacd285c | 44,061 |
import subprocess
import sys
def take_fullscreen_capture():
"""Capture monitor."""
image_filename: str = random_char(amount=10)
image_path: str = f"{Settings.image_folder}{now:%Y}/{now:%m}"
image_url: str = f"{Settings.image_url}{now:%Y}/{now:%m}/{image_filename}.{Settings.file_extension}"
create... | ad6a639014dee8be30ef2f1d218830220eb66e72 | 44,062 |
def upload_file_to_s3_by_job_id(file_path, content_type="text/html", extra_message=None):
"""
Uploads a file to bokeh-travis s3 bucket under a job_id folder
"""
s3_filename = join(job_id, file_path)
return upload_file_to_s3(file_path, s3_filename, content_type, extra_message) | 14a9b2e93614161e458aae8f1e4af7cc62a490d2 | 44,063 |
def do_web_cert(af_ip_pairs, url, task, *args, **kwargs):
"""
Check the web server's certificate.
"""
try:
results = {}
for af_ip_pair in af_ip_pairs:
results[af_ip_pair[1]] = cert_checks(
url, ChecksMode.WEB, task, af_ip_pair, *args, **kwargs)
except Sof... | 6e13e93396cc48ea6432d11312ffa1291fa25bba | 44,064 |
def get_model(model_name):
"""Gets model by name."""
return load_generator(model_name) | 7a240fb5921c3429115b2720a5bc4dd053616710 | 44,065 |
def qhline(widget):
# http://stackoverflow.com/questions/5671354/how-to-programmatically-make-a-horizontal-line-in-qt
# solution
"""
Create a horizontal line
Parameters
----------
widget: widget containing the QFrame to be created
"""
line = QFrame(widget)
line.setFram... | 7d7d3175a15a4f9c5243042e5ae934a4eb4efb6d | 44,066 |
def load_start_time(start_time_file, vid):
"""
load start time
Args:
start_time_file: str
vid: str, video
Returns:
int, start time
"""
df_start_time = csv_read(start_time_file).set_index("video_name")
if vid not in df_start_time.index:
print("Error: ", vid,... | ef5c326fe21b2f88654ea24e923a1b671a069e9f | 44,067 |
import logging
def create_bus(net, level, name, zone=None):
"""
Create a bus on a given network
:param net: the given network
:param level: nominal pressure level of the bus
:param name: name of the bus
:param zone: zone of the bus (default: None)
:return: name of the bus
"""
try:... | eb3a0b711afbe058fcdff4510ec73843b440e4dd | 44,068 |
def instantiate_domains(domains, encoding_cnt):
"""create domain for fields we want to encode. """
instantiated = {}
for d in domains:
if "/encoding/*" in d:
for i in range(encoding_cnt):
instantiated[d.replace("/encoding/*", "/encoding/{}".format(i))] = domains[d]
else:
instantiated[d] = domains[d]
r... | 69857f67070eeabeaf9b1b4b8eb4d62f48563528 | 44,069 |
import struct
def read_float(data):
"""
Read 4 bytes of data as `float`.
Parameters
----------
data : io.BufferedReader
File open to read in binary mode
Returns
-------
float
Python float
"""
s_type = "=%s" % get_type("float")
return struct.unpack(s_type, ... | 46202d2032a7ace69e294566d389d13440b91544 | 44,070 |
def yt8m(is_training):
"""YT8M dataset configs."""
return DataConfig(
name='yt8m',
num_classes=3862,
feature_sizes=[1024, 128],
feature_names=["rgb", "audio"],
max_frames=300,
segment_labels=False,
segment_size=5,
is_training=is_training,
split='train' if is_training else 'valid'... | f8865630fecc1c30908f26af32b7d57ce1eb10fd | 44,071 |
def _filter_checkerboard_roi(xyz, centroid):
"""Filters out the data outside the region of interest defined by the checkerboard centroid.
Args:
xyz: a numpy array of X, Y and Z point cloud coordinates.
centroid: a numpy array of X, Y and Z checkerboard centroid coordinates.
Returns:
... | cf9cc082489e8dc03488f2aa90eab7007382187a | 44,072 |
def dock_panel(panel_name, base_url=DEFAULT_BASE_URL):
"""Dock a panel back into the UI of Cytoscape.
Args:
panel_name (str): Name of the panel. Multiple ways of referencing panels is supported:
(WEST == control panel, control, c), (SOUTH == table panel, table, ta), (SOUTH_WEST == tool panel... | 365854c1c0129a25bc4bf246f83fb3102ae84af7 | 44,073 |
def density(temp):
"""
Calculating density of water due to given temperature (Eq. 3.11)
:param temp: temperature prediction Y[d, t] at depth d and time t
:return: corresponding density prediction
"""
return 1000 * (1 - ((temp + 288.9414) * (temp - 3.9863) ** 2) / (508929.2 * (temp + 68.12963))) | 92d6d7c5639e03790715f62a1027a15357cdf1cf | 44,074 |
import torch
def distance2bbox(points, distance, max_shape=None):
"""Decode distance prediction to bounding box.
Args:
points (Tensor): Shape (n, 3), [t, x, y].
distance (Tensor): Distance from the given point to 4
boundaries (left, top, right, bottom, frDis, 4point, bkDis, 4point... | ea773f3bd0d53a2aaccb85c7b7042c51c3dd0653 | 44,075 |
def paren_matcher_less_space(s: str, open_index: int) -> int:
"""
Solution: Iterate through the s from the open_paren index, keeping track of how many remaining open parens
there are. When we get to 0, return the index.
Complexity:
Time: O(n) - Iterate through our string once
Space: O(1) - We take a slice of th... | 0023c65c9b743f739cf92534b3961725dc990fd3 | 44,076 |
def J_W3(x, y):
"""
Jacobian for the third layer weights.
There is no need to edit this function.
"""
# First get all the activations and weighted sums at each
# layer of the network.
a0, z1, a1, z2, a2, z3, a3 = network_function(x)
# We'll use the variable J to store parts of our result... | 45d6003b377b4543951a48c06ef7ddc7266d1b23 | 44,077 |
import numpy
def projection_from_matrix(matrix, pseudo=False):
"""Return projection plane and perspective point from projection matrix.
Return values are same as arguments for projection_matrix function:
point, normal, direction, perspective, and pseudo.
>>> point = numpy.random.random(3) - 0.5
... | 15ae0e1f2d518780ba0540be8bedb3f7ed372cdc | 44,078 |
def is_debug():
"""Return True iff the alert level is at least at debugging."""
return cfg.level >= L_DEBUG | 8b8b6f0eb3a2a2adea4992a5e48914d05b0ac794 | 44,079 |
def detect_encoding(filename, limit_byte_check=-1):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
encoding = _detect_encoding(input_file.readline)
# Check for correctness of encoding.
with open_with_encoding(filename, encoding) as input_fi... | de276e98d4a09a7f60f9bf769208af20331f7439 | 44,080 |
from typing import Tuple
def _partition(lst: list, pivot: object) -> Tuple[list, list]:
"""Return a partition of <lst> with the chosen pivot.
Return two lists, where the first contains the items in <lst>
that are <= pivot, and the second is the items in <lst> that are > pivot.
"""
smaller = []
... | 07950d665eca6b5591d3c8b65a980c2597b9e45a | 44,081 |
def split_arguments(args, splitter_name=None, splitter_index=None):
"""Split list of args into (other, split_args, other) between splitter_name/index and `--`
:param args: list of all arguments
:type args: list of str
:param splitter_name: optional argument used to split out specific args
:type spl... | c6e800ff6d109699d346c76052a70e4e5ab670d8 | 44,082 |
import torch
def cumulative_laplace_norm(input):
"""
Args:
input: [B, C, F, T]
Returns:
"""
batch_size, num_channels, num_freqs, num_frames = input.size()
input = input.reshape(batch_size * num_channels, num_freqs, num_frames)
step_sum = torch.sum(input, dim=1) # [B * C, F, T] =>... | 1c61399c3b36a6552e59f3ed62da651207370670 | 44,083 |
def requirements(package):
"""
Build a dictionary with the external dependencies of the {{{project.name}}} project
"""
# build the package instances
packages = [
package(name='python', optional=False),
]
# build a dictionary and return it
return {{ package.name: package for p... | 0ec3d0e7d2e225b707eab2bc83d10ad1f42143eb | 44,084 |
def weighted_average_std(grp, weight_col, select_cols=None):
"""
Based on http://stackoverflow.com/a/2415343/190597 (EOL)
"""
tmp = grp.select_dtypes(include=[np.number])
weights = tmp[weight_col]
if select_cols is not None:
values = tmp[select_cols]
else:
values = tmp.drop(w... | ccfebcee9368b35a675a3c79657889ee49d3318b | 44,085 |
def read_lc_int(buf):
"""
Takes a buffer and reads an length code string from the start.
Returns a tuple with buffer less the integer and the integer read.
"""
if len(buf) == 0:
raise ValueError("Empty buffer.")
sizes = {252:2, 253:3, 254:8}
fst = int(buf[0])
if fs... | 6a4d63caed9b83928132136d2a222a6af83e8398 | 44,086 |
def get_geography_countries_list():
"""Get a list of countries ordered by population size."""
data = load('geography')
return [row['country'] for row in data] | 2d9b0b3d21fb63d0a91acedfa1d18b7ea35c9094 | 44,087 |
def sysLogin():
"""Endpoint for getting JWT token by other services
---
requestBody:
required: true
content:
application/json:
schema:
properties:
app:
type: string
key... | bd40b0f940e6515fb45b1ef052fc8cdd524e4811 | 44,088 |
from typing import Dict
from typing import Any
def TemplateResponse(
request: Request, name: str, context: Dict[str, Any], *args, **kwargs
):
""" Create a template response """
context = dict(context)
context["request"] = request
context["scopes"] = parse_scopes(request)
return templates.Temp... | 5f41a4c00b61e2e111250dfefa8e5e65668689ae | 44,089 |
def method_factory(endpoint, client_method_name):
# type: (APIEndpoint, str) -> ClientMethod
"""
Kwargs:
endpoint: the endpoint to generate a callable method for
Returns:
A classmethod to be attached to the APIClient, which will perform
the actual request for this particular end... | a11b851506870dba9bb5bc94b3e298f6e54d0a12 | 44,090 |
from typing import Optional
def elgamal_keypair_from_secret(a: ElementModQ) -> Optional[ElGamalKeyPair]:
"""
Given an ElGamal secret key (typically, a random number in [2,Q)), returns
an ElGamal keypair, consisting of the given secret key a and public key g^a.
"""
secret_key_int = a.to_int()
i... | aa8cd5416e5a7645d4936e68f7ef3795de1769a5 | 44,091 |
import re
def is_valid_record2(parsed_record):
"""Check if parsed_record is properly formatted"""
if not (
"byr" in parsed_record
and parsed_record["byr"].isdigit()
and len(parsed_record["byr"]) == 4
and (1920 <= int(parsed_record["byr"]) <= 2002)
):
return False
... | d3fdb17f6c6726e74e02f41813c665e8be223406 | 44,092 |
def append_to_parquet_table(dataframe, filepath=None, writer=None):
"""Method writes/append dataframes in parquet format.
This method is used to write pandas DataFrame as pyarrow Table in parquet format. If the methods is invoked
with writer, it appends dataframe to the already written pyarrow table.
... | 19f212a61461070e80fb6d09fe34a726be15f823 | 44,093 |
def flw2qs(ex,ey,ep,D,ed,eq=None):
"""
Compute flows or corresponding quantities in the
quadrilateral field element.
Parameters:
ex = [x1, x2, x3, x4]
ey = [y1, y2, y3, y4] element coordinates
ep = [t] element thickness
D = [[kxx... | 48522ed8eaaa5556af908a4e7669c0e0b3ee7b96 | 44,094 |
def top(request):
"""
Return movies from top 3 ranks based on comments amount in some time period
:param request:
:return:
"""
movies = Movie.objects.all()
serializer = TopMovieSerializer(movies, many=True, context={'request': request})
filtered_list = [movie for movie in serializer.data... | 372cf9877db43cbc1e76e5a362762e895dace022 | 44,095 |
def LargestPrimeFactor(num):
"""Calculate greatest prime factor using length of list
It is best practice to use greatest prime factor for hash table's
capacity. This method calculates the greatest prime factor using the
int passed in and returns the prime integer.
Time complexity of O(logn)
:p... | ccb09b7bd385a8b4795dbdeb3a4e886cd0922f20 | 44,096 |
def generate_tool_metadata( tool_config, tool, repository_clone_url, metadata_dict ):
"""Update the received metadata_dict with changes that have been applied to the received tool."""
# Generate the guid.
guid = suc.generate_tool_guid( repository_clone_url, tool )
# Handle tool.requirements.
tool_re... | 6f2f4bd7b4ec8517c574908499de001457df390f | 44,097 |
from inspect import signature
import warnings
def fit_gaussian(data, weight=None, func=elliptical_gaussian):
"""Fit a gaussian on a map.
Parameters
----------
data : array_like
the input 2D map
weight : array_like (optional)
the corresponding weights
func : function
th... | b69b1c286fe7b09bf6531c47d2b2c1c8ad4f8c7c | 44,098 |
def lua_property(name):
""" Decorator for marking methods that make attributes available to Lua """
def decorator(meth):
def setter(method):
meth._setter_method = method.__name__
return method
meth._is_lua_property = True
meth._name = name
meth.lua_setter... | 97cd57cf21c4afdb43b6504af56139228df751cd | 44,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.