content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def file(base_path, other_path):
"""
Returns a single file
"""
return [[Path(base_path), Path(other_path)]] | 3482041757b38929a58d7173731e84a915225809 | 3,655,455 |
import io
def get_md_resource(file_path):
"""Read the file and parse into an XML tree.
Parameters
----------
file_path : str
Path of the file to read.
Returns
-------
etree.ElementTree
XML tree of the resource on disk.
"""
namespaces = Namespaces().get_namespaces... | 809ea7cef3c9191db9589e0eacbba4016c2e9893 | 3,655,456 |
def fmin_style(sfmin):
"""convert sfmin to style"""
return Struct(
is_valid=good(sfmin.is_valid, True),
has_valid_parameters=good(sfmin.has_valid_parameters, True),
has_accurate_covar=good(sfmin.has_accurate_covar, True),
has_posdef_covar=good(sfmin.has_posdef_covar, True),
... | 44ecba0a25c38a5a61cdba7750a6b8ad53d78c3d | 3,655,457 |
def xirr(cashflows,guess=0.1):
"""
Calculate the Internal Rate of Return of a series of cashflows at irregular intervals.
Arguments
---------
* cashflows: a list object in which each element is a tuple of the form (date, amount), where date is a python datetime.date object and amount is an integer o... | a6adbd091fd5a742c7b27f0816021c2e8499c42f | 3,655,458 |
def check_rt_druid_fields(rt_table_columns, druid_columns):
"""
对比rt的字段,和druid物理表字段的区别
:param rt_table_columns: rt的字段转换为druid中字段后的字段信息
:param druid_columns: druid物理表字段
:return: (append_fields, bad_fields),需变更增加的字段 和 有类型修改的字段
"""
append_fields, bad_fields = [], []
for key, value in rt_tab... | 1c60f49e4316cf78f1396689a55d9a1c71123fe8 | 3,655,459 |
from operator import ne
def is_stuck(a, b, eta):
""" Check if the ricci flow is stuck. """
return ne.evaluate("a-b<eta/50").all() | 53f4bb934cc48d2890289fda3fdb3574d5f6aa4c | 3,655,460 |
from typing import Sized
def stable_seasoal_filter(time_series: Sized, freq: int):
"""
Стабильный сезонный фильтр для ряда.
:param time_series: временной ряд
:param freq: частота расчета среднего значения
:return: значения сезонной составляющей
"""
length = len(time_series)
if length ... | fb4997b637d5229ee7f7a645ce19bbd5fcbab0bc | 3,655,462 |
def make_str_lst_unc_val(id, luv):
"""
make_str_lst_unc_val(id, luv)
Make a formatted string from an ID string and a list of uncertain values.
Input
-----
id A number or a string that will be output as a string.
luv A list of DTSA-II UncertainValue2 items. These will be printed
a... | c65b9bb0c6539e21746a06f7a864acebc2bade03 | 3,655,464 |
def plot_faces(ax, coordinates, meta, st):
"""plot the faces"""
for s in st.faces:
# check that this face isnt in the cut region
def t_param_difference(v1, v2):
return abs(meta["t"][v1] - meta["t"][v2])
if all(all(t_param_difference(v1, v2) < 2 for v2 in s) for v1 in s):
... | a7eef2d209f7c15d8ba232b25d20e4c751075013 | 3,655,465 |
import typing
def translate_null_strings_to_blanks(d: typing.Dict) -> typing.Dict:
"""Map over a dict and translate any null string values into ' '.
Leave everything else as is. This is needed because you cannot add TableCell
objects with only a null string or the client crashes.
:param Dict d: dict ... | 1a6cfe2f8449d042eb01774054cddde08ba56f8c | 3,655,466 |
import json
def HttpResponseRest(request, data):
"""
Return an Http response into the correct output format (JSON, XML or HTML),
according of the request.format parameters.
Format is automatically added when using the
:class:`igdectk.rest.restmiddleware.IGdecTkRestMiddleware` and views decorators... | 56682e808dcb9778ea47218d48fb74612ac44b5d | 3,655,467 |
def build_server_update_fn(model_fn, server_optimizer_fn, server_state_type,
model_weights_type):
"""Builds a `tff.tf_computation` that updates `ServerState`.
Args:
model_fn: A no-arg function that returns a `tff.learning.TrainableModel`.
server_optimizer_fn: A no-arg function th... | c0b8285a5d12c40157172d3b48a49cc5306a567b | 3,655,468 |
def madgraph_tarball_filename(physics):
"""Returns the basename of a MadGraph tarball for the given physics"""
# Madgraph tarball filenames do not have a part number associated with them; overwrite it
return svj_filename("step0_GRIDPACK", Physics(physics, part=None)).replace(
".root", ".tar.xz"
... | a0a8bacb5aed0317b5c0fd8fb3de5382c98e267d | 3,655,469 |
def _mk_cmd(verb, code, payload, dest_id, **kwargs) -> Command:
"""A convenience function, to cope with a change to the Command class."""
return Command.from_attrs(verb, dest_id, code, payload, **kwargs) | afd5804937a55d235fef45358ee12088755f9dc9 | 3,655,470 |
def getobjname(item):
"""return obj name or blank """
try:
objname = item.Name
except BadEPFieldError as e:
objname = ' '
return objname | f8875b6e9c9ed2b76affe39db583c091257865d8 | 3,655,471 |
def process_fire_data(filename=None, fire=None, and_save=False, timezone='Asia/Bangkok', to_drop=True):
""" Add datetime, drop duplicate data and remove uncessary columns.
"""
if filename:
fire = pd.read_csv(filename)
# add datetime
fire = add_datetime_fire(fire, timezone)
# drop dup... | 767bb77db2b3815a5646f185b72727aec74ee8d8 | 3,655,472 |
def create_controllable_source(source, control, loop, sleep):
"""Makes an observable controllable to handle backpressure
This function takes an observable as input makes it controllable by
executing it in a dedicated worker thread. This allows to regulate
the emission of the items independently of the ... | 2092de1aaeace275b2fea2945e8d30f529309874 | 3,655,473 |
def getE5():
"""
Returns the e5
Args:
"""
return E5.get() | 35526332b957628a6aa3fd90f7104731749e10ed | 3,655,474 |
def triangulate(pts_subset):
"""
This function encapsulates the whole triangulation algorithm into four
steps. The function takes as input a list of points. Each point is of the
form [x, y], where x and y are the coordinates of the point.
Step 1) The list of points is split into groups. Each g... | 55e145a44303409a4e1ede7f14e4193c06efd769 | 3,655,475 |
def get_session(region, default_bucket):
"""Gets the sagemaker session based on the region.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
`sagemaker.session.Session instance
"""
boto_session = boto3.S... | 1bfbea7aeb30f33772c1b748580f0776463203a4 | 3,655,476 |
def intp_sc(x, points):
"""
SCurve spline based interpolation
args:
x (list) : t coordinate list
points (list) : xyz coordinate input points
returns:
x (relative coordinate point list)
o (xyz coordinate points list, resplined)
"""
sc = vtk.vtkSCurveSpline(... | 13df2e19c91ff0469ce68467e9e4df36c0e4831b | 3,655,477 |
def backend():
"""Publicly accessible method
for determining the current backend.
# Returns
String, the name of the backend PyEddl is currently using.
# Example
```python
>>> eddl.backend.backend()
'eddl'
```
"""
return _BACKEND | b811dd6a760006e572aa02fc246fdf72ac7e608c | 3,655,478 |
import json
def query_collection_mycollections():
"""
Query Content API Collection with access token.
"""
access_token = request.args.get("access_token", None)
if access_token is not None and access_token != '':
# Construct an Authorization header with the value of 'Bearer <access t... | 98b8a75ea515255fde327d11c959f5e9b6d9ea43 | 3,655,479 |
def xmlbuildmanual() -> __xml_etree:
"""
Returns a empty xml ElementTree obj to build/work with xml data
Assign the output to var
This is using the native xml library via etree shipped with the python standard library.
For more information on the xml.etree api, visit: https://docs.python.org/3... | e08d83aca4b140c2e289b5173e8877e3c3e5fee1 | 3,655,480 |
def graclus_cluster(row, col, weight=None, num_nodes=None):
"""A greedy clustering algorithm of picking an unmarked vertex and matching
it with one its unmarked neighbors (that maximizes its edge weight).
Args:
row (LongTensor): Source nodes.
col (LongTensor): Target nodes.
weight (... | c586ffd325697302a2413e613a75fe4302741af6 | 3,655,481 |
def _get_serve_tf_examples_fn(model, tf_transform_output):
"""Returns a function that parses a serialized tf.Example."""
model.tft_layer = tf_transform_output.transform_features_layer()
@tf.function
def serve_tf_examples_fn(serialized_tf_examples):
"""Returns the output to be used in the serving signature... | 801bfde2b72823b2ba7b8329f080774ca9aa536f | 3,655,482 |
import decimal
def get_profitable_change(day_candle):
""" Get the potential daily profitable price change in pips.
If prices rise enough, we have: close_bid - open_ask (> 0), buy.
If prices fall enough, we have: close_ask - open_bid (< 0), sell.
if prices stay relatively still,... | 94adc63d984e7797590a2dd3eb33c8d98b09c76e | 3,655,483 |
def run_epoch():
"""Runs one epoch and returns reward averaged over test episodes"""
rewards = []
for _ in range(NUM_EPIS_TRAIN):
run_episode(for_training=True)
for _ in range(NUM_EPIS_TEST):
rewards.append(run_episode(for_training=False))
return np.mean(np.array(rewards)) | d9f5e33e00eaeedfdff7ebb4d3a7731d679beff1 | 3,655,485 |
def _max_pool(heat, kernel=3):
"""
NCHW
do max pooling operation
"""
# print("heat.shape: ", heat.shape) # default: torch.Size([1, 1, 152, 272])
pad = (kernel - 1) // 2
h_max = nn.functional.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
# print("h_max.shape: ", h_max.shape... | 68edc979d78ee2fc11f94efd2dfb5e9140762a0e | 3,655,486 |
def getBool(string):
"""
Stub function, set PshellServer.py softlink to PshellServer-full.py for full functionality
"""
return (True) | de7f6a4b124b6a1f6e1b878daf01cc14e5d5eb08 | 3,655,487 |
from typing import Counter
def multi_dists(
continuous,
categorical,
count_cutoff,
summary_type,
ax=None,
stripplot=False,
order="ascending",
newline_counts=False,
xtick_rotation=45,
xtick_ha="right",
seaborn_kwargs={},
stripplot_kwargs={},
):
"""
Compare the di... | 84302dfc359c62c67ef0757ea7c0841e5292b19d | 3,655,488 |
import xdg
def expand_xdg(xdg_var: str, path: str) -> PurePath:
"""Return the value of an XDG variable prepended to path.
This function expands an XDG variable, and then concatenates to it the
given path. The XDG variable name can be passed both uppercase or
lowercase, and either with or without the ... | 13b8885a08c384d29636c5f5070a86e05c30b43a | 3,655,489 |
def follow_index(request):
"""Просмотр подписок"""
users = request.user.follower.all()
paginator = Paginator(users, 3)
page_number = request.GET.get('page')
page = paginator.get_page(page_number)
return render(request, 'recipes/follow_index.html',
{'page': page, 'paginator': pa... | 00851ccffde0e76544e5732d0f651f6e00bc45d4 | 3,655,490 |
def test_drawcounties_cornbelt():
"""draw counties on the map"""
mp = MapPlot(sector="cornbelt", title="Counties", nocaption=True)
mp.drawcounties()
return mp.fig | 8bba5c33c374bf3f4e892bc984b72de22c97e38d | 3,655,491 |
import torch
def atomic_degrees(mol: IndigoObject) -> dict:
"""Get the number of atoms direct neighbors (except implicit hydrogens) in a molecule.
Args:
IndigoObject: molecule object
Returns:
dict: key - feature name, value - torch.tensor of atomic degrees
"""
degrees = []
fo... | 114431622574985bd016276a7a809560c896e1bc | 3,655,492 |
def hotspots(raster, kernel, x='x', y='y'):
"""Identify statistically significant hot spots and cold spots in an input
raster. To be a statistically significant hot spot, a feature will have a
high value and be surrounded by other features with high values as well.
Neighborhood of a feature defined by t... | ab091924bb36576e338c38d752df3f856de331cb | 3,655,493 |
import configparser
import logging
def _read_config(filename):
"""Reads configuration file.
Returns DysonLinkCredentials or None on error.
"""
config = configparser.ConfigParser()
logging.info('Reading "%s"', filename)
try:
config.read(filename)
except configparser.Error as ex:
... | bb1282e94500c026072a0e8d76fdf3dcd68e9062 | 3,655,495 |
def view_share_link(request, token):
"""
Translate a given sharelink to a proposal-detailpage.
:param request:
:param token: sharelink token, which includes the pk of the proposal
:return: proposal detail render
"""
try:
pk = signing.loads(token, max_age=settings.MAXAGESHARELINK)
... | 9d88375f1f3c9c0b94ad2beab4f47ce74ea2464e | 3,655,496 |
from sklearn.pipeline import Pipeline
def create(pdef):
"""Scikit-learn Pipelines objects creation (deprecated).
This function creates a list of sklearn Pipeline objects starting from the
list of list of tuples given in input that could be created using the
adenine.core.define_pipeline module.
P... | 552014c652d7de236ba917592108315acfd9c694 | 3,655,497 |
def pressure_differentiable(altitude):
"""
Computes the pressure at a given altitude with a differentiable model.
Args:
altitude: Geopotential altitude [m]
Returns: Pressure [Pa]
"""
return np.exp(interpolated_log_pressure(altitude)) | a6a9e7dcc38ac855f3ba5c9a117506a87a981217 | 3,655,498 |
def create_optimizer(hparams, global_step, use_tpu=False):
"""Creates a TensorFlow Optimizer.
Args:
hparams: ConfigDict containing the optimizer configuration.
global_step: The global step Tensor.
use_tpu: If True, the returned optimizer is wrapped in a
CrossShardOptimizer.
Returns:
A Tens... | 9ff18644fe513e3d01b297e30538c396546746ab | 3,655,499 |
def compare_dirs_ignore_words(dir1, dir2, ignore_words, ignore_files=None):
"""Same as compare_dirs but ignores lines with words in ignore_words.
"""
return compare_dirs(
dir1,
dir2,
ignore=ignore_files,
function=lambda file1, file2:
compare_text_files_ignore_lines(fi... | 2794027a638a7f775ae559b250a500e28a218e4a | 3,655,500 |
def float_to_wazn(value):
"""Converts a float value to an integer in the WAZN notation.
The float format has a maxium of 6 decimal digits.
:param value: value to convert from float to WAZN notation
:returns: converted value in WAZN notation
"""
return int(Decimal(value) / MICRO_WAZN) | 6bf10dfbefe51b2a785c4d0504e446662487b485 | 3,655,501 |
import time
def timer(func):
""" Decorator to measure execution time """
def wrapper(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
elapsed = time.time() - start_time
print('{:s}: {:4f} sec'.format(func.__name__, elapsed))
return ret
retu... | 0f6a8a4dc8eff1aa49efaf5d26ac46e0cc483b3e | 3,655,502 |
import uuid
def _create_keyword_plan_campaign(client, customer_id, keyword_plan):
"""Adds a keyword plan campaign to the given keyword plan.
Args:
client: An initialized instance of GoogleAdsClient
customer_id: A str of the customer_id to use in requests.
keyword_plan: A str of the ke... | b6ce2ee2ec40e1192461c41941f18fe04f901344 | 3,655,503 |
def word2vec(sentences, year):
"""
Creates a word2vec model.
@param sentences: list of list of words in each sentence (title + abstract)
@return word2vec model
"""
print("Creating word2vec model")
model = Word2Vec(sentences, size=500, window=5, min_count=1, workers=4)
model.save(f"models... | 745bd15f4c0cea5b9417fd0562625426bd5cd293 | 3,655,504 |
def true_rjust(string, width, fillchar=' '):
""" Justify the string to the right, using printable length as the width. """
return fillchar * (width - true_len(string)) + string | 53a8cbfd049c21821b64e1a218c9af2a7b4c8b7d | 3,655,505 |
def threshold_generator_with_values(values, duration, num_classes):
"""
Args:
values: A Tensor with shape (-1,)
Values = strictly positive, float thresholds.
duration: An int.
num_classes: An int.
Returns:
thresh: A Tensor with shape
(len(list_values... | 58aa50e08beaba8f299af3ec9dfeb3de652e6471 | 3,655,506 |
def is_hermitian(mx, tol=1e-9):
"""
Test whether mx is a hermitian matrix.
Parameters
----------
mx : numpy array
Matrix to test.
tol : float, optional
Tolerance on absolute magitude of elements.
Returns
-------
bool
True if mx is hermitian, otherwise False... | 31e9a1faff21707b2fc44c7824bb05fc85967f00 | 3,655,507 |
def argmax(a, b, axis=1, init_value=-1, name="argmax"):
""" sort in axis with ascending order """
assert axis<len(a.shape) and len(a.shape)<=2, "invalid axis"
assert b.shape[axis] == 2, "shape mismatch"
size = a.shape[axis] # save max arg index
def argmax2d(A, B):
init = hcl.compute((2,... | 3626126cae255498cab854f8b898a7d0f730b20d | 3,655,508 |
def morphology(src, operation="open", kernel_shape=(3, 3), kernel_type="ones"):
"""Dynamic calls different morphological operations
("open", "close", "dilate" and "erode") with the given parameters
Arguments:
src (numpy.ndarray) : source image of shape (rows, cols)
operation (str, optional)... | f8258616f07b9dd0089d323d9237483c05b86c2e | 3,655,509 |
def msd(traj, mpp, fps, max_lagtime=100, detail=False, pos_columns=None):
"""Compute the mean displacement and mean squared displacement of one
trajectory over a range of time intervals.
Parameters
----------
traj : DataFrame with one trajectory, including columns frame, x, and y
mpp : microns ... | 4511eb3e0d69ab5581635ba93db6dedfd387eb84 | 3,655,510 |
import random
def build_rnd_graph(golden, rel, seed=None):
"""Build a random graph for testing."""
def add_word(word):
if word not in words:
words.add(word)
def add_edge(rel, word1, word2):
data.append((rel, word1, word2))
random.seed(seed)
m, _ = golden.shape
wo... | 46eacb5a51cf94ee27ed33757887afca4cc153ff | 3,655,511 |
from typing import Union
import pathlib
from typing import IO
from typing import AnyStr
import inspect
import pandas
def _make_parser_func(sep):
"""
Create a parser function from the given sep.
Parameters
----------
sep: str
The separator default to use for the parser.
Returns
--... | 318edb7e761e163c828878a1c186edc535d824a1 | 3,655,512 |
def dcm_to_pil_image_gray(file_path):
"""Read a DICOM file and return it as a gray scale PIL image"""
ds = dcmread(file_path)
# Get the image after apply clahe
img_filtered = Image.fromarray(apply_clahe(ds.pixel_array).astype("uint8"))
# Normalize original image to the interval [0, 255]
img = cv... | c85b149dd1d02f24e60411ffb6d0dccfb1afd949 | 3,655,514 |
from typing import Any
def get_object_unique_name(obj: Any) -> str:
"""Return a unique string associated with the given object.
That string is constructed as follows: <object class name>_<object_hex_id>
"""
return f"{type(obj).__name__}_{hex(id(obj))}" | f817abf636673f7ef6704cbe0ff5a7a2b897a3f6 | 3,655,515 |
def create_voting_dict():
"""
Input: a list of strings. Each string represents the voting record of a senator.
The string consists of
- the senator's last name,
- a letter indicating the senator's party,
- a couple of letters indicating the senator's home ... | 4a662c110b88ae92ea548da6caa15b01b82f1cf2 | 3,655,516 |
def areFriends(profile1, profile2):
"""Checks wether profile1 is connected to profile2 and profile2 is connected to profile1"""
def check(p1, p2):
if p1.isServiceIdentity:
fsic = get_friend_serviceidentity_connection(p2.user, p1.user)
return fsic is not None and not fsic.deleted
... | 89eb04d0b8cce054e75d26d194d3f88f9b5970db | 3,655,517 |
def filter_dict(regex_dict, request_keys):
"""
filter regular expression dictionary by request_keys
:param regex_dict: a dictionary of regular expressions that
follows the following format:
{
"name": "sigma_aldrich",
"regexes": ... | fb503f0d4df0a7965c276907b7a9e43bd14f9cac | 3,655,518 |
import six
def calculate_partition_movement(prev_assignment, curr_assignment):
"""Calculate the partition movements from initial to current assignment.
Algorithm:
For each partition in initial assignment
# If replica set different in current assignment:
# Get Difference in ... | 180a47944523f0c814748d1918935e47d9a7ada4 | 3,655,519 |
from typing import List
from typing import Union
import torch
from typing import Sequence
def correct_crop_centers(
centers: List[Union[int, torch.Tensor]],
spatial_size: Union[Sequence[int], int],
label_spatial_shape: Sequence[int],
) -> List[int]:
"""
Utility to correct the crop center if the cr... | d8a28d464a4d0fcd8c1ad8ed0b790713aaa878e2 | 3,655,520 |
def contrast_normalize(data, centered=False):
"""Normalizes image data to have variance of 1
Parameters
----------
data : array-like
data to be normalized
centered : boolean
When False (the default), centers the data first
Returns
-------
data : array-like
norm... | e85e5488e0c69bcf0233c03f3595a336b3ad7921 | 3,655,521 |
def create_gdrive_folders(website_short_id: str) -> bool:
"""Create gdrive folder for website if it doesn't already exist"""
folder_created = False
service = get_drive_service()
base_query = "mimeType = 'application/vnd.google-apps.folder' and not trashed and "
query = f"{base_query}name = '{website... | 21928843c47bbc3b175b65a7268eb63e0bec1275 | 3,655,522 |
def filter_for_recognized_pumas(df):
"""Written for income restricted indicator but can be used for many other
indicators that have rows by puma but include some non-PUMA rows. Sometimes
we set nrows in read csv/excel but this approach is more flexible"""
return df[df["puma"].isin(get_all_NYC_PUMAs())] | fe3c608495603f74300dc79a4e50d185d87ca799 | 3,655,523 |
def school_booking_cancel(request, pk_booking):
"""Render the school booking cancel page for a school representative.
:param request: httprequest received
:type request: HttpRequest
:param pk_booking: Primary Key of a Booking
:type pk_booking: int
:return: Return a HttpResponse whose content is... | 1b0e09119ba453efdf486e11a57d92c508a497ff | 3,655,525 |
def bandpass_filter(df, spiky_var):
"""Detect outliers according to a passband filter specific to each variable.
Parameters
----------
df: pandas DataFrame that contains the spiky variable
spiky_var: string that designate the spiky variable
Returns
-------
id_outlier: index of outliers... | a20e3861f04212fe8b3e44d278da9ed58d545d1c | 3,655,526 |
def load_energy():
"""Loads the energy file, skipping all useluss information and returns it as a dataframe"""
energy = pd.read_excel("Energy Indicators.xls", skiprows=17, header=0,
skip_footer=53-15, na_values="...", usecols=[2,3,4,5])
# Rename columns
energy.columns = ["Coun... | 10c9e638398d74eed57ccab414cac5577623c6cf | 3,655,527 |
import re
def list_list_to_string(list_lists,data_delimiter=None,row_formatter_string=None,line_begin=None,line_end=None):
"""Repeatedly calls list to string on each element of a list and string adds the result
. ie coverts a list of lists to a string. If line end is None the value defaults to "\n", for no se... | d1e69d21205fcc21e186a8dd160c1817fb1f0f68 | 3,655,528 |
def sampen(L, m):
"""
"""
N = len(L)
r = (np.std(L) * .2)
B = 0.0
A = 0.0
# Split time series and save all templates of length m
xmi = np.array([L[i: i + m] for i in range(N - m)])
xmj = np.array([L[i: i + m] for i in range(N - m + 1)])
# Save all matches minus the self-match,... | 0a97e8dd8c4edbf2ec4cbbdff3241af7de3f2a66 | 3,655,530 |
from typing import Union
def total(score: Union[int, RevisedResult]) -> int:
"""
Return the total number of successes (negative for a botch).
If `score` is an integer (from a 1st/2nd ed. die from :func:`standard` or
:func:`special`) then it is returned unmodified.
If `score` is a :class:`Revised... | 849b757875ea461b0ea6bf4a63270e6f5fbac28c | 3,655,531 |
def rbbox_overlaps_v3(bboxes1, bboxes2, mode='iou', is_aligned=False):
"""Calculate overlap between two set of bboxes.
Args:
bboxes1 (torch.Tensor): shape (B, m, 5) in <cx, cy, w, h, a> format
or empty.
bboxes2 (torch.Tensor): shape (B, n, 5) in <cx, cy, w, h, a> format
... | cdd414b02ac08c5a8bc494ed7319942e26bc5f02 | 3,655,533 |
import warnings
def get_target_compute_version(target=None):
"""Utility function to get compute capability of compilation target.
Looks for the arch in three different places, first in the target attributes, then the global
scope, and finally the GPU device (if it exists).
Parameters
----------
... | ad55cbb81fb74521175ea6fbdcba54cc14a409cb | 3,655,534 |
def get_poet_intro_by_id(uid):
"""
get poet intro by id
:param uid:
:return:
"""
return Poet.get_poet_by_id(uid) | d6fd84bd150ee8ce72becdb6b27b67d1c21c7a9b | 3,655,535 |
from datetime import datetime
def create_post():
"""Создать пост"""
user = get_user_from_request()
post = Post(
created_date=datetime.datetime.now(),
updated_date=datetime.datetime.now(),
creator=user,
)
json = request.get_json()
url = json["url"]
if Post.get_or_... | 7b8eaf74cda78198d08ca6eac66f1f13a12c4341 | 3,655,536 |
import async_timeout
async def fetch(session, url):
"""Method to fetch data from a url asynchronously
"""
async with async_timeout.timeout(30):
async with session.get(url) as response:
return await response.json() | d8ff22df047fece338dcfe4c6286766a563ff9aa | 3,655,537 |
def recurse_while(predicate, f, *args):
"""
Accumulate value by executing recursively function `f`.
The function `f` is executed with starting arguments. While the
predicate for the result is true, the result is fed into function `f`.
If predicate is never true then starting arguments are returned... | fd3313760c246336519a2e89281cc94a2bee6833 | 3,655,538 |
import timeit
import logging
def construct_lookup_variables(train_pos_users, train_pos_items, num_users):
"""Lookup variables"""
index_bounds = None
sorted_train_pos_items = None
def index_segment(user):
lower, upper = index_bounds[user:user + 2]
items = sorted_train_pos_items[lower:u... | c3e1087cce5a38d681379f30d7c6dee8d1544e60 | 3,655,540 |
def total_allocation_constraint(weight, allocation: float, upper_bound: bool = True):
"""
Used for inequality constraint for the total allocation.
:param weight: np.array
:param allocation: float
:param upper_bound: bool if true the constraint is from above (sum of weights <= allocation) else from b... | b92c4bd18d1c6246ff202987c957a5098fd66ba1 | 3,655,541 |
def sigmoid(x):
""" computes sigmoid of x """
return 1.0/(1.0 + np.exp(-x)) | cd34b4ed9fe08607ea3fec1dce89bee7c34efeb0 | 3,655,542 |
def handle_error(err):
"""Catches errors with processing client requests and returns message"""
code = 500
error = 'Error processing the request'
if isinstance(err, HTTPError):
code = err.code
error = str(err.message)
return jsonify(error=error, code=code), code | d6f9051bab504852720f657d04bc6afa72794047 | 3,655,543 |
from pyunitwizard.kernel import default_form, default_parser
from pyunitwizard import convert as _convert, get_dimensionality as _get_dimensionality
from typing import Dict
def dimensionality(quantity_or_unit: str) -> Dict[str, int]:
""" Returns the dimensionality of the quantity or unit.
Parameters
... | 4c334c6283a57704036c414cfd52f79b875a93fc | 3,655,544 |
import re
def split_prec_rows(df):
"""Split precincts into two rows.
NOTE: Because this creates a copy of the row values, don't rely on total vote counts, just look at percentage.
"""
for idx in df.index:
# look for rows with precincts that need to be split
if re.search('\d{4}/\d{4}'... | 72ba424080b0ff3e04ecc5d248bc85b4f409167c | 3,655,545 |
def socfaker_elasticecsfields_host():
"""
Returns an ECS host dictionary
Returns:
dict: Returns a dictionary of ECS
host fields/properties
"""
if validate_request(request):
return jsonify(str(socfaker.products.elastic.document.fields.host)) | 41a2624eda28eae736398ece87aee2ee2028987c | 3,655,546 |
from textwrap import dedent
def _moog_writer(photosphere, filename, **kwargs):
"""
Writes an :class:`photospheres.photosphere` to file in a MOOG-friendly
format.
:param photosphere:
The photosphere.
:path filename:
The filename to write the photosphere to.
"""
def _get_x... | da5a952e15984aecd914ebcf9381900924fdeff1 | 3,655,547 |
def upcomingSplits(
symbol="",
exactDate="",
token="",
version="stable",
filter="",
format="json",
):
"""This will return all upcoming estimates, dividends, splits for a given symbol or the market. If market is passed for the symbol, IPOs will also be included.
https://iexcloud.io/docs/... | ae21f8c04bf7bf2eacd8b16aa62c9fae7750e042 | 3,655,548 |
def mu_model(u, X, U, k):
"""
Returns the utility of the kth player
Parameters
----------
u
X
U
k
Returns
-------
"""
M = X.T @ X
rewards = M @ u
penalties = u.T @ M @ U[:, :k] * U[:, :k]
return rewards - penalties.sum(axis=1) | 59bce1ce8617f0e11340d1c1ab18315fd81e6925 | 3,655,549 |
def tokenizer_init(model_name):
"""simple wrapper for auto tokenizer"""
tokenizer = AutoTokenizer.from_pretrained(model_name)
return tokenizer | c54accf802fcbcf1479ccb0745266a5182edb73b | 3,655,550 |
def insert_message(nick, message, textDirection):
"""
Insert record
"""
ins = STATE['messages_table'].insert().values(
nick=nick, message=message, textDirection=textDirection)
res = STATE['conn'].execute(ins)
ltr = 1 if textDirection == 'ltr' else 0
rtl = 1 if textDirection == 'rtl'... | 1163fab2342aa5e41b321055bbf75f4c23fbb031 | 3,655,551 |
from typing import Tuple
from typing import Dict
def process_metadata(metadata) -> Tuple[Dict[str, str], Dict[str, str]]:
""" Returns a tuple of valid and invalid metadata values. """
if not metadata:
return {}, {}
valid_values = {}
invalid_values = {}
for m in metadata:
key, valu... | fbd7affaa8743d6c45bb2a02067d737dac990eb4 | 3,655,552 |
def rightOfDeciSeperatorToDeci(a):
"""This function only convert value at the right side of decimal seperator to decimal"""
deciNum = 0
for i in range(len(a)):
deciNum += (int(a[i]))*2**-(i+1)
return deciNum | 14cfd187758836d329ac4778a30167ddece0f2a0 | 3,655,553 |
import torch
def conv(input, weight):
"""
Returns the convolution of input and weight tensors,
where input contains sequential data.
The convolution is along the sequence axis.
input is of size [batchSize, inputDim, seqLength]
"""
output = torch.nn.functional.conv1d(input... | e213be11c423ff63a1ebffda55331298fcf53443 | 3,655,554 |
import torch
def irr_repr(order, alpha, beta, gamma, dtype = None):
"""
irreducible representation of SO3
- compatible with compose and spherical_harmonics
"""
cast_ = cast_torch_tensor(lambda t: t)
dtype = default(dtype, torch.get_default_dtype())
alpha, beta, gamma = map(cast_, (alpha, b... | ff054a05c2d79a4dcfc903116cefdfce4fa56c8f | 3,655,555 |
from typing import List
from typing import Optional
def label_to_span(labels: List[str],
scheme: Optional[str] = 'BIO') -> dict:
"""
convert labels to spans
:param labels: a list of labels
:param scheme: labeling scheme, in ['BIO', 'BILOU'].
:return: labeled spans, a list of tupl... | 01e3a1f3d72f8ec0b1cfa2c982fc8095c06c09f8 | 3,655,556 |
from typing import Optional
def get_storage_account(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageAccountResult:
"""
The storage account.
:param str account... | c818e801d152f2b11bedac42bcefe322b94ab16e | 3,655,557 |
def format_and_add(graph, info, relation, name):
"""
input: graph and three stirngs
function formats the strings and adds to the graph
"""
info = info.replace(" ", "_")
name = name.replace(" ", "_")
inf = rdflib.URIRef(project_prefix + info)
rel = rdflib.URIRef(project_prefix + rela... | abbe87b923d4ac37262e391a7d9a878b65e4ff41 | 3,655,558 |
def to_log_space(p:float, bounds: BOUNDS_TYPE):
""" Interprets p as a point in a rectangle in R^2 or R^3 using Morton space-filling curve
:param bounds [ (low,high), (low,high), (low,high) ] defaults to unit cube
:param dim Dimension. Only used if bounds are not supplied.
Very ... | 2ab53687481100bda229456b8aa5fad4d8ef817d | 3,655,560 |
def rsi_tradingview(ohlc: pd.DataFrame, period: int = 14, round_rsi: bool = True):
""" Implements the RSI indicator as defined by TradingView on March 15, 2021.
The TradingView code is as follows:
//@version=4
study(title="Relative Strength Index", shorttitle="RSI", format=format.price, prec... | 5b9d96d5e174d6534c2d32a3ece83a5fb09b28ba | 3,655,561 |
def bin_by(x, y, nbins=30):
"""Bin x by y, given paired observations of x & y.
Returns the binned "x" values and the left edges of the bins."""
bins = np.linspace(y.min(), y.max(), nbins+1)
# To avoid extra bin for the max value
bins[-1] += 1
indicies = np.digitize(y, bins)
output = []
... | ff0f9e79f3561cabf2a6498e31a78836be38bfb3 | 3,655,562 |
def calc_stats_with_cumsum(df_tgt, list_tgt_status, dict_diff, calc_type=0):
""" Calculate statistics with cumulative sum of target status types. \n
"dict_diff" is dictionaly of name key and difference value. ex) {"perweek": 7, "per2week": 14} \n
calc_type=0: calculate for each simulation result. \n... | 2dcdd95b8723f250a24afae548b8fd4ce9b5f51c | 3,655,563 |
def _normalize_handler_method(method):
"""Transforms an HTTP method into a valid Python identifier."""
return method.lower().replace("-", "_") | aad23dba304ba39708e4415de40019479ccf0195 | 3,655,564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.