content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_smallerI(x, i):
"""Return true if string x is smaller or equal to i. """
if len(x) <= i:
return True
else:
return False | 1588ef998f4914aa943a063546112766060a9cbf | 3,659,190 |
import re
def _ParseSourceContext(remote_url, source_revision):
"""Parses the URL into a source context blob, if the URL is a git or GCP repo.
Args:
remote_url: The remote URL to parse.
source_revision: The current revision of the source directory.
Returns:
An ExtendedSourceContext suitable for JSO... | 3bb14066280e616f103d3aa55710706c967df432 | 3,659,191 |
def decrypt_and_verify(message, sender_key, private_key):
"""
Decrypts and verifies a message using a sender's public key name
Looks for the sender's public key in the public_keys/ directory.
Looks for your private key as private_key/private.asc
The ASN.1 specification for a FinCrypt message reside... | 9c3d43cc2ee01abd68416eaad4ea21fe066916a7 | 3,659,192 |
def find_best_margin(args):
""" return `best_margin / 0.1` """
set_global_seeds(args['seed'])
dataset = DataLoader(args['dataset'], args)
X_train, X_test, X_val, y_train, y_test, y_val = dataset.prepare_train_test_val(args)
results = []
for margin in MARGINS:
model = Perceptron(feature_... | 40f3a80c56546e0fc9ae42c70cfc633dc83ba111 | 3,659,193 |
def unfold(raw_log_line):
"""Take a raw syslog line and unfold all the multiple levels of
newline-escaping that have been inflicted on it by various things.
Things that got python-repr()-ized, have '\n' sequences in them.
Syslog itself looks like it uses #012.
"""
lines = raw_log_line \
... | 9e23bdd82ac15086468a383a1ef98989aceee25e | 3,659,195 |
def _mcs_single(mol, mols, n_atms):
"""Get per-molecule MCS distance vector."""
dists_k = []
n_atm = float(mol.GetNumAtoms())
n_incomp = 0 # Number of searches terminated before timeout
for l in range(0, len(mols)):
# Set timeout to halt exhaustive search, which could take minutes
r... | fd2adf4ee9e3811acd4acb144f3b7861ac4b64ff | 3,659,197 |
def new_transaction():
"""
新的交易
:return:
"""
values = request.get_json()
# 检查 POST 请求中的字段
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing values', 400
# 创建新的交易
index = blockchain.new_transaction(values['sender'], v... | 06af06839e6afcaf4188cca724cebc7878455534 | 3,659,198 |
async def get_favicon():
"""Return favicon"""
return FileResponse(path="assets/kentik_favicon.ico", media_type="image/x-icon") | 8597f21ad240cd43f59703624d380e3b879a1a8a | 3,659,199 |
def geocentric_rotation(sphi, cphi, slam, clam):
"""
This rotation matrix is given by the following quaternion operations
qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2
or
qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi , [-1,0,0])
where
qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[... | 83d37e79e35cab2fc309a640751fb85a9cab0177 | 3,659,200 |
def get_price_sma(
ohlcv: DataFrame,
window: int = 50,
price_col: str = "close",
) -> Series:
"""
Price to SMA.
"""
return pd.Series(
ohlcv[price_col] / get_sma(ohlcv, window),
name="Price/SMA{}".format(window),
) | 7f356610462b9f0fbc13c02c6f093d5ec29d4e76 | 3,659,201 |
def map_to_closest(multitrack, target_programs, match_len=True, drums_first=True):
"""
Keep closest tracks to the target_programs and map them to corresponding
programs in available in target_programs.
multitrack (pypianoroll.Multitrack): Track to normalize.
target_programs (list): List of availabl... | 7fd91726fbc66dd3a3f233be9056c00b1b793f46 | 3,659,202 |
import time
def train_naive(args, X_train, y_train, X_test, y_test, rng, logger=None):
"""
Compute the time it takes to delete a specified number of
samples from a naive model sequentially.
"""
# initial naive training time
model = get_naive(args)
start = time.time()
model = model.fit... | 0514df318219a9f69dbd49b65cad2664480e3031 | 3,659,203 |
def helperFunction():
"""A helper function created to return a value to the test."""
value = 10 > 0
return value | 2c4f2e5303aca2a50648860de419e8f94581fee7 | 3,659,204 |
def app_config(app_config):
"""Get app config."""
app_config['RECORDS_FILES_REST_ENDPOINTS'] = {
'RECORDS_REST_ENDPOINTS': {
'recid': '/files'
}
}
app_config['FILES_REST_PERMISSION_FACTORY'] = allow_all
app_config['CELERY_ALWAYS_EAGER'] = True
return app_config | 156f48cfd0937e5717de133fdfdf38c86e66ba71 | 3,659,205 |
from datetime import datetime
def ts(timestamp_string: str):
"""
Convert a DataFrame show output-style timestamp string into a datetime value
which will marshall to a Hive/Spark TimestampType
:param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format
:return: A datetime object
... | 1902e75ab70c7869686e3a374b22fa80a6dfcf1a | 3,659,206 |
def boxes(frame, data, f, parameters=None, call_num=None):
"""
Boxes places a rotated rectangle on the image that encloses the contours of specified particles.
Notes
-----
This method requires you to have used contours for the tracking and run boxes
in postprocessing.
Parameters
--... | 813ef54a8c8b99d003b9ca74b28befc63da2c0b9 | 3,659,207 |
def process_states(states):
"""
Separate list of states into lists of depths and hand states.
:param states: List of states.
:return: List of depths and list of hand states; each pair is from the same state.
"""
depths = []
hand_states = []
for state in states:
... | 6f71d2471a50a93a3dac6a4148a6e3c6c2aa61e8 | 3,659,208 |
import torch
import math
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
"""
Perform uniform spatial sampling on the images and corresponding boxes.
Args:
images (tensor): images to perform uniform crop. The dimension is
`num frames` x `channel` x `height` x `... | c3e1d7eeb50b959fe0a075c742e23e5206730748 | 3,659,209 |
from typing import Tuple
def plot_xr_complex_on_plane(
var: xr.DataArray,
marker: str = "o",
label: str = "Data on imaginary plane",
cmap: str = "viridis",
c: np.ndarray = None,
xlabel: str = "Real{}{}{}",
ylabel: str = "Imag{}{}{}",
legend: bool = True,
ax: object = None,
**kw... | 8702f14fe0fbc508c3cb5893cc5a4a73bfdd0b85 | 3,659,210 |
def recommend_with_rating(user, train):
"""
用户u对物品i的评分预测
:param user: 用户
:param train: 训练集
:return: 推荐列表
"""
rank = {}
ru = train[user]
for item in _movie_set:
if item in ru:
continue
rank[item] = __predict(user, item)
return rank.iteritems() | 372cd9f77d8123351f4b76eeea241aa8a3bcaf97 | 3,659,213 |
def nl_to_break( text ):
"""
Text may have newlines, which we want to convert to <br />
when formatting for HTML display
"""
text=text.replace("<", "<") # To avoid HTML insertion
text=text.replace("\r", "")
text=text.replace("\n", "<br />")
return text | d2baf1c19fae686ae2c4571416b4cad8be065474 | 3,659,214 |
import requests
import logging
def get_page_state(url):
"""
Checks page's current state by sending HTTP HEAD request
:param url: Request URL
:return: ("ok", return_code: int) if request successful,
("error", return_code: int) if error response code,
(None, error_message: str)... | f7b7db656968bed5e5e7d332725e4d4707f2b14b | 3,659,215 |
def unique(list_, key=lambda x: x):
"""efficient function to uniquify a list preserving item order"""
seen = set()
result = []
for item in list_:
seenkey = key(item)
if seenkey in seen:
continue
seen.add(seenkey)
result.append(item)
return result | 57c82081d92db74a7cbad15262333053a2acd3a7 | 3,659,216 |
import dateutil
import pytz
def date_is_older(date_str1, date_str2):
"""
Checks to see if the first date is older than the second date.
:param date_str1:
:param date_str2:
:return:
"""
date1 = dateutil.parser.parse(date_str1)
date2 = dateutil.parser.parse(date_str2)
# set or norma... | 48fcf26cde4276e68daa07c1250de33a739bc5cb | 3,659,217 |
def shorten_namespace(elements, nsmap):
"""
Map a list of XML tag class names on the internal classes (e.g. with shortened namespaces)
:param classes: list of XML tags
:param nsmap: XML nsmap
:return: List of mapped names
"""
names = []
_islist = True
if not isinstance(elements, (lis... | 73dfc4f24a9b0a73cf7b6af7dae47b880faa3e27 | 3,659,218 |
def list_select_options_stream_points():
""" Return all data_points under data_stream """
product_uid = request.args.get('productID', type=str)
query = DataStream.query
if product_uid:
query = query.filter(DataStream.productID == product_uid)
streams_tree = []
data_streams = query.many(... | 34ce7df0ecd241a009b1c8ef44bf33ec64e3d82d | 3,659,219 |
import math
def func2():
"""
:type: None
:rtype: List[float]
"""
return [math.pi, math.pi / 2, math.pi / 4, math.pi / 8] | 62984ba7d8c1efd55569449adbf507e73888a1b7 | 3,659,220 |
def get_playlist_name(pl_id):
"""returns the name of the playlist with the given id"""
sql = """SELECT * FROM playlists WHERE PlaylistId=?"""
cur.execute(sql, (pl_id,))
return cur.fetchone()[1] | 9488eb1c32db8b66f3239dcb454a08b8ea80b8b4 | 3,659,221 |
import random
def weight(collection):
"""Choose an element from a dict based on its weight and return its key.
Parameters:
- collection (dict): dict of elements with weights as values.
Returns:
string: key of the chosen element.
"""
# 1. Get sum of weights
weight_sum = s... | 383ddadd4a47fb9ac7be0292ecc079fcc59c4481 | 3,659,222 |
def knnsearch(y, x, k) :
""" Finds k closest points in y to each point in x.
Parameters
----------
x : (n,3) float array
A point cloud.
y : (m,3) float array
Another point cloud.
k : int
Number of nearest neighbors one wishes to compute.
... | 84cc1bf0f960e1fb44dd44ab95eccce1c424ec05 | 3,659,223 |
def segmentation_gaussian_measurement(
y_true,
y_pred,
gaussian_sigma=3,
measurement=keras.losses.binary_crossentropy):
""" Apply metric or loss measurement incorporating a 2D gaussian.
Only works with batch size 1.
Loop and call this function repeatedly over each sa... | 377f2fa7706c166756efdb3047937b8db2047674 | 3,659,224 |
import json
def request_pull(repo, requestid, username=None, namespace=None):
"""View a pull request with the changes from the fork into the project."""
repo = flask.g.repo
_log.info("Viewing pull Request #%s repo: %s", requestid, repo.fullname)
if not repo.settings.get("pull_requests", True):
... | 7b83c83a236ed840ed5b2eefbf87859d5e120aac | 3,659,227 |
from typing import List
def make_matrix(points: List[float], degree: int) -> List[List[float]]:
"""Return a nested list representation of a matrix consisting of the basis
elements of the polynomial of degree n, evaluated at each of the points.
In other words, each row consists of 1, x, x^2, ..., x^n, whe... | d8fbea3a0f9536cb681b001a852b07ac7b17f6c2 | 3,659,228 |
def verify(request, token, template_name='uaccounts/verified.html'):
"""Try to verify email address using given token."""
try:
verification = verify_token(token, VERIFICATION_EXPIRES)
except VerificationError:
return redirect('uaccounts:index')
if verification.email.profile != request.u... | 56971aca43d04d7909ea6015fd48b6f30fa5b0ab | 3,659,229 |
from typing import Tuple
import threading
from pydantic_factories import ModelFactory
def run_train(params: dict) -> Tuple[threading.Thread, threading.Thread]:
"""Train a network on a data generator.
params -> dictionary.
Required fields:
* model_name
* generator_name
* dataset_dir
* tile... | c3a96996c3d34c18bfeab89b14836d13829d183e | 3,659,230 |
def adjust_seconds_fr(samples_per_channel_in_frame,fs,seconds_fr,num_frame):
"""
Get the timestamp for the first sample in this frame.
Parameters
----------
samples_per_channel_in_frame : int
number of sample components per channel.
fs : int or float
sampling frequency.
... | a19775db3ebcdbe66b50c30bc531e2980ca10082 | 3,659,232 |
def add_header(unicode_csv_data, new_header):
"""
Given row, return header with iterator
"""
final_iterator = [",".join(new_header)]
for row in unicode_csv_data:
final_iterator.append(row)
return iter(final_iterator) | 1fa50492d786aa28fba6062ac472f1c6470a6311 | 3,659,234 |
def get_most_energetic(particles):
"""Get most energetic particle. If no particle with a non-NaN energy is
found, returns a copy of `NULL_I3PARTICLE`.
Parameters
----------
particles : ndarray of dtyppe I3PARTICLE_T
Returns
-------
most_energetic : shape () ndarray of dtype I3PARTICLE_... | b43e275183b0c2992cfd28239a7e038965b40ccf | 3,659,235 |
def stack(tup, axis=0, out=None):
"""Stacks arrays along a new axis.
Args:
tup (sequence of arrays): Arrays to be stacked.
axis (int): Axis along which the arrays are stacked.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: Stacked array.
.. seealso:: :func:`n... | 5f97bed62c77f28415ae82402cbb379372b4708c | 3,659,237 |
def winning_pipeline(mydata,mytestdata,myfinalmodel,feature_selection_done = True,myfeatures =None,numerical_attributes = None):
"""
If feature _selection has not been performed:
Function performs Cross Validation (with scaling within folds) on the data passed through.
Scales the data with Robu... | 636d922e405842ea338f774dd45b5ff78158bfdf | 3,659,238 |
def calc_single_d(chi_widths, chis, zs, z_widths, z_SN, use_chi=True):
"""Uses single_m_convergence with index starting at 0 and going along the entire line of sight.
Inputs:
chi_widths -- the width of the comoving distance bins.
chis -- the mean comoving distances of each bin.
zs -- the mean re... | 6cafe9d8d1910f113fdcd8a3417e127f4f1cf5e6 | 3,659,239 |
def ppo(
client, symbol, timeframe="6m", col="close", fastperiod=12, slowperiod=26, matype=0
):
"""This will return a dataframe of Percentage Price Oscillator for the given symbol across the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): Ticker
timeframe (string... | 0b6c48408b810131370500921a7ab2addbccea8b | 3,659,240 |
import random
def getRandomCoin():
""" returns a randomly generated coin """
coinY = random.randrange(20, int(BASEY * 0.6))
coinX = SCREENWIDTH + 100
return [
{'x': coinX, 'y': coinY},
] | 44a5ea7baddc77f8d1b518c3d1adcccd28935108 | 3,659,241 |
def is_success(msg):
"""
Whether message is success
:param msg:
:return:
"""
return msg['status'] == 'success' | 43ecbf3c7ac8d03ce92ab059e7ec902e51505d0a | 3,659,242 |
from bs4 import BeautifulSoup
def scrape_data(url):
"""
scrapes relevant data from given url
@param {string} url
@return {dict} {
url : link
links : list of external links
title : title of the page
description : sample text
}
"""
http = httplib2.Http()
try:
status, response = http.request(url)
exce... | 4ab640aad73506e74e3a899467a90c2ddec34308 | 3,659,243 |
def list_strip_comments(list_item: list, comment_denominator: str = '#') -> list:
"""
Strips all items which are comments from a list.
:param list_item: The list object to be stripped of comments.
:param comment_denominator: The character with which comment lines start with.
:return list: A cleaned... | e5dd6e0c34a1d91586e12e5c39a3a5413746f731 | 3,659,244 |
def guess_number(name):
"""User defined function which performs the all the operations and prints the result"""
guess_limit = 0
magic_number = randint(1, 20)
while guess_limit < 6: # perform the multiple guess operations and print output
user_guess = get_input("Take... | 14c81f8adc18f59c29aa37ecec91808b275524e2 | 3,659,245 |
def writerformat(extension):
"""Returns the writer class associated with the given file extension."""
return writer_map[extension] | a2f981a993ba4be25304c0f41b0e6b51bef68d68 | 3,659,246 |
def index_like(index):
"""
Does index look like a default range index?
"""
return not (isinstance(index, pd.RangeIndex) and
index._start == 0 and
index._stop == len(index) and
index._step == 1 and index.name is None) | 91a8e626547121768ee7708e5c7cdcf8265c3991 | 3,659,247 |
def zplsc_c_absorbtion(t, p, s, freq):
"""
Description:
Calculate Absorption coeff using Temperature, Pressure and Salinity and transducer frequency.
This Code was from the ASL MatLab code LoadAZFP.m
Implemented by:
2017-06-23: Rene Gelinas. Initial code.
:param t:
:para... | af5a7d1ea0ad4fbfacfd1b7142eaf0a31899cb4c | 3,659,248 |
def estimate_quintic_poly(x, y):
"""Estimate degree 5 polynomial coefficients.
"""
return estimate_poly(x, y, deg=5) | be389d9f09208da14d0b5c9d48d3c6d2e6a86e8d | 3,659,249 |
def add(A, B):
"""
Return the sum of Mats A and B.
>>> A1 = Mat([[1,2,3],[1,2,3]])
>>> A2 = Mat([[1,1,1],[1,1,1]])
>>> B = Mat([[2,3,4],[2,3,4]])
>>> A1 + A2 == B
True
>>> A2 + A1 == B
True
>>> A1 == Mat([[1,2,3],[1,2,3]])
True
>>> zero = Mat([[0,0,0],[0,0,0]])
>>> B... | 5b0054397a76a20194b3a34435074fc901a34f6b | 3,659,250 |
def hindu_lunar_event(l_month, tithi, tee, g_year):
"""Return the list of fixed dates of occurrences of Hindu lunar tithi
prior to sundial time, tee, in Hindu lunar month, l_month,
in Gregorian year, g_year."""
l_year = hindu_lunar_year(
hindu_lunar_from_fixed(gregorian_new_year(g_year)))
da... | aca03e1a77ff6906d31a64ab50355642f848f9d9 | 3,659,251 |
async def statuslist(ctx, *, statuses: str):
"""Manually make a changing status with each entry being in the list."""
bot.x = 0
statuses = statuses.replace("\n", bot.split)
status_list = statuses.split(bot.split)
if len(status_list) <= 1:
return await bot.send_embed(ctx, f"You cannot have ... | 99c43ea464759356977bc35ffcd941655763d783 | 3,659,252 |
def kebab(string):
"""kebab-case"""
return "-".join(string.split()) | 24bc29e066508f6f916013fa056ff54408dcd46d | 3,659,253 |
def getUserID(person):
"""
Gets Humhub User ID using name information
:param person: Name of the person to get the Humhub User ID for
:type person: str.
"""
# search for person string in humhub db
# switch case for only one name (propably lastname) or
# two separate strings (firstname +... | 31d40b6dd0aec8f6e8481aeaa3252d71c6935c39 | 3,659,254 |
def b58decode(v, length):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + resu... | 4757e451106691de3d8805e9f7bdaeb24bd52816 | 3,659,256 |
def get_submission_by_id(request, submission_id):
"""
Returns a list of test results assigned to the submission with the given id
"""
submission = get_object_or_404(Submission, pk=submission_id)
data = submission.tests.all()
serializer = TestResultSerializer(data, many=True)
return Response(... | 4504b46a03056cb289bb0b53dc01d58f0c5c986c | 3,659,257 |
import pkg_resources
def get_resource_path(resource_name):
"""Get the resource path.
Args:
resource_name (str): The resource name relative to the project root
directory.
Returns:
str: The true resource path on the system.
"""
package = pkg_resources.Requirement.parse(... | 0f95e5f26edc9f351323a93ddc75df920e65375d | 3,659,258 |
def do_cluster(items, mergefun, distfun, distlim):
"""Pairwise nearest merging clusterer.
items -- list of dicts
mergefun -- merge two items
distfun -- distance function
distlim -- stop merging when distance above this limit
"""
def heapitem(d0, dests):
"""Find nearest neighbor for ... | afcd32c390c5d9b57eb070d3f923b4abd6f9ac6b | 3,659,259 |
import csv
def read_csv(input_file, quotechar='"'):
"""Reads a tab separated value file."""
with open(input_file, "r") as f:
reader = csv.reader(f,quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines | 3b789904ae612b9b211a7dac5c49289659c415c5 | 3,659,260 |
def rotate_coordinates(local3d, angles):
"""
Rotate xyz coordinates from given view_angles.
local3d: numpy array. Unit LOCAL xyz vectors
angles: tuple of length 3. Rotation angles around each GLOBAL axis.
"""
cx, cy, cz = np.cos(angles)
sx, sy, sz = np.sin(angles)
mat33_x = np.array([
... | 3243cc9d82dd08384995f62709d3fabc7b896dce | 3,659,261 |
import torch
def quantize_enumerate(x_real, min, max):
"""
Randomly quantize in a way that preserves probability mass.
We use a piecewise polynomial spline of order 3.
"""
assert min < max
lb = x_real.detach().floor()
# This cubic spline interpolates over the nearest four integers, ensuri... | d73083d6078c47456aeb64859d8361ad37f7d962 | 3,659,262 |
def counter_format(counter):
"""Pretty print a counter so that it appears as: "2:200,3:100,4:20" """
if not counter:
return "na"
return ",".join("{}:{}".format(*z) for z in sorted(counter.items())) | 992993a590eabb2966eb9de26625077f2597718c | 3,659,263 |
def drot(x, y, c, s):
"""
Apply the Givens rotation {(c,s)} to {x} and {y}
"""
# compute
gsl.blas_drot(x.data, y.data, c, s)
# and return
return x, y | 8554586f2069f04db0116dfee7868d5d0527999a | 3,659,264 |
def _update_dict_within_dict(items, config):
""" recursively update dict within dict, if any """
for key, value in items:
if isinstance(value, dict):
config[key] = _update_dict_within_dict(
value.items(), config.get(key, {})
)
else:
config[key]... | 75b840b8091568b80f713b2ca7725b1a1f917d3a | 3,659,265 |
def masterProductFieldUpdate(objectId: str):
"""
Submit handler for updating & removing field overrides.
:param objectId: The mongodb master product id.
"""
key = request.form.get("field-key")
value = request.form.get("field-value")
# Clean up and trim tags if being set.
if key == MAST... | 3d87cf2de42d5ee0ee9d43116c0bff4181f42da0 | 3,659,266 |
def recalc_Th(Pb, age):
"""Calculates the equivalent amount of ThO_2 that would be required to produce the
measured amount of PbO if there was no UO_2 in the monazite.
INPUTS:
Pb: the concentration of Pb in parts per million
age: the age in million years
"""
return (232. / 208.) * Pb / (np... | 79ba3cc8e9db8adba1d31ec6f9fe3588d3531b97 | 3,659,267 |
def relative_periodic_trajectory_wrap(
reference_point: ParameterVector,
trajectory: ArrayOfParameterVectors,
period: float = 2 * np.pi,
) -> ArrayOfParameterVectors:
"""Function that returns a wrapped 'copy' of a parameter trajectory such that
the distance between the final point of the traject... | ee41bdb547367186b82324e3e080b758984b7747 | 3,659,268 |
import warnings
def planToSet(world,robot,target,
edgeCheckResolution=1e-2,
extraConstraints=[],
equalityConstraints=[],
equalityTolerance=1e-3,
ignoreCollisions=[],
movingSubset=None,
**planOptions):
"""
Creates... | d03ec2c6c1e00388d1271af1e17a94eda0f50122 | 3,659,269 |
def itkimage_to_json(itkimage, manager=None):
"""Serialize a Python itk.Image object.
Attributes of this dictionary are to be passed to the JavaScript itkimage
constructor.
"""
if itkimage is None:
return None
else:
direction = itkimage.GetDirection()
directionMatrix = d... | e55f2da9792e4772de4b145375d1eec1e6ee6e06 | 3,659,270 |
def project(pnt, norm):
"""Projects a point following a norm."""
t = -np.sum(pnt*norm)/np.sum(norm*norm)
ret = pnt+norm*t
return ret/np.linalg.norm(ret) | 865b658862ebc47eccc117f0daebc8afcc99a2ac | 3,659,272 |
def fix_trajectory(traj):
"""Remove duplicate waypoints that are introduced during smoothing.
"""
cspec = openravepy.ConfigurationSpecification()
cspec.AddDeltaTimeGroup()
iwaypoint = 1
num_removed = 0
while iwaypoint < traj.GetNumWaypoints():
waypoint = traj.GetWaypoint(iwaypoint, ... | 30e3925c518dd4aff0f38ef7a02aaa9f7ab3680a | 3,659,273 |
def select_report_data(conn):
""" select report data to DB """
cur = conn.cursor()
cur.execute("SELECT * FROM report_analyze")
report = cur.fetchall()
cur.close()
return report | 9d0bf6d4f6758c873bd6643673784239f9bf4557 | 3,659,275 |
import numpy
def func_lorentz_by_h_pv(z, h_pv, flag_z: bool = False, flag_h_pv: bool = False):
"""Gauss function as function of h_pv
"""
inv_h_pv = 1./h_pv
inv_h_pv_sq = numpy.square(inv_h_pv)
z_deg = z * 180./numpy.pi
c_a = 2./numpy.pi
a_l = c_a * inv_h_pv
b_l = 4.*inv_h_pv_sq
z_d... | 802029e167439471e892fbfbfe4d6fdce8cb1a0e | 3,659,276 |
def get_profile(aid):
"""
get profile image of author with the aid
"""
if 'logged_in' in session and aid ==session['logged_id']:
try:
re_aid = request.args.get("aid")
re = aController.getAuthorByAid(re_aid)
if re != None:
return re
... | daa759c1493a15d6a2e300a6ab552aae30f59706 | 3,659,278 |
def SystemSettings_GetMetric(*args, **kwargs):
"""SystemSettings_GetMetric(int index, Window win=None) -> int"""
return _misc_.SystemSettings_GetMetric(*args, **kwargs) | d9d6d00e6cf54f8e2ed8a06c616b17d6b2905526 | 3,659,279 |
from pathlib import Path
def all_files(dir, pattern):
"""Recursively finds every file in 'dir' whose name matches 'pattern'."""
return [f.as_posix() for f in [x for x in Path(dir).rglob(pattern)]] | 45f12cda2e16cb745d99d2c8dfb454b32130e1c8 | 3,659,280 |
def get_identity_groups(ctx):
"""Load identity groups definitions."""
return render_template('identity-groups', ctx) | 820eb3ebf8d141f37a93485e4428e1cd79da6a44 | 3,659,281 |
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser
from ..django_legacy.django2_0.utils.deprecation import CallableFalse, CallableTrue
def fix_behaviour_contrib_auth_user_is_anonymous_is_authenticated_callability(utils):
"""
Make user.is_anonymous a... | b3f94992c0ada29b82e64d40cac190a567db9013 | 3,659,282 |
def matches(spc, shape_):
"""
Return True if the shape adheres to the spc (spc has optional color/shape
restrictions)
"""
(c, s) = spc
matches_color = c is None or (shape_.color == c)
matches_shape = s is None or (shape_.name == s)
return matches_color and matches_shape | fa9c90ea2be17b0cff7e4e76e63cf2c6a70cc1ec | 3,659,284 |
from typing import Any
def jsonsafe(obj: Any) -> ResponseVal:
"""
Catch the TypeError which results from encoding non-encodable types
This uses the serialize function from my.core.serialize, which handles
serializing most types in HPI
"""
try:
return Response(dumps(obj), status=200, he... | 90aaaad3e890eeb09aaa683395a80f80394bba3e | 3,659,285 |
def get_appliances(self) -> list:
"""Get all appliances from Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliance
- GET
- /appliance
:return: Returns list of dictionaries of each appliance
:r... | 2f1e48869f4494a995efd4adba80a235c4fb1486 | 3,659,286 |
def is_str(element):
"""True if string else False"""
check = isinstance(element, str)
return check | c46b80d109b382de761618c8c9a50d94600af876 | 3,659,287 |
import tempfile
import shutil
def anonymize_and_streamline(old_file, target_folder):
"""
This function loads the edfs of a folder and
1. removes their birthdate and patient name
2. renames the channels to standardized channel names
3. saves the files in another folder with a non-identifyable
... | 2210c72891c3faec73a9d5ce4b83d56ee9adef38 | 3,659,288 |
def deal_text(text: str) -> str:
"""deal the text
Args:
text (str): text need to be deal
Returns:
str: dealed text
"""
text = " "+text
text = text.replace("。","。\n ")
text = text.replace("?","?\n ")
text = text.replace("!","!\n ")
text = text.replace(";"... | 8f16e7cd2431dfc53503c877f9d4b5429f738323 | 3,659,289 |
def _find_timepoints_1D(single_stimulus_code):
"""
Find the indexes where the value of single_stimulus_code turn from zero to non_zero
single_stimulus_code : 1-D array
>>> _find_timepoints_1D([5,5,0,0,4,4,4,0,0,1,0,2,0])
array([ 0, 4, 9, 11])
>>> _find_timepoints_1D([0,0,1,2,3,0,1,0,0])
a... | b2c3d08f229b03f9b9f5278fea4e25c25274d213 | 3,659,291 |
def stiffness_tric(
components: np.ndarray = None,
components_d: dict = None
) -> np.ndarray:
"""Generate triclinic fourth-order stiffness tensor.
Parameters
----------
components : np.ndarray
21 components of triclinic tensor, see
stiffness_component_dict
components_d : dic... | f96a2ffb4e0542f56a4329393b77e9a875dc6cd5 | 3,659,292 |
from typing import Optional
from pathlib import Path
def get_dataset(
dataset_name: str,
path: Optional[Path] = None,
regenerate: bool = False,
) -> TrainDatasets:
"""
Get the repository dataset.
Currently only [Retail Dataset](https://archive.ics.uci.edu/ml/datasets/online+retail) is availabl... | f913f613858c444ddac479d65a169b74a9b4db29 | 3,659,293 |
def get_info_safe(obj, attr, default=None):
"""safely retrieve @attr from @obj"""
try:
oval = obj.__getattribute__(attr)
except:
logthis("Attribute does not exist, using default", prefix=attr, suffix=default, loglevel=LL.WARNING)
oval = default
return oval | 24b4bace8a8cef16d7cddc44238a24dd636f6ca8 | 3,659,294 |
def mkviewcolbg(view=None, header=u'', colno=None, cb=None,
width=None, halign=None, calign=None,
expand=False, editcb=None, maxwidth=None):
"""Return a text view column."""
i = gtk.CellRendererText()
if cb is not None:
i.set_property(u'editable', True)
i.... | 7b49154d9d26cc93f5e42116967634eddc06a06e | 3,659,295 |
def list2str(lst, indent=0, brackets=True, quotes=True):
"""
Generate a Python syntax list string with an indention
:param lst: list
:param indent: indention as integer
:param brackets: surround the list expression by brackets as boolean
:param quotes: surround each item with quotes
:return... | ef441632bf59714d3d44ede5e78835625b41f047 | 3,659,296 |
def _roi_pool_shape(op):
"""Shape function for the RoiPool op.
"""
dims_data = op.inputs[0].get_shape().as_list()
channels = dims_data[3]
dims_rois = op.inputs[1].get_shape().as_list()
num_rois = dims_rois[0]
pooled_height = op.get_attr('pooled_height')
pooled_width = op.get_attr('pooled_width')
ou... | 9c84aa0054dacacefcdf2fd9066538239668ee66 | 3,659,298 |
from typing import Optional
def get_users(*, limit: int, order_by: str = "id", offset: Optional[str] = None) -> APIResponse:
"""Get users"""
appbuilder = current_app.appbuilder
session = appbuilder.get_session
total_entries = session.query(func.count(User.id)).scalar()
to_replace = {"user_id": "id... | 5ef71bfcc79314f0e9481dfa78a8e079dce14339 | 3,659,299 |
import torch
from typing import Optional
def ppo_clip_policy_loss(
logps: torch.Tensor,
logps_old: torch.Tensor,
advs: torch.Tensor,
clipratio: Optional[float] = 0.2
) -> torch.Tensor:
"""
Loss function for a PPO-clip policy.
See paper for full loss function math: https://arxiv.org/abs... | 203c4072e1c04db9cceb9fa58f70b9af512ffb1c | 3,659,301 |
from timeseries import timeseries, loadDBstation
from datetime import datetime
def tide_pred_correc(modfile,lon,lat,time,dbfile,ID,z=None,conlist=None):
"""
Performs a tidal prediction at all points in [lon,lat] at times in vector [time]
Applies an amplitude and phase correction based on a time serie... | 883ac85787a700a785a0b0a08f521aaf6ad821d1 | 3,659,303 |
def generate_new_filename(this_key):
"""Generates filename for processed data from information in this_key."""
[_, _, source_id, experiment_id, _, _] = this_key.split('.')
this_fname = THIS_VARIABLE_ID+'_'+experiment_id+'_'+source_id
return this_fname | 2e9edb4730257e8fc4c68bbcbb32cce133041bb8 | 3,659,304 |
def get_connection(user, pwd):
""" Obtiene la conexion a Oracle """
try:
connection = cx_Oracle.connect(user + '/' + pwd + '@' +
config.FISCO_CONNECTION_STRING)
connection.autocommit = False
print('Connection Opened')
return connection
... | ba7ca784f0778fb06843e3c68af63e6348406735 | 3,659,305 |
from re import T
def _generate_select_expression_for_extended_string_unix_timestamp_ms_to_timestamp(source_column, name):
"""
More robust conversion from StringType to TimestampType. It is assumed that the
timezone is already set to UTC in spark / java to avoid implicit timezone conversions.
Is able t... | 22a1220c260406c82ede127b87fa23356d2f5192 | 3,659,306 |
import xmlrpclib
import getpass
def get_webf_session():
"""
Return an instance of a Webfaction server and a session for authentication
to make further API calls.
"""
server = xmlrpclib.ServerProxy("https://api.webfaction.com/")
print("Logging in to Webfaction as %s." % env.user)
if env.pas... | e6ebe8ad51cdf4a33fcfa70e5f1983ede6f66d31 | 3,659,307 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.