content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import hmac
def get_url(request):
"""
Use devId and key and some hashing thing to get the url, needs /v3/api as input
"""
devId = DEV_ID
key = KEY
request = request + ('&' if ('?' in request) else '?')
raw = request + f"devid={devId}"
raw = raw.encode()
hashed = hmac.new(key, ... | 57e6d8dc6c0f282b227559aed5cd9c1f96f7d5b7 | 16,635 |
def _is_mapped_class(cls):
"""Return True if the given object is a mapped class,
:class:`.Mapper`, or :class:`.AliasedClass`."""
if isinstance(cls, (AliasedClass, mapperlib.Mapper)):
return True
if isinstance(cls, expression.ClauseElement):
return False
if isinstance(cls, type):
... | 7f09c1f4908bb62977de07ad4366fb8e6cc84cc2 | 16,636 |
from bs4 import BeautifulSoup
def get_all_links_in_catalog(html) -> list:
"""Получает список всех ссылок на пункты из каталога."""
_soup = BeautifulSoup(html, 'html.parser')
_items = _soup.find('div', class_='catalog_section_list').find_all('li', class_='name')
links_list = []
for item in _items:
... | 53e4fd9aaad8755ddd19328ae5d5f972cfbcdc3c | 16,637 |
def digitize(n):
"""Convert a number to a reversed array of digits."""
l = list(str(n))
n_l = []
for d in l:
n_l.append(int(d))
n_l.reverse()
return n_l | e4355b68da41e4be87ce18b53afb2a406eb120c7 | 16,638 |
def _available_algorithms():
"""Verify which algorithms are supported on the current machine.
This is done by verifying that the required modules and solvers are available.
"""
available = []
for algorithm in ALGORITHM_NAMES:
if "gurobi" in algorithm and not abcrules_gurobi.gb:
... | cd9310cb78d780154c56763cdf14573bc67ae7b5 | 16,640 |
import re
def symbols(*names, **kwargs):
"""
Emulates the behaviour of sympy.symbols.
"""
shape=kwargs.pop('shape', ())
s = names[0]
if not isinstance(s, list):
s = re.split('\s|,', s)
res = []
for t in s:
# skip empty strings
if not t:
continue
... | bcaf1827ccee67098e619c3ec825f3b1aeb3f798 | 16,641 |
def create_intent(intent, project_id, language_code):
"""Create intent in dialogflow
:param intent: dict, intent for api
:param project_id: str, secret project id
:param language_code: event with update tg object
:return:
"""
client = dialogflow.IntentsClient()
parent = client.project_ag... | 59a150d4456d26f4cd8fa93a2cbfc131278d3ba0 | 16,642 |
from typing import List
def construct_object_types(list_of_oids: List[str]) -> List[hlapi.ObjectType]:
"""Builds and returns a list of special 'ObjectType'
from pysnmp"""
object_types: List[hlapi.ObjectType] = []
for oid in list_of_oids:
object_types.append(hlapi.ObjectType(hlapi.ObjectIdentit... | 24eeb7dbd0de49e702acc574c9264d3e7bcdf904 | 16,643 |
def base_sampler(models, nevents, floating_params=None):
"""
Creates samplers from models.
Args:
models (list(model)): models to sample
nevents (list(int)): number of in each sampler
floating_params (list(parameter), optionnal): floating parameter in the samplers
Returns:
... | af575d4a175239c2af4fe0e61658005a12225e5a | 16,644 |
def menu_maker():
"""Top Menu Maker In each html page
"""
result = "<center>"
for i,item in enumerate(page_name):
if item == "Home":
targets_blank = ""
else:
targets_blank = 'target="blank"'
# Hyper Link To Each Page In HTML File
result += '\t... | 6f9b38926d3eab31d1e5d32a49564f083df4f3cc | 16,645 |
import http
def project_generate_private_link_post(auth, node, **kwargs):
""" creata a new private link object and add it to the node and its selected children"""
node_ids = request.json.get('node_ids', [])
name = request.json.get('name', '')
anonymous = request.json.get('anonymous', False)
if ... | bd006f64d02bf36509297b1a0778e3488093c682 | 16,646 |
def access_token_old_api(authen_code):
"""
通过此接口获取登录用户身份(疑似是一个旧接口)
:param authen_code:
:return:
"""
# 先获取app_access_token
app_access_token = _get_app_access_token()
if not app_access_token:
return None
access_token_old_url = cfg.access_token_old_url
headers = {"Content-T... | efb34044bc07aee817050ef39e8d8a72da7611fd | 16,647 |
def denoising(image):
"""improve image quality by remove unimportant details"""
denoised = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21)
return denoised | b5407c1fcd84b49afe5c17e6a221d9da423444f6 | 16,648 |
def teams():
"""Redirect the to the Slack team authentication url."""
return redirect(auth.get_redirect('team')) | 7ea84c5319c7f64a24c7ae42bd0b7467934d8cba | 16,649 |
def _clarans(metric):
"""Clustering Large Applications based on RANdomized Search."""
# choose which implementation to use, hybrid or cpu
get_clusters = _get_clusters(metric, method='cpu')
@jit(nopython=True)
def clarans(data, k, numlocal, maxneighbor):
"""Clustering Large Applications base... | a56321ba094b78eaa6df18917b7c3ad32a3a6bec | 16,650 |
def create_outlier_mask(df, target_var, number_of_stds, grouping_cols=None):
"""
Create a row-wise mask to filter-out outliers based on target_var.
Optionally allows you to filter outliers by group for hier. data.
"""
def flag_outliers_within_groups(df, target_var,
... | 95a7e3e5a0cb8dcc4aa3da1af7e9cb4111cf6b81 | 16,651 |
import contextlib
def closing_all(*args):
"""
Return a context manager closing the passed arguments.
"""
return contextlib.nested(*[contextlib.closing(f) for f in args]) | 075056e1a92c63d5c1db0cda68d7cb447868653b | 16,652 |
def _non_max_suppression(objects, threshold):
"""Returns a list of indexes of objects passing the NMS.
Args:
objects: result candidates.
threshold: the threshold of overlapping IoU to merge the boxes.
Returns:
A list of indexes containings the objects that pass the NMS.
"""
if len(... | 9952386f5a6c6f11b1fdbd37eaca6c273ea4b506 | 16,653 |
def binary_search(x,l):
""" Esse algorítmo é o algorítmo de busca binária, mas ele retorna
qual o índice o qual devo colocar o elemento para que a lista
permaneça ordenada.
Input: elemento x e lista l
Output: Índice em que o elemento deve ser inserido para manter a ordenação da lista
"""
lo... | 457c403ffeb2eb5529c2552bdbe8d7beee9199f2 | 16,654 |
def check_abrp(config):
"""Check for geocodio options and return"""
try:
abrpOptions = config.abrp.as_dict()
except:
return {}
options = {}
abrp_keys = ["enable", "api_key", "token"]
for key in abrp_keys:
if key not in abrpOptions.keys():
_LOGGER.error(f"Miss... | fa9c0f1643ae2793cf66498dbb8f27a033edeafd | 16,655 |
import click
def connect(config, job, attach):
"""
Connect to job.
JOB may be specified by name or ID, but ID is preferred.
"""
jobs = config.trainml.run(config.trainml.client.jobs.list())
found = search_by_id_name(job, jobs)
if None is found:
raise click.UsageError("Cannot find ... | 8a572a92eb9a0cd31af05218dec3ab369109cb31 | 16,656 |
def convert_magicc7_to_openscm_variables(variables, inverse=False):
"""
Convert MAGICC7 variables to OpenSCM variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM variables to MAGICC7
... | 952bca9f07f8e032b33328c1b03470fd3150eabd | 16,657 |
import asyncio
import aiohttp
async def fetch_disclosure(start, end):
"""期间沪深二市所有类型的公司公告
Args:
start (date like): 开始日期
end (date like): 结束日期
Returns:
list: list of dict
"""
start, end = pd.Timestamp(start), pd.Timestamp(end)
start_str = start.strftime(r'%Y-%m-%d')
... | efb6b7706ed73c09c65e5d05567b3fdf38aee887 | 16,658 |
from re import T
def get_loader(
image_dir,
attr_path,
selected_attrs,
crop_size=178,
image_size=128,
batch_size=16,
dataset="CelebA",
mode="train",
affectnet_emo_descr="emotiw",
num_workers=1,
):
"""Build and return a data loader."""
transform = []
if mode == "trai... | 082d1b81b73df7c817fad024911fe431f8cf4a74 | 16,659 |
import json
def remove_samples(request, product_id):
"""Removes passed samples from 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 = temp_id.sp... | e9d0f112f17af463cfe7ddba2bd606d78fb50b3f | 16,660 |
def csu_to_field(field, radar, units='unitless',
long_name='Hydrometeor ID',
standard_name='Hydrometeor ID',
dz_field='ZC'):
"""
Adds a newly created field to the Py-ART
radar object. If reflectivity is a masked array,... | c8052f51bbed2c16c744201b862fa43868d7d527 | 16,661 |
def calculate_com(structure):
"""
Calculates center of mass of the structure (ligand or protein).
Parameters
----------
structure : biopython Structure object
PDB of choice loaded into biopython (only chains of interest).
Returns
-------
A list defining center of mass of th... | 35d6ed62d3943dff0aa1ef0c3a0d04b9235b84ac | 16,663 |
def generate_config(context):
""" Generate the deployment configuration. """
resources = []
name = context.properties.get('name', context.env['name'])
resources = [
{
'name': name,
'type': 'appengine.v1.version',
'properties': context.properties
}
... | 9a997b87a8d4d8f46edbbb9d2da9f523e5e2fdc6 | 16,664 |
def check_regs(region_df, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (o... | ea00a9b755c8dc2943717254ecdb3390bbefe288 | 16,665 |
from typing import List
from typing import Optional
from typing import Sequence
from typing import Union
from typing import Dict
from typing import Any
from typing import cast
def build_assets_job(
name: str,
assets: List[OpDefinition],
source_assets: Optional[Sequence[Union[ForeignAsset, OpDefinition]]] ... | 8e2353677e5085f0c1eb53ee24687e020912b2e5 | 16,666 |
def createBinarySearchTree(vs):
"""
Generate a balanced binary search tree based on the given array.
Args:
vs - an integer array
{4, 5, 5, 7, 2, 1, 3}
4
/ \
2 5
/ \ / \
1 3 5 7
"""
def _help... | 5e1f7723a4b218d980d7d72ca8f949160ff8042d | 16,667 |
def remove_end_same_as_start_transitions(df, start_col, end_col):
"""Remove rows corresponding to transitions where start equals end state.
Millington 2009 used a methodology where if a combination of conditions
didn't result in a transition, this would be represented in the model by
specifying a trans... | f4b3ddca74e204ed22c75a4f635845869ded9988 | 16,668 |
def sieve(iterable, inspector, *keys):
"""Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation.
e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]]
"""
s = {k: [] for k in keys}
for item in iterable:
k = inspector(item)
... | 6ebb76dfb3131342e08a0be4127fba242d126130 | 16,670 |
def get_model(config: BraveConfig) -> embedding_model.MultimodalEmbeddingModel:
"""Construct a model implementing BraVe.
Args:
config: Configuration for BraVe.
Returns:
A `MultimodalEmbeddingModel` to train BraVe.
"""
init_fn, parameterized_fns = _build_parameterized_fns(config)
loss_fn = _build_... | eceff13cf9ec5bd5cdd126af52bbd4eb6fad6ebe | 16,671 |
def upilab6_1_5 () :
"""
6.1.5. Exercice UpyLaB 6.2 - Parcours vert bleu rouge
(D’après une idée de Jacky Trinh le 19/02/2018)
Monsieur Germain est une personne très âgée. Il aimerait préparer une liste de courses à faire à l’avance. Ayant un
budget assez serré, il voudrait que sa liste de courses soit dans ses cap... | 198a11e4059c39550bb398a473711073677a41d4 | 16,672 |
import torch
def construct_filtering_input_data(xyz_s, xyz_t, data, overlapped_pair_tensors, dist_th=0.05, mutuals_flag=None):
"""
Prepares the input dictionary for the filtering network
Args:
xyz_s (torch tensor): coordinates of the sampled points in the source point cloud [b,n,3]
xyz_t (to... | ca316834cc87e1527e4563407138aa92a46b92a3 | 16,673 |
def rmean(x, N):
""" cutting off the edges. """
s = int(N-1)
return np.convolve(x, np.ones((N,))/N)[s:-s] | eb34bd21523e685184155e65ccddc34e2eb6a428 | 16,674 |
def add_variant_to_existing_lines(group, variant, total_quantity):
"""
Adds variant to existing lines with same variant.
Variant is added by increasing quantity of lines with same variant,
as long as total_quantity of variant will be added
or there is no more lines with same variant.
Returns q... | 1e958db4c684f0bf3f2d821fc06f422cc60d0168 | 16,675 |
def calculate_position(c, t):
"""
Calculates a position given a set of quintic coefficients and a time.
Args
c: List of coefficients generated by a quintic polynomial
trajectory generator.
t: Time at which to calculate the position
Returns
Position
"""
retu... | 927737b41006df13e7bf751b06756eea02542491 | 16,676 |
def get_dqa(df):
"""Method to get DQA issues."""
try:
df0 = df[(df.dob == '') | (df.dqa_sex != 'OK') |
(df.dqa_age != 'OK') | (df.case_status == 'Pending')]
df1 = df0[['cpims_id', 'child_names', 'age', 'case_category',
'dqa_sex', 'dqa_dob', 'dqa_age', 'case_st... | f2c30e87937ce4fac1dd00cd597ee52946d80d07 | 16,677 |
import pickle
def get_3C_coords(name):
"""
Formatted J2000 right ascension and declination and IAU name
Returns the formatted J2000 right ascension and declination and IAU name
given the 3C name.
Example
>>> ra,dec,iau = get_3C_coords('3C286')
>>> print ra,dec,iau
13h31m08.287984... | 1e48ca0535c6cdb5eb2330f3dcfd666e40eef33f | 16,678 |
import json
def get(player):
"""Get the cipher that corresponding to the YouTube player version.
Args:
player (dict): Contains the 'sts' value and URL of the YouTube player.
Note:
If the cipher is missing in known ciphers, then the 'update' method will be used.
"""
if DIR.exists(... | dd658d8aad775fa7871e3efa642b0aad89f8f801 | 16,679 |
def divide(x, y):
"""A version of divide that also rounds."""
return round(x / y) | 1bf9e5859298886db7c928613f459f163958ca7b | 16,680 |
def create_root_ca_cert(root_common_name, root_private_key, days=365):
"""
This method will create a root ca certificate.
:param root_common_name: The common name for the certificate.
:param root_private_key: The private key for the certificate.
:param days: The number of days for which the certific... | 5bf83b8ba56c6dde9f6c2ed022c113350425aa33 | 16,681 |
def hist1d(arr, bins=None, amp_range=None, weights=None, color=None, show_stat=True, log=False,\
figsize=(6,5), axwin=(0.15, 0.12, 0.78, 0.80),\
title=None, xlabel=None, ylabel=None, titwin=None):
"""Makes historgam from input array of values (arr), which are sorted in number of bins (bins) in... | c74771de0df0e9f4d65490a09346d2af18d53cc7 | 16,682 |
def format_validate_parameter(param):
"""
Format a template parameter for validate template API call
Formats a template parameter and its schema information from the engine's
internal representation (i.e. a Parameter object and its associated
Schema object) to a representation expected by the curre... | 4ed21c80bf567beca448065089bfe22fef6cfb17 | 16,683 |
import string
def get_template(name):
"""Retrieve the template by name
Args:
name: name of template
Returns:
:obj:`string.Template`: template
"""
file_name = "{name}.template".format(name=name)
data = resource_string("pyscaffoldext.beeproject.templates", file_name)
return... | 933e597b48b5ed01a29d191fd0fe04371b1baeb6 | 16,684 |
def box3d_overlap(boxes, qboxes, criterion=-1, z_axis=1, z_center=1.0):
"""kitti camera format z_axis=1.
"""
bev_axes = list(range(7))
bev_axes.pop(z_axis + 3)
bev_axes.pop(z_axis)
# t = time.time()
# rinc = box_np_ops.rinter_cc(boxes[:, bev_axes], qboxes[:, bev_axes])
rinc = rotate_iou... | 45aa39e9f55f8198ccbe5faf6a00cf27279057fa | 16,685 |
def _apply_graph_transform_tool_rewrites(g, input_node_names,
output_node_names):
# type: (gde.Graph, List[str], List[str]) -> tf.GraphDef
"""
Use the [Graph Transform Tool](
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/
graph_transforms/README... | 15d9609357d45fd164fd1569d35669148e66acd8 | 16,686 |
def big_bcast(comm, objs, root=0, return_split_info=False, MAX_BYTES=INT_MAX):
"""
Broadcast operation that can exceed the MPI limit of ~4 GiB.
See documentation on :meth:`big_gather` for details.
Parameters
----------
comm: mpi4py.MPI.Intracomm
MPI communicator to use.
objs: objec... | 341591b207ef793b32e6b727f14533dbe119312d | 16,687 |
def get_task(appname, taskqueue, identifier):
"""Gets identified task in a taskqueue
Request
-------
```
GET http://asynx.host/apps/:appname/taskqueues/:taskqueue/tasks/:identifier
```
Parameters:
- appname: url param, string, the application name
under wh... | c11aadab178776a6246163f2146e9a91d949e3bc | 16,688 |
def assign_style_props(df, color=None, marker=None, linestyle=None,
cmap=None):
"""Assign the style properties for a plot
Parameters
----------
df : pd.DataFrame
data to be used for style properties
"""
if color is None and cmap is not None:
raise ValueErr... | 93bd50e81a988594a42bce26a48d9d24e0e9c6ba | 16,690 |
def to_dbtext(text):
"""Helper to turn a string into a db.Text instance.
Args:
text: a string.
Returns:
A db.Text instance.
"""
if isinstance(text, unicode):
# A TypeError is raised if text is unicode and an encoding is given.
return db.Text(text)
else:
try:
return db.Text(text, ... | 74704f42e8cb05be24df3b32e8964382da9c488e | 16,691 |
import zmq
import time
def zmq_init(pub_port, sub_port_list):
"""
Initialize the ZeroMQ publisher and subscriber.
`My` publisher publishes `my` data to the neighbors. `My` subscriber listen
to the ports of other neighbors. `sub_port_list` stores all the possible
neighbors' TCP ports.
... | fcde81e7387d49e99cd864cea233b1ba02ac679c | 16,692 |
def dot(u, v):
"""
Returns the dot product of the two vectors.
>>> u1 = Vec([1, 2])
>>> u2 = Vec([1, 2])
>>> u1*u2
5
>>> u1 == Vec([1, 2])
True
>>> u2 == Vec([1, 2])
True
"""
assert u.size == v.size
sum = 0
for index, (compv, compu) in enumerate(zip(u.store,v.st... | e431800750c8f7c14d7412753814e2498fdd3c09 | 16,694 |
def isvalid(number, numbers, choices=2):
"""Meh
>>> isvalid(40, (35, 20, 15, 25, 47))
True
>>> isvalid(62, (20, 15, 25, 47, 40))
True
>>> isvalid(127, (182, 150, 117, 102, 95))
False
"""
return number in sums(numbers, choices) | c32ee0fe1509c0c1f48bdf8f6b9f8fe5b00fb8f8 | 16,695 |
def from_rotation_matrix(rotation_matrix: type_alias.TensorLike,
name: str = "quaternion_from_rotation_matrix"
) -> tf.Tensor:
"""Converts a rotation matrix representation to a quaternion.
Warning:
This function is not smooth everywhere.
Note:
In the fol... | 2eab1984206c57ec64c4be2b3652008773d9c037 | 16,696 |
def mark_text(text):
"""Compact rules processor"""
attrs = {}
rules = []
weight = 0
attrs['len'] = len(text)
text = text.replace('.', ' ').replace(',', ' ').replace(u'№', ' ').strip().lower()
words = text.split()
textjunk = []
spaced = 0
attrs['wl'] = len(words)
attrs['junkl'... | 7287535d3a9c3bb302f9cc98ca6e7fa2ec4c9a40 | 16,697 |
def model_flux(t_dec,B,P_max,R,Ne,d_l,z,mp,me,e,c,sigma_t,time,nu,Gamma,E_k,
n,eps_b,eps_e,p,j_ang):
""" Function for deriving the flux for the spectrum or light curve at
given times and frequencies """
# calculate lorentz factors, characteristic frequencies and
# jet break time
gamma_m = Gamma*eps_e*((p-2)/(p-... | 15658d57ae5d837d416731427e1227eb304b4b75 | 16,699 |
def fix_lng_degrees(lng: float) -> float:
"""
For a lng degree outside [-180;180] return the appropriate
degree assuming -180 = 180°W and 180 = 180°E.
"""
sign = 1 if lng > 0 else -1
lng_adj = (abs(lng) % 360) * sign
if lng_adj > 180:
return (lng_adj % 180) - 180
elif lng_adj < -... | bde58152883874095b15ec38cfb24ea68d73c188 | 16,700 |
def create_code(traits):
"""Assign bits to list of traits.
"""
code = 1
result = {INVALID: code}
if not traits:
return result
for trait in traits:
code = code << 1
result[trait] = code
return result | cfc7b1662edaf7f3e3763009a460157f7ec677bb | 16,701 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
def get_current_table(grid_id: str) -> List[Dict[Any, Any]]:
""" Get current Data from the grid
Args:
grid_id: Grid ID to retrieve data from.
Returns:
list: Exsiting grid data.
"""
... | d1a8c21398aa2aca54ca587aa577c8ff50d8d46f | 16,702 |
def read_graph(filepath):
"""Creates a graph based on the content of the file at given filepath.
Parameters
----------
filename : filepath
Path to a file containing an adjacency matrix.
"""
g_data = np.loadtxt(open(filepath, "rb"), delimiter=",")
return nx.from_numpy_matrix(g_data) | 74e0b687c6cf9e404d9446505799a84b5680c5b3 | 16,703 |
def get_seed(seed=None):
"""Get valid Numpy random seed value"""
# https://groups.google.com/forum/#!topic/briansupport/9ErDidIBBFM
random = np.random.RandomState(seed)
return random.randint(0, 2147483647) | 5ac1280a30265518edcf8bb07a03cfe5fb0ae21d | 16,704 |
import typing
import inspect
def resolve_lookup(
context: dict, lookup: str, call_functions: bool = True
) -> typing.Any:
"""
Helper function to extract a value out of a context-dict.
A lookup string can access attributes, dict-keys, methods without parameters and indexes by using the dot-accessor (e.... | a2090f2488ee10f7c11684952fd7a2498f6d4979 | 16,706 |
def check_actions_tool(tool):
"""2.2.x to 2.3.0 upgrade step checker
"""
atool = getToolByName(tool, 'portal_actions')
try:
atool['user']['change_password']
except KeyError:
return True
try:
atool['global']['members_register']
except KeyError:
return True
... | 2ecc6064cd26aa670743c25018dd27e2ce0f41ca | 16,707 |
def integer_byte_length(number):
"""
Number of bytes needed to represent a integer excluding any prefix 0 bytes.
:param number:
Integer value. If num is 0, returns 0.
:returns:
The number of bytes in the integer.
"""
quanta, remainder = divmod(integer_bit_length(number), 8)
if remainder:
... | 0de5828117107461e23e36cf3c38bab0850b7203 | 16,708 |
def ones(input_dim, output_dim, name=None):
"""All zeros."""
initial = tf.ones((input_dim, output_dim), dtype=tf.float32)
return tf.Variable(initial, name=name) | 02867b278e224e436e470a9eaeac32b44e99a99a | 16,709 |
def enrichment_score2(mat, idx, line_width, norm_factors, distance_range=(20, 40), window_size=10,
stats_test_log=({}, {})):
"""
Calculate the enrichment score of a stripe given its location, width and the contact matrix
Parameters:
----------
mat: np.array (2D)
Contac... | bfb987bd2e2d0770d81f811ba2486893b62d269d | 16,710 |
def paginate(data, page=1, per_page=None):
"""Create a paginated response of the given query set.
Arguments:
data -- A flask_mongoengine.BaseQuerySet instance
"""
per_page = app.config['DEFAULT_PER_PAGE'] if not per_page else per_page
pagination_obj = data.paginate(page=page, per_page=per_p... | c5a692067e5f58a971762316c83bcfe6f75051bf | 16,711 |
def compute_mean_wind_dirs(res_path, dset, gids, fracs):
"""
Compute mean wind directions for given dset and gids
"""
with Resource(res_path) as f:
wind_dirs = np.radians(f[dset, :, gids])
sin = np.mean(np.sin(wind_dirs) * fracs, axis=1)
cos = np.mean(np.cos(wind_dirs) * fracs, axis=1)
... | bd3f91cc0f4b05f630d252f6026e3f27c56cd134 | 16,712 |
import numpy
def plot_area_and_score(samples: SampleList, compound_name: str, include_none: bool = False):
"""
Plot the peak area and score for the compound with the given name
:param samples: A list of samples to plot on the chart
:param compound_name:
:param include_none: Whether samples where the compound wa... | cce2dd3c3fca742627dca5c893f498d83e0d7840 | 16,713 |
def get_strides(fm: NpuFeatureMap) -> NpuShape3D:
"""Calculates STRIDE_C/Y/X"""
if fm.strides is not None:
return fm.strides
elem_size = fm.data_type.size_in_bytes()
if fm.layout == NpuLayout.NHWC:
stride_c = elem_size
stride_x = fm.shape.depth * stride_c
stride_y = fm.sh... | e933fd3b06fb53e44b81bcb28341137a14990dec | 16,714 |
def gram_linear(x):
"""Compute Gram (kernel) matrix for a linear kernel.
Args:
x: A num_examples x num_features matrix of features.
Returns:
A num_examples x num_examples Gram matrix of examples.
"""
return x.dot(x.T) | f0a625d3ca6b846396c3c7c723b1bc8130a6c140 | 16,715 |
def to_feature(shape, properties={}):
"""
Create a GeoJSON Feature object for the given shapely.geometry :shape:.
Optionally give the Feature a :properties: dict.
"""
collection = to_feature_collection(shape)
feature = collection["features"][0]
feature["properties"] = properties
# remov... | 39d8e7658ae2043c081d137f0a69ddd4344876fc | 16,716 |
def read_responses(file):
"""
Read dialogs from file
:param file: str, file path to the dataset
:return: list, a list of dialogue (context) contained in file
"""
with open(file, 'r') as f:
samples = f.read().split('<|endoftext|>')
samples = samples[1:] # responses = [i.strip() f... | e654a075622f04c3eca6c18e3d092593387ef237 | 16,717 |
def build_parametric_ev(data, onset, name, value, duration=None,
center=None, scale=None):
"""Make design info for a multi-column constant-value ev.
Parameters
----------
data : DataFrame
Input data; must have "run" column and any others specified.
onset : string
... | 47400052e2b2f4bf8217d9eaf71a83257180f5c4 | 16,718 |
import operator
import bisect
def time_aware_indexes(t, train_size, test_size, granularity, start_date=None):
"""Return a list of indexes that partition the list t by time.
Sorts the list of dates t before dividing into training and testing
partitions, ensuring a 'history-aware' split in the ensuing clas... | 96e27c7a3f7284476d615a8d03f7c365f0406187 | 16,719 |
def send_invite_mail(invite, request):
"""
Send an email invitation to user not yet registered in the system.
:param invite: ProjectInvite object
:param request: HTTP request
:return: Amount of sent email (int)
"""
invite_url = build_invite_url(invite, request)
message = get_invite_body... | 4554bb6bea20e03749739026583d6215714febbf | 16,720 |
def binary_n(total_N, min_n=50):
"""
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minimal length after division
Ret... | 240296c6024243da5750cb5aa7e64bea45ae91ca | 16,722 |
def thresholding(pred,label,thres):
""" Given the threshold return boolean matrix with 1 if > thres 0 if <= 1 """
conf =[]
for i in thres:
pr_th,lab_th = (pred>i),(label>i)
conf += confusion(pr_th,lab_th)
return np.array(conf).reshape(-1,4) | 97727a75b4f7648c82a095c7804709e9a52f13ed | 16,723 |
def unicode_test(request, oid):
"""Simple view to test funky characters from the database."""
funky = News.objects.using('livewhale').get(pk=oid)
return render(request, 'bridge/unicode.html', {'funky': funky}) | 8357d76bfc22fdc3f12176332a4b19fd3bfb79c9 | 16,724 |
from typing import Optional
from typing import Dict
from typing import Any
def _field_to_schema_object(field: BaseType, apistrap: Optional[Apistrap]) -> Optional[Dict[str, Any]]:
"""
Convert a field definition to OpenAPI 3 schema.
:param field: the field to be converted
:param apistrap: the extension... | 1451f8795dc39d3168c141fd0ad8dd2615903163 | 16,725 |
from typing import Dict
from typing import Any
def drop_test(robot, *, z_rot: float, min_torque: bool, initial_height: float = 1.) -> Dict[str, Any]:
"""Params which have been tested for this task:
nfe = 20, total_time = 1.0, vary_timestep_with=(0.8,1.2), 5 mins for solving
if min_torque is True, quite a... | e6a070fd52356a314e5d2992d03fa61ead40f950 | 16,727 |
from typing import List
from typing import Union
from datetime import datetime
from typing import Dict
from typing import Any
import httpx
from typing import cast
def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
) -> Union[
List[AModel], HTTPValidationError,... | 77ca30fafb6c29f4cb04d25b52b7cca37e3ede04 | 16,728 |
def old_func5(self, x):
"""Summary.
Bizarre indentation.
"""
return x | 5bc9cdbc406fa49960613578296e81bdd4eeb771 | 16,729 |
def get_dotenv_variable(var_name: str) -> str:
""" """
try:
return config.get(var_name)
except KeyError:
error_msg = f"{var_name} not found!\nSet the '{var_name}' environment variable"
raise ImproperlyConfigured(error_msg) | e3a06f3a439f5eb238688805985fb54eea7221e4 | 16,731 |
def load_dataset():
"""
Create a PyTorch Dataset for the images.
Notes
-----
- See https://discuss.pytorch.org/t/computing-the-mean-and-std-of-dataset/34949
"""
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.9720, 0.9720, 0.9720),
... | 204e33cb7cb79ef81349b083e21ed6779c04dad0 | 16,732 |
def vote(pred1, pred2, pred3=None):
"""Hard voting for the ensembles"""
vote_ = []
index = []
if pred3 is None:
mean = np.mean([pred1, pred2], axis=0)
for s, x in enumerate(mean):
if x == 1 or x == 0:
vote_.append(int(x))
else:
vote... | a24858c0f14fe51a70ff2c0146a4e1aa3a2afdeb | 16,734 |
from pathlib import Path
def generate_master_flat(
science_frame : CCDData,
bias_path : Path,
dark_path : Path,
flat_path : Path,
use_cache : bool=True
) -> CCDData:
"""
"""
cache_path = generate_cache_path(science_frame, flat_path) / 'flat'
if use_cach... | 5448e6f95e1d2c9249ac9419c767e675dc424c5b | 16,735 |
def natrix_mqttclient(client_id):
"""Generate a natrix mqtt client.
This function encapsulates all configurations about natrix mqtt client.
Include:
- client_id
The unique id about mqtt connection.
- username & password
Username is device serial number which used to identify who am I;
... | 20960873f265068aff035ec554b880fa93c49e32 | 16,736 |
def insert_singletons(words, singletons, p=0.5):
"""
Replace singletons by the unknown word with a probability p.
"""
new_words = []
for word in words:
if word in singletons and np.random.uniform() < p:
new_words.append(0)
else:
new_words.append(word)
retu... | c99e9ed38287c175cd97f9cec0c0f8fb8f3629a7 | 16,737 |
def talk(text, is_yelling=False, trim=False, verbose=True):
"""
Prints text
is_yelling capitalizes text
trim - trims whitespace from both ends
verbose - if you want to print something on screen
returns transformed text
"""
if trim:
text = text.strip()
if is_yelling:
t... | 22728a877460b4504653e2a0ea9ecdf81fa422f9 | 16,738 |
def getNorthPoleAngle(target, position, C, B, camera):
"""
Get angle north pole of target makes with image y-axis, in radians.
"""
# get target spin axis
# the last row of the matrix is the north pole vector, *per spice docs*
# seems correct, as it's nearly 0,0,1
Bz = B[2]
print 'Bz=nor... | cf6d79ef3af005a170694d5fe00b93e9dd2665dd | 16,739 |
def ray_casting(polygon, ray_line):
""" checks number of intersection a ray makes with polygon
parameters: Polygon, ray (line)
output: number of intersection
"""
vertex_num = polygon.get_count()
ray_casting_result = [False] * vertex_num
''' count for vertices that is colinear and in... | 004c73fbef35bec5af35b6b93cc5b2bdb2e40f33 | 16,740 |
def ErrorWrapper(err, resource_name):
"""Wraps http errors to handle resources names with more than 4 '/'s.
Args:
err: An apitools.base.py.exceptions.HttpError.
resource_name: The requested resource name.
Returns:
A googlecloudsdk.api_lib.util.exceptions.HttpException.
"""
exc = exceptions.HttpE... | ebcce6241f88d0fa4f093f6823d0ccb9ae1bd431 | 16,743 |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) | a7cc28293eb381604112265a99b9c03e762c2f2c | 16,744 |
def calculate_score(arr):
"""Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
It check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1"""
... | 0890c55068b8a92d9f1f577ccf2c5a770f7887d4 | 16,745 |
def tt_true(alpha):
"""Is the propositional sentence alpha a tautology? (alpha will be
coerced to an expr.)
>>> tt_true(expr("(P >> Q) <=> (~P | Q)"))
True
"""
return tt_entails(TRUE, expr(alpha)) | 91ca0d445407f50d4b985e16428dfeb7f1e1b5a2 | 16,746 |
import configparser
def show_config_data_by_section(data:configparser.ConfigParser, section:str):
"""Print a section's data by section name
Args:
data (configparser.ConfigParser): Data
section (str): Section name
"""
if not _check_data_section_ok(data, section):
return None
... | 620abac7791a9e34707236ea6186b4e77591a393 | 16,748 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.