content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def _find_clusters(
data,
cluster_range: Tuple[int, int] = None,
metric: str = "silhouette_score",
target=None,
**kwargs,
):
"""Finds the optimal number of clusters for K-Means clustering using the selected metric.
Args:
data: The data.
cluster_ran... | a73afd74a6401799b6418e45372aee04cf353cb3 | 21,248 |
def _gate_objectives_li_pe(basis_states, gate, H, c_ops):
"""Objectives for two-qubit local-invariants or perfect-entangler
optimizaton"""
if len(basis_states) != 4:
raise ValueError(
"Optimization towards a two-qubit gate requires 4 basis_states"
)
# Bell states as in "Theor... | 76be659f97396384102706fe0bc101a7d85d6521 | 21,249 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_dis... | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 21,250 |
from OpenGL.GLU import gluGetString, GLU_EXTENSIONS
def hasGLUExtension( specifier ):
"""Given a string specifier, check for extension being available"""
if not AVAILABLE_GLU_EXTENSIONS:
AVAILABLE_GLU_EXTENSIONS[:] = gluGetString( GLU_EXTENSIONS )
return specifier.replace(as_8_bit('.'),as_8_bit('_... | cf938ec4d0ec16ae96faa10c50ac5b4bc541a062 | 21,251 |
def do_slots_information(parser, token):
"""Calculates some context variables based on displayed slots.
"""
bits = token.contents.split()
len_bits = len(bits)
if len_bits != 1:
raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0])
return SlotsInformationNode() | e52d724abb435c1b8cba68c352977a1d6c1e1c12 | 21,252 |
def get_region_of_interest(img, sx=0.23, sy=0.15, delta=200, return_vertices=False):
"""
:param img: image to extract ROI from
:param sx: X-axis factor for ROI bottom base
:param sy: Y-axis factor for ROI top base
:param delta: ROI top base length
:param return_vertices: whether to return the RO... | 932588f34ba9cd7e4e71b35df60cf03f40574fad | 21,253 |
from typing import Counter
import json
def load_search_freq(fp=SEARCH_FREQ_JSON):
"""
Load the search_freq from JSON file
"""
try:
with open(fp, encoding="utf-8") as f:
return Counter(json.load(f))
except FileNotFoundError:
return Counter() | 5d5e1d1106a88379eab43ce1e533a7cbb5da7eb6 | 21,254 |
def _sum_of_squares(a, axis=0):
"""
Square each element of the input array, and return the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a... | 5271d40b096e4f6f47e010bf0974bc77804a3108 | 21,255 |
import logging
def get_preprocess_fn(pp_pipeline, remove_tpu_dtypes=True):
"""Transform an input string into the preprocessing function.
The minilanguage is as follows:
fn1|fn2(arg, arg2,...)|...
And describes the successive application of the various `fn`s to the input,
where each function can optiona... | ef3065252b3aa67cebc6a041eba33711e7a17f82 | 21,256 |
def nodeset(v):
"""Convert a value to a nodeset."""
if not nodesetp(v):
raise XPathTypeError, "value is not a node-set"
return v | ccaada2ad8610e0b3561663aab8e90665f6c23de | 21,257 |
import tqdm
def get_char_embs(char_emb_path, char_emb_size, alphabet_size=1422):
"""Get pretrained character embeddings and a dictionary mapping characters to their IDs.
Skips IDs 0 and 1, since these are reserved for PAD and UNK, respectively.
Input:
char_emb_path: path to glove.840B.{char_embeddi... | d4be3ed7780efb3ca378c18d805ff7c5550d98d7 | 21,258 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq... | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 21,259 |
def wave_reduce_min_all(val):
"""
All threads get the result
"""
res = wave_reduce_min(val)
return broadcast(res, 0) | dfac75ecd9aeb75dc37cbaa7d04ce2a2732b9ce9 | 21,260 |
def predict_class(all_headlines):
"""
Predict whether each headline is negative or positive.
:param all_headlines: all headlines
:return: headlines with predictions
"""
clf, v = load_classifier("SVM")
headlines = []
for h in all_headlines:
headlines.append(h.to_array())
df... | 38839eba678659529b7fe83d6dc09ffd3cf87e48 | 21,261 |
def find_tickets_for_seat_manager(
user_id: UserID, party_id: PartyID
) -> list[DbTicket]:
"""Return the tickets for that party whose respective seats the user
is entitled to manage.
"""
return db.session \
.query(DbTicket) \
.filter(DbTicket.party_id == party_id) \
.filter(D... | c59af6629a402f3844e01c5dd86553b8e5d33d64 | 21,262 |
import inspect
from typing import Counter
def insert_features_from_iters(dataset_path, insert_features, field_names, **kwargs):
"""Insert features into dataset from iterables.
Args:
dataset_path (str): Path of the dataset.
insert_features (iter of iter): Collection of iterables representing
... | d6f4547b33a09391188beb96cf408f3148ef643e | 21,263 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching... | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 21,264 |
import tarfile
def get_host_config_tar_response(host):
"""
Build the tar.gz attachment response for the GetHostConfig view.
Note: This is re-used to download host config from the admin interface.
:returns: HttpResponseAttachment
"""
filename = '{host}_v{version}.tar.gz'.format(
... | 8a968885bb197f781faf65abf100aa40568f6354 | 21,265 |
async def update_product_remove_tag_by_id(
*,
product_id: int,
session: Session = Depends(get_session),
db_product: Product = Depends(get_product_or_404),
db_tag: Tag = Depends(get_tag_or_404),
):
"""
Remove tag from product
"""
existing_product = db_product["db_product"]
existin... | 41893e64fa02f24df26ed39128657218cbc87231 | 21,266 |
def hard_sigmoid(x: tf.Tensor) -> tf.Tensor:
"""Hard sigmoid activation function.
```plot-activation
activations.hard_sigmoid
```
# Arguments
x: Input tensor.
# Returns
Hard sigmoid activation.
"""
return tf.clip_by_value(x+0.5, 0.0, 1.0) | 203a41d52888b42b643df84986c5fbc8967222c6 | 21,268 |
def get_image_as_np_array(filename: str):
"""Returns an image as an numpy array
"""
img = Image.open(filename)
return np.asarray(img) | 8d3cc1c5311e675c6c710cbd7633a66748308e7d | 21,269 |
def unreduced_coboundary(morse_complex, akq, cell_ix):
""" Helper """
return unreduced_cells(akq, morse_complex.get_coboundary(cell_ix)) | c074a9b7df35f961e66e31a88c8a7f95f48912c7 | 21,270 |
from typing import Union
def __align(obj: Union[Trace, EventLog], pt: ProcessTree, max_trace_length: int = 1,
max_process_tree_height: int = 1, parameters=None):
"""
this function approximates alignments for a given event log or trace and a process tree
:param obj: event log or single trace
... | 0f684403bb70a158c463b4babcada115e908ee88 | 21,271 |
import resource
def scanProgramTransfersCount(program, transfersCount=None, address=None, args={}):
"""
Scan pools by active program, sort by transfersCount
"""
return resource.scan(**{**{
'type': 'pool',
'index': 'activeProgram',
'indexValue': program,
'sort': 'transfe... | b40a0ff2ea62f840a6c2fd858516dc8998aac30b | 21,272 |
from pedal.tifa.commands import get_issues
from pedal.tifa.feedbacks import initialization_problem
def def_use_error(node, report=MAIN_REPORT):
"""
Checks if node is a name and has a def_use_error
Args:
node (str or AstNode or CaitNode): The Name node to look up.
report (Report): The repo... | 6e0113c451a2c09fdb84392060b672ffb3bc19d3 | 21,273 |
def get_ref_inst(ref):
"""
If value is part of a port on an instance, return that instance,
otherwise None.
"""
root = ref.root()
if not isinstance(root, InstRef):
return None
return root.inst | 55f1a84131451a2032b7012b00f9336f12fee554 | 21,274 |
def not_found(error):
"""
Renders 404 page
:returns: HTML
:rtype: flask.Response
"""
view_args["title"] = "Not found"
return render_template("404.html", args=view_args), 404 | 8882f171c5e68f3b24a1a7bd57dbd025a4b3a070 | 21,275 |
def xml_escape(x):
"""Paranoid XML escaping suitable for content and attributes."""
res = ''
for i in x:
o = ord(i)
if ((o >= ord('a')) and (o <= ord('z'))) or \
((o >= ord('A')) and (o <= ord('Z'))) or \
((o >= ord('0')) and (o <= ord('9'))) or \
... | 018dc7d1ca050641b4dd7198e17911b8d17ce5fc | 21,276 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 21,277 |
def build_model(stage_id, batch_size, real_images, **kwargs):
"""Builds progressive GAN model.
Args:
stage_id: An integer of training stage index.
batch_size: Number of training images in each minibatch.
real_images: A 4D `Tensor` of NHWC format.
**kwargs: A dictionary of
'start_height': An... | d188ef5672e928b1935a97ade3d26614eb700681 | 21,278 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 21,279 |
from typing import Any
from typing import Type
from typing import List
from typing import Dict
def from_serializer(
serializer: serializers.Serializer,
api_type: str,
*,
id_field: str = "",
**kwargs: Any,
) -> Type[ResourceObject]:
"""
Generate a schema from a DRF serializer.
:param s... | 4fb2c0fb83c26d412de5582a8ebfeb4c72ac7add | 21,280 |
def inv_rotate_pixpts(pixpts_rot, angle):
"""
Inverse rotate rotated pixel points to their original positions.
Keyword arguments:
pixpts_rot -- namedtuple of numpy arrays of x,y pixel points rotated
angle -- rotation angle in degrees
Return value:
pixpts -- namedtuple of numpy arrays of pi... | 793b148a0c37d321065dc590343de0f4093abcff | 21,281 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 21,283 |
import array
def adapt_p3_histogram(codon_usages, purge_unwanted=True):
"""Returns P3 from each set of codon usage for feeding to hist()."""
return [array([c.positionalGC(purge_unwanted=True)[3] for c in curr])\
for curr in codon_usages] | d5b0b0b387c3a98f584ca82dad79effbb9aa7a31 | 21,284 |
def handle_logout_response(response):
"""
Handles saml2 logout response.
:param response: Saml2 logout response
"""
if len(response) > 1:
# Currently only one source is supported
return HttpResponseServerError("Logout from several sources not supported")
for entityid, logout_inf... | 18d8983a3e01905e1c7c6b41b65eb7e9191a4bf5 | 21,285 |
def get_value_beginning_of_year(idx, col, validate=False):
"""
Devuelve el valor de la serie determinada por df[col] del
primer día del año del índice de tiempo 'idx'.
"""
beggining_of_year_idx = date(year=idx.date().year, month=1, day=1)
return get_value(beggining_of_year_idx, col, validate) | b3a267620f19cabe1492aea671d34f1142580a5d | 21,286 |
from typing import List
def doc2vec_embedder(corpus: List[str], size: int = 100, window: int = 5) -> List[float]:
"""
Given a corpus of texts, returns an embedding (representation
of such texts) using a fine-tuned Doc2Vec embedder.
ref: https://radimrehurek.com/gensim/models/doc2vec.html
"""
... | e14eb3c1daca1c24f9ebeaa04f44091cc12b03ff | 21,287 |
def PremIncome(t):
"""Premium income"""
return SizePremium(t) * PolsIF_Beg1(t) | 1673f5a18171989e15bdfd7fa3e814f8732fd732 | 21,288 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 21,289 |
def get_bel_node_by_pathway_name():
"""Get Reactome related eBEL nodes by pathway name."""
pathway_name = request.args.get('pathway_name')
sql = f'''SELECT
@rid.asString() as rid,
namespace,
name,
bel,
reactome_pathways
FROM
pro... | 930bb79f70c050acaa052d684de389fc2eee9c36 | 21,290 |
def get_model(model_file, log=True):
"""Load a model from the specified model_file."""
model = load_model(model_file)
if log:
print('Model successfully loaded on rank ' + str(hvd.rank()))
return model | ad699c409588652ac98da0f29b2cb25c53216a46 | 21,291 |
def _sample_weight(kappa, dim, num_samples):
"""Rejection sampling scheme for sampling distance from center on
surface of the sphere.
"""
dim = dim - 1 # since S^{n-1}
b = dim / (np.sqrt(4.0 * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1.0 - b) / (1.0 + b)
c = kappa * x + dim * np.log(1 - x *... | 5760bfe205468e9d662ad0e8d8afa641fa45db2c | 21,293 |
import torch
def variable_time_collate_fn3(
batch,
args,
device=torch.device("cpu"),
data_type="train",
data_min=None,
data_max=None,
):
"""
Expects a batch of time series data in the form of (record_id, tt, vals, mask, labels) where
- record_id is a patient id
- tt is a 1-... | 5158f7ab642ab33100ec5fc1c044e20edd90687c | 21,294 |
import operator
def run_map_reduce(files, mapper, n):
"""Runner to execute a map-reduce reduction of cowrie log files using mapper and files
Args:
files (list of files): The cowrie log files to be used for map-reduce reduction.
mapper (MapReduce): The mapper processing the files using... | a46779fa5546c0e414a6dd4921f52c28cc80535e | 21,295 |
import select
def metadata_record_dictize(pkg, context):
"""
Based on ckan.lib.dictization.model_dictize.package_dictize
"""
model = context['model']
is_latest_revision = not(context.get('revision_id') or
context.get('revision_date'))
execute = _execute if is_lates... | f049faf30322d5d4da45e2a424a6977c894db67c | 21,296 |
def colorbar_set_label_parallel(cbar,label_list,hpos=1.2,vpos=-0.3,
ha='left',va='center',
force_position=None,
**kwargs):
"""
This is to set colorbar label besie the colorbar.
Parameters:
-----------
cb... | 811358f254b05d7fa243c96d91c94ed3cb1d1fcd | 21,298 |
def read_csv(file, tz):
"""
Reads the file into a pandas dataframe, cleans data and rename columns
:param file: file to be read
:param tz: timezone
:return: pandas dataframe
"""
ctc_columns = {1: 'unknown_1',
2: 'Tank upper', # temperature [deg C]
3: 'u... | 9e9ed864dcba6878562ae8686dab1d1f2650f5b3 | 21,299 |
def get_tokenizer_from_saved_model(saved_model: SavedModel) -> SentencepieceTokenizer:
"""
Get tokenizer from tf SavedModel.
:param SavedModel saved_model: tf SavedModel.
:return: tokenizer.
:rtype: SentencepieceTokenizer
"""
# extract functions that contain SentencePiece somewhere in ther... | 6b524f9f14e286aa6ef43fe77773f9ec6503cf75 | 21,300 |
import heapq
def heapq_merge(*iters, **kwargs):
"""Drop-in replacement for heapq.merge with key support"""
if kwargs.get('key') is None:
return heapq.merge(*iters)
def wrap(x, key=kwargs.get('key')):
return key(x), x
def unwrap(x):
_, value = x
return value
iter... | 0693f667fb6b495680066488347d9894e84f6f0a | 21,301 |
def parse_archive_links(html):
"""Parse the HTML of an archive links page."""
parser = _ArchiveLinkHTMLParser()
parser.feed(html)
return parser.archive_links | 7894052d602cbe0db195b6fb9a9c1252163d5266 | 21,303 |
import json
def processing_requests():
"""
Handles the request for what is in processing.
:return: JSON
"""
global processing
global processing_mutex
rc = []
response.content_type = "application/json"
with processing_mutex:
if processing:
rc.append(processing)... | 76334b997efb659fb9d7502ec14357e8e6660293 | 21,304 |
def detect_feature(a, b=None):
"""
Detect the feature used in a relay program.
Parameters
----------
a : Union[tvm.relay.Expr, tvm.IRModule]
The input expression or module.
b : Optional[Union[tvm.relay.Expr, tvm.IRModule]]
The input expression or module.
The two arguments can... | 2b9bf11d9b37da7b4473a6da83867911b22586ec | 21,305 |
def get_urls_from_loaded_sitemapindex(sitemapindex):
"""Get all the webpage urls in a retrieved sitemap index XML"""
urls = set()
# for loc_elem in sitemapindex_elem.findall('/sitemap/loc'):
for loc_elem in sitemapindex.findall('//{http://www.sitemaps.org/schemas/sitemap/0.9}loc'):
urls.update(g... | 1a94166272385768929e1db70b643293e7c325b5 | 21,306 |
def genLinesegsnp(verts, colors = [], thickness = 2.0):
"""
gen objmnp
:param objpath:
:return:
"""
segs = LineSegs()
segs.setThickness(thickness)
if len(colors) == 0:
segs.setColor(Vec4(.2, .2, .2, 1))
else:
segs.setColor(colors[0], colors[1], colors[2], colors[3])... | 71fc5c936fbe5dfdc528fc14fd6c0dd10d15ff3c | 21,307 |
def enhance_puncta(img, level=7):
"""
Removing low frequency wavelet signals to enhance puncta.
Dependent on image size, try level 6~8.
"""
if level == 0:
return img
wp = pywt.WaveletPacket2D(data=img, wavelet='haar', mode='sym')
back = resize(np.array(wp['d'*level].data), img.shape,... | 7c05531bd85dd42296871f884a04cd30c187346e | 21,309 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 21,310 |
def calculate_new_ratings(P1, P2, winner, type):
"""
calculate and return the new rating/rating_deviation for both songs
Args:
P1 (tuple or float): rating data for song 1
P2 (tuple or float): rating data for song 2
winner (str): left or right
type (str): elo or glicko
... | 23853c6fd4d6a977e0c0f28b5665baebcab3ae86 | 21,311 |
def age(a):
"""age in yr - age(scale factor)"""
return _cosmocalc.age(a) | 7f4cb143c1b5e56f3f7b1ebc0a916a371070740d | 21,312 |
def _read_array(raster, band, bounds):
""" Read array from raster
"""
if bounds is None:
return raster._gdal_dataset.ReadAsArray()
else:
x_min, y_min, x_max, y_max = bounds
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_tr... | 12ad55500950d89bdc84ab29157de9faac17e76a | 21,314 |
def makePlayerInfo(pl_name):
""" Recupere toutes les infos d'un player
:param arg1: nom du joueur
:type arg1: chaine de caracteres
:return: infos du player : budget, profit & ventes (depuis le debut de la partie), boissons a vendre ce jour
:rtype: Json
"""
info = calculeMoneyInfo(pl_name, 0)
drinkInfo = ma... | 4ebc7f11397091fa3d0c62db7fcfd82720eac530 | 21,315 |
def _FinalizeHeaders(found_fields, headers, flags):
"""Helper to organize the final headers that show in the report.
The fields discovered in the user objects are kept separate from those
created in the flattening process in order to allow checking the found
fields against a list of those expected. Unexpected... | 9d44f10c4890ca48cc00f79b24e0019e346028d0 | 21,316 |
def get_outmost_points(contours):
"""Get the bounding rectangle of all the contours"""
all_points = np.concatenate(contours)
return get_bounding_rect(all_points) | 173631e3397226459d0bf3a91157d2e74660e506 | 21,318 |
def dhcp_release_packet(eth_dst='ff:ff:ff:ff:ff:ff',
eth_src='00:01:02:03:04:05',
ip_src='0.0.0.0',
ip_dst='255.255.255.255',
src_port=68,
dst_port=67,
bootp_chaddr='00:01:02:03:04:05',
... | 63885cb982fbea5f5ff45c850b1bbf00e1154004 | 21,319 |
from typing import Optional
from datetime import datetime
def dcfc_30_e_plus_360(start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Computes the day count fraction for the "30E+/360" convention.
:param start: The start date of the period.
:param asof: The date which t... | 99cc53d69eb1151056475967459be072cff4f773 | 21,321 |
def get_current_func_info_by_traceback(self=None, logger=None) -> None:
"""
通过traceback获取函数执行信息并打印
use eg:
class A:
def a(self):
def cc():
def dd():
get_current_func_info_by_traceback(self=self)
dd()
... | c89496eb7303acb91ef64587d10d5b7350e9a00e | 21,322 |
def augment_timeseries_shift(x: tf.Tensor, max_shift: int = 10) -> tf.Tensor:
"""Randomly shift the time series.
Parameters
----------
x : tf.Tensor (T, ...)
The tensor to be augmented.
max_shift : int
The maximum shift to be randomly applied to the tensor.
Returns
-------
... | 2a9265ea72478d9c860f549637ea629e4b86f4f0 | 21,323 |
def endpoint(fun):
"""Decorator to denote a method which returns some result to the user"""
if not hasattr(fun, '_zweb_post'):
fun._zweb_post = []
fun._zweb = _LEAF_METHOD
fun._zweb_sig = _compile_signature(fun, partial=False)
return fun | 8050a6d1c6e23c1feeec4744edd45b7ae589aab8 | 21,324 |
import torch
def focal_prob(attn, batch_size, queryL, sourceL):
"""
consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL)
"""
# -> (batch, qu... | 968baad0fa6f78b49eeca1056556a6c2ff3a9cef | 21,325 |
def get_fibonacci_iterative(n: int) -> int:
"""
Calculate the fibonacci number at position 'n' in an iterative way
:param n: position number
:return: position n of Fibonacci series
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a | 0ece23b00d810ce1c67cf5434cf26e1e21685c20 | 21,326 |
def get_sample_content(filename):
"""Return sample content form file."""
with open(
"tests/xml/{filename}".format(
filename=filename), encoding="utf-8") as file:
return file.read() | 2ba60ad6473ec53f6488b42ceb7090b0f7c8f985 | 21,327 |
def create_contrasts(task):
"""
Create a contrasts list
"""
contrasts = []
contrasts += [('Go', 'T', ['GO'], [1])]
contrasts += [('GoRT', 'T', ['GO_rt'], [1])]
contrasts += [('StopSuccess', 'T', ['STOP_SUCCESS'], [1])]
contrasts += [('StopUnsuccess', 'T', ['STOP_UNSUCCESS'], [1])]
c... | 221b1b1ebcc6c8d0e2fcb32d004794d1b0a47522 | 21,328 |
def project(raster_path, boxes):
"""Project boxes into utm"""
with rasterio.open(raster_path) as dataset:
bounds = dataset.bounds
pixelSizeX, pixelSizeY = dataset.res
#subtract origin. Recall that numpy origin is top left! Not bottom left.
boxes["left"] = (boxes["xmin"] * pixelSizeX) +... | 92e7bc01492b3370767ac56b18b2f937caafc6c3 | 21,329 |
def mean_relative_error(preds: Tensor, target: Tensor) -> Tensor:
"""
Computes mean relative error
Args:
preds: estimated labels
target: ground truth labels
Return:
Tensor with mean relative error
Example:
>>> from torchmetrics.functional import mean_relative_error... | 23c7efe3a91179c670383b1687583dc903052a54 | 21,330 |
from typing import Dict
from typing import Any
def render_dendrogram(dend: Dict["str", Any], plot_width: int, plot_height: int) -> Figure:
"""
Render a missing dendrogram.
"""
# list of lists of dcoords and icoords from scipy.dendrogram
xs, ys, cols = dend["icoord"], dend["dcoord"], dend["ivl"]
... | 1dc61a5ddffc85e6baa9bfbb28620a3039dc8993 | 21,331 |
from typing import List
import logging
def sort_by_fullname(data: List[dict]) -> List[dict]:
""" sort data by full name
:param data:
:return:
"""
logging.info("Sorting data by fullname...")
try:
data.sort(key=lambda info: info["FULL_NAME"], reverse=False)
except Exception as excep... | 0b4ecf53893bda7d226b3c26fe51b9abc073294b | 21,332 |
def get_vrf_interface(device, vrf):
""" Gets the subinterfaces for vrf
Args:
device ('obj'): device to run on
vrf ('str'): vrf to search under
Returns:
interfaces('list'): List of interfaces under specified vrf
None
Raises:
None
... | 57dedbd148f208038bd523c1901827ac7eca8754 | 21,333 |
def rsptext(rsp,subcode1=0,subcode2=0,erri='',cmd='',subcmd1='',subcmd2=''):
""" Adabas response code to text conversion """
global rspplugins
if rsp in rspplugins:
plugin = rspplugins[rsp] # get the plugin function
return plugin(rsp, subcode1=subcode1, subcode2=subcode2,
... | 3cc817e812ea7bba346338e09965e025639631eb | 21,334 |
def to_dataframe(data: xr.DataArray, *args, **kwargs) -> pd.DataFrame:
"""
Replacement for `xr.DataArray.to_dataframe` that adds the attrs for the given
DataArray into the resultant DataFrame.
Parameters
----------
data : xr.DataArray
the data to convert to DataFrame
Returns
--... | 69179fc48ce9ca04e8ee99967ce44b15946f9a57 | 21,335 |
def check_position(position):
"""Determines if the transform is valid. That is, not off-keypad."""
if position == (0, -3) or position == (4, -3):
return False
if (-1 < position[0] < 5) and (-4 < position[1] < 1):
return True
else:
return False | f95ab22ce8da386284040626ac90c908a17b53fa | 21,336 |
def mobilenet_wd4_cub(num_classes=200, **kwargs):
"""
0.25 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of cl... | f9e367058261da89a3714b543270628ab3941e12 | 21,337 |
import torch
def base_plus_copy_indices(words, dynamic_vocabs, base_vocab, volatile=False):
"""Compute base + copy indices.
Args:
words (list[list[unicode]])
dynamic_vocabs (list[HardCopyDynamicVocab])
base_vocab (HardCopyVocab)
volatile (bool)
Returns:
MultiV... | e6e9d42186c05d33a04c58c506e0e9b97eadac6a | 21,338 |
def font_encoding(psname):
"""Return encoding name given a psname"""
return LIBRARY.encoding(psname) | fd5d2b000624a4d04980c88cc78cd97bf49bca94 | 21,339 |
def shader_with_tex_offset(offset):
"""Returns a vertex FileShader using a texture access with the given offset."""
return FileShader(shader_source_with_tex_offset(offset), ".vert") | 0df316dd97889b3b2541d6d21970768e1cb70fe6 | 21,340 |
def braycurtis(u, v):
"""
d = braycurtis(u, v)
Computes the Bray-Curtis distance between two n-vectors u and v,
\sum{|u_i-v_i|} / \sum{|u_i+v_i|}.
"""
u = np.asarray(u)
v = np.asarray(v)
return abs(u-v).sum() / abs(u+v).sum() | 693b7f0108f9f99e0950d81c2be1e9dc0bd25d86 | 21,341 |
def _load_pyfunc(path):
"""
Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``.
:param path: Local filesystem path to the MLflow Model with the ``fastai`` flavor.
"""
return _FastaiModelWrapper(_load_model(path)) | f8349d3580c5ca407a47b24f901c8f9a7f532c77 | 21,342 |
def fit_pseudo_voigt(x,y,p0=None,fit_alpha=True,alpha_guess=0.5):
"""Fits the data with a pseudo-voigt peak.
Parameters
-----------
x: np.ndarray
Array with x values
y: np.ndarray
Array with y values
p0: list (Optional)
It contains a initial guess the for the pseudo-vo... | 8abd61b44665632cc4e2ae21f52116757e00d2b9 | 21,343 |
from datetime import datetime
def get_name_of_day(str_date):
"""
Возвращает имя дня.
"""
day = datetime.fromisoformat(str_date).weekday()
return DAYS_NAME.get(day) | ae12d7b8ec44c2fb6edcf252ed3463a385353f30 | 21,345 |
def k_fold_split(ratings, min_num_ratings=10, k=4):
"""
Creates the k (training set, test_set) used for k_fold cross validation
:param ratings: initial sparse matrix of shape (num_items, num_users)
:param min_num_ratings: all users and items must have at least min_num_ratings per user and per item to be... | 8b151e291e3365d7986cdc7b876ef630efcb60b4 | 21,346 |
def merge_dict(a, b, path:str=None):
"""
Args:
a:
b:
path(str, optional): (Default value = None)
Returns:
Raises:
"""
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dic... | cd260c005b07c9c84b14a14cae3d4dc54fe26b8c | 21,347 |
import json
def validateSignedOfferData(adat, ser, sig, tdat, method="igo"):
"""
Returns deserialized version of serialization ser which Offer
if offer request is correctly formed.
Otherwise returns None
adat is thing's holder/owner agent resource
ser is json encoded unicode string of req... | 4aebe14b8a90dc1c3e47763ce49e142d77f99bd9 | 21,348 |
def get_relevant_phrases(obj=None):
""" Get all phrases to be searched for. This includes all SensitivePhrases, and any RelatedSensitivePhrases that
refer to the given object.
:param obj: A model instance to check for sensitive phrases made specifically for that instance.
:return: a dictionary of repl... | 951166c89dc8e257bce512d13cee592e1266efae | 21,349 |
import struct
def _prepare_cabal_inputs(
hs,
cc,
posix,
dep_info,
cc_info,
direct_cc_info,
component,
package_id,
tool_inputs,
tool_input_manifests,
cabal,
setup,
setup_deps,
setup_dep_info,
srcs,
... | 4d42e6b772a64bc721e30907417dd8c734ce79e6 | 21,350 |
def split_kp(kp_joined, detach=False):
"""
Split the given keypoints into two sets(one for driving video frames, and the other for source image)
"""
if detach:
kp_video = {k: v[:, 1:].detach() for k, v in kp_joined.items()}
kp_appearance = {k: v[:, :1].detach() for k, v in kp_joined.item... | 0396003a17172a75b121ddb43c9b9cf14ee3e458 | 21,351 |
def low_shelve(signal, frequency, gain, order, shelve_type='I',
sampling_rate=None):
"""
Create and apply first or second order low shelve filter.
Uses the implementation of [#]_.
Parameters
----------
signal : Signal, None
The Signal to be filtered. Pass None to create ... | 130fd593988d1fd0b85795389dab554d59fedb97 | 21,352 |
from typing import Union
def get_breast_zone(mask: np.ndarray, convex_contour: bool = False) -> Union[np.ndarray, tuple]:
"""
Función de obtener la zona del seno de una imagen a partir del area mayor contenido en una mascara.
:param mask: mascara sobre la cual se realizará la búsqueda de contornos y de ... | 429344c0645fa7bcfa49abcaf9b022f61c48bc35 | 21,353 |
def replace(temporaryans, enterword, answer):
"""
:param temporaryans: str, temporary answer.
:param enterword: str, the character that user guesses.
:param answer: str, the answer for this hangman game.
:return: str, the temporary answer after hyphens replacement.
"""
# s = replace('-----',... | 80d8625dca573744e9945190ee169438754b1829 | 21,354 |
def extract_timestamp(line):
"""Extract timestamp and convert to a form that gives the
expected result in a comparison
"""
# return unixtime value
return line.split('\t')[6] | 84618f02e4116c70d9f6a1518aafb0691a29ef07 | 21,355 |
def svn_stream_from_stringbuf(*args):
"""svn_stream_from_stringbuf(svn_stringbuf_t str, apr_pool_t pool) -> svn_stream_t"""
return _core.svn_stream_from_stringbuf(*args) | 9710061adb6d80527a3f3afa84bf41e0fa6406c6 | 21,356 |
def get_autoencoder_model(hidden_units, target_predictor_fn,
activation, add_noise=None, dropout=None):
"""Returns a function that creates a Autoencoder TensorFlow subgraph.
Args:
hidden_units: List of values of hidden units for layers.
target_predictor_fn: Function that will pred... | 88c58b2c43c26aa8e71baf684688d27db251cdb6 | 21,357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.