content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def has(path: str) -> bool:
""" Test whether object exists in bucket """
_ = path.strip('/').split('/')
bucket = _[0]
key = '/'.join(_[1:])
async with _create_client() as client:
try:
await client.head_object(Bucket=bucket, Key=key)
return True
except Cl... | 1c38da03ce0e4ec3db14ff37a1621151c2b23371 | 65,276 |
def gini( array ):
"""Calculate the Gini coefficient of a numpy array."""
# based on bottom eq: http://www.statsdirect.com/help/content/image/stat0206_wmf.gif
# from: http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
array = array.flatten() #all values are treated equally, array... | 8b70c23c0d6293972b6be5ce641c17b45e9ade62 | 65,277 |
def calculateJacobiMatrixSinj(measurements, nodes_num, Gmatrix, Bmatrix, inj_code, type):
"""
It calculates the Jacobian for Power Injection Measurements
(converted to equivalent rectangualar current measurements)
@param measurements: object of class Measurement that contains all measurements (voltages... | 8aee9a4272693af09d767571de133cc68c053880 | 65,278 |
import requests
import io
import json
def recommend_project(request, person_id):
"""recommend projects api"""
# NLP LOGIC STARTS HERE
projs = requests.get('http://localhost:8000/api/project/')
projs = projs.json()
projs = pd.DataFrame.from_records(projs)
user = requests.get("http://localhost:... | 08a29d95b2fa3958dbc4eb596d307b5058ed9495 | 65,279 |
def _add_to_grid(x, y, marker, color):
"""It adds data to the plot grid."""
h.xplot=[]
h.yplot=[]
for i in range(len(x)):
c=int((x[i] - h.xmin)/h.dx)
r=int((y[i] - h.ymin)/h.dy)
if 0<=r<h.rows and 0<=c<h.cols:
h.xplot.append(c)
h.yplot.append(r)
... | 6e8faa25d818c382680bbb98c9e007ff9be043ea | 65,280 |
import re
def remplace_accents(text: str) -> str:
"""Remplace spanish accents vocab lower case: Unicode code point literal to str"""
text = re.sub(r"á", "a", text, flags=re.I)
text = re.sub(r"é", "e", text, flags=re.I)
text = re.sub(r"í", "i", text, flags=re.I)
text = re.sub(r"ó", "o", text, flags... | d9967d401c637ae5674f88ce72cc86bf7143ba96 | 65,281 |
def encodeProductionCompany(df, filter, threshold):
"""
MultipleHotEncode column production_companies
Json loads does not work here
Regex to extract needed values
Seperate them with | for MultipleHotEncoding
:param df: DataFrame
:param filter: boolean if set should be filtered by threshold
... | 89d97f6a6c4e2d48e2c7823cebc58e6c47ff14ec | 65,282 |
def mock_get_fire_centre_station_codes(__):
""" Returns mocked WFWXWeatherStations codes. """
return all_station_codes | dcaf4c80720427aad43c162368a44fa72ffd4ca7 | 65,283 |
def b(n):
""" Simple function to approximate b(n) when evaluating a Sersic profile
following Capaccioli (1989). Valid for 0.5 < n < 10
Parameters
----------
n: float or array
Sersic index
Returns
-------
b(n): float or array
Approximation to Gamma(2n) = 2 gamma(2n,b(n))... | c0a236c1394cdac31559c2d376b0d62d023e5709 | 65,284 |
from typing import Optional
from datetime import datetime
from typing import Any
async def get_next_task(
*, now: Optional[datetime] = None
) -> tuple[int, str, dict[str, Any], datetime, Optional[int]] | None:
"""
Get and lock the next pending task. Must be called from within a
transaction.
"""
... | 34784db0a60b43d7a93e4f247f1c53e0d99a8c7e | 65,285 |
from typing import List
def compute_sigma_for_given_alpha(bundles:List[float],alpha:float)->float:
"""
This is a helper function to compute_alpha5_using_binary_search.
the function computes one side of the inequality .
:param bundles: valuations of the bags from B1 to Bk, were k is number of agents
... | 08ae1c84f13de03b5404158de146b05b9efbfdce | 65,286 |
def process_upstart_file(pim, filename):
"""Process the UPStart UPE file."""
try:
with open(filename) as file_handle:
_process_file(pim, file_handle)
file_handle.close()
return True
except EnvironmentError as exc:
LOG.error("Cannot open UPStart file: %s", exc)... | c9d42066965d42f8bb3875578857ae3d300d0355 | 65,287 |
def _make_line_map(target_filename, stream=None):
"""
>>> from StringIO import StringIO
>>> _make_line_map('box',
... StringIO('''// ###sourceLocation(file: "foo.bar", line: 3)
... line 2
... line 3
... line 4
... // ###sourceLocation(file: "baz.txt", line: 20)
... line 6
... lin... | d8822c2e8ea026a40cc45c5758aa5feb3fbf5f00 | 65,288 |
from unittest.mock import Mock
def test_app_context_thread(flask_app):
"""Test accessing flask.g from another thread."""
mock_action = Mock()
@flask_app.route(TEST_URL)
def test_handler():
g.test = TEST_G
thread = AppContextThread(target=lambda: mock_action.action(g.test))
thr... | 8c44ecf35cbe08dba54576ea964abcc99500a399 | 65,289 |
from desispec.qa import qalib
import copy
def qa_skysub(param, frame, skymodel, quick_look=False):
"""Calculate QA on SkySubtraction
Note: Pixels rejected in generating the SkyModel (as above), are
not rejected in the stats calculated here. Would need to carry
along current_ivar to do so.
Args:... | 7c0874e607efe4fa7b5b3e3507aeb3868f07b5e0 | 65,290 |
def ind2(e,L):
"""returns the index of an element in a list"""
def indHelp(e,L,c):
if(c==len(L)):
return c
if(e==True):
return c
if(e == L[c]):
return c
return indHelp(e,L,c+1)
return indHelp(e,L,0) | bab0ba443e3b5d9223b6af82763c92e03c91dcb9 | 65,291 |
async def member_novel(
id: int,
page: int = 1,
size: int = 20,
endpoint: PixivEndpoints = Depends(request_client),
):
"""
## Name: `member_novel`
> 通过用户ID获取用户小说列表
---
### Required:
- ***int*** **`id`**
- Description: 用户ID
---
### Optional:
- ***int*** `... | e4673442145d06d5fcf0e2783263e71d534bd877 | 65,292 |
def index():
"""Show homepage"""
# users = User.query.count()
return render_template('site/index.html')
# return render_template('site/index.html', users=users) | b7abdec6e0d2b922b83bb00cb9ab9255ea59467c | 65,293 |
def opponent(team):
"""Given a team, return the opponent team.
>>>opponent(TEAM_WHITES)
-1 #=TEAM_BLACKS
>>>opponent(TEAM_BLACKS)
1 #=TEAM_WHITES
>>>opponent(0)
0
"""
return -team | 4363665bfd8b56c80292c8435b000b4a40fc1a46 | 65,294 |
import logging
def get_query_limit(access_token: str) -> int:
"""
Get the current rate limit for the GitHub GraphQL API
:param access_token: The access token to be used for the query
:return: The current rate limit for the GitHub GraphQL API
"""
try:
data = get_template(
{"... | 0bab08b65ed490ffc09f13c02e7b1e39bfc07ac5 | 65,295 |
def start_razorpay_txn(basket, amount, user=None, email=None):
"""
Record the start of a transaction and calculate costs etc.
"""
if basket.currency:
currency = basket.currency
else:
currency = getattr(settings, 'RAZORPAY_CURRENCY', 'INR')
transaction = Transaction(
user=... | 528ca71d2d222968b016e4787222643207e6a578 | 65,296 |
import random
def create_aug_matrices(nb_matrices, img_width_px, img_height_px,
scale_to_percent=1.0, scale_axis_equally=False,
rotation_deg=0, shear_deg=0,
translation_x_px=0, translation_y_px=0,
seed=None):
"""Create... | 3596be1913d7bbbe723b4e4688dbed1c36d8f00e | 65,297 |
def get_users_composer():
"""Montagem do caso de uso GetUsers"""
user_repository = UserRepository()
usecase = GetUsers(user_repository)
controller = GetUsersController(usecase)
return controller | 6efe265c909c0139ab1268ab7e4d685901ccdd58 | 65,298 |
def get_pairs_over_threshold(m, labels, threshold):
"""
detect pairs over threhold in a similarity matrice
"""
m = np.triu(m)
ind0, ind1 = np.nonzero(m>threshold)
#remove diag
keep = ind0!=ind1
ind0 = ind0[keep]
ind1 = ind1[keep]
pairs = list(zip(labels[ind0], labels[in... | 76e9f471b088c62463d04d44a6f53fd10b4199b3 | 65,299 |
def Interp(theta, intervals):
"""
This just turns the 7 points into 90 points linearly spaced in joint space
"""
long_theta = []
parts = np.zeros((6,intervals-1))
for i in range(int(len(theta)-1)):
delta = (theta[i+1]-theta[i])/intervals
parts[i] = np.linspace(theta[i],the... | e0461aae4c0e3e70ab9e538b45792453003fd36d | 65,300 |
def _makeScriptOrder(gpos):
"""
Run therough GPOS and make an alphabetically
ordered list of scripts. If DFLT is in the list,
move it to the front.
"""
scripts = []
for scriptRecord in gpos.ScriptList.ScriptRecord:
scripts.append(scriptRecord.ScriptTag)
if "DFLT" in scripts:
... | 6c67698c3d084c8e8f038e05a8d8e53811220a15 | 65,302 |
from typing import Union
def tiny(url: str) -> Union[str, None]:
"""
:param url: url
:return: short url
:rtype: Union[str,None]
"""
try:
return Shortener().tinyurl.short(url)
except:
raise tinyUrlError | 16d34a0984a30fbcf2fa0a0239b8c9c01b247d55 | 65,303 |
import math
def axisRotation(axis,angle):
"""Compute rotation matrix. From TDL.
@param axis: The axis of rotation; must be unit length.
@type axis: vec3, vec4, or list of at least three scalars
@type angle: scalar
@param angle: Angle, in radians
@rtype: mat4
"""
#axis=normalize(axis)
... | c8626374d428057d7279859f479065032b8f9b60 | 65,304 |
import importlib
def get_metarig_module(metarig_name):
""" Fetches a rig module by name, and returns it.
"""
name = "rigify.legacy.%s.%s" % (METARIG_DIR, metarig_name)
submod = importlib.import_module(name, package=MODULE_NAME)
importlib.reload(submod)
return submod | 79c16e2ab040286b4a4dda9cf0578bb04d41f7f9 | 65,305 |
import torch
from typing import Tuple
from typing import List
def concat_enc_outs(
input: torch.LongTensor,
enc_out: torch.Tensor,
mask: torch.BoolTensor,
embedding_size: int,
padding_idx: int,
) -> Tuple[torch.Tensor, torch.BoolTensor]:
"""
Concatenate Encoder Outputs.
Does the whole... | 6b1794966229a8f7658afcb70a5e91a652e6b1c5 | 65,306 |
import re
def insert_tags(tags, session):
"""Inserts a list of tag dictionaries into the database
Args:
tags (list): A list of tags, where each tag is a dict with a 'tag' key
and a 'tagged_card' key
session (sqlalchemy session): a session with the database
Returns:
li... | f9f80a421f64540edaa2562d459a26b8b142a6d2 | 65,307 |
def windowed_mean(a, w, mode='reflect', axis=0):
"""
Perform rolling window average (smoothing).
Args:
a: array
w: window length
mode: see jnp.pad
axis: axis to smooth down
Returns: Array the same size as `a`
"""
if w is None:
return jnp.broadcast_to(jnp... | 7d4fed029ba7f523b8b44361784aef4b857b4cee | 65,310 |
import re
def _reg_name_regex():
"""Compile regular expression for RFC3986_ reg-name production
_RFC3986: https://www.ietf.org/rfc/rfc3986
"""
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
unreserved = r"[A-Za-z0-9-._~]"
# pct-encoded = "%" HEXDIG HEXDIG
pct_encoded = r"%[0-9A-... | 9af962094a9d52c49942f472506c37770da2156e | 65,311 |
def _filter_codesign_output(codesign_output):
"""Filters the codesign output which can be extra verbose."""
filtered_lines = []
for line in codesign_output.split("\n"):
if line and not _BENIGN_CODESIGN_OUTPUT_REGEX.search(line):
filtered_lines.append(line)
return "\n".join(filtered_lines) | 9fd429c870a14401386a88dd35c99e12e5a3b395 | 65,313 |
def setup(
epochs: int
) -> tuple:
"""
Setup for running neural network experiments
:param epochs: int, number of epochs to run
:return: tuple, inputs for function to run neural network
"""
ccfd_data = get_data()
train_data, train_target, val_data, val_target, test_data, test_target... | 11254e12ed1ef8497196b0536dc4db7748a81d2b | 65,314 |
def api(tac):
"""TAC API endpoint."""
if len(tac) != 8:
abort(400, 'Bad TAC format')
try:
int(tac)
except ValueError:
abort(400, 'Bad TAC format')
with get_db_connection() as db_conn, db_conn.cursor() as cursor:
cursor.execute('SELECT * FROM gsma_data WHERE tac = %s... | ec4a84e5e480948efbe0e892546e4ceca7d07712 | 65,315 |
def get_global_default_branding(branding_type):
"""
Args:
branding_type (unicode)
Returns:
DefaultBranding
"""
return DefaultBranding.default_key(branding_type).get() | 3d65a39130ad9ede30168fa137df47a13d1dcd89 | 65,316 |
import logging
def _run_binomial_test(contingency_table, verbose):
"""Runs one-sided binomial test using contingency_table.
The null hypothesis is that both models have the same error rate. The
alternative hypothesis is that model 1 has a higher error rate.
See: https://en.wikipedia.org/wiki/Sign_test
Ar... | 88bfa0ec5d3c9db07fc1e567adaaee78d817e3ff | 65,317 |
def translate_address(PARAMETER):
"""
Translates address for use in HBN chain
[PARAMETER] is required and can be any crypto address.
"""
d = urllib2.urlopen(blockexplorer('translate_address') + '/' + str(PARAMETER))
return d.read() | f32da642448781d6d8102cf423d8fa0b86738318 | 65,318 |
def _pressure_conditions(pressure: reaction_pb2.PressureConditions) -> str:
"""Generates a text description of pressure conditions.
Args:
pressure: PressureConditions message.
Returns:
String description of the pressure conditions.
"""
txt = ""
if pressure.atmosphere.type != pr... | 8dfce7a6b402f48ad5612fe736ca8260a3429739 | 65,319 |
def max_future_level(station, poly, shift, start, days):
"""This function returns the maximum relative level predicted for the next day by the best-fit polynomial curve."""
start = date2num(start)
# Array of times from present moment to one day later
x = np.linspace(start, start+days, 100)
# Array of p... | 05ddf0323ff3521d260b3496e86440dbbbe7b38d | 65,320 |
def config_top_path_get(path):
"""Get entry in config top-level
For anything not in the modules section.
"""
config = read_config()
path = path.split("/")
success, end_node = _traverse_module(config, path)
if not success:
return end_node
ret = {"value": end_node}
return js... | ec08e3c08e2344a41ba92ccbde374b9e62a925bf | 65,321 |
def circuit_identity_phasepoly() -> Circuit:
"""Returns a 4-qubit circuit that is equal to the identity, provable by phase polynomial reductions."""
c = Circuit(4)
c.add_gate("ParityPhase",Fraction(1,4),0,1,2,3)
for i in range(4):
c.add_gate("ZPhase",i, Fraction(3,4))
for j in range(i+1,... | a9ed41cdc8462af8efb797ecf1cfe7e96fc3c9c7 | 65,323 |
def build_U (base=None, min_rooms=0, rooms=2, rooms_wide=2, placement=None, outer=None, inner=None, room_height=None):
"""
Modifies the results of base_builder() to result in an U-shaped layout.
:``base``: The base shape collection. If None, a new base will be built from
base_builder. *Defau... | c88944b95bfe73680ec3dc8eed64d54e13e2c7e8 | 65,324 |
def kmp(main, pattern):
"""
kmp字符串匹配
:param main:
:param pattern:
:return:
"""
assert type(main) is str and type(pattern) is str
n, m = len(main), len(pattern)
if m == 0:
return 0
if n <= m:
return 0 if main == pattern else -1
# 求解next数组
next = get_next... | 747379be5fcc52150a82c7ceb3d4343a0934169b | 65,325 |
def make_sentiment_dashboard(topic):
"""
Make a sentiment analysis dashboard for a given topic.
"""
data = load_topic_comprehend(topic)
sent_res = general_sentiment(data)
gauge1 = make_sentiment_gauge(
'Positive Sentiment', sent_res['mean_pos_sent'])
gauge2 = make_sentiment_gauge(
... | 6acf7c3a77788d1e229744dfc7778ebe2c08b92d | 65,326 |
import copy
def GetPackageMap(target):
"""Compiles a package map for the given target from the constants.
Uses a cache in target_version_map, that is dynamically filled in as needed,
since here everything is static data and the structuring is for ease of
configurability only.
Args:
target: The target ... | c37c47bf0832b878debe53a1afa4868507936490 | 65,327 |
def generate_launch_description():
"""launch grasshopper camera node."""
flir_dir = get_package_share_directory('flir_spinnaker_ros2')
config_dir = get_package_share_directory('flir_spinnaker_ros2') + '/config/'
launch_arg = LaunchArg('camera_name', default_value='grasshopper',
... | 78d0425b1c793ff4a7dbaa07a3ad00dc36f119a1 | 65,328 |
import pickle
def deliver(conn, localobj):
"""delivers (recreates) a local object on the other party. the object is
moved by *value*, so changes made to it will not reflect on the local
object. returns a proxy to the remote object"""
return conn.modules.cPickle.loads(pickle.dumps(localobj)) | 5587d08d9ed984a919bdd1fc51e0f3b1e69d5896 | 65,329 |
def calc_all_energies(n, k, params):
"""Calculate all the energies for the 2^n or 3^n states in model.
Parameters
----------
n : int
Number of spins.
k : int
Number of distinct states.
params : ndarray
(h,J) vector
Returns
-------
E : ndarray
Ene... | d9279ce6b59a1148270b69be6c2fefc8c203cebf | 65,330 |
def proximity(geoname_id):
"""
Get cities closest to the specified one.
:param geoname_id: int - ID associated with a city
:returns: Flask response
"""
extra_query_params = [key for key in flask.request.args
if key not in {'k', 'countryCode'}]
if extra_query_params... | 81a4db6da43662421bf64c6666297a9927eacc95 | 65,331 |
def prepare_abe_connectivity_problem_response():
"""
Generates a response to send to AVS indicating there was a problem talking to ABE.
:return {dict}: a response to be sent back to AVS
"""
return prepare_response('There was a problem speaking to ABE. Please contact your Library Overlord.') | 661277db7f20af7b625c0abf2b965702d280aa76 | 65,332 |
def obtener_cantidad_por_ciudades_mensualmente_y_anualmente(PaisOrigen, AnioInicio, AnioFin):
"""
Obtener cantidad de vuelos salientes totales en todas las ciudad de un pais durante un rango de años separando por meses
Obtiene la cantidad de vuelos salientes en todas las ciudades de un pais durante un rango... | 94b2f4d8c4ee39d7ba61b999880727ca28fc7bbd | 65,334 |
import ctypes
def device_array_from_ptr(ptr, nelem, dtype=np.float, finalizer=None):
"""
device_array_from_ptr(ptr, size, dtype=np.float, stream=0)
Create a Numba device array from a ptr, size, and dtype.
"""
# Handle Datetime Column
if dtype == np.datetime64:
dtype = np.dtype("datetim... | 069243086b6aa32218d1252dfba5fca4502ca4b0 | 65,335 |
import math
def poids_attirance(p, dist):
"""
Calcule le poids d'attraction d'une neurone vers une ville.
"""
d = p[0] * p[0] + p[1] * p[1]
d = math.sqrt(d)
d = dist / (d + dist)
return d | 4a997566d19dc7e436a3a1704be7b5ac74424266 | 65,336 |
def computeSamplePvalue(distribution: list, statistic_value: float) -> float:
"""
Compute sample p-value given null distribution and statistic value
"""
N_equal_more_extreme = len(
np.where(np.array(distribution) >= statistic_value)[0]
)
N_total = len(distribution)
return N_equal... | d25444b18cadfc766874829813afe3b45779777c | 65,337 |
from typing import Union
from typing import Tuple
def compute_stats(tris: Union[Triangle64, Triangle32], mass: Real) -> Tuple[np.ndarray, float, float, np.ndarray,
np.ndarray, np.ndarray, np.ndarray]:
"""
Compute statistics on a shape... | 640ecd625aa55fef475f1d16c54e196fff9e9a39 | 65,338 |
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
con... | 94cf2bfb3b8fe9817628932544b00efe560ebfda | 65,340 |
def save_route(route):
""" Save route information into database. """
u_id = current_user.get_id()
db.session.add(Route(u_id, route))
db.session.commit()
flash('Your route has been saved.')
return redirect('/') | 9e05664e6204175e783fe492ab3362d98323ac1c | 65,341 |
def dedup(records):
"""Remove any identical records from the list.
Args:
records (list(dict)): the list of dicts to be filtered.
Returns:
list(dict): the list of records with any duplicates removed.
The list returned contains records in the same order as the original list.
"""
... | f3aadddf1458a08d36331a74722e12057d8ab8f9 | 65,342 |
import inspect
def is_functional_member(member):
"""
Check whether a class member from the __dict__ attribute is a method.
This can be true in two ways:
- It is literally a Python function
- It is a method descriptor (wrapping a function)
Args:
member (object): An object in t... | 268068600689a7935c9a8b26aa14ca09f9679228 | 65,343 |
def read_mask(img_gt_path):
""""
Thay đổi ảnh mask trong grayscale về 0, 1, 2(background/non-neoplastic/neoplastic).
@param: img_gt_path(path to folder contains gt)
@return: img_gt sau khi quy về mask 0, 1, 2
"""
img_gt = cv2.imread(img_gt_path, 0)
img_gt[img_gt < 10] = 0
img_gt[(img_gt... | d4ca70c4f4f9f90f2a5a89d625997f11f0b8c7fc | 65,344 |
import time
def algo_graph_iht(
x_mat, y_tr, max_epochs, lr, x0, tol_algo, edges, costs, s,
g=1, root=-1, gamma=0.1, proj_max_num_iter=50, verbose=0):
""" Graph Iterative Hard Thresholding proposed in [4] and projection
operator is proposed in [2].
:param x_mat: the design ma... | 6e7f66a07b30d360c46217246b1cd598df158aae | 65,345 |
def restore_reply(request, id):
"""Restore reply"""
reply = get_object_or_404(Reply, pk=id)
if reply.status == '6deleted' or reply.status == '5hidden':
reply.status = '1normal'
reply.save()
else:
return error_page(request)
referer = get_referer(request)
return redirect(r... | c8a26f26605ad8b6ca7731c6e12bddff91e47cb3 | 65,346 |
from datetime import datetime
import math
def format_unixtime_ms(unixtime):
"""
Format a unix timestamp in ms to a human readable string
"""
if unixtime:
return str(datetime.datetime.fromtimestamp(math.floor(unixtime / 1000)).strftime("%x %X %Z"))
else:
return "" | e17aa14612686ca5156862352c424c1bdcb3a519 | 65,347 |
def convert_x1y1x2y2_to_XcYcWH(box):
"""
Convert box from dictionary of {"x1":,"y1":,"x2":,"y2"} to {"x_centre":,"y_centre":,"width":,"height":}
Assumption 1: point 1 is the top left and point 2 is the bottom right hand corner
"""
assert box["x1"] <= box["x2"]
assert box["y1"] <= box["y2... | e7da7353b64b969b4c51dc7ece06729b05bad31e | 65,348 |
import numpy
def _plot_panel(ax, ds, fieldName, scale, lower, upper, cmap, normType):
"""
Plot a single panel for a given model in a movie frame
"""
ax.set_adjustable('box')
ds = ds.where(ds[fieldName].notnull(), drop=True)
field = ds[fieldName].values
x = 1e-3*ds['xGL'].values
y = ... | d64d46358fb512d17f41b7315a3f1ca53d4ac820 | 65,349 |
def cms_cancel(request, context):
"""show menu"""
if context.get('edit_mode'):
url = context.get('coop_cms_cancel_url', None)
if url:
return make_link(
url, _('Cancel'), 'times', classes=['alert_on_click', 'icon']
) | 772f6e601fd4f361438861c1f56afdc269029f77 | 65,350 |
def convert_to_onehot(
xs: ArrayLike,
n_classes: int = 0,
) -> np.ndarray:
"""Convert an integer-valued ordinal array to one-hot representation.
Also supports converting binary probabilities to categorical ones,
via the mapping p -> [1-p, p].
If `n_classes == 0`, then
it is inf... | 0cd86216beca7ab3d1a4bd80e1184e34574c4a5f | 65,351 |
def get_decoded_token(token, secret_key='aws-saas-factory'):
"""
Decodes token using PyJWT library
:param token:
:param secret_key='aws-saas-factory':
"""
return jwt.decode(jwt=token,
key=secret_key,
algorithm='HS256') | 3ccbd0f27debfa213d17dd455e95d8609eecc234 | 65,352 |
def format_date_pretty(date_to_format: str) -> str:
"""
Format a date that is in the format YYYY-MM-DD into: 'Name_Of_Month Day, Year'
:param date_to_format: The date to convert.
:return: An easier to read format of the date_to_format.
"""
date_array = date_to_format.split("-")
day = date_a... | 02f8c872057b5b601b83dee9bf34f2174c03340e | 65,353 |
def get_unbounded_params(params):
"""Retrieve unbounded version of model parameters used to fit concentration history.
Parameters
----------
params : sequence
Values of the model parameters. Values should respect the parameter bounds.
Returns
-------
u_params : sequence
Val... | f39f4d1edeac8745962472c302cb1d25ed9bb267 | 65,354 |
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
lst = []
with open(FILE, 'r') as f:
for word in f:
lst.append(word.strip())
return lst | 99a71ba31de68686348e06f4c6f1e34cb9785861 | 65,355 |
import json
def get_word_vec_top_sentences(block_vec,wiki_fpath,num_output=10):
""" Takes in a sentence and returns the most similar sentences within the wikipedia corpus.
args:
block_vec (np.array): shape(300,), average word embeddings for a block of text
wiki_fpath (str): path to the wikiped... | b83c1c05a56c1d55968e25562bed6237c6455b4b | 65,356 |
def resnet_v2(input_shape, depth, num_classes=10):
"""ResNet Version 2 Model builder [b]
Stacks of (1 x 1)-(3 x 3)-(1 x 1) BN-ReLU-Conv2D or also known as
bottleneck layer
First shortcut connection per layer is 1 x 1 Conv2D.
Second and onwards shortcut connection is identity.
At the beginning of... | 370146c54b5c11f59a7a2519fad036180103b953 | 65,357 |
from typing import Union
def get_quantize_parent_for_dequantize_node(
quantized_model: ModelProto, dequantize_node: NodeProto
) -> Union[NodeProto, None]:
"""
Returns the first quantize node found by traversing the first node input of the
given de-quantize node's ancestors. All inputs to de-quantize n... | 90589484e31db357fe416216f98dd3c6200fd3b4 | 65,358 |
import six
def colormap_to_rgba(colormap):
"""
Convert color ma to rgba colors.
"""
if 'continuous' in colormap:
return {k: hex_to_rgba(v) if isinstance(v, (six.string_types, int)) and k in ['from', 'to', 'over'] else v for k, v in colormap.items()}
else:
return {k: hex_to_rgba(v) ... | 5d54173f4b93876c7050377218206343e688fd03 | 65,359 |
def align(a, b, d=-5, s=lambda x,y: x==y, key=lambda x: x, gap=None):
"""Find the globally optimal alignment between the two sequences a and b
using gap penalty d and similarity function s, and return the aligned
sequences. The similarity function is applied to the result of key(x)
and key(y) for each x... | f02b37fedfe8aefec215bbce98902efc59318ff6 | 65,360 |
import importlib
def find_dataset_using_name(dataset_mode):
"""
Get the dataset of certain mode
"""
dataset_filename = "datasets." + dataset_mode + "_dataset"
datasetlib = importlib.import_module(dataset_filename)
# Instantiate the dataset class
dataset = None
# Change the name format... | 665f0a7510f60f6b1455b778dca0969393e3e47f | 65,361 |
def ParseOneFile(f, iwyu_record):
"""Given a file object, read and classify the lines of the file.
For each file that iwyu_output mentions, we return a list of LineInfo
objects, which is a parsed version of each line, including not only
its content but its 'type', its 'key', etc.
Arguments:
f: an iterab... | 2bf1a17d846be95fd595f68bc4dccec181c07c20 | 65,363 |
def get_warcraft_logs_url(zone_id, character_name, wcl_token, realm):
"""
Returns the warcraft logs url for the player with the given character name
and the given zone id.
Returns None if warcraft logs could not be found for the given character.
"""
parse_url = f'https://classic.warcraftlogs.... | 84a0ea83f2f77f630573a9a851ab382a3a5c2ee2 | 65,364 |
def svn_repos_verify_fs3(*args):
"""svn_repos_verify_fs3(svn_repos_t * repos, svn_revnum_t start_rev, svn_revnum_t end_rev, svn_boolean_t check_normalization, svn_boolean_t metadata_only, svn_repos_notify_func_t notify_func, void * notify_baton, svn_repos_verify_callback_t verify_callback, void * verify_baton, svn_... | e4022ac5bb22c3918e9f603842d457d79ba9c321 | 65,365 |
def sigma(find="sigma", printEqs=True, **kwargs):
"""
Stress
Where:
sigma = stress
P = load
A0 = original cross-sectional area
"""
eq = list()
eq.append("Eq(sigma, P / A)")
return solveEqs(eq, find=find, printEq=printEqs, **kwargs) | 67ff64a1692dee0f6b2d6f21a3cae4734ebeae2a | 65,366 |
def check_authentication(func):
"""
检测是否登录成功过,不成功则跳转到登录页面
:param flask_app:
:return:
"""
def __check_authentication(*args, **kwargs):
if "ok" in session and session["ok"]:
return func(*args, **kwargs)
else:
return jsonify(status=403, message="未能授权成功", d... | ba659418c6261e2a4c7a998e58cf94abced59a88 | 65,367 |
def polynomial_3_integral_from_zero(x, a, b, c, d):
"""Integral of polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3.
Integral(f(x)) 0 -> x = a * x + b * x**2 / 2 + c * x**3 / 3 + d * x**4 / 4
"""
return x * (a + x * (b / 2.0 + x * (c / 3.0 + x * d / 4.0))) | 50e7d899e2f509bef0d15cef4fffca6d4af44934 | 65,368 |
def get_event_signature_with_args(hex_signature, args):
"""
Requests the event signature from the CSV file based on the hex_signature
including ongoing names for the parameters
Args:
hex_signature: the 32-byte signature of the event as hex value
args: the names of the parameters of the even... | 7cc8f3cc8742ef364aab5aac573980a38fdfd48f | 65,369 |
import logging
def convert_label_map_to_categories(label_map,
max_num_classes,
use_display_name=True):
"""Loads label map proto and returns categories list compatible with eval.
This function loads a label map and returns a list of dicts, ea... | 3dd504f90e129986378a6a7e4130953e89c50bd1 | 65,370 |
def RPL_ENDOFUSERS(sender, receipient, message):
""" Reply Code 394 """
return "<" + sender + ">: " + message | 3591d9bf24060ae3baf443824a5bd16ecf1309be | 65,371 |
def pancake(N=500, band=0, seed=42):
"""
Sample of the :func:`pancake_field <skgstat.data.pancake_field>`.
By default, the Red band is sampled at 500 random
location without replacement.
Parameters
----------
N : int
Number of sample points to use.
band : int
can be 0 (R... | 618a819f02d55cb146a3273a2c14ddd52715825a | 65,372 |
def get_dataset_url(hit):
"""Select dataset url."""
ret_url = None
for url in hit["_source"].get("urls", []):
if url.startswith("http"):
ret_url = url
if url.startswith("http") and "amazonaws.com" in url:
ret_url = url
if url.startswith("http") and "googleapi... | 1d78757dda61d762008a78e4b9463c7248978f56 | 65,373 |
def test_dag():
"""Creates a test DAG with a few operators to test on."""
def f(task_id):
return f"OP:{task_id}"
with DAG(dag_id="test_xcom_dag", default_args=DEFAULT_ARGS) as dag:
operators = [PythonOperator(python_callable=f, task_id="test_op_%i" % i) for i in range(4)]
return da... | 9acd944fd57a13baa525141d768c8740237a1f04 | 65,374 |
def flip(x: tf.Tensor) -> tf.Tensor:
"""Flip augmentation
Args:
x: Image to flip
Returns:
Augmented image
"""
x = tf.image.random_flip_left_right(x)
x = tf.image.random_flip_up_down(x)
return x | 949defcc6a76866273aaebc4e9da108996efb72f | 65,375 |
def n_dyts_by_count(cnt, dytmat):
"""
Used to "triangle" dytmats, return the dyt_i for the last of a given count.
"""
# Concat an extra False on to this list because argmin of a uniform
# array has the annoying property of returning -1.
# argmin([True, True, True]) == -1 but I want it to return ... | f19816a2261bbee9590beeb3722c018b7e46fc5b | 65,376 |
def peak_slicer(peaks_dirs, peaks_values=None, mask=None, affine=None,
colors=(1, 0, 0), opacity=1, linewidth=1,
lod=False, lod_points=10 ** 4, lod_points_size=3):
""" Visualize peak directions as given from ``peaks_from_model``
Parameters
----------
peaks_dirs : ndarray... | 84b1ea9de050ebfc4d45f088ecd698e94a5fb6ea | 65,377 |
from typing import List
def create_path_from_se2(states: List[StateSE2]) -> InterpolatedPath:
"""
Constructs an InterpolatedPath from a list of StateSE2.
:param states: Waypoints to construct an InterpolatedPath.
:return: InterpolatedPath.
"""
progress_list = calculate_progress(states)
# ... | 7368e3a35a9443c64a44d8079c19cdeb1ce45e85 | 65,379 |
def col(name=None, dtype=None):
"""Return a symbolic column variable (ndim=2, broadcastable=[False,True]).
Parameters
----------
dtype : numeric
None means to use aesara.config.floatX.
name
A name to attach to this variable.
"""
if dtype is None:
dtype = config.floa... | 0b16ba2e2766fc0039c83b2ba52b3ec1b4e8dfd3 | 65,380 |
def _needed_for_ringsdb(card):
""" Check whether a card is needed for RingsDB or not.
"""
card_type = ('Treasure' if card.get(CARD_SPHERE) == 'Boon'
else card.get(CARD_TYPE))
return (card_type in CARD_TYPES_PLAYER and
card.get(CARD_ADVENTURE) != 'Promo') | 7a0efa91d97d85730a2c94c7332684c3c0320337 | 65,381 |
def AMOC_max(AMOC):
""" AMOC maximum at 26 deg N, 1000 m """
lats = approx_lats('ocn')
tdepths = create_tdepth('ocn')
j26 = find_array_idx(lats, 26) # 1451
z1000 = find_array_idx(tdepths, 1000) # 21
return AMOC.isel({'z_t':z1000, 'nlat':j26}) | 913df758a6ed03a9e6065ee484f8fbf9782f26fe | 65,382 |
def all_true_like(arr: pa.Array) -> pa.Array:
"""Return a boolean array with all-True with the same size as the input and the same valid bitmap."""
valid_buffer = arr.buffers()[0]
if valid_buffer:
valid_buffer = valid_buffer.slice(arr.offset // 8)
output_offset = arr.offset % 8
output_lengt... | d7f6b94e5e7e244377f1389d938c4daa06edecd9 | 65,386 |
def phrase_prob(lang1p, lang2p,
transfrom=2,
transto=1,
db="sqlite:///:memory:",
init_val=1.0e-10):
"""
"""
engine = create_engine(db)
Session = sessionmaker(bind=engine)
session = Session()
# search
query = session.query(TransP... | bf2dc8cb62395890fcfa84d77c379bccff1f60d4 | 65,387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.