content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def join_paths(path, *paths):
"""
"""
return os.path.join(path, *paths) | fdd069ba4414831a201192d096cdb7723037d3dc | 3,644,100 |
def determine_configure_options(module):
"""
Determine configure arguments for this system.
Automatically determine configure options for this system and build
options when the explicit configure options are not specified.
"""
options = module.params['configure_options']
build_userspace = m... | 02026dfa737edd8a3c7b60e5e34f48dc7a958858 | 3,644,101 |
def getElementTypeToolTip(t):
"""Wrapper to prevent loading qtgui when this module is imported"""
if t == PoolControllerView.ControllerModule:
return "Controller module"
elif t == PoolControllerView.ControllerClass:
return "Controller class" | 6862b10bc940daec1c13ef97fafbf525c2683e9e | 3,644,102 |
def parse_dates(array):
"""Parse the valid dates in an array of strings.
"""
parsed_dates = []
for elem in array:
elem = parse_date(elem)
if elem is not None:
parsed_dates.append(elem)
return parsed_dates | 1ec89f084cdd68709a37ea05356ceeb1a21f98bd | 3,644,103 |
def app_factory(global_config, **local_config):
"""
定义一个 app 的 factory 方法,以便在运行时绑定具体的 app,而不是在配置文件中就绑定。
:param global_config:
:param local_config:
:return:
"""
return MyApp() | c4c29963f88253c272319bc2369d4801df284fbf | 3,644,104 |
import pytz
def str_to_datetime(dt_str):
""" Converts a string to a UTC datetime object.
@rtype: datetime
"""
try:
return dt.datetime.strptime(
dt_str, DATE_STR_FORMAT).replace(tzinfo=pytz.utc)
except ValueError: # If dt_str did not match our format
return None | a9ac073c11b13dca011cca46860080cdc638dcbe | 3,644,105 |
def quantize(img):
"""Quantize the output of model.
:param img: the input image
:type img: ndarray
:return: the image after quantize
:rtype: ndarray
"""
pixel_range = 255
return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) | 49abd32d8b2cf54c955e16765602bbff77a2a1b9 | 3,644,106 |
def is_normalized(M, x, eps):
"""Return True if (a Fuchsian) matrix M is normalized, that
is all the eigenvalues of it's residues in x lie in [-1/2, 1/2)
range (in limit eps->0). Return False otherwise.
Examples:
>>> x, e = var("x epsilon")
>>> is_normalized(matrix([[(1+e)/3/x, 0], [0, e/x]]), ... | 01715cd58cad25a805ffd260b78641701483ad86 | 3,644,107 |
def _get_dashboard_link(course_key):
""" Construct a URL to the external analytics dashboard """
analytics_dashboard_url = f'{settings.ANALYTICS_DASHBOARD_URL}/courses/{str(course_key)}'
link = HTML("<a href=\"{0}\" rel=\"noopener\" target=\"_blank\">{1}</a>").format(
analytics_dashboard_url, settin... | fa9fb656ff4e7cf70c3512755351a46302cec71b | 3,644,108 |
def figure1_control(data1, cols):
""" Creates a data set to plot figure 1, Panel B, D, F.
Args:
- data1 (pd.DataFrame): the original data set
- cols (list): a list of column names ["agus", "bct", "bcg"]
Returns:
- df_fig1_contr (pd.DataFrame): a data set for plotting panels with co... | 5eef05c567159a623fdaaafa5a5707c48c7fe7fa | 3,644,109 |
import ctypes
def GetEffectiveRightsFromAclW(acl, sid):
"""
Takes a SID instead of a trustee!
"""
_GetEffectiveRightsFromAclW = windll.advapi32.GetEffectiveRightsFromAclW
_GetEffectiveRightsFromAclW.argtypes = [PVOID, PTRUSTEE_W, PDWORD] #[HANDLE, SE_OBJECT_TYPE, DWORD, PSID, PSID, PACL, PACL, PSECURITY_DESCRIPT... | 3edb0080a98a7d9d0d040914435c76cd20f30e0a | 3,644,110 |
def store(mnemonic, opcode):
""" Create a store instruction """
ra = Operand("ra", Or1kRegister, read=True)
rb = Operand("rb", Or1kRegister, read=True)
imm = Operand("imm", int)
syntax = Syntax(["l", ".", mnemonic, " ", imm, "(", ra, ")", ",", " ", rb])
patterns = {"opcode": opcode, "ra": ra, "r... | c9d1d7376b5c73eed87b5c3a7438cc54ecab9ad2 | 3,644,111 |
import ctypes
def hlmlDeviceGetPowerUsage(device: hlml_t.HLML_DEVICE.TYPE) -> int:
""" Retrieves power usage for the device in mW
Parameters:
device (HLML_DEVICE.TYPE) - The handle for a habana device.
Returns:
power (int) - The given device's power usage in mW.
"""
... | ed2d64be06a8e319221b2c3e2017f07a6c16a028 | 3,644,112 |
def usgs_coef_parse(**kwargs):
"""
Combine, parse, and format the provided dataframes
:param kwargs: potential arguments include:
dataframe_list: list of dataframes to concat and format
args: dictionary, used to run flowbyactivity.py ('year' and 'source')
:return: d... | 9cfa29cc5390717fd4a36360dcdb373614ae7345 | 3,644,113 |
def success_poly_overlap(gt_poly, res_poly, n_frame):
"""
:param gt_poly: [Nx8]
:param result_bb:
:param n_frame:
:return:
"""
thresholds_overlap = np.arange(0, 1.05, 0.05)
success = np.zeros(len(thresholds_overlap))
iou_list = []
for i in range(gt_poly.shape[0]):
iou ... | 3de9e308fd8a29fb7e7ed4a7132ce5157b5794eb | 3,644,114 |
import io
def my_get_size_png(gg, height, width, dpi, limitsize):
"""
Get actual size of ggplot image saved (with bbox_inches="tight")
"""
buf = io.BytesIO()
gg.save(buf, format= "png", height = height, width = width,
dpi=dpi, units = "in", limitsize = limitsize,verbose=False,
... | fe6417f35480048b70f25bfab97978515fd7d7d1 | 3,644,115 |
def getRnnGenerator(vocab_size,hidden_dim,input_dim=512):
"""
"Apply" the RNN to the input x
For initializing the network, the vocab size needs to be known
Default of the hidden layer is set tot 512 like Karpathy
"""
generator = SequenceGenerator(
Readout(readout_dim = vocab_size,
... | b1c033da42a0079e8c539fd908b715b8e6cb076f | 3,644,116 |
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b... | 66c6b3e282cfdf60819d5df2d48cdea31484a4f1 | 3,644,117 |
import subprocess
def get_length(filename):
"""
Get the length of a specific file with ffrobe from the ffmpeg library
:param filename: this param is used for the file
:type filename: str
:return: length of the given video file
:rtype: float
"""
# use ffprobe because it is faster then o... | 335e220c14612ea5a5d0a330043b75e4d4d1a050 | 3,644,118 |
import os
def is_File(path):
"""Takes the path of the folder as argument
Returns is the path is a of a Folder or not in bool"""
if os.path.isfile(path):
return True
else:
return False | 63ec104ab50c8644856d980bedf04b101f2730e1 | 3,644,119 |
def get_device_serial_no(instanceId, gwMgmtIp, fwApiKey):
"""
Retrieve the serial number from the FW.
@param gwMgmtIP: The IP address of the FW
@type: ```str```
@param fwApiKey: Api key of the FW
@type: ```str```
@return The serial number of the FW
@rtype: ```str```
"""
serial... | e13d90da032f4084b2c1cafcf4d3a77b189a5d58 | 3,644,120 |
from typing import Optional
import torch
def multilabel_cross_entropy(
x: Tensor,
target: Tensor,
weight: Optional[Tensor] = None,
ignore_index: int = -100,
reduction: str = 'mean'
) -> Tensor:
"""Implements the cross entropy loss for multi-label targets
Args:
x (torch.Tensor[N, K... | 12f1bdb41955fc6ba05b125956cdef40e42ca94c | 3,644,121 |
def dataset_string(dataset):
"""Generate string from dataset"""
data = dataset_data(dataset)
try:
# single value
return fn.VALUE_FORMAT % data
except TypeError:
# array
if dataset.size > 1:
return fn.data_string(data)
# probably a string
return fn.shor... | 25d82bc87ae83599857a6b8d83b671d25339df9f | 3,644,122 |
from typing import Type
from typing import Callable
def create_constant_value_validator(
constant_cls: Type, is_required: bool
) -> Callable[[str], bool]:
"""
Create a validator func that validates a value is one of the valid values.
Parameters
----------
constant_cls: Type
The consta... | d225c4a225a4e24c809ef8cc6d557cf989375542 | 3,644,123 |
import pprint
def process_arguments(arguments):
"""
Process command line arguments to execute VM actions.
Called from cm4.command.command
:param arguments:
"""
result = None
if arguments.get("--debug"):
pp = pprint.PrettyPrinter(indent=4)
print("vm processing arguments")
... | cacb2f4696b19a92fcbad3c98017a81a8fdf0567 | 3,644,124 |
import json
def deliver_hybrid():
"""
Endpoint for submissions intended for dap and legacy systems. POST request requires the submission JSON to be
uploaded as "submission", the zipped transformed artifact as "transformed", and the filename passed in the
query parameters.
"""
logger.info('Proc... | 87bb05f376c1791668bd5e160cc5940377363f64 | 3,644,125 |
from pathlib import Path
import os
def change_path(path, dir="", file="", pre="", post="", ext=""):
"""
Change the path ingredients with the provided directory, filename
prefix, postfix, and extension
:param path:
:param dir: new directory
:param file: filename to replace the filename ... | b629da207f96f4476d6eda3a1c88b1c63f701742 | 3,644,126 |
def midi_to_chroma(pitch):
"""Given a midi pitch (e.g. 60 == C), returns its corresponding
chroma class value. A == 0, A# == 1, ..., G# == 11 """
return ((pitch % 12) + 3) % 12 | 25ef72f78269c3f494ca7431f1291891ddea594a | 3,644,127 |
import re
def _snippet_items(snippet):
"""Return all markdown items in the snippet text.
For this we expect it the snippet to contain *nothing* but a markdown list.
We do not support "indented" list style, only one item per linebreak.
Raises SyntaxError if snippet not in proper format (e.g. contains... | bdeb5b5c5e97ef3a8082b7131d46990de02a59af | 3,644,128 |
def get_collection(*args, **kwargs):
""" Returns event collection schema
:param event_collection: string, the event collection from which schema is to be returned,
if left blank will return schema for all collections
"""
_initialize_client_from_environment()
return _client.get_collection(*args,... | 95698a5c750b2d40caad0f0ddfe9e17a8354be03 | 3,644,129 |
def get_tf_generator(data_source: extr.PymiaDatasource):
"""Returns a generator that wraps :class:`.PymiaDatasource` for the tensorflow data handling.
The returned generator can be used with `tf.data.Dataset.from_generator
<https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator>`_ in or... | 2b786b111c2e2b17c3ee2887f93aff02de63f369 | 3,644,130 |
def is_mechanical_ventilation_heat_recovery_active(bpr, tsd, t):
"""
Control of activity of heat exchanger of mechanical ventilation system
Author: Gabriel Happle
Date: APR 2017
:param bpr: Building Properties
:type bpr: BuildingPropertiesRow
:param tsd: Time series data of buildin... | 626e24da9f0676be27e15a4422676034a94e1702 | 3,644,131 |
import aiohttp
async def fetch_user(user_id):
"""
Asynchronous function which performs an API call to retrieve a user from their ID
"""
session = aiohttp.ClientSession()
res = await session.get(url=str(f'{MAIN_URL}/api/user/{user_id}'),
headers=headers)
await sessio... | 725c4f7f89efc242948799c48541a25a2bd17d8c | 3,644,132 |
from typing import List
import requests
from bs4 import BeautifulSoup
def category(category: str) -> List[str]:
"""Get list of emojis in the given category"""
emoji_url = f"https://emojipedia.org/{category}"
page = requests.get(emoji_url)
soup = BeautifulSoup(page.content, 'lxml')
symbols: List... | 61eaff867e9d9c75582f31435a6c22f3b92fd85a | 3,644,133 |
from typing import Optional
def calc_cumulative_bin_metrics(
labels: np.ndarray,
probability_predictions: np.ndarray,
number_bins: int = 10,
decimal_points: Optional[int] = 4) -> pd.DataFrame:
"""Calculates performance metrics for cumulative bins of the predictions.
Args:
labels: An array of ... | c3574c8e74d5c6fd649ea4258b9a8518811210f6 | 3,644,134 |
def rootbeta_cdf(x, alpha, beta_, a, b, bounds=(), root=2.):
"""
Calculates the cumulative density function of the log-beta distribution, i.e.::
F(z; a, b) = I_z(a, b)
where ``z=(ln(x)-ln(a))/(ln(b)-ln(a))`` and ``I_z(a, b)`` is the regularized incomplete beta function.
Parameters
-------... | e0b951c177f288bc89536494485904e1839af7de | 3,644,135 |
def get_scores(treatment, outcome, prediction, p, scoring_range=(0,1), plot_type='all'):
"""Calculate AUC scoring metrics.
Parameters
----------
treatment : array-like
outcome : array-like
prediction : array-like
p : array-like
Treatment policy (probability of treatment for each row... | c59cc98e08cfff6b01eff5c3ff4f74973ababf34 | 3,644,136 |
def get_arima_nemo_pipeline():
""" Function return complex pipeline with the following structure
arima \
linear
nemo |
"""
node_arima = PrimaryNode('arima')
node_nemo = PrimaryNode('exog_ts')
node_final = SecondaryNode('linear', nodes_from=[node_arima, node_nemo])
... | 1ae171d29624ecc615f213f343c4a88c733d3554 | 3,644,137 |
from typing import Counter
import math
def conditional_entropy(x,
y,
nan_strategy=REPLACE,
nan_replace_value=DEFAULT_REPLACE_VALUE):
"""
Calculates the conditional entropy of x given y: S(x|y)
Wikipedia: https://en.wikipedia.org/wiki/... | c0a9c943efdd4da1ad2f248ef7eaa2e4b1b7be06 | 3,644,138 |
def peaks_in_time(dat, troughs=False):
"""Find indices of peaks or troughs in data.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data
troughs : bool
if True, will return indices of troughs instead of peaks
Returns
-------
nadarray of i... | acafee26ac6bc236aa68f48fbea5953020faa471 | 3,644,139 |
def read_submod_def(line):
"""Attempt to read SUBMODULE definition line"""
submod_match = SUBMOD_REGEX.match(line)
if submod_match is None:
return None
else:
parent_name = None
name = None
trailing_line = line[submod_match.end(0):].split('!')[0]
trailing_line = tr... | 27ed8d88fdb8fd112b072f50dba00bad783eb9f3 | 3,644,140 |
def predict(model, images, labels=None):
"""Predict.
Parameters
----------
model : tf.keras.Model
Model used to predict labels.
images : List(np.ndarray)
Images to classify.
labels : List(str)
Labels to return.
"""
if type(images) == list:
i... | a6c2261e7fea262fb1372f870ba3096a9faf2a68 | 3,644,141 |
import codecs
import re
def process_span_file(doc, filename):
"""Reads event annotation from filename, and add to doc
:type filename: str
:type doc: nlplingo.text.text_theory.Document
<Event type="CloseAccount">
CloseAccount 0 230
anchor 181 187
CloseAccount/Source 165 170
CloseAccou... | e2ae8f32947a6c99dfba69b0da06adcfffa3fc3c | 3,644,142 |
from typing import Tuple
def mask_frame_around_position(
frame: np.ndarray,
position: Tuple[float, float],
radius: float = 5,
) -> np.ndarray:
"""
Create a circular mask with the given ``radius`` at the given
position and set the frame outside this mask to zero. This is
sometimes required ... | cf616a0193cf9150821ed00c8e20c61a88b64d9e | 3,644,143 |
import numpy as np
def apogeeid_digit(arr):
"""
NAME:
apogeeid_digit
PURPOSE:
Extract digits from apogeeid because its too painful to deal with APOGEE ID in h5py
INPUT:
arr (ndarray): apogee_id
OUTPUT:
apogee_id with digits only (ndarray)
HISTORY:
2017-O... | 48e21ab69c9f733dbf7b612994bfed35b8980424 | 3,644,144 |
def transform_user_weekly_artist_chart(chart):
"""Converts lastfm api weekly artist chart data into neo4j friendly
weekly artist chart data
Args:
chart (dict): lastfm api weekly artist chart
Returns:
list - neo4j friendly artist data
"""
chart = chart['weeklyartistchart']
a... | 1034211f6c21774044d767aeb7861b6aa80b4023 | 3,644,145 |
def plotter(fdict):
""" Go """
pgconn = get_dbconn('isuag')
ctx = get_autoplot_context(fdict, get_description())
threshold = 50
threshold_c = temperature(threshold, 'F').value('C')
hours1 = ctx['hours1']
hours2 = ctx['hours2']
station = ctx['station']
oldstation = XREF[station]
... | f8a412065700ab111f5bf846938721aa397803b3 | 3,644,146 |
def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... | c3293fa36e32d2ebea610a88a6e29ba47906ab7b | 3,644,147 |
import pandas
import numpy
import tqdm
import torch
def extract_peaks(peaks, sequences, signals, controls=None, chroms=None,
in_window=2114, out_window=1000, max_jitter=128, min_counts=None,
max_counts=None, verbose=False):
"""Extract sequences and signals at coordinates from a peak file.
This function will tak... | f3a3696f2e31b7b91384df50dd0374c2e4e46443 | 3,644,148 |
import re
import fnmatch
import os
def findfiles(which, where='.'):
"""Returns list of filenames from `where` path matched by 'which'
shell pattern. Matching is case-insensitive.
# findfiles('*.ogg')
"""
# TODO: recursive param with walk() filtering
rule = re.compile(fnmatch.translate(whic... | a19a9684b44c1ec1f668071edb74dd5f1f411e65 | 3,644,149 |
def map_feature(value, f_type):
""" Builds the Tensorflow feature for the given feature information """
if f_type == np.dtype('object'):
return bytes_feature(value)
elif f_type == np.dtype('int'):
return int64_feature(value)
elif f_type == np.dtype('float'):
return float64_featur... | 26416b27737542c8ac6100168775f47b271206a3 | 3,644,150 |
def is_text_area(input):
"""
Template tag to check if input is file
:param input: Input field
:return: True if is file, False if not
"""
return input.field.widget.__class__.__name__ == "Textarea" | 4657a93809e123aaa27ee0a202b33e0383ac23cc | 3,644,151 |
def print_album_list(album_list):
"""Print album list and return the album name choice.
If return is all then all photos on page will be download."""
for i in range(len(album_list)):
print("{}. {} ({} photo(s))".format(
i + 1, album_list[i]['name'], album_list[i]['count']))
choice... | 2a3c4fde9fc56da179ea43c88f966735fc5c7beb | 3,644,152 |
import os
import sys
def dprepb_imaging(vis_input):
"""The DPrepB/C imaging pipeline for visibility data.
Args:
vis_input (array): array of ARL visibility data and parameters.
Returns:
restored: clean image.
"""
# Load the Input Data
# ----------------------------... | 1452d6c1a5ddd5391c68b3ced15f93b77a204489 | 3,644,153 |
import os
import sys
def procure_data(args):
"""Load branches from specified file as needed to calculate
all fit and cut expressions. Then apply cuts and binning, and
return only the processed fit data."""
# look up list of all branches in the specified root file
# determine four-digit number of DRS board used... | da7a05f5a7af8fa6de112a040f880494e3605484 | 3,644,154 |
import os
def after_file_name(file_to_open):
"""
Given a file name return as:
[file_to_open root]_prep.[file-to_open_ending]
Parameters
----------
file_to_open : string
Name of the input file.
Returns
--------
after_file : string
Full path to the (new) file.
... | 8b06b3cabbe8dd388cafc2d9d48b30feb2f6c254 | 3,644,155 |
import struct
def read_bool(data):
"""
Read 1 byte of data as `bool` type.
Parameters
----------
data : io.BufferedReader
File open to read in binary mode
Returns
-------
bool
True or False
"""
s_type = "=%s" % get_type("bool")
return struct.unpack(s_type,... | 9302a3f4831143c44b0a67cfe0f146463e8ba27e | 3,644,156 |
def sectorize(position):
""" Returns a tuple representing the sector for the given `position`.
Parameters
----------
position : tuple of len 3
Returns
-------
sector : tuple of len 3
"""
x, y, z = normalize(position)
x, y, z = x // GameSettings.SECTOR_SIZE, y // GameSettings.S... | 689fc3ee350e5493d037df290c5df05d50621b7e | 3,644,157 |
import random
def add_random_phase_shift(hkl, phases, fshifts=None):
"""
Introduce a random phase shift, at most one unit cell length along each axis.
Parameters
----------
hkl : numpy.ndarray, shape (n_refls, 3)
Miller indices
phases : numpy.ndarray, shape (n_refls,)
phas... | 7739d99b58bec80283a5e49fc2e6eaa6161286ae | 3,644,158 |
import os
def hierarchical_dataset(root, opt, select_data="/", data_type="label", mode="train"):
"""select_data='/' contains all sub-directory of root directory"""
dataset_list = []
dataset_log = f"dataset_root: {root}\t dataset: {select_data[0]}"
print(dataset_log)
dataset_log += "\n"
for ... | 100b2d5b8f8829df4f3545ec2f37c05df4961897 | 3,644,159 |
from typing import get_args
import os
import sys
def main() -> None:
"""Run main entrypoint."""
# Parse command line arguments
get_args()
# Ensure environment tokens are present
try:
SLACK_TOKEN = os.environ["PAGEY_SLACK_TOKEN"]
except KeyError:
print("Error, env variable 'PAG... | e55c513d1123abd236487466d1878bfb7a58e37b | 3,644,160 |
from vistrails.core.packagemanager import get_package_manager
def save_vistrail_bundle_to_zip_xml(save_bundle, filename, vt_save_dir=None, version=None):
"""save_vistrail_bundle_to_zip_xml(save_bundle: SaveBundle, filename: str,
vt_save_dir: str, version: str)
-> (save_bun... | 8027074d485607a789dd5aa1d01be84910199d69 | 3,644,161 |
import itertools
import re
def parse_cluster_file(filename):
"""
Parse the output of the CD-HIT clustering and return a dictionnary of clusters.
In order to parse the list of cluster and sequences, we have to parse the CD-HIT
output file. Following solution is adapted from a small wrapper script
... | d50eaeb926be3a7b8d1139c82142e4a1b595c1a0 | 3,644,162 |
def app(par=None):
"""
Return the Miniweb object instance.
:param par: Dictionary with configuration parameters. (optional parameter)
:return: Miniweb object instance.
"""
return Miniweb.get_instance(par) | 3d2b0d1a9fd87e9e5c26ea9a141e40fbe342b764 | 3,644,163 |
def openTopics():
"""Opens topics file
:return: list of topics
"""
topicsFile = 'topics'
with open(topicsFile) as f:
topics = f.read().split()
return topics | e6d43ff6717122532a71355b71134d6f78f9db85 | 3,644,164 |
from django.forms.boundfield import BoundField
from django.utils.inspect import func_supports_parameter, func_accepts_kwargs
def fix_behaviour_widget_render_forced_renderer(utils):
"""
Restore the behaviour where the "renderer" parameter of Widget.render() may not be supported by subclasses.
"""
orig... | 7d55ecc18fae91af221b806448fa30203fdd9cd4 | 3,644,165 |
from typing import List
def split_blocks(blocks:List[Block], ncells_per_block:int,direction:Direction=None):
"""Split blocks is used to divide an array of blocks based on number of cells per block. This code maintains the greatest common denominator of the parent block. Number of cells per block is simply an esti... | e7ebf6189b3f140b006d74846c4979058023784a | 3,644,166 |
def get_entry_details(db_path, entry_id):
"""Get all information about an entry in database.
Args:
db_path: path to database file
entry_id: string
Return:
out: dictionary
"""
s = connect_database(db_path)
# find entry
try:
sim = s.query(Main).filter(Main.... | 7a4023fa32a0e41cf3440bcd8fd2140ce88b8c33 | 3,644,167 |
import bisect
def pose_interp(poses, timestamps_in, timestamps_out, r_interp='slerp'):
"""
:param poses: N x 7, (t,q)
:param timestamps: (N,)
:param t: (K,)
:return: (K,)
"""
# assert t_interp in ['linear', 'spline']
assert r_interp in ['slerp', 'squad']
assert len(pos... | cc8e49b6bab918c6887e37973d09469fcddc298d | 3,644,168 |
from datetime import datetime
def checklist_saved_action(report_id):
"""
View saved report
"""
report = Report.query.filter_by(id=report_id).first()
return render_template(
'checklist_saved.html',
uid=str(report.id),
save_date=datetime.now(),
report=report,
... | 302bc174ffe0ed7d3180b2a59c5212b3a38e7eaf | 3,644,169 |
def trilinear_memory_efficient(a, b, d, use_activation=False):
"""W1a + W2b + aW3b."""
n = tf.shape(a)[0]
len_a = tf.shape(a)[1]
len_b = tf.shape(b)[1]
w1 = tf.get_variable('w1', shape=[d, 1], dtype=tf.float32)
w2 = tf.get_variable('w2', shape=[d, 1], dtype=tf.float32)
w3 = tf.get_variable('w3', shape=[... | d6ed8cc216019987674b86ef36377a6af45a6702 | 3,644,170 |
def private_questions_get_unique_code(assignment_id: str):
"""
Get all questions for the given assignment.
:param assignment_id:
:return:
"""
# Try to find assignment
assignment: Assignment = Assignment.query.filter(
Assignment.id == assignment_id
).first()
# Verify that t... | 1c94404168ac659e9ee3c45b3ecf7c2c398d1cca | 3,644,171 |
def make_ngram(tokenised_corpus, n_gram=2, threshold=10):
"""Extract bigrams from tokenised corpus
Args:
tokenised_corpus (list): List of tokenised corpus
n_gram (int): maximum length of n-grams. Defaults to 2 (bigrams)
threshold (int): min number of n-gram occurrences before inclusion
... | 8897456e9da4cd3c0f1c3f055b43e7d27c7261d8 | 3,644,172 |
def bw_estimate(samples):
"""Computes Abraham's bandwidth heuristic."""
sigma = np.std(samples)
cand = ((4 * sigma**5.0) / (3.0 * len(samples)))**(1.0 / 5.0)
if cand < 1e-7:
return 1.0
return cand | 44629f9e774d07f7c55a5a77dcb7b06ae38a964b | 3,644,173 |
def process_coins():
"""calculate the amount of money paid based on the coins entered"""
number_of_quarters = int(input("How many quarters? "))
number_of_dimes = int(input("How many dimes? "))
number_of_nickels = int(input("How many nickels? "))
number_of_pennies = int(input("How many pennies? "))
... | 6a26ad161720554079a76f6bdadbbf9555d6b82d | 3,644,174 |
def getLastSegyTraceHeader(SH,THN='cdp',data='none', bheadSize = 3600, endian='>'): # added by A Squelch
"""
getLastSegyTraceHeader(SH,TraceHeaderName)
"""
bps=getBytePerSample(SH)
if (data=='none'):
data = open(SH["filename"]).read()
#... | 19de6339bcc3ec63b0e33007f51fa50ddb619449 | 3,644,175 |
def get_data_url(data_type):
"""Gets the latest url from the kff's github data repo for the given data type
data_type: string value representing which url to get from the github api; must be either 'pct_total' or 'pct_share'
"""
data_types_to_strings = {
'pct_total': 'Percent of Total Populatio... | f92520243ee7f952ff69c7c62c315225982a24fe | 3,644,176 |
def kl(p, q):
"""Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=float, shape=n
Discrete probability distributions.
"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.where(p != 0, ... | 06b6283ea83a729f9c374dabbe1c1a94a8ed8480 | 3,644,177 |
import torch
def get_loaders(opt):
""" Make dataloaders for train and validation sets
"""
# train loader
opt.mean = get_mean(opt.norm_value, dataset=opt.mean_dataset)
# opt.std = get_std()
if opt.no_mean_norm and not opt.std_norm:
norm_method = transforms.Normalize([0, 0, 0], [1, 1, 1])
elif not opt.std_norm... | d7a166a477c535a60846e05598dd19bbe84062be | 3,644,178 |
def trapezoidal(f, a, b, n):
"""Trapezoidal integration via iteration."""
h = (b-a)/float(n)
I = f(a) + f(b)
for k in xrange(1, n, 1):
x = a + k*h
I += 2*f(x)
I *= h/2
return I | f2887a3b0d1732f322dca52d0d869c1063e08c22 | 3,644,179 |
def writetree(tree, sent, key, fmt, comment=None, morphology=None,
sentid=False):
"""Convert a tree to a string representation in the given treebank format.
:param tree: should have indices as terminals
:param sent: contains the words corresponding to the indices in ``tree``
:param key: an identifier for this tr... | cf8181596a4882ae18a8adcd0411e1c4e2ee8a33 | 3,644,180 |
import struct
def xor_string(hash1, hash2, hash_size):
"""Encrypt/Decrypt function used for password encryption in
authentication, using a simple XOR.
Args:
hash1 (str): The first hash.
hash2 (str): The second hash.
Returns:
str: A string with the xor applied.
"""
xor... | 4efc263a0ff9fb05b0ee7cb7b7b3fdd4c8c0c2ec | 3,644,181 |
def create_secret_key(string):
"""
:param string: A string that will be returned as a md5 hash/hexdigest.
:return: the hexdigest (hash) of the string.
"""
h = md5()
h.update(string.encode('utf-8'))
return h.hexdigest() | eb31e149684074b18fdbc1989ecfc14f21756dea | 3,644,182 |
import base64
def decode_password(base64_string: str) -> str:
"""
Decode a base64 encoded string.
Args:
base64_string: str
The base64 encoded string.
Returns:
str
The decoded string.
"""
base64_bytes = base64_string.encode("ascii")
sample_st... | 0f04617c239fbc740a9b4c9c2d1ae867a52e0c74 | 3,644,183 |
def _generate_overpass_api(endpoint=None):
""" Create and initialise the Overpass API object.
Passing the endpoint argument will override the default
endpoint URL.
"""
# Create API object with default settings
api = overpass.API()
# Change endpoint if desired
if endpoint is not None:
... | 9b8016035e87428286f68622e9a6129bcf818c4a | 3,644,184 |
def to_pascal_case(value):
"""
Converts the value string to PascalCase.
:param value: The value that needs to be converted.
:type value: str
:return: The value in PascalCase.
:rtype: str
"""
return "".join(character for character in value.title() if not character.isspace()) | 138ab9ddf7ca814b50bf8ff0618de03b236535c7 | 3,644,185 |
from typing import Iterable
from typing import Any
from typing import List
def drop(n: int, it: Iterable[Any]) -> List[Any]:
"""
Return a list of N elements drop from the iterable object
Args:
n: Number to drop from the top
it: Iterable object
Examples:
>>> fpsm.drop(3, [1, 2... | 0732bd560f0da0a43f65ee3b5ed46fd3a05e26f5 | 3,644,186 |
def generate_classification_style_dataset(classification='multiclass'):
"""
Dummy data to test models
"""
x_data = np.array([
[1,1,1,0,0,0],
[1,0,1,0,0,0],
[1,1,1,0,0,0],
[0,0,1,1,1,0],
[0,0,1,1,0,0],
[0,0,1,1,1,0]])
if classification=='multiclass':
y_data = np.array([
[1, 0, 0],
[1, 0, 0],
... | 77a65bb3445216a9a21aa30a7c7201983328efce | 3,644,187 |
def c2_get_platform_current_status_display(reference_designator):
"""
Get C2 platform Current Status tab contents, return current_status_display.
Was: #status = _c2_get_instrument_driver_status(instrument['reference_designator'])
"""
start = dt.datetime.now()
timing = False
contents = []
... | f10f5d242a5fd9b4d8aea33166025a73c21486c6 | 3,644,188 |
def getSupportedDatatypes():
"""
Gets the datatypes that are supported by the framework
Returns:
a list of strings of supported datatypes
"""
return router.getSupportedDatatypes() | 635612975c271bdbe22b622787a2d7f823277baa | 3,644,189 |
def run_stacking(named_data, subjects_data, cv=10, alphas=None,
train_sizes=None, n_jobs=None):
"""Run stacking.
Parameters
----------
named_data : list(tuple(str, pandas.DataFrame))
List of tuples (name, data) with name and corresponding features
to be used for predict... | 75b97509097652fdccc444cfd3731ce68b49e992 | 3,644,190 |
def add_random_shadow(img, w_low=0.6, w_high=0.85):
"""
Overlays supplied image with a random shadow poligon
The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high)
"""
cols, rows = (img.shape[0], img.shape[1])
top_y = np.random.random_sample() * rows
... | 3b520312941ffc4b125ce0a777aeb76fecd6b263 | 3,644,191 |
def csv_args(value):
"""Parse a CSV string into a Python list of strings.
Used in command line parsing."""
return map(str, value.split(",")) | b2596180054f835bfe70e3f900caa5b56a7856a6 | 3,644,192 |
def get_tokens():
"""
Returns a tuple of tokens in the format {{site/property}} that will be used to build the dictionary passed into execute
"""
return (HAWQMASTER_PORT, HAWQSTANDBY_ADDRESS) | 4664feb568a3a5599b9da64594d09a034e9aaebb | 3,644,193 |
def projl1_epigraph(center):
"""
Project center=proxq.true_center onto the l1 epigraph. The bound term is
center[0], the coef term is center[1:]
The l1 epigraph is the collection of points $(u,v): \|v\|_1 \leq u$
np.fabs(coef).sum() <= bound.
"""
norm = center[0]
coef = center[1:]
... | d7b8c70f45853eef61322fdb9583c8279780982f | 3,644,194 |
import requests
from datetime import datetime
def crypto_command(text):
""" <ticker> -- Returns current value of a cryptocurrency """
try:
encoded = quote_plus(text)
request = requests.get(API_URL.format(encoded))
request.raise_for_status()
except (requests.exceptions.HTTPError, re... | 0b0757a8b657791204d74b8536be3b6cb5af2ff5 | 3,644,195 |
import torch
def byol_loss_multi_views_func(p: torch.Tensor, z: torch.Tensor,p1: torch.Tensor, z1: torch.Tensor, simplified: bool = True) -> torch.Tensor:
"""Computes BYOL's loss given batch of predicted features p and projected momentum features z.
Args:
p, p1 (torch.Tensor): NxD Tensor containing p... | 705cbe9e62fa1e58da0a1f4087e6090d7b8002b8 | 3,644,196 |
def a_test_model(n_classes=2):
"""
recover model and test data from disk, and test the model
"""
images_test, labels_test, data_num_test = load_test_data_full()
model = load_model(BASE_PATH + 'models/Inception_hemorrhage_model.hdf5')
adam_optimizer = keras.optimizers.Adam(
lr=0.0001,
... | d060f79a149d7659d74ffac316f71d7ef7b63368 | 3,644,197 |
def generate_synchronous_trajectory(initial_state):
"""
Simulate the network starting from a given initial state in the synchronous strategy
:param initial_state: initial state of the network
:return: a trajectory in matrix from, where each row denotes a state
"""
trajectory = [initial_state]
... | 85f452f7665028e29085296820f67cf2e5cdb8bf | 3,644,198 |
import inspect
from textwrap import dedent
import ast
def arg_names(level=2):
"""Try to determine names of the variables given as arguments to the caller
of the caller. This works only for trivial function invocations. Otherwise
either results may be corrupted or exception will be raised.
level: 0 is... | ce5b26747404442bfd017827435e9515c60aace0 | 3,644,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.