content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def plot_displacement(A, B, save=False, labels=None):
"""
A and B are both num_samples x num_dimensions
for now, num_dimensions must = 2
"""
assert A.shape == B.shape
assert A.shape[1] == 2
if not labels is None:
assert len(labels) == A.shape[0]
delta = B - A
delta_dir = delt... | 8cd05bbe56c590923e5d3a51d2b6eaf933b6a71b | 3,700 |
import math
def t_dp(tdb, rh):
""" Calculates the dew point temperature.
Parameters
----------
tdb: float
dry-bulb air temperature, [°C]
rh: float
relative humidity, [%]
Returns
-------
t_dp: float
dew point temperature, [°C]
"""
c = 257.14
b = 18... | d3cd7de10ef51f36bc5d5bd978d991d5bfe3ba4c | 3,701 |
import os
import zipfile
def extract_archive(filepath):
"""
Returns the path of the archive
:param str filepath: Path to file to extract or read
:return: path of the archive
:rtype: str
"""
# Checks if file path is a directory
if os.path.isdir(filepath):
path = os.path.absp... | 2a066b7bd888833d035d30945d5b24653b0620a6 | 3,702 |
def LinkConfig(reset=0, loopback=0, scrambling=1):
"""Link Configuration of TS1/TS2 Ordered Sets."""
value = ( reset << 0)
value |= ( loopback << 2)
value |= ((not scrambling) << 3)
return value | 901fe6df8bbe8dfa65cd516ac14692594608edfb | 3,703 |
def test_tedlium_release():
"""
Feature: TedliumDataset
Description: test release of tedlium
Expectation: release
set invalid data
get throw error
"""
def test_config(release):
try:
ds.TedliumDataset(DATA_DIR_TEDLIUM_RELEASE12, ... | a25f042745d1eea4dca62195e1259b7bcb8beb8d | 3,704 |
def get_data(n, input_dim, y_dim, attention_column=1):
"""
Data generation. x is purely random except that it's first value equals the target y.
In practice, the network should learn that the target = x[attention_column].
Therefore, most of its attention should be focused on the value addressed by atten... | 4c132abec92e8cd0ca6afd06e4032116d3631a50 | 3,705 |
def generate_tautomer_hydrogen_definitions(hydrogens, residue_name, isomer_index):
"""
Creates a hxml file that is used to add hydrogens for a specific tautomer to the heavy-atom skeleton
Parameters
----------
hydrogens: list of tuple
Tuple contains two atom names: (hydrogen-atom-name, he... | 69ec0c489d93edc7d8fe3ccde8df25c9c2fd01c9 | 3,706 |
def login(client=None, **defaults):
"""
@param host:
@param port:
@param identityName:
@param password:
@param serviceName:
@param perspectiveName:
@returntype: Deferred RemoteReference of Perspective
"""
d = defer.Deferred()
LoginDialog(client, d, defaults)
return d | a6c4593ef5b1fd29f46cba4a6484049bd093b6da | 3,707 |
import time
import json
import traceback
def insertInstrument():
""" Insert a new instrument or edit an existing instrument on a DAQBroker database. Guest users are not allowed to
create instruments. Created instruments are
.. :quickref: Create/Edit instrument; Creates or edits a DAQBroker instrument ins... | 537b89fa72b161c86c4b49a7a6813cf95df45f09 | 3,708 |
def find_distance_to_major_settlement(country, major_settlements, settlement):
"""
Finds the distance to the nearest major settlement.
"""
nearest = nearest_points(settlement['geometry'], major_settlements.unary_union)[1]
geom = LineString([
(
settlement['geomet... | 0bb33d3777ab0f60dfb05e69cb2f5ed711585b17 | 3,709 |
def x_for_half_max_y(xs, ys):
"""Return the x value for which the corresponding y value is half
of the maximum y value. If there is no exact corresponding x value,
one is calculated by linear interpolation from the two
surrounding values.
:param xs: x values
:param ys: y values corresponding to... | b18525664c98dc05d72a29f2904a13372f5696eb | 3,710 |
from typing import Union
from pathlib import Path
from typing import Dict
def get_dict_from_dotenv_file(filename: Union[Path, str]) -> Dict[str, str]:
"""
:param filename: .env file where values are extracted.
:return: a dict with keys and values extracted from the .env file.
"""
result_dict = {}
... | 97bce5a69e29f9606a58a54ed5cc4d05ab45fbca | 3,711 |
def calculate_note_numbers(note_list, key_override = None):
"""
Takes in a list of notes, and replaces the key signature (second
element of each note tuple) with the note's jianpu number.
Parameters
----------
note_list : list of tuples
List of notes to calculate jianpu numbers for.... | a32bbae7f64b381ad3384fdd8ae5c045c6887c87 | 3,712 |
import numpy as np
def _from_Gryzinski(DATA):
"""
This function computes the cross section and energy values from the files
that store information following the Gryzinski Model
"""
a_0 = DATA['a_0']['VALUES']
epsilon_i_H = DATA['epsilon_i_H']['VALUES']
epsilon_i = DATA['epsilon_... | 925fb1e76bf23915385cf56e3a663d111615700d | 3,713 |
from haversine import haversine
def stations_within_radius(stations, centre, r):
"""Returns an alphabetically-ordered list of the names of all the stations (in a list of stations objects) within a radius r (in km) of a central point
(which must be a Lat/Long coordinate)"""
# creates empty list
... | 36bf8312e4295638c1e297f4a31b535c9ee96eaf | 3,714 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import List
def read_data_with_plugins(
path: Union[str, Sequence[str]],
plugin: Optional[str] = None,
plugin_manager: PluginManager = napari_plugin_manager,
) -> List[LayerData]:
"""Iterate reader hooks and r... | e6b83c4a55a39b07bfc8eddcd77c82351f91b1d7 | 3,715 |
def ticket_message_url(request, structure_slug, ticket_id): # pragma: no cover
"""
Makes URL redirect to add ticket message by user role
:type structure_slug: String
:type ticket_id: String
:param structure_slug: structure slug
:param ticket_id: ticket code
:return: redirect
"""
s... | 29cec06302e943d74236ff82647cd28deb634107 | 3,716 |
from pathlib import Path
from datetime import datetime
from re import T
def load(
fin: Path,
azelfn: Path = None,
treq: list[datetime] = None,
wavelenreq: list[str] = None,
wavelength_altitude_km: dict[str, float] = None,
) -> dict[str, T.Any]:
"""
reads FITS images and spatial az/el calib... | bb656482c1db134c3045ac5a30b9cecb8d9f6716 | 3,717 |
import logging
def loadData(data_source, loc, run, indexes, ntry=0, __text__=None, __prog__=None):
"""
Loads the data from a remote source. Has hooks for progress bars.
"""
if __text__ is not None:
__text__.emit("Decoding File")
if data_source.getName() == "Local WRF-ARW":
url = d... | d06fd6fb6194dac63911a5b9c3ad267525098cd2 | 3,718 |
def comp_psip_skin(self, u):
"""psip_skin for skin effect computation
Parameters
----------
self : Conductor
An Conductor object
Returns
-------
None
"""
y = (1 / u) * (sinh(u) + sin(u)) / (cosh(u) + cos(u)) # p257 Pyrhonen
# y[u==0]=1
return y | 23fe18a13b56f38c49fd3ca14b557983064c65b3 | 3,719 |
import random
def homepage(var=random.randint(0, 1000)):
"""
The function returns the homepage html template.
"""
return render_template("index.html", var=var) | 17e9033b8abeaa990cd31008861e5c412e35d1d7 | 3,720 |
import numbers
def tier(value):
"""
A special function of ordinals which does not
correspond to any mathematically useful function.
Maps ordinals to small objects, effectively compressing the range.
Used to speed up comparisons when the operands are very different sizes.
In the current vers... | 851b36cf22c09d8f94168a0aa55292754451e351 | 3,721 |
from .models import Sequence
def get_next_value(
sequence_name="default",
initial_value=1,
reset_value=None,
*,
nowait=False,
using=None,
overrite=None,
):
"""
Return the next value for a given sequence.
"""
# Inner import because models cannot be imported before their app... | 0770c8d4a4bea732bacfe6b7eaa404546bb79699 | 3,722 |
def expected_shd(posterior, ground_truth):
"""Compute the Expected Structural Hamming Distance.
This function computes the Expected SHD between a posterior approximation
given as a collection of samples from the posterior, and the ground-truth
graph used in the original data generation process.
Pa... | 5e0daf39a13fc0a4cb7a4f5d0a9fe692fdae82db | 3,723 |
import json
def package_list_read(pkgpath):
"""Read package list"""
try:
with open(PACKAGE_LIST_FILE, 'r') as pkglistfile:
return json.loads(pkglistfile.read())
except Exception:
return [] | afb97afd20823563ecfda3b5c908f7ad70322868 | 3,724 |
import pandas
import types
def hpat_pandas_series_le(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.le` implementation.
.. only:: developer
Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op8
Parameters
--------... | f2969e17dd79b71a033e3c84ffd82e3bf2448554 | 3,725 |
def add_obs_info(telem, obs_stats):
"""
Add observation-specific information to a telemetry table (ok flag, and outlier flag).
This is done as part of get_agasc_id_stats. It is a convenience for writing reports.
:param telem: list of tables
One or more telemetry tables (potentially many observ... | beea2b87337412f34d1a854c14eebf46265f78c9 | 3,726 |
def map_view(request):
"""
Place to show off the new map view
"""
# Define view options
view_options = MVView(
projection='EPSG:4326',
center=[-100, 40],
zoom=3.5,
maxZoom=18,
minZoom=2
)
# Define drawing options
drawing_options = MVDraw(
... | 5d037262b2c93c538b5a5b6fe076ee04a9d9b5ee | 3,727 |
def decompose_jamo(compound):
"""Return a tuple of jamo character constituents of a compound.
Note: Non-compound characters are echoed back.
WARNING: Archaic jamo compounds will raise NotImplementedError.
"""
if len(compound) != 1:
raise TypeError("decompose_jamo() expects a single characte... | 56eb503b47a966d7f88750f7fdc1bcc55ba1aa1b | 3,728 |
from typing import Optional
def cp_in_drive(
source_id: str,
dest_title: Optional[str] = None,
parent_dir_id: Optional[str] = None,
) -> DiyGDriveFile:
"""Copy a specified file in Google Drive and return the created file."""
drive = create_diy_gdrive()
if dest_title is None:
dest_title... | 981cfa18da78a160447778cab5f3326f35dbfc59 | 3,729 |
def label_tuning(
text_embeddings,
text_labels,
label_embeddings,
n_steps: int,
reg_coefficient: float,
learning_rate: float,
dropout: float,
) -> np.ndarray:
"""
With N as number of examples, K as number of classes, k as embedding dimension.
Args:
'text_embeddings': flo... | 83e4181c6600065bfb2cc98b4ca4957ea920ad7c | 3,730 |
def create_nan_filter(tensor):
"""Creates a layer which replace NaN's with zero's."""
return tf.where(tf.is_nan(tensor), tf.zeros_like(tensor), tensor) | 4e03c4c4c275430e5228e2d73b09e24f8c787e71 | 3,731 |
def requestor_is_superuser(requestor):
"""Return True if requestor is superuser."""
return getattr(requestor, "is_superuser", False) | 7b201601cf8a1911aff8271ff71b6d4d51f68f1a | 3,732 |
from typing import Dict
def process(business: Business, # pylint: disable=too-many-branches
filing: Dict,
filing_rec: Filing,
filing_meta: FilingMeta): # pylint: disable=too-many-branches
"""Process the incoming historic conversion filing."""
# Extract the filing informat... | 78f5033251cb90023c2e0c0ad064b92af5212e65 | 3,733 |
def est_const_bsl(bsl,starttime=None,endtime=None,intercept=False,val_tw=None):
"""Performs a linear regression (assuming the intercept at the origin).
The corresponding formula is tt-S*1/v-c = 0 in which tt is the travel
time of the acoustic signal in seconds and 1/v is the reciprocal of the
harmonic ... | 906119dcc66f4ab536d4a89c9c9b633bb6835058 | 3,734 |
def SeasonUPdate(temp):
""" Update appliance characteristics given the change in season
Parameters
----------
temp (obj): appliance set object for an individual season
Returns
----------
app_expected_load (float): expected load power in Watts
app_expected_dur (float): expected ... | 7fdfa932bedf2ac17490df6aaeedb547e1774c4d | 3,735 |
def pad_and_reshape(instr_spec, frame_length, F):
"""
:param instr_spec:
:param frame_length:
:param F:
:returns:
"""
spec_shape = tf.shape(instr_spec)
extension_row = tf.zeros((spec_shape[0], spec_shape[1], 1, spec_shape[-1]))
n_extra_row = (frame_length) // 2 + 1 - F
extension ... | 097bc2e8f58f1e947b8f69a6163d1c64d2197f9e | 3,736 |
def GetExclusiveStorageForNodes(cfg, node_uuids):
"""Return the exclusive storage flag for all the given nodes.
@type cfg: L{config.ConfigWriter}
@param cfg: cluster configuration
@type node_uuids: list or tuple
@param node_uuids: node UUIDs for which to read the flag
@rtype: dict
@return: mapping from n... | b93625bc2b865530bef0c648885f5615905e54c1 | 3,737 |
import csv
def get_read_data(file, dic, keys):
""" Assigns reads to labels"""
r = csv.reader(open(file))
lines = list(r)
vecs_forwards = []
labels_forwards = []
vecs_reverse = []
labels_reverse = []
for key in keys:
for i in dic[key]:
for j in lines:
... | 355c44cbf83ab9506755bda294723bfd1e8a15c1 | 3,738 |
def removeDuplicates(listToRemoveFrom: list[str]):
"""Given list, returns list without duplicates"""
listToReturn: list[str] = []
for item in listToRemoveFrom:
if item not in listToReturn:
listToReturn.append(item)
return listToReturn | 8265e7c560d552bd9e30c0a1140d6668abd1b4d6 | 3,739 |
def check_hms_angle(value):
"""
Validating function for angle sexagesimal representation in hours.
Used in the rich_validator
"""
if isinstance(value, list):
raise validate.ValidateError("expected value angle, found list")
match = hms_angle_re.match(value)
if not match:
raise... | bf1b6ec14cc131263913c331cb1d3cb9a06cdc76 | 3,740 |
import logging
def get_logger(module_name):
"""Generates a logger for each module of the project.
By default, the logger logs debug-level information into a
newscrapy.log file and info-level information in console.
Parameters
----------
module_name: str
The name of the module for whi... | df9e07df89c43bc156812834c70b5b007200581e | 3,741 |
def stats():
"""Retrives the count of each object type.
Returns:
JSON object with the number of objects by type."""
return jsonify({
"amenities": storage.count("Amenity"),
"cities": storage.count("City"),
"places": storage.count("Place"),
"reviews": storage.count("Re... | 31ebd630381fe33cdbff507a3d34497423dfd621 | 3,742 |
def addflux2pix(px,py,pixels,fmod):
"""Usage: pixels=addflux2pix(px,py,pixels,fmod)
Drizel Flux onto Pixels using a square PSF of pixel size unity
px,py are the pixel position (integers)
fmod is the flux calculated for (px,py) pixel
and it has the same length as px and py
pixels is the imag... | 808f99dac20cda962146fee8f2b9878a07804f9b | 3,743 |
def get_dea_landsat_vrt_dict(feat_list):
"""
this func is designed to take all releveant landsat bands
on the dea public database for each scene in stac query.
it results in a list of vrts for each band seperately and maps
them to a dict where band name is the key, list is the value pair.
"""
... | 79009cc9fbcd085c8e95cf15f4271419d598d1ce | 3,744 |
import logging
import json
def load_json() -> tuple[list["Team"], list["User"]]:
"""Load the Json file."""
logging.debug("Starting to load data file.")
with open(".example.json") as file:
data = json.load(file)
if any(field not in data for field in REQUIRED_DATA_FIELDS):
raise ValueEr... | 602a55faa1f89a6adc7e4246b666b4f098f3b190 | 3,745 |
def is_zh_l_bracket(uni_ch):
"""判断一个 unicode 是否是中文左括号。"""
if uni_ch == u'\uff08':
return True
else:
return False | 3ba18418005824a51de380c898726d050d464ec2 | 3,746 |
def petlink32_to_dynamic_projection_mMR(filename,n_packets,n_radial_bins,n_angles,n_sinograms,time_bins,n_axial,n_azimuthal,angles_axial,angles_azimuthal,size_u,size_v,n_u,n_v,span,n_segments,segments_sizes,michelogram_segments,michelogram_planes, status_callback):
"""Make dynamic compressed projection from list-mo... | 9764da2a2fb0c021274133fdd46661a44cf0dc31 | 3,747 |
from typing import Dict
def is_core_recipe(component: Dict) -> bool:
"""
Returns True if a recipe component contains a "Core Recipe"
preparation.
"""
preparations = component.get('recipeItem', {}).get('preparations') or []
return any(prep.get('id') == PreparationEnum.CORE_RECIPE.value for prep... | 451798c6f31297a80ac43db00243fb2dd85ced46 | 3,748 |
def build_estimator(output_dir, first_layer_size, num_layers, dropout,
learning_rate, save_checkpoints_steps):
"""Builds and returns a DNN Estimator, defined by input parameters.
Args:
output_dir: string, directory to save Estimator.
first_layer_size: int, size of first hidden layer of ... | 339e26fd910aa7412b8e2b66845718e440ccada6 | 3,749 |
import json
def importConfig():
"""設定ファイルの読み込み
Returns:
tuple:
str: interface,
str: alexa_remote_control.sh path
list: device list
"""
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
interface = config["interface"]
... | 84f8fc0deec4aebfe48209b01d1a35f7373d31e6 | 3,750 |
from google.cloud import datalabeling_v1beta1 as datalabeling
import os
def create_dataset(project_id):
"""Creates a dataset for the given Google Cloud project."""
client = datalabeling.DataLabelingServiceClient()
# [END datalabeling_create_dataset_beta]
# If provided, use a provided test endpoint - t... | f808115479503aae52c7ef1b3863164355b5a091 | 3,751 |
from typing import List
from typing import Dict
from typing import Any
def create_local_command(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata: List[Options]) -> str:
"""Create a terminal command to run the jobs locally."""
cmd = ""
for meta, job in zip(jobs_metadata, jobs):
input_file =... | f5d23c1fb2271b44a323d1d17e9dda35df29fcd7 | 3,752 |
import time
def time_for_log() -> str:
"""Function that print the current time for bot prints"""
return time.strftime("%d/%m %H:%M:%S - ") | 0f964d5c827782ff8cc433e57bb3e78d0a7c7cba | 3,753 |
import math
def _is_int(n) -> bool:
"""
is_int 是判断给定数字 n 是否为整数,
在判断中 n 小于epsilon的小数部分将被忽略,
是则返回 True,否则 False
:param n: 待判断的数字
:return: True if n is A_ub integer, False else
"""
return (n - math.floor(n) < _epsilon) or (math.ceil(n) - n < _epsilon) | 076a82d245333890d6790f65a58e5507905ca68f | 3,754 |
def _cpp_het_stat(A, t_stop, rates, t_start=0. * pq.ms):
"""
Generate a Compound Poisson Process (CPP) with amplitude distribution
A and heterogeneous firing rates r=r[0], r[1], ..., r[-1].
Parameters
----------
A : np.ndarray
CPP's amplitude distribution. A[j] represents the probabilit... | adc00577e9a6cb1ff7f9e0313befe98c81332ab1 | 3,755 |
def return_bad_parameter_config() -> CloudSettings:
"""Return a wrongly configured cloud config class."""
CloudSettingsTest = CloudSettings( # noqa: N806
settings_order=[
"init_settings",
"aws_parameter_setting",
"file_secret_settings",
"env_settings",
... | 06f8af87873d571be9c5ae7fd2e563402e57b2d0 | 3,756 |
def update(isamAppliance, instance_id, id, filename=None, contents=None, check_mode=False, force=False):
"""
Update a file in the administration pages root
:param isamAppliance:
:param instance_id:
:param id:
:param name:
:param contents:
:param check_mode:
:param force:
:return:... | af0b95096638fb34af130623b0929c4394a1a845 | 3,757 |
def view_deflate_encoded_content():
"""Returns Deflate-encoded data.
---
tags:
- Response formats
produces:
- application/json
responses:
200:
description: Defalte-encoded data.
"""
return jsonify(get_dict("origin", "headers", method=request.method, deflated=True)) | ff8d39f75a6cb526b3a61e85234e71efa174a208 | 3,758 |
def predict_from_word_vectors_matrix(tokens, matrix, nlp, POS="NOUN", top_number=constants.DEFAULT_TOP_ASSOCIATIONS):
"""
Make a prediction based on the word vectors
:param tokens:
:param matrix:
:param nlp:
:param POS:
:param top_number:
:return:
"""
vector_results = collect_wor... | 6a491e481238af932994bb8d383baca4da1ebd55 | 3,759 |
import os
def get_luis_keys():
"""Retrieve Keys for LUIS app"""
load_dotenv()
key = os.getenv("LUIS_KEY")
region = os.getenv("LUIS_REGION")
app_id = os.getenv("LUIS_APP_ID")
return key, region, app_id | 94c880c26d08a60ecde6c86952de64d8ea45a46d | 3,760 |
import re
from typing import OrderedDict
def xls_to_dict(path_or_file):
"""
Return a Python dictionary with a key for each worksheet
name. For each sheet there is a list of dictionaries, each
dictionary corresponds to a single row in the worksheet. A
dictionary has keys taken from the column heade... | 8ac0ca78dae6bec7025565607ddc174205d0389a | 3,761 |
def blendImg(img_a, img_b, α=0.8, β=1., γ=0.):
"""
The result image is computed as follows:
img_a * α + img_b * β + γ
"""
return cv2.addWeighted(img_a, α, img_b, β, γ) | f60918ba424b0d59e9025c088c0f2c9a3f739fde | 3,762 |
def setup(app):
"""Sets up the extension"""
app.add_autodocumenter(documenters.FunctionDocumenter)
app.add_config_value(
"autoclass_content", "class", True, ENUM("both", "class", "init")
)
app.add_config_value(
"autodoc_member_order",
"alphabetical",
True,
E... | b6cf9cfcc59eb83c10be441faebd24e6000673f3 | 3,763 |
def genoimc_dup4_loc():
"""Create genoimc dup4 sequence location"""
return {
"_id": "ga4gh:VSL.us51izImAQQWr-Hu6Q7HQm-vYvmb-jJo",
"sequence_id": "ga4gh:SQ.-A1QmD_MatoqxvgVxBLZTONHz9-c7nQo",
"interval": {
"type": "SequenceInterval",
"start": {
"valu... | 3ea1b39fed22487bebffc78d45cb493b7d7afa4a | 3,764 |
def compare_versions(a, b):
"""Return 0 if a == b, 1 if a > b, else -1."""
a, b = version_to_ints(a), version_to_ints(b)
for i in range(min(len(a), len(b))):
if a[i] > b[i]:
return 1
elif a[i] < b[i]:
return -1
return 0 | 0b22589164f7d3731edc34af97d306186e677371 | 3,765 |
def get_machine_action_data(machine_action_response):
"""Get machine raw response and returns the machine action info in context and human readable format.
Notes:
Machine action is a collection of actions you can apply on the machine, for more info
https://docs.microsoft.com/en-us/windows/sec... | 1e0ffc37d8d3b5662b64ec28cb850c6277b1bad2 | 3,766 |
import os
def BulkRemove(fname,masterfile=None,edlfile=None):
"""
Given a file with one IP per line, remove the given IPs from the EDL if they are in there
"""
global AutoSave
success = True
removes = list()
if os.path.exists(fname):
with open(fname,"rt") as ip_list:
for ip in ip_list:
removes.appe... | c6ffe54e8b20437f6eb48459e775dd0a38b4c5d2 | 3,767 |
import torch
def convolutionalize(modules, input_size):
"""
Recast `modules` into fully convolutional form.
The conversion transfers weights and infers kernel sizes from the
`input_size` and modules' action on it.
n.b. This only handles the conversion of linear/fully-connected modules,
altho... | 5693a17bac0f39538bfcada3280ce06ef91230a3 | 3,768 |
def is_unique2(s):
"""
Use a list and the int of the character will tell if that character has
already appeared once
"""
d = []
for t in s:
if d[int(t)]:
return False
d[int(t)] = True
return True | b1a1bdea8108690a0e227fd0b75f910bd6b99a07 | 3,769 |
import random
def uncomplete_tree_parallel(x:ATree, mode="full"):
""" Input is tuple (nl, fl, split)
Output is a randomly uncompleted tree,
every node annotated whether it's terminated and what actions are good at that node
"""
fl = x
fl.parent = None
add_descendants_ancestors... | f59e0f0279c9c439034116f769f51d60a924c4af | 3,770 |
def stations_by_river(stations):
"""Give a dictionary to hold the rivers name as keys and their corresponding stations' name as values"""
rivers_name = []
for i in stations:
if i.river not in rivers_name:
rivers_name.append(i.river)
elif i.river in rivers_name:
contin... | 66fd928415619d175b7069b8c3103a3f7d930aac | 3,771 |
def QA_SU_save_huobi(frequency):
"""
Save huobi kline "smart"
"""
if (frequency not in ["1d", "1day", "day"]):
return QA_SU_save_huobi_min(frequency)
else:
return QA_SU_save_huobi_day(frequency) | cdea45afe6d7e0b61dea517adb8fc484e8eafa38 | 3,772 |
import os
def get_cachefile(filename=None):
"""Resolve cachefile path
"""
if filename is None:
for f in FILENAMES:
if os.path.exists(f):
return f
return IDFILE
else:
return filename | 39046ce95f763720a6ad23584717f4da379cf690 | 3,773 |
def inverse(a):
"""
[description]
calculating the inverse of the number of characters,
we do this to be able to find our departure when we arrive.
this part will be used to decrypt the message received.
:param a: it is an Int
:return: x -> it is an Int
"""
x = 0
while a * x % 9... | 2893d2abda34e4573eb5d9602edc0f8e14246e09 | 3,774 |
from typing import Optional
from typing import Union
def currency_column_to_numeric(
df: pd.DataFrame,
column_name: str,
cleaning_style: Optional[str] = None,
cast_non_numeric: Optional[dict] = None,
fill_all_non_numeric: Optional[Union[float, int]] = None,
remove_non_numeric: bool = False,
) ... | e382752e5aff389872da69f42a3ec62785df336f | 3,775 |
async def subreddit_type_submissions(sub="wallstreetbets", kind="new"):
"""
"""
comments = []
articles = []
red = await reddit_instance()
subreddit = await red.subreddit(sub)
if kind == "hot":
submissions = subreddit.hot()
elif kind == "top":
submissions = subreddit.top()... | 9cc8655575ca8fd3729e220b0ee3fc8e45e4ed56 | 3,776 |
import getopt
import sys
def get_args():
"""Get argument"""
try:
opts, args = getopt.getopt(
sys.argv[1:],
"i:s:t:o:rvh",
["ibam=",
"snp=",
"tag=",
"output=",
"rstat", "verbose", "help"])
except getopt.GetoptEr... | 2caf9ac202c788da2587e37e0754a7789fdc8142 | 3,777 |
import typing
import json
def _get_bundle_manifest(
uuid: str,
replica: Replica,
version: typing.Optional[str],
*,
bucket: typing.Optional[str] = None) -> typing.Optional[dict]:
"""
Return the contents of the bundle manifest file from cloud storage, subject to the rules... | 7881e1514a9a645c1f7ee6479baa6e74bae4dabb | 3,778 |
def handler400(request, exception):
"""
This is a Django handler function for 400 Bad Request error
:param request: The Django Request object
:param exception: The exception caught
:return: The 400 error page
"""
context = get_base_context(request)
context.update({
'message': {
... | 0dc1b81ec86d675f348728863dfe07efbd936e8e | 3,779 |
import os
import json
def object_trajectory_proposal(vid, fstart, fend, gt=False, verbose=False):
"""
Set gt=True for providing groundtruth bounding box trajectories and
predicting classme feature only
"""
vsig = get_segment_signature(vid, fstart, fend)
name = 'traj_cls_gt' if gt else 'traj_cl... | c8a0fc1dc8109055a16becc40e94e0e15ec8289e | 3,780 |
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size):
"""Gather top beams from nested structure."""
_, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size)
return _gather_beams(nested, topk_indexes, batch_size, beam_size) | ebdaf391104a3f271a42549708f3e7adfaf8b0b0 | 3,781 |
import scipy
import numpy
def _traceinv_exact(K, B, C, matrix, gram, exponent):
"""
Finds traceinv directly for the purpose of comparison.
"""
# Exact solution of traceinv for band matrix
if B is not None:
if scipy.sparse.isspmatrix(K):
K_ = K.toarray()
B_ = B.toa... | 3637a5aa726ef1bf8489783c435c429b59422240 | 3,782 |
def create_feature_vector_of_mean_mfcc_for_song(song_file_path: str) -> ndarray:
"""
Takes in a file path to a song segment and returns a numpy array containing the mean mfcc values
:param song_file_path: str
:return: ndarray
"""
song_segment, sample_rate = librosa.load(song_file_path)
mfccs... | 8992feafd483bfe7b4af5e715ba1455884e1b710 | 3,783 |
def stations_highest_rel_level(stations, N):
"""Returns a list containing the names of the N stations
with the highest water level relative to the typical range"""
names = [] # create list for names
levels = [] # create list for levels
for i in range(len(stations)): # iterate through stat... | 780a03a424c9b2f0dedee2e93eb9bd27cc1fce36 | 3,784 |
def read_image(file_name, format=None):
"""
Read an image into the given format.
Will apply rotation and flipping if the image has such exif information.
Args:
file_name (str): image file path
format (str): one of the supported image modes in PIL, or "BGR"
Returns:
image (n... | ffa2cd8cbea750a08fa28942e71c48bbcfbefdaf | 3,785 |
def add_global_nodes_edges(g_nx : nx.Graph, feat_data: np.ndarray, adj_list: np.ndarray,
g_feat_data: np.ndarray, g_adj_list: np.ndarray):
"""
:param g_nx:
:param feat_data:
:param adj_list:
:param g_feat_data:
:param g_adj_list:
:return:
"""
feat_da... | 1097becfe88f05008541aaa6c3c074fcd5c3149a | 3,786 |
import os
def _load_readme(file_name: str = "README.md") -> str:
"""
Load readme from a text file.
Args:
file_name (str, optional): File name that contains the readme. Defaults to "README.md".
Returns:
str: Readme text.
"""
with open(os.path.join(_PATH_ROOT, file_name), "r", ... | 5815ded89c5b952edc8a8b691afe48f99d121be6 | 3,787 |
def get_data_collector_instance(args, config):
"""Get the instance of the data
:param args: arguments of the script
:type args: Namespace
:raises NotImplementedError: no data collector implemented for given data source
:return: instance of the specific data collector
:rtype: subclass of BaseDat... | 75fda1231e1489da4b0c10473c9f657b143047c1 | 3,788 |
def timeIntegration(params):
"""Sets up the parameters for time integration
:param params: Parameter dictionary of the model
:type params: dict
:return: Integrated activity variables of the model
:rtype: (numpy.ndarray,)
"""
dt = params["dt"] # Time step for the Euler intergration (ms)
... | 24d6702a92f82c6cc7fc1a337cd351b54c567e8b | 3,789 |
def is_role_user(session, user=None, group=None):
# type: (Session, User, Group) -> bool
"""
Takes in a User or a Group and returns a boolean indicating whether
that User/Group is a component of a service account.
Args:
session: the database session
user: a User object to check
... | 3d6b62b1708882b734031d737fa00f29ba9a9f95 | 3,790 |
def argCOM(y):
"""argCOM(y) returns the location of COM of y."""
idx = np.round(np.sum(y/np.sum(y)*np.arange(len(y))))
return int(idx) | 197ac25043b10575efb7405dba12c0d2e6f9976f | 3,791 |
def fringe(z, z1, z2, rad, a1):
"""
Approximation to the longitudinal profile of a multipole from a permanent magnet assembly.
see Wan et al. 2018 for definition and Enge functions paper (Enge 1964)
"""
zz1 = (z - z1) / (2 * rad / pc.pi)
zz2 = (z - z2) / (2 * rad / pc.pi)
fout = ( (1 / ... | b1d0138937d1c622809d6f559f17430e89259fed | 3,792 |
import random
def random_param_shift(vals, sigmas):
"""Add a random (normal) shift to a parameter set, for testing"""
assert len(vals) == len(sigmas)
shifts = [random.gauss(0, sd) for sd in sigmas]
newvals = [(x + y) for x, y in zip(vals, shifts)]
return newvals | 07430572c5051b7142499bcbdbc90de5abfcbd4d | 3,793 |
def compute_encrypted_request_hash(caller):
"""
This function will compute encrypted request Hash
:return: encrypted request hash
"""
first_string = get_parameter(caller.params_obj, "requesterNonce") or ""
worker_order_id = get_parameter(caller.params_obj, "workOrderId") or ""
worker_id = ge... | cf87c354df550b142030781e8b84ec1cb385489f | 3,794 |
def translate_line_test(string):
"""
Translates raw log line into sequence of integer representations for word tokens with sos and eos tokens.
:param string: Raw log line from auth_h.txt
:return: (list) Sequence of integer representations for word tokens with sos and eos tokens.
"""
data = strin... | d311eb9c6b398391724e868071d89f2f6c442912 | 3,795 |
def preprocess_signal(signal, sample_rate):
"""
Preprocess a signal for input into a model
Inputs:
signal: Numpy 1D array containing waveform to process
sample_rate: Sampling rate of the input signal
Returns:
spectrogram: STFT of the signal after resampling to 10kHz and adding
... | d2b6c5cb700ae877f7bf8bd4b5a772471e69a75d | 3,796 |
def get_frameheight():
"""return fixed height for extra panel
"""
return 120 | 3bd810eea77af15527d3c1df7ab0b788cfe90000 | 3,797 |
def default_heart_beat_interval() -> int:
"""
:return: in seconds
"""
return 60 | 58171c8fb5632aa2aa46de8138828cce2eaa4d33 | 3,798 |
import re
def email_valid(email):
"""test for valid email address
>>> email_valid('test@testco.com')
True
>>> email_valid('test@@testco.com')
False
>>> email_valid('test@testco')
False
"""
if email == '':
return True
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_... | c76a621647595c741b1da71734a34372919e800f | 3,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.