content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def lorentzian_sim(xdata, Amp, Width, Center):
"""
Estimates sum of Lorentzian functions where:
Amp = 1 X N lorentzian of amplitudes
Width = 1 X N lorentzian of widths
Center = 1 X N lorentzian of centers
xdata = 1XN indepedent variable
"""
# Convert to arrays (just in case):
Amp =... | 04560cf52c212ea504939b1ad2d65dd516176cd4 | 3,637,501 |
def convertASTtoThreeAddrForm(ast):
"""Convert an AST to a three address form.
Three address form is (op, reg1, reg2, reg3), where reg1 is the
destination of the result of the instruction.
I suppose this should be called three register form, but three
address form is found in compiler theory.
... | 17bcd628b2b6feb916cdfaea2f6a210f47afa7bf | 3,637,502 |
def aggregate_corrupt_metrics(metrics,
corruption_types,
max_intensity,
alexnet_errors_path=None,
fine_metrics=False):
"""Aggregates metrics across intensities and corruption types."""
results = {... | 3857eae3bf2260fb80c80ff7c7c77770a1ea67ce | 3,637,503 |
def lc_reverse_integer(n):
"""
Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could
only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your
function returns 0 when the reversed integer over... | eff1054873ef0e77a82e34b7cf7af51d42f27d6c | 3,637,504 |
def hard_swish(x_tens: Tensor, inplace: bool = False):
"""
| Hardswish layer implementation:
| 0 for x <= -3
| x for x >= 3
| x * (x + 3) / 6 otherwise
More information can be found in the paper
`here <https://arxiv.org/abs/1905.02244>`__.
:param x_tens: the input tensor to pe... | 29b59d24ce321ac3f08aa72d3c9175b7453d6977 | 3,637,505 |
def get_buttons():
""" renders the ok and cancel buttons. Called from get_body() """
# this is going to be what we actually do when someone clicks the button
def ok_button_callback(button):
raise ExitPasterDemo(exit_token='ok')
# leading spaces to center it....seems like there should be a bet... | 87a44506d95d4cb91ee10a9fd140e6a18e64d2e8 | 3,637,506 |
def dist_weights(distfile, weight_type, ids, cutoff, inverse=False):
"""
Returns a distance-based weights object using user-defined options
Parameters
----------
distfile: string, a path to distance csv file
weighttype: string, either 'threshold' or 'knn'
ids: a numpy array of id values... | 1e9e5743933f15de89ac768cea268a52842db9e0 | 3,637,507 |
def alias_phased_obs_with_phase(x, y, start, end):
"""
:param x: a list containing phases
:param y: a list containing observations
:param start: start phase
:param end: end phase
:return: aliased phases and observations
"""
x = [float(n) for n in x]
y = [float(n) for n in y]
if... | 4b9bd3507180d2e7cd2c9957e1c2ea4ce3e17cb6 | 3,637,509 |
import webbrowser
import time
def create_storage_account(subscription: str, resource_group: str, name: str) -> None:
"""Creates an Azure storage account. Also adds upload access, as well
as possibility to list/generate access keys, to the user creating it
(i.e. the currently logged in user).
Note tha... | c6b58f6b2b0e3d2a980fff90df4cb54d99151536 | 3,637,510 |
import platform
def get_os():
"""
Checks the OS of the system running and alters the directory structure accordingly
:return: The directory location of the Wordlists folder
"""
if platform.system() == "Windows":
wordlist_dir = "Wordlists\\"
else:
wordlist_dir = "Wordlists/"
... | 6f4a6f70505b1512987e75a069a960b136f66d97 | 3,637,511 |
def _try_warp(image, transform_, large_warp_dim, dsize, max_dsize, new_origin,
flags, borderMode, borderValue):
"""
Helper for warp_affine
"""
if large_warp_dim == 'auto':
# this is as close as we can get to actually discovering SHRT_MAX since
# it's not introspectable thro... | 8634aa11c5b26a581f80643bc4a22d1456d29c3d | 3,637,512 |
from datetime import datetime
from typing import Any
import requests
import json
def read_leaderboard(
*,
db: Session = Depends(deps.get_db),
rank_type: schemas.RankType,
skip: int = None,
limit: int = 10,
min_studied: int = 10,
deck_id: int = None,
date... | bbb4b8dfc9223aa982a419596b6f9391c1f600aa | 3,637,513 |
from essentia import array
import essentia.standard as ess
def getMultiFeatureOnsets(XAudio, Fs, hopSize):
"""
Call Essentia's implemtation of multi feature
beat tracking
:param XAudio: Numpy array of raw audio samples
:param Fs: Sample rate
:param hopSize: Hop size of each onset function valu... | 4fefeeb2e87a2c32676d7f3c42ca8c426c15ba79 | 3,637,514 |
def check_derivation(derivation, premises, conclusion):
"""Checks if a derivation is ok. If it is, returns an empty list, otherwise returns [step, error]
Does not check if the conclusion and premises are ok, for that there is another function"""
for step in sorted(derivation):
try:
# ... | 67c15ae26ee399e95808495845c260ca55808532 | 3,637,515 |
def __trunc__(self,l) :
"""Return a bitstring formed by truncating self to length |l|; if l < 0, from left"""
if not isint(l) :
raise IndexError('length not an integer');
if l < 0 :
B = self._B;
if self._l <= max(B,-l) :
return __itrunc__(type(self)(self),l);
s = type(self)();
if -l <= B... | 52dbe55e16aa32a36a83ef5567768fcde2babe9e | 3,637,516 |
def version_list_url(content):
"""Returns a URL to list of content model versions,
filtered by `content`'s grouper
"""
versionable = _cms_extension().versionables_by_content[content.__class__]
return _version_list_url(
versionable, **versionable.grouping_values(content, relation_suffix=False... | adce83b018b79f9b75eeb1f359cc8ec3a6633756 | 3,637,518 |
def as_ops(xs):
"""
Converts an iterable of values to a tuple of Ops using as_op.
Arguments:
xs: An iterable of values.
Returns:
A tuple of Ops.
"""
return tuple(as_op(x) for x in xs) | a47d82ca27655e02cd5ee45aa787d0d42272da63 | 3,637,519 |
def send_neighbors():
"""
The node sends its neighbors to the requesting node.
:return: <json> This node's neighbors.
"""
bc_nodes_mutex.acquire()
neighbors = blockchain.nodes
neighbors_dict = {}
for i, node in enumerate(neighbors):
neighbors_dict[i] = node
bc_nodes_mutex.r... | 3155f102e3af00be52c5312a9ce4c57fee06afe3 | 3,637,520 |
from typing import Optional
def get_db_home(db_home_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDbHomeResult:
"""
This data source provides details about a specific Db Home resource in Oracle Cloud Infrastructure Database service.
Gets information... | 43d855888e0e884e637fb5e06eab3b2397758eae | 3,637,521 |
def all_daily_file_paths_for_month(hemisphere, year, month, search_paths):
"""Return a list of all the filenames available for the given year and month.
"""
start_date = dt.date(year, month, 1)
end_date = dt.date(year, month, monthrange(year, month)[1])
return daily_file_paths_in_date_range(hemisph... | 8bd251b16b3591f704c3d88327c2f577b259a171 | 3,637,523 |
def uniques_only(iterable):
"""
This works only for sequence, but not for all iterable
"""
items = []
for i, n in enumerate(iterable):
if n not in iterable[:i]:
items.append(n)
return items | 159e220be340fc027053b7dbae0d146ae88ceea9 | 3,637,524 |
def str2date(start_time_str):
"""
将到到期日中的大写中文字符转化为标准数字格式
2020年1月1日 --> 2020-1-1
"""
list_s = [i for i in start_time_str]
num_list = []
for index, s in enumerate(list_s):
list_s[index] = CN_NUM.get(s, s)
if isinstance(list_s[index], int):
num_list.append((index, s... | dbe289dbab8721fdb4a2d095b2754dcea61fff1e | 3,637,525 |
import json
def load_omnical_metrics(filename):
"""Load an omnical metrics file.
Parameters
----------
filename : str
Path to an omnical metrics file.
Returns
-------
metrics : dict
A dictionary containing omnical metrics.
Raises
------
IOError:
If th... | ed2082f74904d0101efcd958f0acdb8383adf849 | 3,637,526 |
def tsallis(ion_temp, avg_temp, n):
"""
Non-normalized probability of an ion at ion-temp using a Tsallis distribution
:param ion_temp: temperature of ion (K)
:param avg_temp: average temperature of ions (K)
:param n: average harmonic oscillator level
:return: value
"""
kb = 1.38e-23
... | 4598c5241fc06219938beced4c9d5a4473cf8363 | 3,637,527 |
def nasnet_dual_path_sequential(return_two=True,
first_ordinals=0,
last_ordinals=0,
can_skip_input=False):
"""
NASNet specific dual path sequential container.
Parameters:
----------
return_two : bool, de... | bb148410e1261444586224ea32f981e340b2f1e3 | 3,637,528 |
def _extractRGBFromHex(hexCode):
"""
Extract RGB information from an hexadecimal color code
Parameters:
hexCode (string): an hexadecimal color code
Returns:
A tuple containing Red, Green and Blue information
"""
hexCode = hexCode.lstrip('#') # Remove the '#' from the string
... | e1d67b4f2004e5e2d4a646a3cc5dc49a1e8cd890 | 3,637,529 |
def summarise(indices, fields, **kwargs):
"""Summarise taxonomy."""
summary = {}
meta = kwargs['meta']
try:
if 'taxid' in meta.taxon:
summary.update({'taxid': meta.taxon['taxid']})
names = []
for rank in ('superkingdom', 'kingdom', 'phylum', 'class', 'order', 'family'... | 87f04cb86978e2350f3e535b65a1efa14af77ee8 | 3,637,530 |
def _get_active_user_p_by_date(start_date, end_date, *, seed=None):
"""Generate a trajectory for % daily active users (DAU).
The series is a random walk with drift.
DAU % starts between approx. 20-30% range and then follows random walk
with drift over time. In bad cases, DAU % might halve within a yea... | 6e4df3c7ab5a114aa177563e1898c22dd523576a | 3,637,532 |
def get_unknow_opttrans_attr(path):
"""Utility method that gives a `dict` of unknown optional transitive
path attributes of `path`.
Returns dict: <key> - attribute type code, <value> - unknown path-attr.
"""
path_attrs = path.pathattr_map
unknown_opt_tran_attrs = {}
for _, attr in path_attr... | a3bb4c039ad713a03ad6bdeb2a438530d34af074 | 3,637,533 |
def get_user_partition_groups(course_key, user_partitions, user, partition_dict_key='name'):
"""
Collect group ID for each partition in this course for this user.
Arguments:
course_key (CourseKey)
user_partitions (list[UserPartition])
user (User)
partition_dict_key - i.e. 'i... | 3bb2f76f4a48ce0af745637810903b8086b2fc02 | 3,637,534 |
import requests
from bs4 import BeautifulSoup
import yaml
def getemptybracket(league, testyear):
"""
Generates an empty bracket for the current year. Does not work for any other year due to the url only containing
info for the current year. Prefer to use the output yaml as a guide and correct as needed ea... | b3a81085a600d9bf9b23dd2e46577932aec2cdfe | 3,637,535 |
def kendall_tau(solar_ts, wind_ts):
"""
Compute Kendall's tau correlation between the given solar
and wind timeseries data. Return just the correlation coefficient.
Parameters
----------
solar_ts : ndarray
Solar time-series vector for a single site
wind_ts : ndarray
Wind tim... | e9e256cf4578d6d3a6fa4b835ea5a2eefff6ba2e | 3,637,536 |
from unittest.mock import patch
def test_osx_memdata_with_comma():
"""
test osx memdata method when comma returns
"""
def _cmd_side_effect(cmd):
if "hw.memsize" in cmd:
return "4294967296"
elif "vm.swapusage" in cmd:
return "total = 1024,00M used = 160,75M fr... | a111965caec46a271e6c56582148e56637539b8e | 3,637,538 |
import html
def convert_html_to_dash(el, style=None):
"""[Quite] Conveniently auto-converts whole input HTML
into the corresponding Python Dash HTML components. Uses
Beautiful Soup to auto-parse into required HTML elements
('el') if given str input.
Parameters
----------
el : bs.element.N... | 1bcc95c8cc9d9c2704d5ecc711a78a1c59c3a62a | 3,637,539 |
def _ice_d2gdt2(temp,pres):
"""Calculate ice Gibbs free energy TT-derivative.
Calculate the second derivative of the specific Gibbs free energy of
ice with respect to temperature.
:arg float temp: Temperature in K.
:arg float pres: Pressure in Pa.
:returns: Gibbs free energy derivative... | fcbb08801c2767b16163e9c10fb84916ff0633c7 | 3,637,540 |
def ifht(A, dln, mu, offset=0.0, bias=0.0):
"""ifht multimethod."""
return (Dispatchable(A, np.ndarray),) | d7c597ba10a6d83afffd7e085556c44a263a6b8c | 3,637,541 |
def make_import_names_callback(library_calls, library_addr):
""" Return a callback function used by idaapi.enum_import_names(). """
def callback(ea, name, ordinal):
""" Callback function to retrieve code references to library calls. """
library_calls[name] = []
library_addr[name] = ea
... | 316d51e09ee564fb87ef3eeaeb38c1f6fba94a1d | 3,637,542 |
def unNormalizeData(normalizedData, data_mean, data_std, dimensions_to_ignore, actions, one_hot):
"""Borrowed from SRNN code. Reads a csv file and returns a float32 matrix.
https://github.com/asheshjain399/RNNexp/blob/srnn/structural_rnn/CRFProblems/H3.6m/generateMotionData.py#L12
Args
normalizedData... | 83371c999b78b4843f9d4dc4359b65fa8028b7b5 | 3,637,544 |
def rbf_approx(t, y, centers, eps, C):
"""
function to return vector field of a single point (rbf)
:param t: time (for solve_ivp)
:param y: single point
:param centers: all centers
:param eps: radius of gaussians
:param C: coefficient matrix, found with least squares
:return: derivative ... | f988ba7e1ee5c68c7335fc88cdfffd894c7d845c | 3,637,545 |
def get_preview_fragment(request, descriptor, context):
"""
Returns the HTML returned by the XModule's student_view or author_view (if available),
specified by the descriptor and idx.
"""
module = _load_preview_module(request, descriptor)
preview_view = AUTHOR_VIEW if has_author_view(module) el... | 7f220983f36321b0ad5a4bac76ad4c5118fb66ed | 3,637,546 |
def expr_close(src, size = 5):
"""
Same result as core.morpho.Close(), faster and workable in 32 bit.
"""
close = expr_dilate(src, size)
return expr_erode(close, size) | 25d69ca4c53d08676143d8bfc7a2053dd236fc80 | 3,637,547 |
def recent_records(request):
"""
The landing view, at /.
"""
interval = request.GET.get('interval', 'month')
days = 31
if interval == 'week':
days = 7
recent_records, last_processed = _get_recent_records_range(0, NR_OF_RECENT_RECORDS, days)
context = {
'active': 'home'... | 17a9aa4858c1aa5238468618473141cb6d41c73f | 3,637,548 |
import threading
def create_background_consumers(count, before_start=None, target='run', *args, **kwargs):
"""Create new Consumer instances on background threads, starts them, and
return a tuple ([consumer], [thread]).
:param count: The number of Consumer instances to start.
:param before_start: A ca... | 9870d3b26b84367975323d6f54c6f751297c558d | 3,637,549 |
from datetime import datetime
def linkGen(year):
"""
This function generates the download links based on user input.
"""
current_year = datetime.datetime.now().year
try:
if (int(year) >= 2016) and (int(year) <= int(current_year)):
url = f"http://dev.hsl.fi/citybikes/od-trips-{y... | a45727a61613770db5ee09ee81ee008bba1588a3 | 3,637,550 |
import collections
def factory_dict(value_factory, *args, **kwargs):
"""A dict whose values are computed by `value_factory` when a `__getitem__` key is missing.
Note that values retrieved by any other method will not be lazily computed; eg: via `get`.
:param value_factory:
:type value_factory: A function fr... | f7d4898e62377958cf9d9c353ed12c8d381f042f | 3,637,551 |
def build_or_passthrough(model, obj, signal):
"""Builds the obj on signal, or returns the signal if obj is None."""
return signal if obj is None else model.build(obj, signal) | bee9c8557a89a458cf281b42f968fe588801ed46 | 3,637,552 |
def load_generated_energy_gwh_yearly_irena():
"""Returns xr.DataArray with dims=year and integer as coords, not timestamp!"""
generated_energy_twh = pd.read_csv(
INPUT_DIR / "energy_generation_irena" / "irena-us-generation.csv",
delimiter=";",
names=("year", "generation"),
)
gene... | 98a0b12cef9a214d2254e33c073320374f497a3b | 3,637,553 |
import requests
import json
def warc_url(url):
"""
Search the WARC archived version of the URL
:returns: The WARC URL if found, else None
"""
query = "http://archive.org/wayback/available?url={}".format(url)
response = requests.get(query)
if not response:
raise RuntimeError()
... | afc24876f72915ba07233d5fde667dd0ba964f5a | 3,637,554 |
def check_gpu():
"""
Check if GPUs are available on this machine
"""
try:
cuda.gpus.lst
tf = True
except cuda.CudaSupportError:
tf = False
return tf | f2145426a658185856b99961be9a72c1407707fa | 3,637,555 |
def vm_impl_avg_pool(self):
"""Generate vm_impl function for AvgPool"""
def vm_impl(x):
x = x.asnumpy()
out = vm.avg_pooling(x, self.ksize[-2], self.ksize[-1], self.strides[-2])
return Tensor(out)
return vm_impl | 5e38b84668747a416c8018a0c3b017f637534950 | 3,637,556 |
def plotAllPoints(x,y,z,f,x0,con):
"""
Args:
x- initial x points
y- initial y points
z- initial z points
f- objective function for optimization
x0- flattened initial values to be shoved into objective function
con- list of dicts of constraints to be placed on the ... | c42626d9562b655fac9c4620bea2e9d2eb33dacd | 3,637,558 |
import json
def add_samples(request, product_id):
"""Adds passed samples (by request body) to product with passed id.
"""
parent_product = Product.objects.get(pk=product_id)
for temp_id in request.POST.keys():
if temp_id.startswith("product") is False:
continue
temp_id = ... | 35a982cf4309a727a19aea20bb9a8a392d67292d | 3,637,559 |
def array_to_top_genes(data_array, cluster1, cluster2, is_pvals=False, num_genes=10):
"""
Given a data_array of shape (k, k, genes), this returns two arrays:
genes and values.
"""
data_cluster = data_array[cluster1, cluster2, :]
if is_pvals:
order = data_cluster.argsort()
else:
... | 4f9a0ea673f4ddfa59e7d4fc2249597daef4a260 | 3,637,560 |
def set_attrib(node, key, default):
"""
Parse XML key for a given node
If key does not exist, use default value
"""
return node.attrib[key] if key in node.attrib else default | 0e21b6b0e5a64e90ee856d4b413084a8c395b070 | 3,637,562 |
def nested_hexagon_stretched():
"""A stretched, nested hexagon"""
poly = [
[
(0.86603, -0.5),
(0.86603, 1.5),
(0.0, 2.0),
(-0.86603, 1.5),
(-0.86603, -0.5),
(-0.0, -1.0),
(0.86603, -0.5),
],
[
... | 722a53c74787e9fa8962dd6f8970c96c1ae4c9fd | 3,637,563 |
def vector(math_engine, size, dtype):
"""
"""
if dtype != "float32" and dtype != "int32":
raise ValueError('The `dtype` must be one of {`float32`, `int32`}.')
if size < 1:
raise ValueError('The `size` must be > 0.')
shape = (size, 1, 1, 1, 1, 1, 1)
return Blob(PythonWrapper.ten... | c71ed713140d4a8dc4a9465be3b32b8bfab1e86c | 3,637,564 |
def is_order_exist(context, symbol, side) -> bool:
"""判断同方向订单是否已经存在
:param context:
:param symbol: 交易标的
:param side: 交易方向
:return: bool
"""
uo = context.unfinished_orders
if not uo:
return False
else:
for o in uo:
if o.symbol == symbol and o.side == side:... | 42363c8b3261e500a682b65608c27537b93bcfb1 | 3,637,565 |
import random
import math
def getBestMove(board,selectedFunction = "minmax"):
"""find the best move
Args:
board (board): board object from chess
Returns:
UCI.move: piece movement on the board, i.e. "g2g4"
"""
#Get AI Movement
maxWeight = 0
deplacement = None
#Get... | babb0130f495e15b582e3ea68e07183672927587 | 3,637,566 |
def newline_prep(target_str, do_escape_n=True, do_br_tag=True):
"""
Set up the newlines in a block of text so that they will be processed correctly by Reportlab and logging
:param target_str:
:param do_escape_n:
:param do_br_tag:
:return:
"""
newline_str = get_newline_str(do_escape_n=do_... | 6156438c8bd1f400e37fc6145a6fd558ed6a750b | 3,637,567 |
import warnings
def romb_extrap(sr, der_init, expon, compute_amp = False):
"""
Perform Romberg extrapolation for estimates formed within derivest.
Arguments:
sr : Decrease ratio between successive steps.
der_init : Initial derivative estimates.
expon : L... | 707afc236ec44489c2b8edc06fd07fd54545ae4d | 3,637,568 |
def nativeTextOverline(self):
"""
TOWRITE
:rtype: bool
"""
return self.textOverline() | 69c67bb49446c74f59d880fdcf2ea591f7a4553b | 3,637,570 |
def ca_(arr, l_bound=4000, guard_len=4, noise_len=8):
"""Perform CFAR-CA detection on the input array.
Args:
arr (list or ndarray): Noisy array.
l_bound (int): Additive lower bound of detection threshold.
guard_len (int): Left and right side guard samples for leakage protection.
... | efae86d2740677e77929018b11b4412257870c40 | 3,637,571 |
def create_nodes_encoder(properties):
"""Create an one-hot encoder for node labels."""
nodes_encoder = OneHotEncoder(handle_unknown='ignore')
nodes_labels = list(get_nodes_labels(properties))
nodes_encoder.fit(np.array(nodes_labels).reshape((-1, 1)))
return nodes_encoder | 06a38d25c94562250b9e28ac01d4d376c28d171b | 3,637,572 |
import requests
def get_response(data_type, client_id=None, device_id=None):
"""Request GET from API server based on desired type, return
raw response data
Args:
data_type (str): Type of request, 'client', 'site',
'device', 'scan'
client_id (int): Active client ID ... | 3ed355164995411e7ce017f590b8d7143f1529f5 | 3,637,573 |
def average_pool(inputs, masks, axis=-2, eps=1e-10):
"""
inputs.shape: [A, B, ..., Z, dim]
masks.shape: [A, B, ..., Z]
inputs.shape[:-1] (A, B, ..., Z) must be match masks.shape
"""
assert inputs.shape[:-1] == masks.shape, f"inputs.shape[:-1]({inputs.shape[:-1]}) must be equal to masks.shape({ma... | e6f99634245a4c46e2b5d776afcd73e855da68de | 3,637,574 |
def validate_graph_without_circle(data):
"""
validate if a graph has not cycle
return {
"result": False,
"message": "error message",
"error_data": ["node1_id", "node2_id", "node1_id"]
}
"""
nodes = [data["start_event"]["id"], data["end_event"]["id"]]
nodes += list(d... | dee8c9e2671505dd17de09903c7fe093ca6394cc | 3,637,575 |
import logging
def generate_landsat_ndvi(src_info, no_data_value):
"""Generate Landsat NDVI
Args:
src_info <SourceInfo>: Information about the source data
no_data_value <int>: No data (fill) value to use
Returns:
<numpy.2darray>: Generated NDVI band data
list(<int>): Loca... | 8def6cde518fc4a88c40fddaa7fc1d5f0e7ae36b | 3,637,576 |
def ordinal(string):
"""
Converts an ordinal word to an integer.
Arguments:
- string -- the word to parse.
Returns: an integer if successful; otherwise None.
-----------------------------------------------------------------
"""
try:
# Full word.
if s... | fc744ab90c89019cf0ac22eb4d48e26057d655a0 | 3,637,577 |
def get_tables_stats(dbs=None,tables=None,period=365*86400):
"""
obtains counts and frequencies stats from all data tables from all dbs
"""
dbs = dbs or pta.multi.get_hdbpp_databases()
result = fn.defaultdict(fn.Struct)
date = int(fn.clsub('[^0-9]','',fn.time2str().split()[0]))
if period:
... | f3671bda3dca41b3d2c96e7fee86d9f13f52157e | 3,637,578 |
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
A value of factor 0.0 means only image1 is used.
A value of 1.0 means only image2 is used. A value between 0.0 and
1.0 means we linearly interpolate the pixel values between the two
images. A value greater than 1.0 "ext... | f8cb28b68b809bce6a258f9b6e15c19120a123de | 3,637,579 |
from sklearn.preprocessing import MinMaxScaler
def _minmax_scaler(data, settings):
"""Normalize by min max mode."""
info = settings['model']
frag = settings['id_frag']
features = settings['input_col']
alias = settings.get('output_col', [])
min_r, max_r = settings.get('feature_range', (0, 1))
... | d60a94382b1ceadc99bd46ab4d121fa6c9031641 | 3,637,581 |
def find_by_id(widget_id):
"""
Get a widget by its ulid.
"""
return db.select_single('widgets', {'widget_id':widget_id}, None,
['widget_id', 'widget_name', 'user_id', 'user_email', 'description']) | 2640261d1a702ce029c95ef54d43c825a5478431 | 3,637,582 |
def sainte_lague(preliminary_divisor, data, total_available_seats):
"""Iterative Sainte-Lague procedure which applies core_sainte_lague
Input:
preliminary_divisor (float): Guess for the divisor
data (pd.DateFrame): data processed with divisors (e.g. votes by party)
total_available_seats (int): numb... | 899157982c14ea8adea3decbd0e267211b0f031f | 3,637,583 |
def nonchangingdims(index, ndim, axes, shape=None):
"""nonchanging for particular dimensions
Args:
index(index): object used in slicing (expanded)
ndim(num): dimensions before indexings
axes(array): dimensions for which you want to know the index
shape(Optional(tuple)): dimensio... | 72b348314344123b6aee194293102ec1af35f6a0 | 3,637,584 |
def get_voxels(df, center, config, rot_mat=np.eye(3, 3)):
"""
Generate the 3d grid from coordinate format.
Args:
df (pd.DataFrame):
region to generate grid for.
center (3x3 np.array):
center of the grid.
rot_mat (3x3 np.array):
rotation matrix to a... | f806840209dd4542f91834c761b1b5ccadba175c | 3,637,585 |
def dispatch_factory(msg: Result, **kwargs) -> DispatchCallOutSchema:
"""result_factory Generate result as expected by Daschat
Examples:
from daschat_base.messages import MSGS, msg_factory
msg_factory(MSGS.success)
msg_factory(MSGS.not_logged_in, user="abner")
Args:
msg (Re... | 290519532babe33c3472b7096d7b5631c6383d40 | 3,637,586 |
def local_config(config_path=FIXTURE_CONFIG_PATH):
"""Return an instance of the Config class as a fixture available
for a module."""
return Config(config_path=config_path) | bde94430ec174da3950357d7c5f5203a5eebb5cd | 3,637,587 |
def ln_prior(theta, parameters_to_fit):
"""priors - we only reject obviously wrong models"""
if theta[parameters_to_fit.index("t_E")] < 0.:
return -np.inf
if theta[parameters_to_fit.index("t_star")] < 0.:
return -np.inf
return 0.0 | 8121904e00443a5df76e3477339ca3444219bd3e | 3,637,588 |
def get_axis_letter_aimed_at_child(transform):
"""
Returns the axis letter that is poinitng to the given transform
:param transform: str, name of a transform
:return: str
"""
vector = get_axis_aimed_at_child(transform)
return get_vector_axis_letter(vector) | 22b523583571330030595f8cb787d979692740bc | 3,637,589 |
import math
def computeLatitudePrecision(codeLength):
"""
Compute the latitude precision value for a given code length. Lengths <=
10 have the same precision for latitude and longitude, but lengths > 10
have different precisions due to the grid method having fewer columns than
rows.
"""
... | a9614e6ad68c126333a818f545766ca055ff3165 | 3,637,590 |
def EmptyStateMat(nX,nU,nY):
""" Returns state matrices with proper dimensions, filled with 0 """
Xx = np.zeros((nX,nX)) # Ac
Yx = np.zeros((nY,nX)) # Gc
Xu = np.zeros((nX,nU)) # Xu
Yu = np.zeros((nY,nU)) # Jc
return Xx,Xu,Yx,Yu | 6efce17ae8908b543afe5f7bec45252623f1b99b | 3,637,591 |
def get_market(code):
"""
非常粗糙的通过代码获取交易市场的函数
:param code:
:return:
"""
trans = {
"USD": "US",
"GBP": "UK",
"HKD": "HK",
"CNY": "CN",
"CHF": "CH",
"JPY": "JP",
"EUR": "DE",
"AUD": "AU",
"INR": "IN",
"SGD": "SG",
... | 9e91263bea34033bee83f943eb8ea864a5fd4e5e | 3,637,592 |
import numpy
def rawPlot():
"""Description.
More...
"""
def f(t):
return numpy.exp(-t) * numpy.cos(2*numpy.pi*-t)
plot_x = 495
plot_y = 344
fig = plt.figure(figsize=[plot_x * 0.01, plot_y * 0.01], # Inches.
dpi=100, # 100 dots per inch, so the result... | da2b74c26157da58d7081ebbee764d1c22137303 | 3,637,593 |
def corrupt_single_relationship(triple: tf.Tensor,
all_triples: tf.Tensor,
max_range: int,
name=None):
""" Corrupt the relationship by __sampling from [0, max_range]
:param triple:
:param all_triples:
:param... | efb875764d4530033d9b889685501b1928cfee7d | 3,637,595 |
def save_ipynb_from_py(folder: str, py_filename: str) -> str:
"""Save ipynb file based on python file"""
full_filename = f"{folder}/{py_filename}"
with open(full_filename) as pyfile:
code_lines = [line.replace("\n", "\\n").replace('"', '\\"')
for line in pyfile.readlines()]
... | f2711f0282c2bf40e9da2fec6e372c76038ac04a | 3,637,596 |
def send():
"""
Updates the database with the person who is responding and their busy times.
"""
invitee = request.args.get('invitee')
busy_times = request.args.get('busy_times')
meetcode = flask.session['meetcode']
# Get the record with this meet code.
record = collection.find({"code":... | 40dc5c34e7e638da68e1be8e1169f8167506d11a | 3,637,597 |
import tqdm
def get_plos_article_type_list(article_list=None, directory=None):
"""Makes a list of of all internal PLOS article types in the corpus
Sorts them by frequency of occurrence
:param article_list: list of articles, defaults to None
:param directory: directory of articles, defaults to get_cor... | bc06bb0179e1f8014c59db3835df844908b312ab | 3,637,598 |
def e_coordenada(arg):
"""tuplo -> Boole
Esta funcao verifica se o argumento que recebe e um tuplo do tipo coordenada"""
return isinstance(arg,tuple) and len(arg)==2 and 1<=coordenada_linha(arg)<=4 and 1<=coordenada_coluna(arg)<=4 and isinstance(coordenada_linha(arg),int) and isinstance(coordenada_coluna(ar... | 61dacd4b775b0276220fe99e6fad2b1684fc6f4c | 3,637,599 |
def make_coro(func):
"""Wrap a normal function with a coroutine."""
async def wrapper(*args, **kwargs):
"""Run the normal function."""
return func(*args, **kwargs)
return wrapper | 080e543bc91daee13c012225ba47cd6d054c9ea5 | 3,637,600 |
def eliminate(values):
"""Apply the eliminate strategy to a Sudoku puzzle
The eliminate strategy says that if a box has a value assigned, then none
of the peers of that box can have the same value.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
d... | a8f41f2cf789c1c14a4f70f760731864af65cc80 | 3,637,601 |
def sqlpool_blob_auditing_policy_update(
cmd,
instance,
workspace_name,
resource_group_name,
sql_pool_name,
state=None,
blob_storage_target_state=None,
storage_account=None,
storage_endpoint=None,
storage_account_access_key=None,
st... | 1248e12dae9f6299d86e26d069c22f560856a7e3 | 3,637,602 |
def find_unique_ID(list_of_input_smpls):
"""Attempt to determine a unique ID shared among all input
sample names/IDs, via a largest substring function performed
combinatorially exhaustively pairwise among the input list.
Parameters
----------
list_of_input_smpls : list
Returns
-------
... | c6ab308ac4e03d1ea6d855348a35eb3d58938439 | 3,637,603 |
import math
def cartesian_to_polar(xy):
"""Convert :class:`np.ndarray` `xy` to polar coordinates `r` and `theta`.
Args:
xy (:class:`np.ndarray`): x,y coordinates
Returns:
r, theta (tuple of float): step-length and angle
"""
assert xy.ndim == 2, f"Dimensions are {xy.ndim}, expectin... | c38c4abfbbe3acea6965530d58a1e6a9614a035b | 3,637,604 |
def return_manifold(name):
"""
Returns a list of possible manifolds with name 'name'.
Args:
name: manifold name, str.
Returns:
list of manifolds, name, metrics, retractions
"""
m_list = []
descr_list = []
if name == 'ChoiMatrix':
list_of_metrics = ['euclidean']
... | 5361a8c38069d01c5fc9383e4bc06407f485c0d2 | 3,637,605 |
def change_to_rgba_array(image, dtype="uint8"):
"""Converts an RGB array into RGBA with the alpha value opacity maxed."""
pa = image
if len(pa.shape) == 2:
pa = pa.reshape(list(pa.shape) + [1])
if pa.shape[2] == 1:
pa = pa.repeat(3, axis=2)
if pa.shape[2] == 3:
alphas = 255 *... | 3328ec90e114a7b2c0c2529d126494756f0ce608 | 3,637,606 |
def spacetime_lookup(ra,dec,time=None,buffer=0,print_table=True):
"""
Check for overlapping TESS ovservations for a transient. Uses the Open SNe Catalog for
discovery/max times and coordinates.
------
Inputs
------
ra : float or str
ra of object
dec : float or str
dec of object
time : float
reference t... | efdcfc315c82db808478c302163a146512659f0b | 3,637,607 |
from typing import Union
from datetime import datetime
import time
def utc2local(utc: Union[date, datetime]) -> Union[datetime, date]:
"""Returns the local datetime
Args:
utc: UTC type date or datetime.
Returns:
Local datetime.
"""
epoch = time.mktime(utc.timetuple())
offset ... | 34997f08a8ca7e2156849bb6be346964cc3fadcd | 3,637,608 |
import math
def gvisc(P, T, Z, grav):
"""Function to Calculate Gas Viscosity in cp"""
#P pressure, psia
#T temperature, °R
#Z gas compressibility factor
#grav gas specific gravity
M = 28.964 * grav
x = 3.448 + 986.4 / T + 0.01009 * M
Y = 2.447 - 0.2224... | 5ff1ad63ef581cea0147348104416913c7b77e37 | 3,637,610 |
def get_closest_mesh_normal_to_pt(mesh, pt):
"""
Finds the closest vertex normal to the point.
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
pt: :class: 'compas.geometry.Point'
Returns
----------
:class: 'compas.geometry.Vector'
The closest normal of the ... | 95c9bf82c0c24da27ba8433feb9c5c02cf453713 | 3,637,611 |
def algo_reg_deco(func):
"""
Decorator for making registry of functions
"""
algorithms[str(func.__name__)] = func
return func | 56228dcf557e7de64c75b598fe8d283eb08050ba | 3,637,613 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.