content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def f_score_one_hot(labels,predictions,beta=1.0,average=None):
"""compute f score, =(1+beta*beta)precision*recall/(beta*beta*precision+recall)
the labels must be one_hot.
the predictions is prediction results.
Args:
labels: A np.array whose shape matches `predictions` and must be one_hot.
... | 091143244858dee1e001042931f625db30c58195 | 31,449 |
def articles():
"""Show a list of article titles"""
the_titles = [[a[0], a[1]] for a in articles]
return render_template('articles.html', titles = the_titles) | bb8f9af9cedb30f89fa950f60c7710ac840f026c | 31,450 |
import json
from pathlib import Path
import uuid
def create_montage_for_background(montage_folder_path: str, im_b_path: str, f_path: str, only_face: bool) -> str:
"""
Creates and saves the montage from a designed background. If a folder is provided for faces, it will create a file
'faces.json' inside the ... | b0c229d16e0ffdf2a8ea63cbc5785be918c09d46 | 31,451 |
def deserialize_question(
question: QuestionDict
) -> Question:
"""Convert a dict into Question object."""
return Question(
title=question['title'],
content=question.get('content'),
choices=[
Choice(
title=title,
goto=goto
)
... | c6f5dd962cdc7a0ef273d4397472de572f92c1f8 | 31,452 |
from datetime import datetime
def ensure_utc_datetime(value):
"""
Given a datetime, date, or Wayback-style timestamp string, return an
equivalent datetime in UTC.
Parameters
----------
value : str or datetime.datetime or datetime.date
Returns
-------
datetime.datetime
"""
... | 0d5c631d2736094f5a60c2eb4ca7c83fcb1e3e6a | 31,453 |
def get_pod_status(pod_name: str) -> GetPodEntry:
"""Returns the current pod status for a given pod name"""
oc_get_pods_args = ["get", "pods"]
oc_get_pods_result = execute_oc_command(oc_get_pods_args, capture_output=True).stdout
line = ""
for line in oc_get_pods_result.splitlines():
if po... | 1353fb4f457a4818ffcfda188ca4d3db55ce5cc9 | 31,454 |
def helix_evaluate(t, a, b):
"""Evalutes an helix at a parameter.
Parameters
----------
t: float
Parameter
a: float
Constant
b: float
Constant
c: float
Constant
Returns
-------
list
The (x, y, z) coordinates.
Notes
-----
An i... | 2d62cae57dac72cd244d66df8de2d0a5d3b70c38 | 31,455 |
import scipy
def get_pfb_window(num_taps, num_branches, window_fn='hamming'):
"""
Get windowing function to multiply to time series data
according to a finite impulse response (FIR) filter.
Parameters
----------
num_taps : int
Number of PFB taps
num_branches : int
Number o... | 1193a29ab754e2c8f30e1a58f34c9efcf58513af | 31,456 |
from typing import Dict
from typing import OrderedDict
def retrieve_bluffs_by_id(panelist_id: int,
database_connection: mysql.connector.connect,
pre_validated_id: bool = False) -> Dict:
"""Returns an OrderedDict containing Bluff the Listener information
for ... | f3f5d3e86423db20aa4ffe22410cc491ec5e80ed | 31,457 |
def extract_protein_from_record(record):
"""
Grab the protein sequence as a string from a SwissProt record
:param record: A Bio.SwissProt.SeqRecord instance
:return:
"""
return str(record.sequence) | a556bd4316f145bf23697d8582f66f7dcb589087 | 31,458 |
import cftime
def _diff_coord(coord):
"""Returns the difference as a `xarray.DataArray`."""
v0 = coord.values[0]
calendar = getattr(v0, "calendar", None)
if calendar:
ref_units = "seconds since 1800-01-01 00:00:00"
decoded_time = cftime.date2num(coord, ref_units, calendar)
co... | e430d7f22f0c4b9ac125768b5c69a045e44046a5 | 31,459 |
import _tkinter
def checkDependencies():
"""
Sees which outside dependencies are missing.
"""
missing = []
try:
del _tkinter
except:
missing.append("WARNING: _tkinter is necessary for NetworKit.\n"
"Please install _tkinter \n"
"Root privileges are necessary for this. \n"
"If you have these, t... | 05aad218f3df84ddb5656d0206d50ec32aa02dcb | 31,460 |
from typing import Dict
from typing import Any
def get_user_groups_sta_command(client: Client, args: Dict[str, Any]) -> CommandResults:
""" Function for sta-get-user-groups command. Get all the groups associated with a specific user. """
response, output_data = client.user_groups_data(userName=args.get('user... | b21b087e4e931e33111720bbc987b1bb6749fee8 | 31,461 |
def get_capital_flow(order_book_ids, start_date=None, end_date=None, frequency="1d", market="cn"):
"""获取资金流入流出数据
:param order_book_ids: 股票代码or股票代码列表, 如'000001.XSHE'
:param start_date: 开始日期
:param end_date: 结束日期
:param frequency: 默认为日线。日线使用 '1d', 分钟线 '1m' 快照 'tick' (Default value = "1d"),
:param... | f7c3f94fd012672b75d960ef1c4d749959a7e6cc | 31,462 |
def split_quoted(s):
"""Split a string with quotes, some possibly escaped, into a list of
alternating quoted and unquoted segments. Raises a ValueError if there are
unmatched quotes.
Both the first and last entry are unquoted, but might be empty, and
therefore the length of the resulting list must... | 0790e7b2fecfd6c2aa1ca04c8cb5f1faebb3722b | 31,463 |
import torch
def calc_IOU(seg_omg1: torch.BoolTensor, seg_omg2: torch.BoolTensor, eps: float = 1.e-6) -> float:
"""
calculate intersection over union between 2 boolean segmentation masks
:param seg_omg1: first segmentation mask
:param seg_omg2: second segmentation mask
:param eps: eps for numerica... | 6586b1f9995858be9ab7e40edd1c3433cd1cd6f4 | 31,464 |
def td_path_join(*argv):
"""Construct TD path from args."""
assert len(argv) >= 2, "Requires at least 2 tdpath arguments"
return "/".join([str(arg_) for arg_ in argv]) | 491f1d50767a50bfbd7d3a2e79745e0446f5204c | 31,466 |
import torch
def calculate_segmentation_statistics(outputs: torch.Tensor, targets: torch.Tensor, class_dim: int = 1, threshold=None):
"""Compute calculate segmentation statistics.
Args:
outputs: torch.Tensor.
targets: torch.Tensor.
threshold: threshold for binarization of predictions.... | ccc017dd5c7197565e54c62cd83eb5cdc02d7d17 | 31,467 |
def sample_from_cov(mean_list, cov_list, Nsamples):
"""
Sample from the multivariate Gaussian of Gaia astrometric data.
Args:
mean_list (list): A list of arrays of astrometric data.
[ra, dec, plx, pmra, pmdec]
cov_list (array): A list of all the uncertainties and covariances:
... | 353c08bfd8951610fdcf1511107888c1153d3eed | 31,468 |
def get_finger_distal_angle(x,m):
"""Gets the finger angle th3 from a hybrid state"""
return x[2] | f93b1931f3e4a9284ccac3731dfeea21526ea07c | 31,469 |
def get_karma(**kwargs):
"""Get your current karma score"""
user_id = kwargs.get("user_id").strip("<>@")
session = db_session.create_session()
kama_user = session.query(KarmaUser).get(user_id)
try:
if not kama_user:
return "User not found"
if kama_user.karma_points == ... | 29f2622e65c45e642285014bbfa6dc33abb0e326 | 31,470 |
def plotly_shap_violin_plot(X, shap_values, col_name, color_col=None, points=False, interaction=False):
"""
Returns a violin plot for categorical values.
if points=True or color_col is not None, a scatterplot of points is plotted next to the violin plots.
If color_col is given, scatter is colored by c... | 03754df82272826965e73266075f3a0334620e93 | 31,472 |
def animation():
"""
This function gives access to the animation tools factory - allowing you
to access all the tools available.
Note: This will not re-instance the factory on each call, the factory
is instanced only on the first called and cached thereafter.
:return: factories.Factor... | 682cfe96f5682296ae721519be03aeb98b918e20 | 31,473 |
def merge(pinyin_d_list):
"""
:rtype: dict
"""
final_d = {}
for overwrite_d in pinyin_d_list:
final_d.update(overwrite_d)
return final_d | 512f551620ccedae8fb53f0c60f7caf931aae249 | 31,474 |
def dprnn_tasnet(name_url_or_file=None, *args, **kwargs):
""" Load (pretrained) DPRNNTasNet model
Args:
name_url_or_file (str): Model name (we'll find the URL),
model URL to download model, path to model file.
If None (default), DPRNNTasNet is instantiated but no pretrained
... | cf3190656d9c24730d9bab1554987d684ec33712 | 31,477 |
def utcnow():
"""Better version of utcnow() that returns utcnow with a correct TZ."""
return timeutils.utcnow(True) | a23cc98eca8e291f6e9aff5c0e78494930476f78 | 31,478 |
def build_profile(base_image, se_size=4, se_size_increment=2, num_openings_closings=4):
"""
Build the extended morphological profiles for a given set of images.
Parameters:
base_image: 3d matrix, each 'channel' is considered for applying the morphological profile. It is the spectral inf... | 7f7cd0e1259cdd52cd4ce73c3d6eee9c9f87b474 | 31,479 |
def mujoco_env(env_id, nenvs=None, seed=None, summarize=True,
normalize_obs=True, normalize_ret=True):
""" Creates and wraps MuJoCo env. """
assert is_mujoco_id(env_id)
seed = get_seed(nenvs, seed)
if nenvs is not None:
env = ParallelEnvBatch([
lambda s=s: mujoco_env(env_id, seed=s, s... | 5bad4500be5261f33a19e49612ce62e1db8c66dd | 31,480 |
import torch
def polar2cart(r, theta):
"""
Transform polar coordinates to Cartesian.
Parameters
----------
r, theta : floats or arrays
Polar coordinates
Returns
-------
[x, y] : floats or arrays
Cartesian coordinates
"""
return torch.stack((r * theta.cos(), ... | c13225a49d6435736bf326f70af5f6d4039091d8 | 31,481 |
def belongs_to(user, group_name):
"""
Check if the user belongs to the given group.
:param user:
:param group_name:
:return:
"""
return user.groups.filter(name__iexact=group_name).exists() | e1b70b4771dfec45218078ca16335ddc3c6214e2 | 31,482 |
import torch
def sum_log_loss(logits, mask, reduction='sum'):
"""
:param logits: reranking logits(B x C) or span loss(B x C x L)
:param mask: reranking mask(B x C) or span mask(B x C x L)
:return: sum log p_positive i over all candidates
"""
num_pos = mask.sum(-1) # B... | 88a312f74e7d4dce95d8dcadaeeaa1a136fceca6 | 31,483 |
from acor import acor
from .autocorrelation import ipce
from .autocorrelation import icce
def _get_iat_method(iatmethod):
"""Control routine for selecting the method used to calculate integrated
autocorrelation times (iat)
Parameters
----------
iat_method : string, optional
Routine to use... | a5bbe3a4f4bad486f9bab6ca4b367040ce516478 | 31,484 |
def run():
"""Main entry point."""
return cli(obj={}, auto_envvar_prefix='IMPLANT') # noqa | ae9e96478dbf081469052ff29d31873263060bff | 31,485 |
def qtl_test_interaction_GxG(pheno, snps1, snps2=None, K=None, covs=None, test="lrt"):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] np.array of 1 phenotype for N individuals
snps1: [N x S1] np.array of S1 SNPs for N individuals
snps2: [N x S2] np.array of S2 S... | 77eebc7c1c673562b1b793e9e5513b9a50aa6f1b | 31,486 |
import copy
import io
def log_parser(log):
"""
This takes the EA task log file generated by e-prime and converts it into a
set of numpy-friendly arrays (with mixed numeric and text fields.)
pic -- 'Picture' lines, which contain the participant's ratings.
res -- 'Response' lines, which contain the... | 7793cb1b53100961aca5011655211b0da47af856 | 31,487 |
from typing import List
def line_assign_z_to_vertexes(line_2d: ogr.Geometry,
dem: DEM,
allowed_input_types: List[int] = None) -> ogr.Geometry:
"""
Assign Z dimension to vertices of line based on raster value of `dem`. The values from `dem` are interp... | ae3e6c496cd10848e35830c1122a77589f322aad | 31,488 |
def backoff_linear(n):
"""
backoff_linear(n) -> float
Linear backoff implementation. This returns n.
See ReconnectingWebSocket for details.
"""
return n | a3a3b3fc0c4a56943b1d603bf7634ec50404bfb3 | 31,489 |
import pkg_resources
def _doc():
"""
:rtype: str
"""
return pkg_resources.resource_string(
'dcoscli',
'data/help/config.txt').decode('utf-8') | e83f8a70b9d6c9cff38f91b980cd3f9031d84fd7 | 31,490 |
def sk_algo(U, gates, n):
"""Solovay-Kitaev Algorithm."""
if n == 0:
return find_closest_u(gates, U)
else:
U_next = sk_algo(U, gates, n-1)
V, W = gc_decomp(U @ U_next.adjoint())
V_next = sk_algo(V, gates, n-1)
W_next = sk_algo(W, gates, n-1)
return V_next @ W_next @ V_next.adjoint() @ W... | e8251d7a41899584f92c808af1d4fdee10757349 | 31,491 |
def get_movie_list():
"""
Returns:
A list of populated media.Movie objects
"""
print("Generating movie list...")
movie_list = []
movie_list.append(media.Movie(
title='Four Brothers',
summary='Mark Wahlberg takes on a crime syndicate with his brothers.',
trailer_yo... | e00f67b55a47bf13075a4b2065b94feec4138bcd | 31,492 |
def check_dna_sequence(sequence):
"""Check if a given sequence contains only the allowed letters A, C, T, G."""
return len(sequence) != 0 and all(base.upper() in ['A', 'C', 'T', 'G'] for base in sequence) | 2f561c83773ddaaad2fff71a6b2e5d48c5a35f87 | 31,493 |
def test_inner_scalar_mod_args_length():
"""
Feature: Check the length of input of inner scalar mod.
Description: The length of input of inner scalar mod should not less than 2.
Expectation: The length of input of inner scalar mod should not less than 2.
"""
class Net(Cell):
def __init__... | 06bc7530106c5bf2f586e08ee2b941bd964228f1 | 31,494 |
import requests
def zip_list_files(url):
"""
cd = central directory
eocd = end of central directory
refer to zip rfcs for further information :sob:
-Erica
"""
# get blog representing the maximum size of a EOBD
# that is 22 bytes of fixed-sized EOCD fields
# plus t... | 694f6340145d509e7a18aa7b427b75f521c389df | 31,495 |
import torch
import numpy
import math
def project_ball(tensor, epsilon=1, ord=2):
"""
Compute the orthogonal projection of the input tensor (as vector) onto the L_ord epsilon-ball.
**Assumes the first dimension to be batch dimension, which is preserved.**
:param tensor: variable or tensor
:type ... | 188eda46ede2b6ac08bc6fc4cfa72efb56e2918e | 31,496 |
def load_model(filename):
"""
Loads the specified Keras model from a file.
Parameters
----------
filename : string
The name of the file to read from
Returns
-------
Keras model
The Keras model loaded from a file
"""
return load_keras_model(__construct_path(file... | 89656f682f1e754a08c756f0db49fc3138171384 | 31,498 |
from datetime import datetime
def testjob(request):
"""
handler for test job request
Actual result from beanstalk instance:
* testjob triggerd at 2019-11-14 01:02:00.105119
[headers]
- Content-Type : application/json
- User-Agent : aws-sqsd/2.4
- X-Aws-Sqsd-Msgid : 6998edf8-3f19-4c69-... | c2a751d64e76434248029ec1805265e80ef30661 | 31,500 |
from datetime import datetime
def todatetime(mydate):
""" Convert the given thing to a datetime.datetime.
This is intended mainly to be used with the mx.DateTime that psycopg
sometimes returns,
but could be extended in the future to take other types.
"""
if isinstance(mydate, datet... | 10ce9e46f539c9d12b406d65fb8fd71d75d98191 | 31,502 |
from datetime import datetime
def generate_datetime(time: str) -> datetime:
"""生成时间戳"""
today: str = datetime.now().strftime("%Y%m%d")
timestamp: str = f"{today} {time}"
dt: datetime = parse_datetime(timestamp)
return dt | f6fa6643c5f988a7e24cf807f987655803758479 | 31,503 |
def get_rgb_scores(arr_2d=None, truth=None):
"""
Returns a rgb image of pixelwise separation between ground truth and arr_2d
(predicted image) with different color codes
Easy when needed to inspect segmentation result against ground truth.
:param arr_2d:
:param truth:
:return:
"""
ar... | 7d5fff0ac76bf8326f9db8781221cfc7a098615d | 31,504 |
def calClassMemProb(param, expVars, classAv):
"""
Function that calculates the class membership probabilities for each observation in the
dataset.
Parameters
----------
param : 1D numpy array of size nExpVars.
Contains parameter values of class membership model.
expVars : 2D num... | a77b1c6f7ec3e8379df1b91c804d0253a20898c5 | 31,505 |
from typing import List
def detect_statistical_outliers(
cloud_xyz: np.ndarray, k: int, std_factor: float = 3.0
) -> List[int]:
"""
Determine the indexes of the points of cloud_xyz to filter.
The removed points have mean distances with their k nearest neighbors
that are greater than a distance thr... | 2e48e207c831ceb8ee0f223565d2e3570eda6c4f | 31,506 |
def collinear(cell1, cell2, column_test):
"""Determines whether the given cells are collinear along a dimension.
Returns True if the given cells are in the same row (column_test=False)
or in the same column (column_test=True).
Args:
cell1: The first geocell string.
cell2: The second geocell string.
... | f79b34c5d1c8e4eed446334b1967f5e75a679e8a | 31,507 |
def plasma_fractal(mapsize=512, wibbledecay=3):
"""Generate a heightmap using diamond-square algorithm.
Modification of the algorithm in
https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
Args:
mapsize: side length of the heightmap, must be a power of two.
wibbledecay: integer, decay facto... | 96457a0b00b74d269d266512188dfb4fab8d752c | 31,508 |
import pwd
import grp
import time
def stat_to_longname(st, filename):
"""
Some clients (FileZilla, I'm looking at you!)
require 'longname' field of SSH2_FXP_NAME
to be 'alike' to the output of ls -l.
So, let's build it!
Encoding side: unicode sandwich.
"""
try:
n_link = str(s... | c0a4a58ec66f2af62cef9c3fa64c8332420bfe1c | 31,509 |
def driver():
"""
Make sure this driver returns the result.
:return: result - Result of computation.
"""
_n = int(input())
arr = []
for i in range(_n):
arr.append(input())
result = solve(_n, arr)
print(result)
return result | fcd11f88715a45805fa3c1629883fc5239a02a91 | 31,510 |
def load_element_different(properties, data):
"""
Load elements which include lists of different lengths
based on the element's property-definitions.
Parameters
------------
properties : dict
Property definitions encoded in a dict where the property name is the key
and the property ... | a6fe0a28bb5c05ee0a82db845b778ddc80e1bb8c | 31,511 |
def start_survey():
"""clears the session and starts the survey"""
# QUESTION: flask session is used to store temporary information. for permanent data, use a database.
# So what's the difference between using an empty list vs session. Is it just for non sens. data like user logged in or not?
# QUESTI... | 9a9cc9aba02f31af31143f4cc33e23c78ae61ec2 | 31,512 |
def page(token):
"""``page`` property validation."""
if token.type == 'ident':
return 'auto' if token.lower_value == 'auto' else token.value | 5b120a8548d2dbcbdb080d1f804e2b693da1e5c4 | 31,513 |
def index():
"""
Gets the the weight data and displays it to the user.
"""
# Create a base query
weight_data_query = Weight.query.filter_by(member=current_user).order_by(Weight.id.desc())
# Get all the weight data.
all_weight_data = weight_data_query.all()
# Get the last 5 data points f... | a812dd55c5d775bcff669feb4aa55b798b2042e8 | 31,515 |
def upload_binified_data(binified_data, error_handler, survey_id_dict):
""" Takes in binified csv data and handles uploading/downloading+updating
older data to/from S3 for each chunk.
Returns a set of concatenations that have succeeded and can be removed.
Returns the number of failed FTPS so... | 8b4499f3e5a8539a0b0fb31b44a5fe06ce5fd16b | 31,516 |
from enum import Enum
def system_get_enum_values(enum):
"""Gets all values from a System.Enum instance.
Parameters
----------
enum: System.Enum
A Enum instance.
Returns
-------
list
A list containing the values of the Enum instance
"""
return list(Enum.GetValues(e... | b440d5b5e3012a1708c88aea2a1bf1dc7fc02d18 | 31,517 |
def skip_leading_ws_with_indent(s,i,tab_width):
"""Skips leading whitespace and returns (i, indent),
- i points after the whitespace
- indent is the width of the whitespace, assuming tab_width wide tabs."""
count = 0 ; n = len(s)
while i < n:
ch = s[i]
if ch == ' ':
c... | e787a0a1c407902a2a946a21daf308ca94a794c6 | 31,518 |
import sh
def get_minibam_bed(bamfile, bedfile, minibam=None):
""" samtools view -L could do the work, but it is NOT random access. Here we
are processing multiple regions sequentially. See also:
https://www.biostars.org/p/49306/
"""
pf = op.basename(bedfile).split(".")[0]
minibamfile = minib... | 48142e8df2468332699459a6ff0a9c455d5ad32f | 31,520 |
def create_app(config_object="tigerhacks_api.settings"):
"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split(".")[0])
logger.info("Flask app initialized")
app... | 7bd2af062b770b80454b1f1fc219411fdb174a41 | 31,521 |
def dest_in_spiral(data):
"""
The map of the circuit consists of square cells. The first element in the
center is marked as 1, and continuing in a clockwise spiral, the other
elements are marked in ascending order ad infinitum. On the map, you can
move (connect cells) vertically and horizontally.... | a84a00d111b80a3d9933d9c60565b7a31262f878 | 31,522 |
from datetime import datetime
def get_current_time():
""" returns current time w.r.t to the timezone defined in
Returns
-------
: str
time string of now()
"""
srv = get_server()
if srv.time_zone is None:
time_zone = 'UTC'
else:
time_zone = srv.time_zone
ret... | 3b8d547d68bbc0f7f7f21a8a5b375cb898e53d30 | 31,523 |
import async_timeout
import aiohttp
import asyncio
async def _update_google_domains(hass, session, domain, user, password, timeout):
"""Update Google Domains."""
url = f"https://{user}:{password}@domains.google.com/nic/update"
params = {"hostname": domain}
try:
async with async_timeout.timeo... | 372137db20bdb1c410f84dfa55a48269c4f588bc | 31,524 |
def smoothen_over_time(lane_lines):
"""
Smooth the lane line inference over a window of frames and returns the average lines.
"""
avg_line_lt = np.zeros((len(lane_lines), 4))
avg_line_rt = np.zeros((len(lane_lines), 4))
for t in range(0, len(lane_lines)):
avg_line_lt[t] += lane_lines[t... | 64c31747ed816acbaeebdd9dc4a9e2163c3d5274 | 31,525 |
from typing import List
from typing import Optional
import random
def select_random(nodes: List[DiscoveredNode]) -> Optional[DiscoveredNode]:
"""
Return a random node.
"""
return random.choice(nodes) | 7bb41abd7f135ea951dbad85e4dc7290d6191e44 | 31,526 |
def convert(from_path, ingestor, to_path, egestor, select_only_known_labels, filter_images_without_labels):
"""
Converts between data formats, validating that the converted data matches
`IMAGE_DETECTION_SCHEMA` along the way.
:param from_path: '/path/to/read/from'
:param ingestor: `Ingestor` to rea... | 0407768620b3c703fec0143d2ef1297ba566ed7f | 31,527 |
import timeit
def timer(method):
"""
Method decorator to capture and print total run time in seconds
:param method: The method or function to time
:return: A function
"""
@wraps(method)
def wrapped(*args, **kw):
timer_start = timeit.default_timer()
result = method(*args, **... | 526a7b78510efb0329fba7da2f4c24a6d35c2266 | 31,528 |
def macro_states(macro_df, style, roll_window):
"""
Function to convert macro factors into binary states
Args:
macro_df (pd.DataFrame): contains macro factors data
style (str): specify method used to classify. Accepted values:
'naive'
roll_window (int): specify rolling... | 1d4862cfb43aeebd33e71bc67293cbd7b62eb7b5 | 31,529 |
import torch
def get_sparsity(lat):
"""Return percentage of nonzero slopes in lat.
Args:
lat (Lattice): instance of Lattice class
"""
# Initialize operators
placeholder_input = torch.tensor([[0., 0]])
op = Operators(lat, placeholder_input)
# convert z, L, H to np.float64 (simplex ... | 703bd061b662a20b7ebce6111442bb6597fddaec | 31,530 |
def XYZ_to_Kim2009(
XYZ: ArrayLike,
XYZ_w: ArrayLike,
L_A: FloatingOrArrayLike,
media: MediaParameters_Kim2009 = MEDIA_PARAMETERS_KIM2009["CRT Displays"],
surround: InductionFactors_Kim2009 = VIEWING_CONDITIONS_KIM2009["Average"],
discount_illuminant: Boolean = False,
n_c: Floating = 0.57,
)... | bf694c7a66052b3748f561018d253d2dfcdfc8df | 31,531 |
from typing import Union
from pathlib import Path
from typing import Optional
def load_capsule(path: Union[str, Path],
source_path: Optional[Path] = None,
key: Optional[str] = None,
inference_mode: bool = True) -> BaseCapsule:
"""Load a capsule from the filesyste... | f6810bdb82ab734e2bd424feee76f11da18cccf4 | 31,532 |
def geodetic2ecef(lat, lon, alt):
"""Convert geodetic coordinates to ECEF."""
lat, lon = radians(lat), radians(lon)
xi = sqrt(1 - esq * sin(lat))
x = (a / xi + alt) * cos(lat) * cos(lon)
y = (a / xi + alt) * cos(lat) * sin(lon)
z = (a / xi * (1 - esq) + alt) * sin(lat)
return x, y, z | 43654b16d89eeeee0aa411f40dc12d5c12637e80 | 31,533 |
def processor_group_size(nprocs, number_of_tasks):
"""
Find the number of groups to divide `nprocs` processors into to tackle `number_of_tasks` tasks.
When `number_of_tasks` > `nprocs` the smallest integer multiple of `nprocs` is returned that
equals or exceeds `number_of_tasks` is returned.
When ... | f6d9a760d79ff59c22b3a95cc56808ba142c4045 | 31,534 |
def skin_base_url(skin, variables):
""" Returns the skin_base_url associated to the skin.
"""
return variables \
.get('skins', {}) \
.get(skin, {}) \
.get('base_url', '') | 80de82862a4a038328a6f997cc29e6bf1ed44eb8 | 31,535 |
import json
def validate_dumpling(dumpling_json):
"""
Validates a dumpling received from (or about to be sent to) the dumpling
hub. Validation involves ensuring that it's valid JSON and that it includes
a ``metadata.chef`` key.
:param dumpling_json: The dumpling JSON.
:raise: :class:`netdumpl... | 7d6885a69fe40fa8531ae58c373a1b1161b1df49 | 31,538 |
def _recurse_to_best_estimate(
lower_bound, upper_bound, num_entities, sample_sizes
):
"""Recursively finds the best estimate of population size by identifying
which half of [lower_bound, upper_bound] contains the best estimate.
Parameters
----------
lower_bound: int
The lower bound... | 969b550da712682ae620bb7158ed623785ec14f5 | 31,540 |
def betwix(iterable, start=None, stop=None, inc=False):
""" Extract selected elements from an iterable. But unlike `islice`,
extract based on the element's value instead of its position.
Args:
iterable (iter): The initial sequence
start (str): The fragment to begin with (inclusive)
... | e1079158429e7d25fee48222d5ac734c0456ecfe | 31,541 |
import logging
def map_configuration(config: dict) -> tp.List[MeterReaderNode]: # noqa MC0001
"""
Parsed configuration
:param config: dict from
:return:
"""
# pylint: disable=too-many-locals, too-many-nested-blocks
meter_reader_nodes = []
if 'devices' in config and 'middleware' in con... | 0d9212850547f06583d71d8d9b7e2995bbf701d5 | 31,542 |
def places(client, query, location=None, radius=None, language=None,
min_price=None, max_price=None, open_now=False, type=None, region=None,
page_token=None):
"""
Places search.
:param query: The text string on which to search, for example: "restaurant".
:type query: string
:... | 50aea370006d5d016b7ecd943abc2deba382212d | 31,543 |
def load_data(_file, pct_split):
"""Load test and train data into a DataFrame
:return pd.DataFrame with ['test'/'train', features]"""
# load train and test data
data = pd.read_csv(_file)
# split into train and test using pct_split
# data_train = ...
# data_test = ...
# concat and labe... | 1a02f83aba497bc58e54c262c3f42386938ee9bd | 31,544 |
def sorted_items(d, key=None, reverse=False):
"""Given a dictionary `d` return items: (k1, v1), (k2, v2)... sorted in
ascending order according to key.
:param dict d: dictionary
:param key: optional function remapping key
:param bool reverse: If True return in descending order instead of default as... | 4e4302eebe2955cdd5d5266a65eac3acf874474a | 31,545 |
def randint_population(shape, max_value, min_value=0):
"""Generate a random population made of Integers
Args:
(set of ints): shape of the population. Its of the form
(num_chromosomes, chromosome_dim_1, .... chromesome_dim_n)
max_value (int): Maximum value taken by a given gene.
... | 79cbc5ceba4ecb3927976c10c8990b167f208c0e | 31,547 |
def simplex_creation(
mean_value: np.array, sigma_variation: np.array, rng: RandomNumberGenerator = None
) -> np.array:
"""
Creation of the simplex
@return:
"""
ctrl_par_number = mean_value.shape[0]
##################
# Scale matrix:
# Explain what the scale matrix means here
##... | a25ac6b6f92acb5aaa1d50f6c9a5d8d5caa02639 | 31,548 |
def _scale_db(out, data, mask, vmins, vmaxs, scale=1.0, offset=0.0):
# pylint: disable=too-many-arguments
""" decibel data scaling. """
vmins = [0.1*v for v in vmins]
vmaxs = [0.1*v for v in vmaxs]
return _scale_log10(out, data, mask, vmins, vmaxs, scale, offset) | dab3125f7d8b03ff5141e9f97f470211416f430c | 31,549 |
def make_tree(anime):
"""
Creates anime tree
:param anime: Anime
:return: AnimeTree
"""
tree = AnimeTree(anime)
# queue for BFS
queue = deque()
root = tree.root
queue.appendleft(root)
# set for keeping track of visited anime
visited = {anime}
# BFS downwards
while len(queue) > 0:
current = queue.pop()... | d93257e32b024b48668e7c02e534a31e54b4665d | 31,550 |
def draw_bboxes(images, # type: thelper.typedefs.InputType
preds=None, # type: Optional[thelper.typedefs.AnyPredictionType]
bboxes=None, # type: Optional[thelper.typedefs.AnyTargetType]
color_map=None, # type: Optional[thelpe... | 6e82ee3ad211166ad47c0aae048246052de2d21c | 31,551 |
def html_table_from_dict(data, ordering):
"""
>>> ordering = ['administrators', 'key', 'leader', 'project']
>>> data = [ \
{'key': 'DEMO', 'project': 'Demonstration', 'leader': 'leader@example.com', 'administrators': ['admin1@example.com', 'admin2@example.com']}, \
{'key': 'FOO', 'project': ... | f3a77977c3341adf08af17cd3d907e2f12d5a093 | 31,552 |
import random
def getRandomChests(numChests):
"""Return a list of (x, y) integer tuples that represent treasure
chest locations."""
chests = []
while len(chests) < numChests:
newChest = [random.randint(0, BOARD_WIDTH - 1),
random.randint(0, BOARD_HEIGHT - 1)]
# Make... | 285b35379f8dc8c13b873ac77c1dcac59e26ccef | 31,553 |
import random
def random_tolerance(value, tolerance):
"""Generate a value within a small tolerance.
Credit: /u/LightShadow on Reddit.
Example::
>>> time.sleep(random_tolerance(1.0, 0.01))
>>> a = random_tolerance(4.0, 0.25)
>>> assert 3.0 <= a <= 5.0
True
"""
valu... | abe631db8a520de788540f8e0973537306872bde | 31,554 |
def routes_stations():
"""The counts of stations of routes."""
return jsonify(
[
(n.removeprefix("_"), int(c))
for n, c in r.zrange(
"Stats:Route.stations", 0, 14, desc=True, withscores=True
)
]
) | 2e0e865681c2e47da6da5f5cbd9dc5b130721233 | 31,555 |
import math
def montage(packed_ims, axis):
"""display as an Image the contents of packed_ims in a square gird along an aribitray axis"""
if packed_ims.ndim == 2:
return packed_ims
# bring axis to the front
packed_ims = np.rollaxis(packed_ims, axis)
N = len(packed_ims)
n_tile = math.c... | 27d2de01face567a1caa618fc2a025ec3adf2c8c | 31,556 |
def blocks2image(Blocks, blocks_image):
""" Function to stitch the blocks back to the original image
input: Blocks --> the list of blocks (2d numpies)
blocks_image --> numpy 2d array with numbers corresponding to block number
output: image --> stitched image """
image = np.zeros(np.shape(blocks_im... | ef6f5af40946828af664fc698e0b2f64dbbe8a96 | 31,557 |
def create_bucket(storage_client, bucket_name, parsed_args):
"""Creates the test bucket.
Also sets up lots of different bucket settings to make sure they can be moved.
Args:
storage_client: The storage client object used to access GCS
bucket_name: The name of the bucket to create
p... | df7ccc9979007ee7278770f94c27363936961286 | 31,559 |
from typing import Dict
from typing import List
from typing import Tuple
def learn_parameters(df_path: str, pas: Dict[str, List[str]]) -> \
Tuple[Dict[str, List[str]], nx.DiGraph, Dict[str, List[float]]]:
"""
Gets the parameters.
:param df_path: CSV file.
:param pas: Parent-child relationship... | ea34c67e5bf6b09aadc34ee271415c74103711e3 | 31,560 |
import io
def extract_urls_n_email(src, all_files, strings):
"""IPA URL and Email Extraction."""
try:
logger.info('Starting IPA URL and Email Extraction')
email_n_file = []
url_n_file = []
url_list = []
domains = {}
all_files.append({'data': strings, 'name': 'IP... | edb0dd4f0fe24de914f99b87999efd9a24795381 | 31,561 |
def find_scan_info(filename, position = '__P', scan = '__S', date = '____'):
"""
Find laser position and scan number by looking at the file name
"""
try:
file = filename.split(position, 2)
file = file[1].split(scan, 2)
laser_position = file[0]
file = file[1].split(date... | f98afb440407ef7eac8ceda8e15327b5f5d32b35 | 31,562 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.