content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import gzip
def read_consanguineous_samples(path, cutoff=0.05):
"""
Read inbreeding coefficients from a TSV file at the specified path.
Second column is sample id, 6th column is F coefficient. From PLINK:
FID, IID, O(HOM), E(HOM), N(NM), F
Additional columns may be present but will be ignored.
... | be3515e6704966ae927bfaff2594be9191063889 | 34,340 |
from re import T
def component(graph: Graph[T], node: T) -> Graph[T]:
"""Returns the connected component that contains the given vertex, as a new Graph object.
A vertex with no incident edges is itself a component.
A graph that is itself connected has exactly one component, consisting of the whole graph.
... | 6d1d23b28e35f291e79369f39e66d7444f0395ba | 34,341 |
import six
from datetime import datetime
import typing
def _deserialize(data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if klass ... | 7f008dc9edcdb433fe6561f5ad30695e8103c347 | 34,342 |
def smooth(data, fwhm, mask = 0):
""" smooth
Parameters
---------------------
data an object of class field
fwhm
mask a numpy.nd array,
with the same dimensions as the data
Returns
---------------------
An object of class field with
Examples
--------------... | feba63fe44605c4c59ca9b83794daad046ac3244 | 34,343 |
def get_xy_coords(xda):
"""Return the dimension name for x and y coordinates
e.g. XC or XG
Parameters
----------
xda : xarray DataArray
with all grid information
Returns
-------
x,y : str
with e.g. 'XC' or 'YC'
"""
x = 'XC' if 'XC' in xda.coords else 'X... | 6aca5de1eda17df617027c742a06f97cf77af1d5 | 34,344 |
def remote_docker(client_ip, docker_host, *args):
"""
Run ``docker`` on ``client_ip``.
:param bytes docker_host: The DOCKER_HOST environment variable to set
before running ``docker``.
:param args: Other command line arguments to supply to ``docker``.
:returns: A ``Deferred`` when the comman... | cbbff3fdd1460c61dbbc48b4833bede2a60312aa | 34,347 |
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore):
"""
Compute aggregate metric for xView3 scoring
Args:
loc_fscore (float): F1 score for overall maritime object detection
length_acc (float): Aggregate percent error for vessel length estimation
... | c3120882e50710d6874def60ad85e7a8be47c5d7 | 34,349 |
def index(request):
"""
Index view: shows a form with a list of ticket that one can buy
"""
ticket_types = TicketType.objects.all()
form = TicketsForm(ticket_types,[], request.POST)
if form.is_valid():
data = form.cleaned_data
p = TicketPurchase()
print data
if da... | 997ed750187586077d5ca24d17326d5f5510382e | 34,350 |
from typing import Union
def _on_vertex(
easting: Union[int, float], northing: Union[int, float], resolution: int
) -> bool:
"""Test if point lies on vertex."""
return (
True
if (int(easting) % resolution == 0) and (int(northing) % resolution == 0)
else False
) | 06902474da9bfc49e209ada65d160c0fa7f28cbf | 34,351 |
def add_jitter(df, jitter):
"""
Adds jitter to a data set based on a random normal
distribution.
Requirements: numpy, pandas
"""
return abs(df + np.random.normal(df, jitter, size=len(df))) | dc03d1506db3e21908a02a370122b8735167606b | 34,352 |
import torch
import itertools
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (query, positive, negatives).
Args:
data: list of tuple (query, positive, negatives).
- query: torch tensor of shape (3, h, w).
- positive: torch tensor of shape (3, h, w)... | d6e4985b7b0e248f05e78684a2a09136da865799 | 34,353 |
def complete_graph(number_of_vertices, name="Complet graph", directed=False):
"""
Construction of a complete graph.
The number of edges is exactly n*(n-1)/2 (where n is the number of vertices)
:param number_of_vertices:
:param name:
:param directed: False for undirected graph
:return: the ... | e603583abcc6e1de10f057965bf587cde1eebcc0 | 34,354 |
def obv(df, price, volume, obv):
"""
The On Balance Volume (OBV) is a cumulative total of the up and down volume.
When the close is higher than the previous close, the volume is added to
the running total, and when the close is lower than the previous close,
the volume is subtracted from the running... | 19f4c456ed501523d2b349e2766d482bd1fef13b | 34,355 |
def is_data(line):
"""
Function utilized by itertool's groupby method in determining
the delimiter between our blocks of data.
"""
return True if line.strip() else False | da3db970c5c5a3169446513cb4148ffedf598095 | 34,356 |
def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = licenses_api.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils.che... | c500224309e71d0e14a641980deaa75714a9c117 | 34,357 |
def _browse_device(device_id: MediaId, device: Device) -> BrowseMediaSource:
"""Return details for the specified device."""
device_info = NestDeviceInfo(device)
return BrowseMediaSource(
domain=DOMAIN,
identifier=device_id.identifier,
media_class=MEDIA_CLASS_DIRECTORY,
media_... | 76f36c2cf5eedad06f527d78aa45fac1d6ea6b11 | 34,358 |
def get_organization_suggestions(config, donl_type):
"""
Get organization suggestions for a given type
:param dict[str, Any] config: The configuration to use for selecting DONL
organizations
:param str donl_type: The DONL type to get suggestions for
:rtype: list of... | 6d306c49bc7671707479b5327e69a74320ebf3a6 | 34,359 |
def make_func_entry(func, name=None, description=None, params=None):
"""
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is ... | d5fb2067d0c69bc5cffc47376f3f91573c5cc1d4 | 34,360 |
import copy
def instance_update(context, instance_uuid, values, session=None):
"""Updates an existing VM instance in the Database"""
values = copy.deepcopy(values)
power_specs = values.pop('power_specs', None)
#Merge in the existing MetaData if they asked for Partial Updates
_instance_merge_metada... | 80296ff02a320bdf3192802bbde50d8adc6778c5 | 34,361 |
from bs4 import BeautifulSoup
def xkcdt():
"""
Return the title of the
most recent xkcd, taken from
the wesite's source code.
"""
page=BeautifulSoup(urllib2.urlopen('https://xkcd.com'),'lxml')
return page.title.string | 55f90a86d8e0410743a968bf1c3351f23709b728 | 34,363 |
import warnings
def log_cpm_hvg(adata: ad.AnnData, n_genes: int = 1000) -> ad.AnnData:
"""Normalize logCPM HVG
Normalize data to log counts per million and select n_genes highly
variable genes
"""
adata = log_cpm(adata)
if adata.n_vars < n_genes:
warnings.warn(
f"Less th... | ee9cda4caedde03d81fbc361a5c70d90c7bfc1f7 | 34,364 |
def c_string_arguments(encoding='UTF-8', *strings):
""" Convenience function intended to be passed to in_format which allows
easy arguments which are lists of null-terminated strings.
"""
payload = b""
# Add each string, followed by a null character.
for string in strings:
payload ... | 5c93afae01d199f31a27f658e133024c8fb9f92f | 34,365 |
async def create_mirror(request):
"""
Create a debian aptly mirror.
---
description: Create a debian aptly mirror.
tags:
- Mirrors
consumes:
- application/x-www-form-urlencoded
parameters:
- name: name
in: query
required: true
type: stri... | b6e60120580f25a967f19ec5ec7fff3fd0fa9478 | 34,366 |
def anneal(c_max, step, iteration_threshold):
"""Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599).
Args:
c_max: Maximum capacity.
step: Current step.
iteration_threshold: How many iterations to reach c_max.
Returns:
Capacity annealed linearly until c_max.
"""
... | ca6cbb5fe109e5d6b36870b398604ee79042827f | 34,367 |
import json
def update_timer_interval(acq_state, chart_data_json_str, chart_info_json_str,
active_channels, samples_to_display):
"""
A callback function to update the timer interval. The timer is temporarily
disabled while processing data by setting the interval to 1 day and the... | 1bc695ab2e5d63d4734d27417efc3d17a5e3a471 | 34,368 |
def constant_change_luminance(img):
"""
luminance noise added to image
:param img: image: numpy input image
:return: blurred image
"""
# constant [-25, 25]
constant = np.random.randint(-25, 25, size=(img.shape[0], img.shape[1], 1))
new_img = np.clip(img.astype(np.float32) - constant, 0.0... | e5e11a49db0c2ac051f7e8fb881f724ed94a1ad6 | 34,369 |
def rectify(x):
"""Rectify activation function :math:`\\varphi(x) = \\max(0, x)`
Parameters
----------
x : float32
The activation (the summed, weighted input of a neuron).
Returns
-------
float32
The output of the rectify function applied to the activation.
"""
# Th... | f781c4a382d211fbcadfe599c470523d3a59c2f1 | 34,370 |
def login_form():
"""Show login form."""
return render_template("login_form.html", loggingin=True) | 9f70323f1936f9b68200e3e1c75dfd52c262bc44 | 34,371 |
from typing import Union
from typing import Sequence
def truncate_batches(*xl: Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]) \
-> Sequence[Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]]:
"""
Truncate a list of batched items so that all items have the batch size of the input with t... | a39a4e8fec318b8e27ce6df1029051c07e058180 | 34,373 |
def get_loss_f(**kwargs_parse):
"""Return the loss function given the argparse arguments."""
return Loss(lamL1attr=kwargs_parse["lamL1attr"]) | 0389a9ca1799d7f98965caed7c0474543ed3c24a | 34,374 |
def input_reading_mod(input_dir, input):
"""This helper convert input"""
with open('%s/%s' %(input_dir, input), 'r') as input_fid:
pred = input_fid.readlines()
det = [x.strip('\n') for x in pred]
return det | 34fd8e5fe53d809ee1cc870c031bca8691756a63 | 34,376 |
async def connect(config, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
if config.identifier is None:
raise exceptions.DeviceIdMissingError("no device identifier")
service = config.main_service(protocol=protocol)
supported_implementations = {
const.PROTOC... | 1f6357737ce93a69e0b75093a5da8c72aebbb660 | 34,377 |
def _is_none(s: str) -> bool:
"""Check if a value is a text None."""
if s == 'None':
return True
return False | b7a6118b2c04c965d808911405d23a168f0fbff3 | 34,378 |
def get_C_and_Ic(Cin_est, Icin_est, f01, f02on2):
"""Get the capacitance and critical current for a transmon of a certain
frequency and anharmonicity.
Args:
Cin_est (float): Initial guess for capacitance (in fF)
Icin_est (float): Initial guess for critical current (in nA)
f01 (float... | ad7597b1e525a5d5818d6f79058cbe1213d38e2a | 34,379 |
def read_positionfixes_postgis(sql, con, geom_col="geom", **kwargs):
"""Reads positionfixes from a PostGIS database.
Parameters
----------
sql : str
SQL query e.g. "SELECT * FROM positionfixes"
con : str, sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
Connection string or... | f55f6934f675c76a99e544243b0f1cf779820e44 | 34,380 |
import logging
def get_model(letters, max_length):
"""Create a LSTM model."""
logging.info("Create model")
input_dim = len(letters)
logging.info("input_dim=%i", input_dim)
model = Sequential()
model.add(LSTM(8,
return_sequences=True,
input_shape=(max_lengt... | 0506c1f892ca2518b95c9edfc4deedfd8ebd4174 | 34,381 |
def _group_auto_update_helper(auto_update):
"""Helper that prepares the given group auto update for JSON
serialization.
:param GroupAutoUpdate auto_update: the auto update to serialize
:return: dictionary suitable for JSON serialization
:rtype: dict
"""
fields = {
'to': auto_upda... | fd95526cbea8d4888b7e581ab5eec5260f557517 | 34,383 |
import pyemd
def emd(hist1, hist2, cost_matrix='sift'):
"""
earth mover's distance by robjects(lpSovle::lp.transport)
require: lpsolve55-5.5.0.9.win32-py2.7.exe
CommandLine:
python -m vtool.distance --test-emd
Example:
>>> # DISABLE_DOCTEST
>>> from vtool.distance import ... | 21a364ef673190ce2a25175154bd275ebc764506 | 34,385 |
def equal_angle_stereographic_projection_conv_YZ_plane(x,y,z):
"""Function to take 3D grid coords for a cartesian coord system and convert to 2D equal area projection."""
Y = y/(1+x)
Z = z/(1+x)
return Y,Z | 121b24f20ef0ff7f0655a4b39c7ede70c632ef2a | 34,386 |
def download_past_trees(test: bool, number: int):
"""
Download a number of past trees
:param number: number of trees to download from the latest
"""
trees = []
key = "badger-tree.json"
bucket = env_config.bucket
response = s3.list_object_versions(Prefix=key, Bucket=bucket)
versions =... | 810ebc9ca714e4b9377bb7dd5d0cba0e9dd4089f | 34,387 |
import re
def read_init_values(srclines, init_names=None):
""" srclines - an ODE-file content in the list of strings,
if init_names is None all parameters will be read
init_names - the list of parameters names
return:
the dict of parameters, where keys=pars_names, values are parsed from srclines
... | e793399c4d258134e3767c067b1754bcd820c430 | 34,388 |
def getCategorySentiments(termSentiData,trainLexicon,finalDF):
"""
Module to extract category-wise sentiment scores and
generate final dataframe with predicted and true sentiment
Args:
termSentiData: dictionary of aspect terms and its sentiment
trainLexicon: Lexicon of defining terms und... | d8efc2ea0d1ffb18d3949f104c21ce6eae923a2e | 34,389 |
def get_test_pipeline():
"""Return an arbitrary pipeline definition."""
return {
'sg1': [
'step1',
'step2',
{'step3key1': 'values3k1', 'step3key2': 'values3k2'},
'step4'
],
'sg2': False,
'sg3': 77,
'sg4': None
} | 036cfdca7324be6940e1ed095292b0ac494ab771 | 34,390 |
def get_package_type(name):
"""
Returns the package type. Available package types are defined in PackageType.
Only ASR9K supports Service Packs concept
Example: asr9k-px-4.3.2.sp-1.0.0 or asr9k-px-4.3.2.k9-sp-1.0.0
"""
if name.find(SMU_INDICATOR) != -1:
return PackageType.SMU
elif ... | 89543d14c83f666c102dd11f3e093552b03c84d9 | 34,391 |
def merge(df1, df2, on=None, how="left"):
"""
DESCRIPTION
-----------
Merge two pandas dataframes on a common field name or specified fields in
each frame.
PARAMETERS
----------
df1 : pd.DataFrame
A pandas dataframe instance
df2 : pd.DataFrame
A pandas dataframe ins... | f297fcc005bdb6425ebb5306eae285c747ab46be | 34,392 |
def resident_required(a_view):
"""居住者権限を持つユーザのみ実行を許可する
居住者権限を持つユーザとは 1 つ以上の community.Unit と関連づけられたユーザ.
不許可なら 403 Forbidden を返す.
Args:
a_view (func): ビュー関数
"""
def _wrapped_view(request, *args, **kwargs):
if request.user.unit_set.count():
return a_view(request, *args, **kwargs)
else:
return HttpRes... | db211cb5861bfd1c47d23fc30b20a7ebf3080a4b | 34,393 |
import logging
def _stdout_logging(level):
"""Setup logging to stdout and return logger's `info` method.
"""
formatter = logging.Formatter(
'%(levelname)s %(asctime)s %(module)s %(funcName)s(): %(message)s',
'%Y-%m-%d %H:%M:%S')
stdout = logging.StreamHandler()
stdout.setLevel(leve... | a2fff81c0425b35f855c0372607d708f1c2aa3b4 | 34,395 |
def standardize_phone(raw: str) -> str:
"""Make sure it's 10 digits, remove everything else
>>> standardize_phone("(555) 555-1212")
'5555551212'
"""
raw = [x for x in raw if x.isnumeric()]
raw = "".join(raw)
if len(raw) != 10:
raw = None
return raw | a0d3afc2ffdaffee9d084ed7f50d49a1e3a023e0 | 34,396 |
async def find(req):
"""
Get a list of all existing group documents.
"""
cursor = req.app["db"].groups.find()
return json_response([virtool.utils.base_processor(d) async for d in cursor]) | d78fb6d84c18cbcdf07ee6d3699d58bd539e5fb2 | 34,397 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
def template_readable_response(responses: Union[dict, List[dict], str]) -> Union[str, List[Dict[str, Any]]]:
"""
Creates a readable response for responses that have fields in the form of:
{
'def... | 56b416aae9e254453855c27910d2e4d20365b6fc | 34,398 |
def rehtml(content):
"""
does unicode bullshit
:param content:
:return:
"""
doc = UnicodeDammit(content, is_html=True)
parser = ht.HTMLParser(encoding=doc.original_encoding)
root = ht.fromstring(content, parser=parser)
return root | 157a1659c0b5af469acfddc175eb37376f1914af | 34,399 |
def center_film(structure):
"""
Centers a film at z=0
Args:
structure: AiiDA structure
returns: AiiDA structure
"""
if structure.pbc != (True, True, False):
raise TypeError('Only film structures having surface normal to z are supported')
sorted_struc = sort_atoms_z_value(... | 121a9252e5a0da2e50f4b7fdf95a7c37a1245695 | 34,400 |
def get_stop_response():
""" end the session, user wants to quit the game """
speech_output = STOP_MESSAGE
return response(speech_response(speech_output, True)) | 4843b735859428a4d12337a7b26f42ed40900c2f | 34,401 |
import re
def __extract_clusters_from_html(html):
"""Parse the clusters of a balancer manager page.
:param html: The raw HTML of the balancer manager page.
:returns: a list of clusters.
"""
clusters = []
for section in re.findall('(<h3>.+?)<hr />', html.replace('\n', '')):
cluster = _... | 2c5077e264a7bf853886d55c2e9c64b149da40a0 | 34,402 |
from typing import Union
def _value_to_int(value: Union[int, str]) -> int:
"""String value to int."""
try:
return int(value)
except ValueError as error:
raise Exception("The value is not integer") | 635afb6d75edec8df64b12dad8db7dd408502250 | 34,403 |
import calendar
def era5_temp_anomalies(obs_directory, save_directory, start_range='1999-01-01', end_range='2019-12-31',
save=False, author=None):
"""
Create ERA5 temperature hindcast anomalies.
Args:
obs_directory (str): Directory where files are located.
save... | 7c49cc3aad3c9b92e9520f0b709d4118f59afec3 | 34,404 |
def is_supported(browser):
"""
指定したブラウザがサポート対象かチェック
Attributes:
browser (str): チェック対象ブラウザ
Returns:
bool: ブラウザのサポート有無
"""
return browser in _browser_modules | d3e49446b8c333f72b5e652899491b46960fd2ae | 34,405 |
from typing import Sequence
from typing import Tuple
import operator
def pie_marker(
ratios: Sequence[float],
res: int = 50,
direction: str = "+",
start: float = 0.0,
) -> Tuple[list, list]:
"""
Create each slice of pie as a separate marker.
Parameters:
r... | 61522394a5356f1a7c0e9e2e112c0025ae7dc9cc | 34,406 |
def indref_dust_wolff_2009(wav):
"""
This function returns the index of refraction for dust.
The data used are nominally taken from Wolff (2009), which extends from 236 nm to 98.5423 micron. There are only 5 points in our wavelength region of interest.
For the moment, we use the compendium provided by the Ames GC... | 864bc7efd908c9da47f050e82315f1ddd48ad500 | 34,407 |
def select_columns(
df: pd.DataFrame,
*args,
invert: bool = False,
) -> pd.DataFrame:
"""
Method-chainable selection of columns.
Not applicable to MultiIndex columns.
It accepts a string, shell-like glob strings `(*string*)`,
regex, slice, array-like object, or a list of the previous o... | a0881fbcf078f4c501b5dd0d706b7801ab47794d | 34,409 |
def compute_distance(location_1, location_2):
"""
Euclidean distance between 3D points.
Parameters
----------
location_1 : carla.Location
Start point of the measurement.
location_2 : carla.Location
End point of the measurement.
"""
x = location_2.x - location_1.x
y ... | 8511a59cb949a355ceaaeb85035474285412ba49 | 34,410 |
def ewma_2d(x, halflife):
"""
Exponentially Weighted Moving Average,
optimised for 2D data sets.
"""
assert x.ndim == 2
assert np.isfinite(halflife) and halflife > 0
decay_coefficient = np.exp(np.log(0.5) / halflife)
out = np.empty_like(x, dtype=np.float64)
for i in range(out.shape... | 23232e3050dd6280a1a0819ad5261a8c9545cfd3 | 34,411 |
def DT2str(dt):
"""
convert a datetime to a string in the GNOME format.
"""
dt_string = "%3i, %3i, %5i, %3i, %3i"%(dt.day, dt.month, dt.year, dt.hour, dt.minute)
return dt_string | 7d0b26c9d4517738be448e2ab897b1ffb419179f | 34,412 |
def get_active_lines(lines, comment_char="#"):
"""
Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List o... | b49c8cd034c8fa8e7dcf0b5153c8d5bcce52a1f3 | 34,413 |
def is_shutout(goalie_dict, goalies_in_game):
"""
Checks whether current goalie game can be considered a shutout.
"""
# only goalies that played and didn't concede any goals can have a shutout
if (goalie_dict['games_played'] and not goalie_dict['goals_against']):
# if more than two goalies (... | c9aa7adead449366e8845b562fd04b98396321cc | 34,414 |
def phase_segmentation(image, threshold, area_bounds=[0.5, 6.0],
ip_dist=0.160):
"""
Segement a phase image and return the mask.
Parameters
----------
image : 2d-array
The phase image to be segmented. This image will be converted to a
float type.
threshold... | a4eeb7dd8f9602c0dada2a62f3e2cabda3036950 | 34,415 |
from datetime import datetime
def _fix_other_columns(df):
"""
Fills all other columns using reasonably similar rows.
"""
cols_to_fill1 = [
"season",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
"cnt",
]
dhour =... | c710d6342dbcf1c340479a7dc3b8eacfeee7cfb1 | 34,416 |
def storage_get_all_by_project(context, project_id, marker, limit, sort_key,
sort_dir):
"""Get all storages belonging to a project."""
return IMPL.storage_get_all_by_project(context, project_id, marker, limit,
sort_key, sort_dir) | aa8e20ce1fda6e80a7e9033ede16aa2f457557ce | 34,417 |
def evaluate_parentheses(token):
"""
Evaluates parentheses.
Parameters
----------
token : ``Token``
Returns
-------
new_token : ``Token``
The final evaluated token.
"""
new_token = evaluate_tokens(token.sub_tokens)
new_token.start = token.start
new_token... | 7f0b3044fd25c3d0ae958abadea668ca07dec3c3 | 34,418 |
def typprice(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of typical price for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): T... | 3d7e8621a9c85e48913df15d59944a480c0cda35 | 34,419 |
import json
def evaluate_grants(path_to_gt_json, path_to_test_json):
"""
This function measures the micro recall of the grantIDs identified by a system.
Input:
- gt_json: Path to ground truth .json file
- test_json: Path to user submitted .json file
Output:
- Float value of mic... | 465bfb885780983ac5df05d590f0570dee52d6bd | 34,420 |
def read_puzzle(board, input_puzzle):
"""
Reads unsolved puzzle
If the string given is a filename with .txt of .sud suffix, the puzzle
is read from the file, otherwise a string containing the puzzle is considered
Expected format:
1 line, row-wise saved values where unknown cells are marked with
... | b8c44230fdccebb6122ab16f924ee10dd6e3e171 | 34,421 |
from typing import get_args
import dataclasses
def dataclass_from_dict(klass, d):
"""
Converts a dictionary based on a dataclass, into an instance of that dataclass.
Recursively goes through lists, optionals, and dictionaries.
"""
if is_type_SpecificOptional(klass):
# Type is optional, dat... | 434f05ba49db17016c175155b89986f044c914e3 | 34,422 |
def depolarization_factor(wl):
"""Bucholtz 95 Table 1
Depolarization factor as fct of wavelength in nm"""
rho = np.array([[0.200, 4.545],
[0.205, 4.384],
[0.210, 4.221],
[0.215, 4.113],
[0.220, 4.004],
[0.225... | ccc2212391e1439b74f5399e82a9bc8c7825b14b | 34,423 |
def draw_line (surface, color, a, b, width=1):
"""draw_line (...) -> Rect
Draws a line on a surface.
The 'color' argument needs to match the pygame color style. 'a' and
'b' are sequences of the x- and y-coordinate on the surface and
'width' denotes the width of the line in pixels. The return valu... | 33519d943fad5979e5ccadb1ce03c4d35baea497 | 34,424 |
def judge_all_tests(judge: LocalJudge, verbose_level, score_dict, total_score):
"""Judge all tests for given program.
If `--input` is set, there is only one input in this judgement.
"""
judge.build()
report = Report(
report_verbose=verbose_level, score_dict=score_dict, total_score=total_s... | 9f442cdd9a38f17528f6802f76c6ceddabfe6022 | 34,426 |
import re
def generate_per_sample_fastq_command(forward_seqs, reverse_seqs, barcode_fps,
mapping_file, output_dir, params_str):
"""Generates the per-sample FASTQ split_libraries_fastq.py command
Parameters
----------
forward_seqs : list of str
The list of... | 44d3cef9cca598a8ce36a46637bfa288c49a5f98 | 34,427 |
def renderInlineStyle(d):
"""If d is a dict of styles, return a proper style string """
if isinstance(d, (str, int, float)):
result = str(d)
else:
style=[]
for k,v in d.items():
style.append("{}:{};".format(k, v))
separator = ' '
result = separator.join(st... | f08ea415e4fa29404b7c879f2346832dc84d2e67 | 34,428 |
from typing import cast
def selftest(silent: bool=False) -> bool:
"""Run a simple self-test of DHParser.
"""
if not silent:
print("DHParser selftest...")
print("\nSTAGE I: Trying to compile EBNF-Grammar:\n")
builtin_ebnf_parser = get_ebnf_grammar()
docstring = str(builtin_ebnf_par... | 6353abac840ee7a66b2a40133f427ec9ae91f8f2 | 34,429 |
def bounding_box(grid, cell_kji0, points_root = None, cache_cp_array = False):
"""Returns the xyz box which envelopes the specified cell, as a numpy array of shape (2, 3)."""
result = np.zeros((2, 3))
cp = grid.corner_points(cell_kji0, points_root = points_root, cache_cp_array = cache_cp_array)
result[... | e526a4ee029a02d224bd264aee9c160a5ecdaa85 | 34,430 |
def test_dup_args_in_call(x):
"""The naive gradient update rule fails when a function's arguments
contain the same variable more than once."""
return x * x | 978f4f6e901b4b4aba01bbad098c107eacab59f3 | 34,432 |
def snake_to_camel_case(snake_text):
"""
Converts snake case text into camel case
test_path --> testPath
:param snake_text:str
:return: str
"""
components = snake_text.split('_')
# We capitalize the first letter of each component except the first one with
# the 'title' method and j... | b42e1393cf99b88e2ebbcf4b38643c770e218ceb | 34,433 |
def compute_accuracy(dist, labels, threshold):
"""
Compute the average accuracy over the given set of images.
dist: computed distance between pair of images.
labels: true class labels
threshold: decision threshold.
"""
trueclass = np.sum(np.logical_and((dist <= threshold)... | d59388c89fe5da610ca51fb7198cd52aa063502b | 34,434 |
def http_take_solver():
"""Return the string of answer"""
request_data = request.get_json()
answers = ai.take_solver(request_data)
return jsonify({"answers": answers}) | c11977b0180037f4e458f526533ce604ff10859a | 34,436 |
def create_organization(
*, db_session: Session = Depends(get_db), organization_in: OrganizationCreate
):
"""
Create a new organization.
"""
organization = get_by_name(db_session=db_session, name=organization_in.name)
if organization:
raise HTTPException(
status_code=400, det... | 7511a20a1588b122f02d0c930c3a6e209907a482 | 34,437 |
import networkx
def check_all(logic_forms: list, checks=None, verbose=False) -> list:
""" Do all Logic Form Graph checking.
Parameter:
logic forms (list): logical forms
verbose (bool): enable printing details
Returns:
lf_graphs (list): dicts of id (int) and a graph (LogicalFormGraph)
""... | 21bc30647ab379e98566bf7dc1e7dd3d0e88e86b | 34,438 |
def remove_noise(line,minsize=8):
"""Remove small pixels from an image."""
if minsize==0: return line
bin = (line>0.5*amax(line))
labels,n = morph.label(bin)
sums = measurements.sum(bin,labels,range(n+1))
sums = sums[labels]
good = minimum(bin,1-(sums>0)*(sums<minsize))
return good | 0ee16876ed90f84be1abcd911689dafafad7ef96 | 34,439 |
def get_wide_dword(*args):
"""
get_wide_dword(ea) -> uint64
Get two wide words (4 'bytes') of the program at 'ea'. Some processors
may access more than 8bit quantity at an address. These processors
have 32-bit byte organization from the IDA's point of view. This
function takes into account order of bytes ... | 4d8574128bfca6a48e595516c4e9bee6a9bbfc75 | 34,440 |
import copy
def corrupt(x, mask=None):
"""Take an input tensor and add uniform masking.
Parameters
----------
x : Tensor/Placeholder
Input to corrupt.
mask: none
Returns
-------
x_corrupted : Tensor
50 pct of values corrupted.
"""
cor = copy.deepcopy(x)
if ... | f8b91f07012bd231570981824a0759b40f30f4b0 | 34,441 |
def bvi(model, guide, claims, learning_rate=1e-5, num_samples=1):
"""perform blackbox mean field variational inference on simpleLCA.
This methods take a simpleLCA model as input and perform blackbox variational
inference, and returns a list of posterior distributions of hidden truth and source
reliabil... | bb7469efd4615156219f0f514200784a50a84ad6 | 34,442 |
from pathlib import Path
import json
def load_metadata(bucket: str, prefix: str) -> dict[str, dict]:
"""
Get general export metadata file and table status metadatas. The
former contains column names / types as well as a string containig
schema and table name.
Export metadata contains info about t... | 578b7cb312d1490a9d9ded1574b9e5a445d93d5d | 34,443 |
from datetime import datetime
def get_dbtbl(options: list):
"""Handles dbtbl (available lobby table) calls."""
main.terminate_incorrect_lobbies()
order = None
resort = None
for option in options:
option = option.strip("'")
if option.startswith("order="):
order = option[... | f0c14f2cabc7a600b1296ed012b5c2b814a90708 | 34,444 |
def compare_parsed_text(seq_list, auto_stripped_text):
"""
This is a stupid workaround to the fact that bs4 parsers generally suck.
Tries to measure whether parsing was "successful" by looking at the
automatically scraped text of the policy to the text we parse here.
Note: can't match/replace entir... | c1bc7b2fd87dbd90082a434f7193cfed08d3164d | 34,445 |
import ctypes
def repmi(instr, marker, value, lenout=None):
"""
Replace a marker with an integer.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type marker: str
:param value: Re... | c366f8a2077cc51bfff5f2d7e2f0b019e48c09f7 | 34,446 |
def _get_parameter_state(sender_owner, sender_type, param_name, component):
"""Return ParameterState for named parameter of a Mechanism requested by owner
"""
# Validate that component is a Mechanism or Projection
if not isinstance(component, (Mechanism, Projection)):
raise ParameterStateError(... | 11c72ad6bdf4bd28f25c771d4d4283b88522e1a2 | 34,447 |
def start_volume( mdserver_name ):
"""
Start up an existing metadata server for a volume. Return 1 on success.
"""
global conf
ctl_root = VOLUME_CTL_ROOT( conf, {'NAME': mdserver_name} )
config_file = VOLUME_CONF_PATH( ctl_root )
md_logfile = LOGFILE_PATH( ctl_root )
md_pidfile = PIDFIL... | 1d8ed9310d9e67f3ca77f97eed935b0ff45661a6 | 34,448 |
from typing import Any
def _pycall_path_dest_only(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""A TDL function which samples the dest coordinate only."""
return ffi.from_handle(handle)(x2, y2) | 808a50335bc3c70aa49f6fe198beb4817655dc8a | 34,449 |
from datetime import datetime
def calculate_leap_seconds(year, month, day):
"""
get the leap seconds for the given year to convert GPS time to UTC time
.. note:: GPS time started in 1980
.. note:: GPS time is leap seconds ahead of UTC time, therefore you
should subtract leap seconds fr... | 236d71d4827c4647999aef90e8f9f7ee49053f85 | 34,450 |
import re
def convert_vpc_name_to_vpc(possible_vpc_id, error_on_exit=True):
""" Convert a given VPC name into the VPC ID.
If the input VPC name looks like an existing VPC ID, then return the VPC immediately.
If the VPC with the given VPC name exists, then return the VPC.
If there is no suc... | 3b5f644001bf12a3d2b1758a9bb045ee2e8e88b1 | 34,451 |
def preprocess_person(hh_dat, person_dat):
"""
This function preprocesses person-level features and merge with household data.
Nominal categorical variables, such as years of age are
transformed into continuous values.
Input:
Preprocessed household-level data
Original perosn-le... | 5becaeb1141ad72a85128340d2c9f47e5899f0e9 | 34,452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.