content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def otsu(img):
"""
Method to threshold via a OTSU binarization
"""
gray = ImageIO.grayscale(img)
gray = cv2.GaussianBlur(img, (5,5), 0)
ret, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return th | bb5c10455ecf5e96062d8e9579945fb79f715c9f | 3,607,700 |
import sqlite3
def get_con_cur(db_filename):
"""Returns an open connection and cursor associated with the sqlite
database associated with db_filename.
Args:
db_filename: (str) the filename of the db to which to connect
Returns: a tuple of:
-an open connection to the sqlite database
... | 5b99bb2df4f5a59a89d842f125a04252b86aab38 | 3,607,701 |
import json
def get_image_mean_value(imagepath):
"""
get image first band max vlaue and min value
Args:
imagepath: image path
Returns:(mean value list for each band) if successful, (False) otherwise
"""
mean_value = []
cmd_list = ['gdalinfo','-json','-stats', '-mm', imagepath] ... | 9998737ee6efb87f734b48b11ce9e619910e6461 | 3,607,702 |
def get_eccentricity_critical_inc(ecc=None):
"""Calculates the eccentricity when a frozen orbit has critical inclination
If ecc is None we set an arbitrary value which is the Moon ecc because it seems reasonable
Parameters
----------
ecc: : ~astropy.units.Quantity, optional
Eccentricity, o... | 648e21f4399285ab276a4a1519f39b2fc7f8a1ff | 3,607,703 |
def rotate_point_cloud_by_angle_xyz(data, angle_x=0, angle_y=0, angle_z=0):
""" Rotate the point cloud along up direction with certain angle.
Rotate in the order of x, y and then z.
"""
rotated_data = data.reshape((-1, 3))
cosval = np.cos(angle_x)
sinval = np.sin(angle_x)
rotation_... | 6cb2332a1fb2cd3d4bbfebdc318bf886daee4083 | 3,607,704 |
def correct_background(image, background):
"""Correct the background of an image using a calculated
interpolated background
Parameters
----------
image : 2D numpy array
image to correct
background : 2D numpy array
background image
Returns
-------
im_enhnace... | 6b5bd61ee17e66492a9764b37e73cf015378f0c1 | 3,607,705 |
def search_kepler_tpf_products(target, cadence='long', quarter=None,
campaign=None):
"""Returns a table of Kepler or K2 Target Pixel Files for a given target.
Parameters
----------
cadence: 'short' or 'long'
Specify short (1-min) or long (30-min) cadence data.
... | 1dc7cc3dda5e35d63c2249a5d940f9e72a49c8c6 | 3,607,706 |
def invites_view(user: User, used: bool, include_dead: bool) -> flask.Response:
"""
View sent invites. If a user_id is specified, only invites sent by that user
will be returned, otherwise only your invites are returned. If requester has
the ``invites_view_others`` permission, they can view sent invites... | fd58a9efd363ed513368d6d4b75cd5428de7b49f | 3,607,707 |
def create_card(**kwargs):
"""Create card.
---
This function is called by the create method in serializer
after saving an instance of task.
The instance data is sended to Trello, and saved as a card.
"""
url = "https://api.trello.com/1/cards"
user = kwargs.pop("user_id")
print(kwargs)
resp... | 0410106e604a0d29ab3aa7fb2e51ccc9c1c52eca | 3,607,708 |
def MOL2_setup_ATOM(block_atom):
"""
Setup MOL2 ATOM block as mol attributes
"""
block = Bunch()
### get ###
natoms = len(block_atom)
#assert natoms == num_atoms
aidxs = [None] * natoms
anames = [None] * natoms
atypes = [None] * natoms
resids = [None] * natoms
re... | 7458967ace5f5566aa48e83b05cb3db07be789fa | 3,607,709 |
import scipy
def resize_slits2arc(shape_arc, shape_orig, trace_orig):
"""
Resizes a a trace created with some original binning to be a
relevant to an arc with a different binning
Args:
shape_arc (tuple):
shape of the arc
shape_orig (tuple):
original shape of th... | 8aa01249ad7b2a3769294f209d77dedc4aa48bbf | 3,607,710 |
from typing import Union
from pathlib import Path
def parse_docs_bist(
parser,
docs: Union[str, PathLike],
out_dir: Union[str, PathLike] = None,
show_tok=True,
show_doc=True,
):
"""Parse raw documents in the form of text files in a directory or lines in a text file.
Args:
parser
... | 4977e72d1530392eb497372c7f3fb10da9c81925 | 3,607,711 |
def csr_sum_duplicates(*args):
"""
csr_sum_duplicates(npy_int32 const n_row, npy_int32 const n_col, npy_int32 [] Ap, npy_int32 [] Aj, npy_bool_wrapper [] Ax)
csr_sum_duplicates(npy_int32 const n_row, npy_int32 const n_col, npy_int32 [] Ap, npy_int32 [] Aj, signed char [] Ax)
csr_sum_duplicates(npy_int32 c... | d01da592a3c8c95b597d5456aa82f73675457723 | 3,607,712 |
def send(attachment):
"""Send to download URI."""
path = make_path(attachment.aid)
try:
fp = gcs.open(path)
return flask.send_file(
fp,
mimetype=attachment.content_type,
attachment_filename=attachment.filename,
add_etags=False, as_attachment=Tr... | 02d7f8a563abc7a179a1c1890c27b1ca9e40c1ac | 3,607,713 |
def group_milestones(milestones, include_completed):
"""Group milestones into "open with due date", "open with no due date",
and possibly "completed". Return a list of (label, milestones) tuples."""
def category(m):
return 1 if m.is_completed else 2 if m.due else 3
open_due_milestones, open_not_... | 67b6cae8f30bcf5ff04c83bdf227c4dff0ae0f1c | 3,607,714 |
def small_straight(dice):
"""Score the given roll in the 'Small Straight' category.
"""
if sorted(dice) == [1, 2, 3, 4, 5]:
return sum(dice)
else:
return 0 | 4b88652b32efd49d5d4247ce88584011a43a0b10 | 3,607,715 |
from typing import Sequence
def get_line_items_for_article(
article_number: ArticleNumber,
) -> Sequence[LineItem]:
"""Return all line items for that article."""
line_items = db.session \
.query(DbLineItem) \
.filter_by(article_number=article_number) \
.all()
return list(map(l... | 9135f9157ec988191c9127b527deb7aac4969dd0 | 3,607,716 |
def get_degenerated_faces(mesh):
""" A thin wrapper for :py:func:`get_degenerated_faces_raw`.
"""
return get_degenerated_faces_raw(mesh.vertices, mesh.faces); | f157e0cf23d8402d6f216f6d4801f2082e2e0f5f | 3,607,717 |
import socket
def openServerConn(port, hostname):
"""Waits for client to open connection and returns the connection"""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((hostname, port))
sock.listen(5)
# Wait for a connection
print('Waiting for the frontend to... | e80a64549bd167daee323529740be3a240611b99 | 3,607,718 |
def format_internal_tas(row):
"""Concatenate TAS components into a single field for internal use."""
# This formatting should match formatting in dataactcore.models.stagingModels concatTas
tas = ''.join([
row['allocation_transfer_agency'] if row['allocation_transfer_agency'] else '000',
row[... | 0a1db8f1958d3ee1f06b323f9d00de66814e2a6b | 3,607,719 |
import torch
import os
def validate(dataset, model, criterion, epoch, device, args, save_path_pictures):
"""
Trains/updates the model for one epoch on the training dataset.
Parameters:
train_loader (torch.utils.data.DataLoader): The trainset dataloader
model (torch.nn.module): Model to be... | 386204e1b4ebdfc01a617529a70234091a0449ef | 3,607,720 |
def build_from_issues(gh_token, body):
"""Create a WebhookMetadata from an opening issue text."""
if body["action"] in ["opened", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body["repository"]["full_name"])
issue = repo.get_issue(body["issue"]["number"])
t... | 189bc988d07b059d846864e9498e0b9911fe2df2 | 3,607,721 |
def input_fn_impl(text, model, batch_size, metadata):
"""
Initializes the model with the metadata, creates a single-tensor dataset
from the input text and creates a process function that convert the input into
a sequence. Then creates an iterator that creates predictions for all input tensors.
Will ... | 4567a447ee659ea15aa12a6f78927fb7481e2ad2 | 3,607,722 |
import torch
def optimize_points(opt_points, z, c,
rep_weight=1.,
iterations=1000,
printing=False):
"""Optimization process on point coordinates.
Args:
opt_points (tensor): input init points to be optimized
z (tensor): latent code
... | a979eda3421b0304686291377626f5df6c1268e5 | 3,607,723 |
def build_connstr(**args) -> str:
""" Build commection string from the received parameters. """
# Database client type to connect.
client = args.get("client")
if not client:
raise RuntimeError("Database `client` must be provided to connect to.")
defaults = DEFAULTS.get(client)
if not ... | b3e72a667ebaafc754e0091c6b8d5da6a99c163f | 3,607,724 |
import numpy
def replicate_image(im: Image, polarisation_frame=PolarisationFrame('stokesI'), frequency=numpy.array([1e8]))\
-> Image:
""" Make a new canonical shape Image, extended along third and fourth axes by replication.
The order of the data is [chan, pol, dec, ra]
:param frequency:
:p... | c55927d92b7c1fda2ef0f7f073b606f3a3d5a5ae | 3,607,725 |
def get_symmetry_groups(mol):
"""
Computes the symmetry class for each atom and returns a list with the idx of non-symmetric atoms.
Parameters
----------
mol : rdkit molecule object.
Fragment from custom-made library.
Returns
-------
symmetry_list : list
L... | b2f34fccb600e0127cff9bfc3b0181612de761a5 | 3,607,726 |
def form(self, lab="", **kwargs):
"""Specifies the format of the file dump.
APDL Command: FORM
Parameters
----------
lab
Format:
RECO - Basic record description only (minimum output) (default).
TEN - Same as RECO plus the first ten words of each record.
LONG - Sa... | 68c2ec60889bac22a8f97789acb1586c41c60a06 | 3,607,727 |
from aiida_quantumespresso.utils.mapping import get_logging_container
def parse_output_base(filecontent, codename=None, message_map=None):
"""Parses the output file of a QE calculation, just checking for basic content like JOB DONE, errors with %%%% etc.
:param filecontent: a string with the output file cont... | 28c617e34cd7dee5d4a413afb1503ee1ea5f8d0d | 3,607,728 |
def percent(values, p=0.5):
"""Return a value a faction of the way between the min and max values in a list."""
m = min(values)
interval = max(values) - m
return m + p*interval | 80d3d291122d42e8b9936c4ef994e9ca1a7e98b5 | 3,607,729 |
def get_svm_classification_grid():
"""Hyperparameter space for SVM classifiers."""
cfg = get_svm_config()
cache_size = 100
svc_rbf = {'C': cfg.c, 'gamma': cfg.gamma, 'tol': cfg.tol,
'kernel': ['rbf'],
'max_iter': cfg.max_iter, 'probability': cfg.probability, 'cache_size': ... | ed5d1829ec7ef78d9816496256bb2593eb780d94 | 3,607,730 |
def rank(v):
"""
Returns a list of the ranks from an unsorted list
"""
sx = sorted([(v[i], i) for i in range(len(v))])
rowidx = [i for (_,i) in sx]
ranks = range(len(v))
for i in range(len(v)):
ranks[rowidx[i]] = i
return ranks | 67dfd25b52758eb43d168fad8b647414da470205 | 3,607,731 |
import json
def choices_async(request):
"""Return JSON data for HTML multiselect elements that load their options
dynamically (on type) using the passed (as GET parameter) query string.
"""
report_type = request.GET.get("report_type")
choice_type = request.GET.get("choice_type")
query_str = re... | 0f6b96b901778d35b717345cfd335457f8abf21e | 3,607,732 |
def draw_transformed_box(im, dst, color=(0, 0, 255), thickness=3):
"""
Draws a transformed box on the image similar to drawing contours.
im: The image to be drawn on
dst: The transformed rectangle
color: The color of the rectangle drawn
thickness: The thickness of each side of the rectangle.
... | a4039eea2a4d5da3188f5409c976bb4bfdb8126c | 3,607,733 |
def fit_entropy_classifier(X, y, method, model, calibration_threshold, batch):
"""
Fit a surrogate model to the X,y parameter combinations in the binary case.
Parameters
----------
X:
Parameter combinations to train the model on.
y:
Output of the abm for these parameter com... | d00a1693e002bd5bc6376b14d153fbd29bd90eb2 | 3,607,734 |
def distance(first_point, second_point):
""" Finds the Euclidean distance between points
Args:
first_point(Point): first point
second_point(Point): second point
Returns:
distance between points
"""
return sqrt((first_point.x - second_point.x) ** 2 + (first_point.y - second_... | 864f3e5e0afbd9e87338b3d9d3590f28376bc1dd | 3,607,735 |
import sys
import os
import argparse
import logging
def arg_parse():
"""Base all default folders from script location
scripts: ./pymetric/tools/gridmet
tools: ./pymetric/tools
output: ./pymetric/gridmet
"""
script_folder = sys.path[0]
code_folder = os.path.dirname(script_fol... | f1835c0c184cfc3f8f09a1343bb16e0de419e362 | 3,607,736 |
def _get_plugin_arguments(name):
"""
Get list of host discovery plugin specific cmdline arguments
:param name: plugin module name
"""
try:
plugin = __import__(name, globals(), locals(), ['HostDiscoveryPlugin'])
except ImportError as e:
lg.error("Can't load module %s: %s" % (name... | e580ac8cc70197075e11f7a20180cd44a1a5baf0 | 3,607,737 |
def audio_features(audio_win):
"""
returns audio features for a win
"""
if audio_win.shape[0] % 2 == 1:
audio_win = audio_win[:-1]
spectrum = esst.Spectrum(size=audio_win.shape[0])(audio_win)
_bands, mfcc = esst.MFCC(inputSize=spectrum.shape[0],
sampleRate=SR... | f490c33ee5461c1f74a8f3c5c65f36e0b6827982 | 3,607,738 |
def get_rgbd():
"""
Return rgb and depth image from setup camera pipeline
"""
frames = pipe.wait_for_frames()
aligned_frames = align.process(frames)
aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image
color_frame = aligned_frames.get_color_f... | 487145228902a294d5bf9c49647f35c4fb7da6b7 | 3,607,739 |
import os
def FindRacerdBinary( user_options ):
"""
Find path to racerd binary
This function prefers the 'racerd_binary_path' value as provided in
user_options if available. It then falls back to ycmd's racerd build. If
that's not found, attempts to use racerd from current path.
"""
racerd_user_binary ... | 1efd3df6ccd22885b865a600b6faa1403bc40789 | 3,607,740 |
from typing import Callable
def execute_appropriate_validator(
user_type: str, password: str
) -> Callable[[str], Callable]:
"""
Return a class instance of the correct password validator to use based on
the type of user.
Args:
user_type (str): Identify the type of user.
password (... | 55a79000b2ce2da613a1af244b8a256ce7ddf858 | 3,607,741 |
from pathlib import Path
import sys
def check(database):
""" Checks if the selected database exists.
Args:
database: name of the database.
Returns:
database: name of the database.
"""
if Path(database).is_file(): # Database found.
return database
else: # Database not ... | d1c8bc7f191b343d70d86853a644a380c4786978 | 3,607,742 |
def KK_RC10_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | a762ed275e96c3bb6e2605af09a4dbc79d57c369 | 3,607,743 |
def get_tag_structure(simple=False):
"""Get all categories, their tags and the number of recipies per tag."""
data = []
categories = TagCategory.select()
tags = Tag.select().join(TagCategory)
for category in categories:
catname = category.categoryname
thesetags = tags.where(TagCatego... | ea1bd59b6bd22c09fc0ed32bda35d29c50831ee0 | 3,607,744 |
def coa_cropland_parse(dataframe_list, args):
"""
Functions to being parsing and formatting data into flowbyactivity format
:param dataframe_list: list of dataframes to concat and format
:param args: arguments as specified in flowbyactivity.py ('year' and 'source')
:return: dataframe parsed and part... | a6d72a42ce1db2e01ac83779c2e816bac846b999 | 3,607,745 |
from typing import Optional
from typing import Dict
from typing import Any
import warnings
import time
import torch
def collect_and_record(
self,
n_step: Optional[int] = None,
n_episode: Optional[int] = None,
obs_shape: tuple = (84, 84),
stack_num: int = 4,
random: bool... | ed46ec53ee92e25546fb9b9a8e8a98821614c963 | 3,607,746 |
def fns2dict(*functions) -> dict:
"""
Returns a dictionary of function name -> function,
given functions as *arguments.
Return:
Dict[str, Callable]
"""
return {f.__name__: f for f in functions} | 7ddfc5b5a99d016e13e66e4521d9f60b34051505 | 3,607,747 |
import random
def get_rand_enum_val(obj_name=core_pb2.ProgressState):
"""get a random value from an enum list"""
return random.choice(obj_name.values()) | 763af356e4d11efc7419b604a5f24c2ced276218 | 3,607,748 |
def even(n: int) -> bool:
"""Return :py:const:`True` when ``n`` is even."""
return modulo(2, equal(0))(n) | 1ff4db799ca1853c35d581d97c90c2b5904cdf95 | 3,607,749 |
def cudify(x, use_cuda):
"""
Args
x: input Tensor
use_cuda: boolean
"""
if use_cuda:
return x.cuda()
else:
return x | 98987fadd057597c1396f50b3c0456edfb443507 | 3,607,750 |
def compute_lev2_granger_general_case(filedata, order=10, N=None, n_jobs=-1):
"""Compute the granger causality coefficients for each triad in the entire set
"""
print "Computing Granger causality coefficients"
data = pickle.load(open(filedata))
data_timeseries = data['data']
[nTrial, nTime, nCh]... | 28c5f4f942aab158b025e8c071303a9736a71730 | 3,607,751 |
from datetime import datetime
def make_query():
"""
Main function for User to make requests to.
Args:
-----
hashkey: (str, optional) identification; intended to be their hashkey
to manage exclusive knowledge base access.
query: (str) query string con... | 8d5a367a83262f599d8a18d89f5897ee86195e29 | 3,607,752 |
import warnings
def empirical_Ey_and_Ey2_tf(ct=1.0, rt=1.0, cb=0.1, rb=0.1,
nsamples_latent=100, nsamples_output=3,
N=1, M=1, K=25):
""" Returns E_prior[Y] and E_prior[Y^2] for given set of hyperparameters.
The outputs are (tf) differentiable w.r... | 7d5d2d0d712916b2907cc8adf3acc0c101d6a893 | 3,607,753 |
def get_color_dataset(test_set_pct: int, shuffle: bool = True):
"""Create the dataset of light gray squares and dark gray triangles from the images in the directory.
Args:
test_set_pct (int): The percentage of images to use for the test set.
shuffle (bool, optional): Shuffle the images before c... | 020bc562f332629003f32276ff209f71c2d75a22 | 3,607,754 |
def main(base_url=BASE_URL, api_key=API_KEY, new_creds=NEW_CREDS): # noqa: E501
"""getting creds"""
mitto = Mitto(
base_url=BASE_URL,
api_key=API_KEY
)
created_creds = created_credentials(new_creds=new_creds) # noqa: F841, E501# pylint: disable=W0612
creds = mitto.get_credentials()... | 11fe6d8247612ac490bc3bd08f0170fd2c436a21 | 3,607,755 |
from typing import Sequence
def make_flow_model(event_shape: Sequence[int],
num_layers: int,
hidden_sizes: Sequence[int],
num_bins: int) -> distrax.Transformed:
"""Creates the flow model."""
# Alternating binary mask.
mask = jnp.arange(0, np.prod(event... | c7dbbb0864651bf9f66b3b50f9a965566ec6ea3e | 3,607,756 |
def form_str(string: str) -> str:
"""
Форматирование строки по markdown
- Строка с тегами разделенными пробелами
- Теги можно комбинировать
- italic
- bold
- marker wrap
- a tag
"""
return format_string(string.replace(' ', '|')).replace('|', ' ') | ec1f153573ede6ae91ad6c46ad849a13743f2901 | 3,607,757 |
def create_idea():
"""
Create a new idea
"""
# keep track form inputs as payload
payload = dict(request.form.items())
# create new object
obj = insert_one('ideas', **payload)
# redirect to listing page for type
return redirect(url_for('idea', id=obj.inserted_id)) | 3c6d85dc1ebe30ec30c9ffd589a6fca7745f680c | 3,607,758 |
def maxabs(vals):
"""convenience function for the maximum of the absolute values"""
return max([abs(v) for v in vals]) | ec79fe4de1aa658b40a7495f484b26493e5d8fc2 | 3,607,759 |
def get_row_sql(row):
"""Function to get SQL to create column from row in PROC CONTENTS."""
postgres_type = row['postgres_type']
if postgres_type == 'timestamp':
postgres_type = 'text'
return row['name'].lower() + ' ' + postgres_type | 4efecaefa8b79bdeec7447138586cc93268c54df | 3,607,760 |
from typing import List
def create_app(
config: ApiConfiguration,
resources: List[ZResource],
main_path: str,
path_cors_allow=None,
) -> Flask:
"""
API Builder
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config)
path_allow = path_cors_allow
... | 67f20d22897cf4601ae642b1cd343daee0dbc68c | 3,607,761 |
import contextlib
def get_set_rvar(
ir_set: irast.Set, *,
ctx: context.CompilerContextLevel) -> pgast.PathRangeVar:
"""Return a PathRangeVar for a given IR Set.
@param ir_set: IR Set node.
"""
path_id = ir_set.path_id
scope_stmt = relctx.maybe_get_scope_stmt(path_id, ctx=ctx)
... | 6cd0b4663bfe17266f497b359c81603c8a7d0f3b | 3,607,762 |
def energy_column_divg_adj_time_mean(temp, z, q, q_ice, u, v, swdn_toa,
swup_toa, olr, swup_sfc, swdn_sfc,
lwup_sfc, lwdn_sfc, shflx, evap, precip,
ps, dp, radius):
"""Column energy divergence with energy ... | d7506705a4752d88bc0cdb8726c3f5b59101ac44 | 3,607,763 |
def login_user(request):
""" Login function """
username, password = retrieve_user_password(request)
_user = authenticate(username=username, password=password)
if _user is not None:
if _user.is_active:
login(request, _user)
load_data(request, _user)
return Jso... | 1bbd00ddfd739fd677c783c1febce8cec6717a96 | 3,607,764 |
def get_image_index(glTF, image):
"""
Return the image index in the glTF array.
"""
if glTF.get('images') is None:
return -1
image_name = get_image_name(image)
for index, current_image in enumerate(glTF['images']):
if image_name == current_image['name']:
return ind... | 9aa4259c9a4ab2a0377a0f2750c8f5efcd4f409d | 3,607,765 |
import base64
def base64_decode(string):
"""base64 decodes a single bytestring (and is tolerant to getting
called with a unicode string).
The result is also a bytestring.
"""
string = want_bytes(string, encoding='ascii', errors='ignore')
return base64.urlsafe_b64decode(string + b'=' * (-len(st... | 6bfe4c5d584b3a70a9c83199233d2f63ef721a77 | 3,607,766 |
def get_parent_inv_matrix(m_obj, i):
"""
Returns the parentInverseMatrix MMatrix of the given MObject.
Args:
m_obj
i
Return:
matrix
"""
if not m_obj.hasFn(oMa.MFn.kTransform):
return
fn_obj = oMa.MFnDependencyNode(m_obj)
plug = fn_obj.findPlug('parentInv... | 0360e64e413f385dd84e8140e8914dfdb54e9458 | 3,607,767 |
import array
def _refine_ssi_nm(surface1, surface2, u1, v1, u2, v2, tol):
"""
Refine using Nelder-Mead optimization.
"""
def _obj(x):
# factor = 1.
# if x[0] < surface1.au or x[0] > surface1.bu:
# factor = 1000.
# elif x[1] < surface1.av or x[1] > surface1.bv:
... | b358d93867f5b86f207f3f48fb5de7ed571c4e9e | 3,607,768 |
import tqdm
def save_chunks_to_file(
chunks, filename, progress_bar=True, file_size=None, target_name=""
):
"""Saves chunks to a local file
Returns
-------
file_size : int
File size saved in bytes. ``0`` means no file was written.
"""
pbar = None
if progress_bar:
pba... | d12a61da8e21aa20b0039b80b887bf7709825ef9 | 3,607,769 |
from typing import Optional
def get_iot_core_device(device_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetIotCoreDeviceResult:
"""
Get information about a Yandex IoT Core device. For more informa... | 52887a13b35c740afc21f40b9c2443ab110acf88 | 3,607,770 |
def fetch_mid_pts(h, pop_name):
"""gets the mid points from a file, of a particular population name"""
all_pts = h['/data/static/morphology/' + pop_name]
x = (all_pts['x0'] + all_pts['x1']) / 2.
y = (all_pts['y0'] + all_pts['y1']) / 2.
z = (all_pts['z0'] + all_pts['z1']) / 2.
x = x.reshape(x.siz... | e10517cf7a58ab5184a0f4b23cb6323310414165 | 3,607,771 |
def get_jwt_claims():
"""
In a protected endpoint, this will return the dictionary of custom claims
in the JWT that is accessing the endpoint. If no custom user claims are
present, an empty dict is returned instead.
"""
return get_raw_jwt().get(config.user_claims_key, {}) | 39ae0bba41c80979f2b79e1a991b3cff88d9ea0d | 3,607,772 |
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, complex):
return str(obj)
raise TypeError("Type %s not serializable" % type(obj)) | b2968e5841e7d62e350de462086f8e323f747988 | 3,607,773 |
from .get_data import get_data
from .write_data import write_data
def aw_server_world_add(server: data.ServerData) -> data.ServerReturnData:
"""
Add a world to the universe.
Args:
server (ServerCreateData): The world data.
Returns:
ServerReturnData: The created world data.
"""
... | bf9a57ba4e2087d1ff9ee7fbc19047475cf5b050 | 3,607,774 |
def siamese_lstm(pre_trained_embedding_file, max_length, lstm_hidden_dim, vector_dim):
"""Create siamese network
"""
base = base_model(pre_trained_embedding_file, max_length, lstm_hidden_dim, vector_dim)
return siamese_model([max_length], base, metric="cosine") | 4a2db1800a4f630dbe78873bfc725414ba2ffdaa | 3,607,775 |
from typing import Optional
from typing import Mapping
from typing import Any
def get_image(hidden: Optional[bool] = None,
member_status: Optional[str] = None,
most_recent: Optional[bool] = None,
name: Optional[str] = None,
owner: Optional[str] = None,
... | 13b6b7ea7574177a055069b108b4e4d29d7b60e6 | 3,607,776 |
def InverseGnomon(_gnomonX, _gnomonY):
""" from x,y in gnomonic projection gives lat and long
return theta and chi of Q (direction of Q)
WARNING: assume that center of projection is centerlat, centerlongit = 45 deg, 0
"""
lat0 = np.ones(len(_gnomonX)) * np.pi / 4
longit0 = np.zeros(len(_gnomonX... | c86d9323122e66f0fbe96c983daa5d7058b5f75b | 3,607,777 |
from typing import Optional
from typing import List
from typing import cast
def sync_get_processor_arches_from_instance_type(instance_type: str, region_name: Optional[str]=None) -> List[str]:
"""Returns a list of processor architectures supported by the given EC2 instance type
Args:
instance_type (str): An... | c9353d2928fd4961466f96e2cf91248710e58197 | 3,607,778 |
def sectorize(position):
""" Returns a tuple representing the sector for the given `position`.
Parameters
----------
position : tuple of len 3
Returns
-------
sector : tuple of len 3
"""
x, y, z = normalize(position)
x, y, z = x / SECTOR_SIZE, y / SECTOR_SIZE, z / SECTOR_SIZE
... | 89fb69b881baaee1ce21979221446984fdd50158 | 3,607,779 |
def to_normal_strokes(big_stroke):
"""Convert from stroke-5 format back to stroke-3."""
l = 0
for i in range(len(big_stroke)):
if big_stroke[i, 4] > 0:
l = i
break
if l == 0:
l = len(big_stroke)
result = np.zeros((l, 3))
result[:, 0:2] = big_stroke[0:l, 0:... | 2fd45bb92f13193290a0c5b396ad29cdf25c0bc7 | 3,607,780 |
def grid(vis, uvw, flags, weights, frequencies, grid_config,
wmin=-1e30, wmax=1e30, streams=None):
"""
Grids the supplied visibilities in parallel. Note that
a grid is create for each visibility chunk.
Parameters
----------
vis : :class:`dask.array.Array`
visibilities of shape ... | db34e7858d16024a82e115eb5ce79cd8f5db08d3 | 3,607,781 |
def _parse_timestamp(timestamp_in):
"""
Parse flexible timestamp strings, like "tomorrow at 8am".
:param timestamp_in: A string description of the time.
:returns: A timezone aware python datetime object.
:raises: ParseError if the timestamp string is not parsable.
"""
timestamp_out = datepa... | 0c777db3eaa9434a6a5db2be63a5ff6feae0767c | 3,607,782 |
def yices_get_mpq_value(mdl, t, val):
"""Places the value of the mpq term into val, returns 0 on success, and -1 on failure."""
assert mdl is not None
return libyices.yices_get_mpq_value(mdl, t, val) | 0a2f5d96fa7847b1dbb9f2f5f81d373ff2123243 | 3,607,783 |
def CalcPrize(row):
"""Compute the peptide prize as -log10(min p-value)"""
return -np.log10(min(row)) | 6b3308e233fcb5af61f5d62e7a782a327e22a24e | 3,607,784 |
def quotes_t2(ticker: str):
"""Возвращает данные по котировкам в режиме T+2 из локальной версии данных, при необходимости обновляя их
Parameters
----------
ticker
Тикер для которого необходимо получить данные
Returns
-------
pandas.DataFrame
В строках даты торгов
В ... | f82e1bee2edc6a17dbd3cdef4deacfa5f5cf233a | 3,607,785 |
import re
def fetch_csrc_industry_categories():
"""证监会行业分类"""
id_p = re.compile(r'a-l-bd04[A-Z]{2}\d{2}')
href = re.compile(r'bd04[A-Z]{2}\d{2}')
df = _fetch_categories(id_p, href)
return df | 78b0063181b95a1989d240577548ba2312831d3a | 3,607,786 |
def get_graphs() -> dict:
"""
@return:
{
[module_name]: list of graph classes
}
"""
graphs_dict = find_graphs_in_package()
for k, v in graphs_dict.items():
graphs_dict[k] = [i.__name__ for i in v]
return graphs_dict | a3a4c8376a96cbc5550c29de2c9754fd56d4831d | 3,607,787 |
def _plot_merged_dataset(
merged: xr.Dataset,
axis_params: dict,
shade_threshold: int = 500000,
plot_size: tuple = (888, 450),
) -> dict:
"""Use hvplot to plot the dataset and parse the plot dataframe"""
def _change_z(k):
if k == 'z':
return 'color'
return k
ras... | ead663d5a5eaac5bb0538dd59e42b03b5d30daee | 3,607,788 |
def query(cursor, sql, params=None):
"""accepts a database connection or cursor"""
if type(cursor) == psycopg2._psycopg.connection:
cursor = cursor.cursor()
LOG.debug('QUERY "{}" {}', sql, params)
try:
if params:
cursor.execute(sql, params)
else:
cursor.ex... | 14bb155cf103cc85ecf02ecaba015a3c0db35821 | 3,607,789 |
def resolve_relative_path(filename):
"""
Returns the full path to the filename provided, taken relative to the current file
e.g.
if this file was file.py at /path/to/file.py
and the provided relative filename was tests/unit.py
then the resulting path would be /path/to/tests/unit.py
"""... | 447df7fb94dbb3a0796c5207a99062b04dfbbf50 | 3,607,790 |
def CalculateNormalizedMoreauBrotoAutoResidueASA(ProteinSequence):
"""
####################################################################################
Calculte the NormalizedMoreauBorto Autocorrelation descriptors based on
ResidueASA.
Usage:
result=CalculateNormalizedMoreauBrotoAutoResid... | 8c10de95fc4058b0185f84ce2eff0035f2e0c561 | 3,607,791 |
from typing import Dict
def empty_okay_response(headers: Dict = None, status: int = 200) -> Response:
"""Return a Response with empty JSON object and a 200."""
return Response(body='{}', status=status, content_type='application/json',
headers=headers) | 25c33a536153a07407c92fe48e070b25f9065375 | 3,607,792 |
def exact_n_recordingchannels(container, n):
"""
Given input is checked if it has exactly `n` **neo.core.RecordingChannel**
objects.
Parameters
----------
container : list, tuple, iterable, dict, neo container
The container for the neo objects.
n: int
Number of RecordingChan... | 5ab4b60d2beeee9bcfa01ee0a24e780be627149e | 3,607,793 |
from zenml.services.service_status import ServiceState
def get_service_status_emoji(service: "BaseService") -> str:
"""Get the rich emoji representing the operational status of a Service.
Args:
service: Service to get emoji for.
Returns:
String representing the emoji.
"""
if ser... | fc86c0fd22aa31a18b491615630be87f07decdb1 | 3,607,794 |
import torch
def predict_nocuda(image, model, topk=3):
"""Make a prediction for an image using a trained model. No CUDA.
Only returns probabilities vector and categories vector."""
img_tensor = process_image(image) # to pytorch tensor
img_tensor = img_tensor.view(1, 3, 224, 224)
... | 650a312f51180e413b21ab657da533cc3947445a | 3,607,795 |
from rospy import Duration
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def or_to_ros_trajectory(robot, traj, time_tolerance=0.01):
""" Convert an OpenRAVE trajectory to a ROS trajectory.
@param robot: OpenRAVE robot
@type robot: openravepy.Robot
@param traj: input trajector... | 46346079cb30d76ab49eb8f5f3a737e39aac47f4 | 3,607,796 |
def get_last_step(inputs: tf.Tensor, seq_length: tf.Tensor) -> tf.Tensor:
"""Returns the last step of inputs by the sequence length.
If the sequence length is zero, it will return the zero tensor.
Args:
inputs: tensor of [batch_size, max_seq_length, hidden_size].
seq_length: tensor of [batch_size] recor... | b6b10a44e0ca67f45da05812116d090fd54418da | 3,607,797 |
def get_closest_chips_to(chip_x, chip_y, max_x, max_y, invalid_chips):
""" Get the closest chip to a given chip coordinates
:param chip_x: the chip coord in x axis for looking for closest to
:param chip_y: the chip coord in y axis for looking for closest to
:param max_x: the max x coord in the machine
... | a2e53bf0c433cf1653d75621a0886ae806c3e5eb | 3,607,798 |
from typing import OrderedDict
def get_partitions(comm):
"""
Maps partition labels (such as "recovery") to block devices (such as
"mmcblk0p0"), sorted by the number in the block device.
"""
name_cmd = 'ls -l /dev/block/bootdevice/by-name'
output = comm.call(lglaf.make_exec_request(name_cmd))[1... | 8a23e37b350e6ed07ff86b34d07b5767ac2fab28 | 3,607,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.