content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def from_array(flwdir, _mv=_mv, dtype=np.intp):
"""convert 2D LDD data to 1D next downstream indices"""
nrow, ncol = flwdir.shape
flwdir_flat = flwdir.ravel()
# get downsteam indices
pits_lst = []
idxs_ds = np.full(flwdir.size, core._mv, dtype=dtype)
n = 0
for idx0 in range(flwdir.size):... | 039c2255c2ee7b03299ca9f91e11160da68643d2 | 53,000 |
def get_checks_by_status(api_key, status='new'):
"""
Возвращает JsonResponse с чеками соответствующего статуса status.
:param api_key: str: Ключ доступа API
:param status: str: Статус получаемых чеков
:return: :class:`Response <Response>` serialized to JSON
:rtype: http.JsonResponse"""
try... | 5f7a78ddb30c67e6a5310b80a47a7b36f325c1ec | 53,001 |
from datetime import datetime
def current_time():
""" Current UTC datetime """
return datetime.datetime.utcnow() | 2eb04fd6843c9d2f75c27a86e0d8b4f31c5e2194 | 53,002 |
import bnpy.birthmove.BLogger as BirthLogger
import bnpy.deletemove.DLogger as DeleteLogger
import bnpy.mergemove.MLogger as MergeLogger
import bnpy.mergemove.SLogger as SLogger
import bnpy.allocmodel.topics.LocalStepLogger as LocalStepLogger
import bnpy.learnalg.ElapsedTimeLogger as ElapsedTimeLogger
import os
def _... | 0b0846f2d53ffcd22c74f7f1fde0172c4a9f4e4d | 53,003 |
def value_and_multigrad(fun, argnums=[0]):
"""Returns a function that returns both value and gradients wrt multiple
arguments simultaneously."""
def combined_arg_fun(multi_arg, *args, **kwargs):
extra_args_list = list(args)
for argnum_ix, arg_ix in enumerate(argnums):
extra_args_... | fe0c305cf1ef038c856a23e0151e3d69fa3386d1 | 53,004 |
from datetime import datetime
def day_of_year(t=None):
"""Returns the day of year."""
SECONDS_IN_DAY = 60 * 60 * 24.0
time = parse_time(t)
time_diff = parse_time(t) - datetime(time.year, 1, 1, 0, 0, 0)
result = time_diff.days + time_diff.seconds / SECONDS_IN_DAY
return result | c68923603a58719b762415ba46ccd43ff52af383 | 53,005 |
def show_object_id_by_date(
move_data: 'PandasMoveDataFrame' | 'DaskMoveDataFrame',
kind: list | None = None,
figsize: tuple[float, float] = (21, 9),
return_fig: bool = False,
save_fig: bool = False,
name: str = 'shot_points_by_date.png',
) -> figure | None:
"""
Generates four visualizat... | 4e128c517745472d0033815099aa5cbd2634e18f | 53,006 |
from typing import Optional
from typing import Tuple
from pathlib import Path
def retrieve_experiment_name_and_path(experiment_name: Optional[str]) -> Tuple[Path, str]:
"""
Retrieve the experiment_path and experiment_name from the cwd and parameters given.
"""
path = Path.cwd()
if experiment_name ... | f37b57bc0abcfe3dbbb358309819a1d7b4043ddb | 53,007 |
from typing import List
import requests
def option_sse_list_sina(symbol: str = "50ETF", exchange: str = "null") -> List[str]:
"""
新浪财经-期权-上交所-50ETF-合约到期月份列表
https://stock.finance.sina.com.cn/option/quotes.html
:param symbol: 50ETF or 300ETF
:type symbol: str
:param exchange: null
:type exc... | e6ef3b22f8f02c938063b7b5a786248a046a8318 | 53,008 |
async def login(user_data: UserLoginIn):
"""Login Users
Endpoint for users login
Args:
- user_data (UserLoginIn): user_data with fields email and password. This user_data
corresponds a UserLoginIn schema
Returns:
string: Returns jwt token wich the user can navigate for anothers endpoints (i... | 6a857f3d317a20dcc2819090ff003ada3267d20b | 53,009 |
def S_stat(data, data_label, refdata, refdata_label, obj_prop=True,
lsmask=None):
"""
Function to calculate the structure component (S). The basic idea is to
compare the volume of the normalized precipitation objects. This property
captures information of the geometrical characteristics (siz... | fc1f902d9431f59307ad71f619829116cd66c099 | 53,010 |
import re
def fix_bad_next_statements(vba_code):
"""
Change things like "Next x,y" to "Next x\nNext y"
"""
uni_vba_code = None
try:
uni_vba_code = vba_code.decode("utf-8")
except UnicodeDecodeError:
# Punt.
return vba_code
pat = "Next +(?:\w+ *, *)+\w+ *\n"
... | e27bdc733094fbc05268e7dd6dd6c830f1afe4d6 | 53,011 |
import contextlib
import wave
def read_wave(path):
"""Reads a .wav file.
Takes the path, and returns (PCM audio data, sample rate).
"""
print(path)
with contextlib.closing(wave.open(path, "rb")) as wf:
num_channels = wf.getnchannels()
assert num_channels == 1
sample_width =... | 28be6146d30c80b171b8b3ec24e621209b751e12 | 53,012 |
import json
def copy_metrics_and_parameters(report_file=REPORT_FILE):
"""
Returns Parameters and Metrics from the report_file.
:param report_file:
"""
metrics = {}
parameters = {}
with open(report_file) as f_in:
result_json = json.load(f_in)
if 'Metrics' in result_json:
... | c816a5098df50e5c0d7395b2a5d4630bf92aacae | 53,013 |
def MnistLI2(list_x,list_y, n_sec=20):
"""
Linear interpolation function for up sampling
"""
FinerArray = np.array([]).reshape(0,2)
for i in range(len(list_x)-1):
if list_x[i]<list_x[i+1]:
xvals = np.linspace(list_x[i], list_x[i+1], n_sec)
xvals = np.delete(xvals, 0)
... | a19b8b909623e76ed1f55809a4acb73ce604c22e | 53,014 |
def log_prior(theta):
"""
Priors, limit the values to a range but otherwise flat.
"""
#limit the values to 0 < theta < 256
if (all(theta > 0) and all(theta < 256)):
return 0
else:
return -np.inf | 4d921dbe9dc39078338c44c2efc065ec6551d6d2 | 53,015 |
def cdf(x, mean=0.0, stdev=1.0):
""" Returns the cumulative distribution function at x.
"""
return min(1.0, 0.5 * erfc((-x + mean) / (stdev * 2**0.5))) | 5a52c23872716fb5cafe4ba0873280f824367488 | 53,016 |
def binarize(img_gray,
diameter=10,
sigmaColor=150,
sigmaSpace=150,
a_thresh_type=2,
a_thresh_blocksize=20,
a_thresh_offset=0,
a_thresh_offset2=0):
"""Binarize an image
Binarize an image using OpenCV library
Args:
... | 6badad6ead77147dc8a00677df1aea273fd69d5f | 53,017 |
def random_SBM(n_nodes, block_sizes, p_in_min, p_out_max):
"""
Full random SBM
"""
nb_communities = len(block_sizes)
outmat = np.random.uniform(low=0, high=p_out_max, size=(nb_communities,nb_communities))
W = 0.5 * (outmat + outmat.T)
inmat = np.random.uniform(low=p_in_min, high=1, size=(nb_... | d1162d5bed9eca674bdf1d9a3b286df3df41a84d | 53,018 |
def add_meta(match):
"""return a dict from the match"""
attr_name, attr_value = match.groups()
return {attr_name: strip_quotes(attr_value)} | 5fa3642a9dbd768d3495fc6517e527a5f4351422 | 53,019 |
def remap_labels(labels, mappings):
"""
:param labels:
:param mappings:
:return:
"""
for source, target in mappings.items():
labels[labels == int(source)] = target
return labels | df418b76c7831ac315e095cd9bf75b7596b04a91 | 53,020 |
def mean_absolute_deviation(array):
"""
Calculate the mean_absolute_deviation on EEG data
input:
array: numpy array. The temporal signal for feature extraction. 1d or with multiple dimensions
return
de: int or numpy array, depends on the input shape
"""
def cal_mad(s):
r... | 8fd013614dd3459d18c3a08683fe60570c31154d | 53,021 |
import os
import numpy
from datetime import datetime
import calendar
def polychart(data):
"""
Description: generates a timeseries for a given point and given variable defined by the user.
Arguments: A dictionary object from the AJAX-ed JSON object that contains coordinates and the variable name.
Autho... | e1f190dc38864aef8ce84eb7c549a88e86222b15 | 53,022 |
def render(context, file='index.html', template_name='aquarius'):
"""Render a template in a string, by file.
A webloft template is often much more than a file. Each file is a
django template. Rendering all the files in the template directory
gives a full render of the website.
The template name is... | 234273ad21e11d29cc1d2a62caa61e60125308bf | 53,023 |
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
get_csv(symbols)
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: #add SPY for reference, if absent
symbols.insert(0,'SPY')
for symbol in symbols:
get_csv(symbol)
df_temp = pd.read_csv(symbol_to_pat... | 25c2d47dc097a9950e3bf9407d94aada74fc149d | 53,024 |
def load_network(path, weighted=False, directed=False):
"""
Load the edgelist as a networkx.Graph() object.
Input:
path::string: path to the edgelist
weighted::bool: whether the network has edge weights
directed::bool: whether the network is directed
Return:
::networkx.... | 0a2e4f2789583f70c9b1598c5a4cbb78cacc8b27 | 53,025 |
from . import sill
from clawpack.pyclaw.util import check_diff
import numpy as np
from clawpack.pyclaw.util import gen_variants
from itertools import chain
def test_1d_sill():
"""test_1d_sill
tests against expected classic solution of shallow water equations over
a sill."""
def verify_expected(expe... | 5190b75a4f3dcfc47f019023d450d5e568a2df5e | 53,026 |
def integrations_create(response):
"""Creates an integration. Link"""
return validate_response(response) | d4a119fd8c51c4a2b815dc41dfdccd5a5381a181 | 53,027 |
def select_from_multiple_candidates(transcripts, refseqscan, appris_principal, selected, missing, log, hgncid, build, cartseries, cartidx):
"""Select from multiple transcript candidates"""
if not all_have_same_cds(transcripts):
to_missing_list(missing, log, hgncid, 'coding_mismatch', 'Not all of these ... | f6a73b91162eca742bca73d06ed3d92ceb8b06b0 | 53,028 |
from datetime import datetime
import time
import pytz
def str_date(dt):
"""datetime to ISO 8601 str"""
if not dt or not isinstance(dt, (datetime, date, time)):
raise TypeError('dt should be date object, and not a %s' % type(dt))
if not dt.tzinfo:
# update dt with utc zone
dt = pytz... | 4e4455dc5d30df6fc303b4fa9977f9838f5206cb | 53,029 |
import os
def locate_file(refname, mode=None):
"""Given a valid reffilename in CDBS or CRDS format, return a cache path for the file.
The aspect of this which is complicated is determining instrument and an instrument
specific sub-directory for it based on the filename alone, not the file contents.
... | 7339e23754c42c6e69d18beb7d661966621945b9 | 53,030 |
def get_bprop_l2_loss(self):
"""Grad definition for `L2Loss` operation."""
def bprop(x, out, dout):
dx = x * dout
return (dx,)
return bprop | 6f52c07d9133939f5a7dc6d12a2416169f32147e | 53,031 |
def change_dimension_shape_resolution(changed_dimension_shape_conflict):
"""Create a resolution for a changed shape prior"""
return changed_dimension_shape_conflict.ChangeDimensionResolution(
changed_dimension_shape_conflict
) | c6f93f080ed14876a4724924dc848fb835364c33 | 53,032 |
def process_atbat(atbat_elem, atbat):
"""
Call process_pitch for every pitch in that atbat
"""
balls = 0
strikes = 0
pitches = []
for pitch_elem in atbat_elem:
if pitch_elem.tag == 'pitch':
pitch = process_pitch(pitch_elem, atbat, balls, strikes)
pitches.app... | a7c0d37336c375a75aca313b8085fecdcb488b38 | 53,033 |
def extract_tracklist_begin_num(content):
"""Return list of track names extracted from messy web content.
The name of a track is defined as a line which begins with a number
(excluding whitespace).
"""
tracklist = []
for line in content.splitlines():
# Empty line
if not line:
... | 7d860fb0ea444ae0d9bd536a4644fa6b1c11a826 | 53,034 |
import os
import requests
from datetime import datetime
def weather(searchterm):
"""Get the weather for a place given by searchterm
Returns a title and a list of forecasts.
The title describes the location for the forecast (i.e. "Portland, ME USA")
The list of forecasts is a list of dictionaries in ... | 4b7235934af260b5df5fb1eae596ee65ef8597eb | 53,035 |
import logging
def post_image(conn, image, image_name, description=None, dataset_id=None,
source_image_id=None, channel_list=None):
"""Create a new OMERO image from numpy array.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
image : ``n... | 465fca773a9d66ef1e013a6acc0f4c6e0db60258 | 53,036 |
def save_to_mongo(data, mongo_db, mongo_db_coll, **mongo_conn_kw):
"""Saves data to Mongo"""
client = pymongo.MongoClient(**mongo_conn_kw)
db = client[mongo_db]
coll = db[mongo_db_coll]
return coll.insert(data) | 10cd2bfda0f7165ff2dd68e34d44fbdb0375a483 | 53,037 |
from typing import List
def _append_autopep8_lint_command_if_module_updated(
lint_commands: List[LintCommand],
module_paths: List[str]) -> List[str]:
"""
Append the autopep8 lint command to the list if the
modules have been updated.
Parameters
----------
lint_commands : list o... | f6361b5f8f97376295535ff0efea96e0117c8325 | 53,038 |
def rgb2hsv(rgb:np.ndarray):
"""Compute luminance of an RGB image.
Args:
rgb (tensor): rgb image (shape:(H,W,C))
Returns:
gray(tensor): gray-scale image(shape:(H,W))
Examples:
>>> import cv2
>>> from skimage import color
>>> img=cv2.cvtColor(cv2.imread('../../... | 195ef06973b3c01f594e0c0ad515925a51ce6910 | 53,039 |
def net_solar_radiation(rs, albedo=0.23):
"""
Calculate the fraction of the solar radiation that is not reflected from
the surface (Allen et al. 1998).
Parameters
----------
rs : float
Solar radiation (MJ m-2 day-1).
albedo : float, optional
Albedo (-), default is 0.23 (valu... | 41a8930966db4a658d1c3ec31e754987bc9ed387 | 53,040 |
from typing import Callable
from typing import Dict
from typing import Any
from typing import Collection
def resolve_nodes(fn: Callable, config: Dict[str, Any]) -> Collection[node.Node]:
"""Gets a list of nodes from a function. This is meant to be an abstraction between the node
and the function that it imple... | 4e573e027467fef4452c9faf35744c062156498c | 53,041 |
def request_from_dict(d, processor=None):
"""Create Request object from a dict.
If a spider is given, it will try to resolve the callbacks looking at the
spider for methods with the same name.
"""
cb = d['callback']
if cb and processor:
cb = _get_method(processor, cb)
eb = d['errbac... | 5e84e7261cfeea997daa6b974e629aec45e094dc | 53,042 |
def text_color(message='{}', color_code='\033[0;37m'):
"""Set text to a color, default color is White"""
no_color = '\033[0m'
return f'{color_code}{message}{no_color}' | bede08b771b33ce26bbb0ee4fd42f3712d224cc1 | 53,043 |
import torch
def masked_max(
vector: torch.Tensor,
mask: torch.BoolTensor,
dim: int,
keepdim: bool = False,
) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
# Parameters
vector : `torch.Tensor`
The vector to calculate max, assume unmasked part... | b37b2007939df46c8963770c12f031cc347144ae | 53,044 |
def count_correct_correspondences(
keypoints_i1: Keypoints,
keypoints_i2: Keypoints,
intrinsics_i1: Cal3Bundler,
intrinsics_i2: Cal3Bundler,
i2Ti1: Pose3,
epipolar_dist_threshold: float,
) -> int:
"""Checks the correspondences for epipolar distances and counts ones which are below the thresh... | c783757438f9b2486271149728c1f81e8cd4c586 | 53,045 |
def get_max_elements_in_row(row: list) -> int:
"""
Loops through the dataset and gets the max elements in a list if
one is found in the list or 1 if all strings.
"""
max_array_count = 0
# get the max height of the cells.
for item in row:
if isinstance(item, list) and len(item) > max... | 0f8573bbabe95c03e3eda5949ff9c1c209b0f5fa | 53,046 |
def coord_type_from_ctype(ctype):
"""
Determine whether a particular WCS ctype corresponds to an angle or scalar
coordinate.
"""
if ctype[:4] == 'RA--':
return 'longitude', u.hourangle, None
elif ctype[:4] == 'HPLN':
return 'longitude', u.arcsec, 180.
elif ctype[:4] == 'HPLT'... | d7f26f5268f4b06e6dceae571516937e85543dee | 53,047 |
def swac()->(int,str):
"""run an analysis on a signle word based on a corpus"""
print('Available corpora:')
for c in corpora:
print(c)
while True:
corpus = input("Please enter an available corpus to refrence by index number: ")
try:
corpus = int(corpus)
if... | a10cd6a4dff6b2fc16d8ecb02024bc1d90ebbdc1 | 53,048 |
def get_adventure(): # noqa: E501
"""Get all adventures
# noqa: E501
:rtype: List[Adventure]
"""
return "do some magic!" | 8ca2cb6b8e0aa004ca7fa54ec35f907c3351cab8 | 53,049 |
def return_pkl_files(pkl_dirs):
"""return pkl filenames"""
pkl_list = []
pkl_filenames = []
for pkl in pkl_dirs:
pkl_list.append(dataparser.load_pkl_file(pkl))
pkl_filenames.append(dataparser.get_filename(pkl))
return pkl_list, pkl_filenames | e8653006d98734e284ffcd0ee908514bb5d51a81 | 53,050 |
def get_control_flow_graph(program):
"""Get a ControlFlowGraph for the provided AST node.
Args:
program: Either an AST node, source string, or a function.
Returns:
A ControlFlowGraph.
"""
control_flow_visitor = ControlFlowVisitor()
node = program_utils.program_to_ast(program)
control_flow_visitor... | 946e39fe4d793bdf591f3934e49943c3bb79f6e5 | 53,051 |
def rebuild_schemas(index):
"""
Resets the schema for all checkpoints to the latest version based off the
current document structure. Returns the number of checkpoints updated.
"""
db = ExportSchema.get_db()
all_checkpoints = ExportSchema.get_all_checkpoints(index)
config = ExportConfigurati... | b89b4460cf1081f22ab193bada1fc77477e2104a | 53,052 |
def warp_occupancy(info, cc, smem_config=None):
"""Returns a dictionary of {threadperblock: occupancy, factor}
Only threadperblock of multiple of warpsize is used.
Only threadperblock of non-zero occupancy is returned.
"""
ret = {}
try:
limits = PHYSICAL_LIMITS[cc]
except KeyError:
... | 1eb7f4ec40a73615cb51fc05dc20c4225cb6b16d | 53,053 |
def cst_efield_2freq_cut_healpix(cst_efield_2freq_cut_healpix_main):
"""Make function level cut down HEALPix 2-freq efield beam."""
return cst_efield_2freq_cut_healpix_main.copy() | b7b2388efbe4f6ca1e22c08e46ec70d391c68ce8 | 53,054 |
import collections
import typing
def is_an_iterable_type_hint(rel_type_hint) -> bool:
"""Check if typing.Iterable wraps the relationship type hint.
###### Parameters ######
* `rel_type_hint`: type hint to check
For a given class `C`, all following expressions are evaluated to `True`:
```python... | a77c80ea5f3a0fa546c4280d1f2b3e1c5f04ae57 | 53,055 |
import json
def gnmi_get(dut, xpath, **kwargs):
"""
API to do GNMI get operations
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:param xpath:
:param kwargs:
:return:
"""
gnmi_debug(dut)
credentails = st.get_credentials(dut)
ip_address = kwargs.get... | b97068ee7b7555fab9cb28d10a58336271545261 | 53,056 |
def shift_chord(chord, shift):
"""Shift chord"""
if chord < 12:
new_chord = (chord + shift) % 12
elif chord < 24:
new_chord = (chord - 12 + shift) % 12 + 12
else:
new_chord = chord
return new_chord | bc72df71282d8ae7d15e591bb2a46e5d00f1cd30 | 53,057 |
def register_new_user(access, username, password):
""" Register a new user & handle duplicate detection """
if access.user_data(username) is not None:
raise ValueError("User '%s' already exists!" % username)
if username in access.pending_users():
raise ValueError("User '%s' has already regis... | 25b98c4def9da81d71176aed196f61b2e71d64c5 | 53,058 |
import sys
def player_strategy_from_argv(i):
""" Parses argv at the given index and returns strategy for user """
# Ensure we don't look out of range
if len(sys.argv) < i:
sys.exit(USAGE_ERROR)
if sys.argv[i].lower() == "human":
return human_strategy
elif sys.argv[i].lower() == "... | c15ac7b61068c935fb2b57e8e48527e571be2bbb | 53,059 |
import os
def get_sources_plot_dir(cybershake_root, realisation):
"""
Gets the folder for storing plots that can be generated
before installing a cybershake. eg. srf square & map plots.
"""
return os.path.join(
cybershake_root,
"Data",
"Sources",
get_fault_from_real... | 53dc7c0505ad4af8c12910541d787bedc872ae7f | 53,060 |
def main():
"""
This function is called from the main block. The purpose of this function is to contain all the calls to
business logic functions
:return: int - Return 0 or 1, which is used as the exist code, depending on successful or erroneous flow
"""
# Wrap in a try block so ... | f243787ae86cbf77c5ccae44a68e171618c89c1d | 53,061 |
def report_3ware(line, log, controller):
"""Report findings in 3ware pipeline, return BOOL of health check."""
success = True
progress = None
data_type = None
if line[0] == "u":
data_type = "Unit"
status = line.split()[2]
if status == "REBUILDING":
progress = li... | cdb14dabe67614cae111020cced19752babca4cb | 53,062 |
import yaml
def load_properties():
"""
Load yaml file containing program's properties. Check the ReadMe.md file of the directory for a complete list of
the possible configuration properties and their values.
Returns:
dict: the properties dictionary
"""
properties_folder = join(app_dir... | 0e38e3bb9c420e823f911530165b5c5592ff29fa | 53,063 |
def cdf_to_pdf(cdf):
"""Compute a pdf (probability distribution function) from its cdf (cumulative distribution function)."""
pdf = deepcopy(cdf)
pdf[1:] -= pdf[:-1].copy()
return pdf | 5d9af93ba75d94c08c992474dd0302766aaa9210 | 53,064 |
import yaml
import time
import copy
def stardist_polygon(data_config):
"""Build DSA annotation json from stardist geojson classification results
Args:
data_config (string): path to your data config file that includes input/output parameters.
input (string): path to stardist geojson classific... | c83f1c75cb0fad7a0644686b401ac2c74e8abcec | 53,065 |
def normalize_code(code):
"""
归一化证券代码
:param code 如000001
:return 证券代码的全称 如000001.XSHE
"""
return JQDataClient.instance().normalize_code(**locals()) | e87717aa55ea614db614fa662f9ce1580961e601 | 53,066 |
def get_not_constant_species(model):
"""
get species of the model that are not constant
@param model: libsbml.model
@type model: libsbml.model
@return: list of species
@rtype: list[libsbml.species]
"""
def not_const(s): return not( s.getConstant() or s.getBoundaryCondition() )
return... | abb376899405fa1623ec5ca646d0399e067fd5cc | 53,067 |
def remap_document_keys(document, key_map, inplace=True):
"""Remap keys in given JSON document.
>>> remap_keys({'foo': 1}, {'foo': 'bar'})
{'bar': 1}
"""
assert isinstance(document, dict)
if inplace:
# modify given document
for key in document.keys():
new_key = key_m... | feaafecc2e64ab2bd5f7cf5438bfa60897a4f334 | 53,068 |
def clientcompressionsupport(proto):
"""Returns a list of compression methods supported by the client.
Returns a list of the compression methods supported by the client
according to the protocol capabilities. If no such capability has
been announced, fallback to the default of zlib and uncompressed.
... | ac690e20a17bbf535c9f41ee5846cb408cfbda4c | 53,069 |
def preprocess_pbt_df(df: pd.DataFrame, x_tag: str) -> pd.DataFrame:
"""Align the x_tag index used in plot_progress before plotting.
Args:
----
df (pd.DataFrame): Dataframe of the progress.csv file
x_tag (str): Desired tag in df to use as index of plot
Return:
------
df (pd... | d669383bba44983e949cbfdf5103ae3f1f97de42 | 53,070 |
from typing import List
import math
def standard_deviation(xs: List[float]) -> float:
"""The standard deviation is the square root of the variance"""
return math.sqrt(variance(xs)) | 9287f9ba4bec6bf5ffc28ebeb7e2aae1265b5d22 | 53,071 |
from ...data import COCODetection
def ssd_512_resnet50_v1_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with ResNet v1 50 layers for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weights for mod... | 7740e92aabe168be02266a2ca421e9cb79480557 | 53,072 |
def filter_otsu_threshold(np_img):
"""
Compute Otsu threshold on image as a NumPy array and return binary image based on pixels above threshold.
Args:
np_img: Image as a NumPy array.
output_type: Type of array to return (bool, float, or uint8).
Returns:
NumPy array (bool, float, ... | 9402a2bf695bb19cb4b0e1524364b9e34c44e9e9 | 53,073 |
def get_default_build_presets(default_run_config):
""" Read the build presets from the config """
return dict(default_run_config[ue4_constants.UNREAL_BUILD_SETTINGS_STRUCTURE]) | 1f2c2364dc14ce146ffba4f55ec327fed946e21a | 53,074 |
import os
def which(executable):
"""find the location of an executable"""
if 'PATH' in os.environ:
envpath = os.environ['PATH']
else:
envpath = os.defpath
PATH = envpath.split(os.pathsep)
locations = PATH + [
'/usr/local/bin',
'/bin',
'/usr/bin',
'/... | 4f118a640772c153f86e58cfebe3d6e585903ec1 | 53,075 |
from math import floor
from typing import Tuple
from typing import Union
def conv_output_shape(
h_w: Tuple[int, int],
kernel_size: Union[int, Tuple[int, int]] = 1,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
) -> Tuple[int, int]:
"""
Calculates the output shape (height and width)... | ea757a413a3b38ea024b85dd6987beda8a3b9aeb | 53,076 |
from ._vector import Vector
def reflection_matrix(v):
"""Generate reflection matrix that represents reflection of points \
in a mirror plane defined by normal `Vector` `v`.
Parameters
----------
v : :class:`~sknano.core.math.Vector`
Returns
-------
:class:`~numpy:numpy.ndarray`
... | 91498c87a02fc58f7138651f667c9837ea54fc52 | 53,077 |
from typing import Optional
async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await han... | 552c02f05be604a16be93d6b7c8c09f30a3302a0 | 53,078 |
def normalize_v(x):
"""
normalize a vector
:param x: input
:return: normalized vector
"""
mn = np.min(x)
mx = np.max(x)
for i in range(len(x)):
x[i] = (x[i] - mn) / mx - mn
return x | 7487216a9b56b29823c759f85a13aeb04c3ec960 | 53,079 |
def checkout(request, template_name="order/checkout.html"):
"""
Displays the customer info form for checkout
"""
loginform = LoginForm()
addressform = AddressForm()
if request.method == 'POST':
addressform = AddressForm(request.user, request.POST)
if addressform.is_valid():
... | da6abc6712acc72a8c03b81f37987d610f249150 | 53,080 |
def extract(s):
"""Return a list of each individual emoji in the string."""
return EMOJI.findall(s) | 6c4d0681c5a69fa2d00cc0fabe17a36ba7bd6ba9 | 53,081 |
def fixture_grid_result():
"""
Load the expected grdproject grid result.
"""
return xr.DataArray(
data=[
[427.85062, 431.05698, 452.34268],
[563.92957, 540.5212, 501.46896],
[740.80133, 679.1116, 554.78534],
[794.233, 829.4449, 764.12225],
... | 9f3c9d43cd1eef64d6683940498142d18aab52bb | 53,082 |
from typing import List
def all_scalars(fields: List[Field]) -> bool:
"""Checks if all fields are scalars."""
boolean = True
for f in fields:
boolean = boolean and f.is_boson
return boolean | 4dcadd50a7db4efa4a0e99a399f2fc1b54c2d5c2 | 53,083 |
def sum_all(grid_values):
"""
Calculates the sum of all grid values.
Results in scores from
:param grid_values: values of grid
:return: metrics score
"""
score = sum(grid_values)
return score | a7741961c240cb8edbff050566b7f9341a203af7 | 53,084 |
def _ec_helper_native():
"""Loads the ec_helper_native library.
Returns:
The ctypes ec_helper_native library.
"""
cdll.LoadLibrary(find_library('crypto'))
cdll.LoadLibrary(find_library('ssl'))
return cdll.LoadLibrary('./ec_helper_native.so') | 5fc6ddf931e061bf4a3f11669b8112016266f7d0 | 53,085 |
import re
def formulate_condition(analyses_pattern: str, analyses_list: str) -> str:
""" formulate WHERE SQL condition from analyses_pattern """
condition = ''
if analyses_pattern:
a_range = re.match(r'(\d+)\.\.(\d+)', analyses_pattern)
if a_range:
condition = " WHERE analysis_... | 3504c233a4168295ceb39307898f2aa81ef95f29 | 53,086 |
def lossNet(input_shape=(256, 256, 3),
styleLayers=["block1_conv2", "block2_conv2", "block3_conv3", "block4_conv3"],
contentLayers=["block3_conv3"]):
"""Creates the network to compute the style loss.
This network outputs a dictionary with outputs values for style and content, based on a ... | badb39bfe3454ad395dac9aae5a512c680d45f8d | 53,087 |
def _path(from_object, to_object):
"""
Calculates the 'path' of objects starting from 'from_object'
to 'to_object', along with the index of the first common
ancestor in the tree.
Returns (index, list) tuple.
"""
if from_object._root != to_object._root:
raise ValueError('No connecti... | 0ccfe54d36832b8dce3c55168f02abb3c79261ef | 53,088 |
from rfpipe import search, state, metadata
import time
def initialize_worker():
""" Function called to initialize python on workers
"""
t0 = time.Time.now().mjd
search.set_wisdom(512)
st = state.State(inmeta=metadata.mock_metadata(t0, t0+0.001, 27, 16, 16*32, 4, 5e4, datasource='sim'))
return... | 3fc07d291e6b44b9fdc5ddb537c81cf2b59687b7 | 53,089 |
def parse_filter(components, kind):
"""
Parese any filter
"""
filters = []
pieces = kind.split('_')
parenthsis =0
is_in_quotes = False
start_tracking = False
# loop the the data
for ii, s in enumerate(components):
#print('where - ' + s)
# find the end of the columns
(p, is_in_quotes) = track_parenth... | d3c262de47254864e3f5688154c50e5742050377 | 53,090 |
def getATT(file):
"""use Ohlbergs code to read in attitude data from file
and creates a dictionary for easy insertation
into a postgresdatabase.
"""
ap = attitude.AttitudeParser([file])
# sorting attitudes
tbl = ap.table
keys = tbl.keys()
if not keys:
return
keys.sort()
... | f79344830f28803209a8c98c8787ba1340e08527 | 53,091 |
def keysInter(x):
"""Keys interpolation function
"""
y = np.zeros(x.shape)
abs_x = np.abs(x)
idx1 = np.bitwise_and(abs_x >= 0, abs_x < 1)
idx2 = np.bitwise_and(abs_x >= 1, abs_x <= 2)
y[idx1] = 1.5 * abs_x[idx1] ** 3 - 2.5 * abs_x[idx1] ** 2 + 1
y[idx2] = -0.5 * abs_x[idx2] ** 3 + 2.5 * ... | c43d33be8e3e56a94c0afd86aa0dc75447895c23 | 53,092 |
def rotate_landmarks(landmarks, eye_center, angle, row):
""" rotate landmarks to fit the aligned face
:param landmarks: dict of landmarks for facial parts as keys and tuple of coordinates as values
:param eye_center: tuple of coordinates for eye center
:param angle: degrees of rotation
:param row: r... | 3185adc07df68afb08f3938f0bfc03ed2db25a98 | 53,093 |
def _lookup(name, func, multi, converters):
"""Look up a Webware field/cookie/value/session value. Return
'(realName, value)' where 'realName' is like 'name' but with any
conversion suffix strips off. Applies numeric conversion and
single vs multi values according to the comments in the source.
""... | 0001df664ecfe0c0dbad2ba9240637dd774d6496 | 53,094 |
def generate_random_unit_vector():
"""
Generates a random unit vector.
:return: 3-elem np array with magnitude 1
"""
vec = np.random.normal(size=3)
mag = np.linalg.norm(vec)
if mag <= 1e-5:
return generate_random_unit_vector()
else:
return vec / mag | 8d9438d3fef67e412b561956a69394bf71826025 | 53,095 |
def read_chunk(addr):
"""Read a chunk's metadata."""
# In GLIBC versions <= 2.24 the `mchunk_[prev_]size` field was named `[prev_]size`.
# To support both versions, change the new names to the old ones here so that
# the rest of the code can deal with uniform names.
renames = {
"mchunk_size"... | 4b85387a620aa0deadde11d76d3de4173e3a3877 | 53,096 |
import subprocess
def version():
"""
Determine ffmpeg version and build information
"""
verdata = subprocess.check_output([bpath.ffpath, '-version'])
vdx = {
'version': vmatch(r'^ffmpeg version ([^ ]+).*', verdata),
'date': vmatch(r'.*^built on (.+) with.*$', verdata),
... | 419495ef5835df67ba421c244efb3da728ed75fb | 53,097 |
def dense_brightness_weight(image, sigma_X = 4, sigma_I = 10, r = 5):
"""
Calculate bright_weight(connection) for image
Args:
image: ndarray [B,H,W,C].
sigma_X: sigma for metric of distance.
sigma_I: sigma for metric of intensity.
r: radius of circle that only the neighb... | 6a2d2fc04385a8c03a2e62d18adbc86d5cfe49c0 | 53,098 |
def to_dict_of_lists(G,nodelist=None):
"""Return adjacency representation of graph as a dictionary of lists.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list
Use only nodes specified in nodelist
Notes
-----
Completely ignores edge data for MultiGr... | 682250ea22fc93a23ee7ad65b3d1ecc742eb0f12 | 53,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.