content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from re import T
def detect_on_image(img_path, img_is_path=False, threshold=0.5, rect_th=1, text_th=1, text_size=1):
"""
img_path: absolute path, or an RGB tensor.
threshold: determines minimum confidence in order to consider prediction.
img_is_path: toggles if img_path is an absolute path or an RGB t... | 8741e5519b4177bd3471912ce7fcd19d2fb829b7 | 13,400 |
import random
def base_hillclimb(base_sol: tuple, neighbor_method: str, max_fevals: int, searchspace: Searchspace, all_results, kernel_options, tuning_options, runner, restart=True, randomize=True, order=None):
""" Hillclimbing search until max_fevals is reached or no improvement is found
Base hillclimber th... | 4007f66d14d52620b7917fb45a7701a8ec2ae96f | 13,401 |
def filter_dates(dates):
"""filter near dates"""
j = 0
while j < len(dates):
date = dates[j]
i = 3
j += 1
while True:
date += timedelta(days=1)
if date in dates:
i += 1
else:
if i > 2:
del... | 447f2e082672c8f37918fce02863bad1f141854b | 13,402 |
def biweight_location(a, c=6.0, M=None, axis=None, eps=1e-8):
"""
Copyright (c) 2011-2016, Astropy Developers
Compute the biweight location for an array.
Returns the biweight location for the array elements.
The biweight is a robust statistic for determining the central
location of... | 4743b85f01f0d655a22f3b6037aaababcd375c7f | 13,403 |
import os
import shutil
def update_copy(src, dest):
"""
Possibly copy `src` to `dest`. No copy unless `src` exists.
Copy if `dest` does not exist, or mtime of dest is older than
of `src`.
Returns: None
"""
if os.path.exists(src):
if (not os.path.exists(dest) or
os.path... | 4f83e633d9348cf8273309707713060e5611c277 | 13,404 |
def model_21(GPUS = 1):
""" one dense: 3000 """
model = Sequential()
model.add(Convolution3D(60, kernel_size = (3, 3, 3), strides = (1, 1, 1), input_shape = (9, 9, 9, 20))) # 32 output nodes, kernel_size is your moving window, activation function, input shape = auto calculated
model.add(BatchNormalization())
... | 990b1f1c8b1271d44cb371733f7cf17c7f288997 | 13,405 |
from datetime import datetime
def strWeekday(
date: str,
target: int,
after: bool = False,
) -> str:
"""
Given a ISO string `date` return the nearest `target` weekday.
**Parameters**
- `date`: The date around which the caller would like target searched.
- `target`: Weekday number as... | d3511212cbbe8935b7acc7e63afff5b454aa039e | 13,406 |
def combine_bincounts_kernelweights(
xcounts, ycounts, gridsize, colx, coly, L, lenkernel, kernelweights, mid, binwidth
):
"""
This function combines the bin counts (xcounts) and bin averages (ycounts) with
kernel weights via a series of direct convolutions. As a result, binned
approximations to X'W... | b283d3dd19720e7d5074a39866cb4cf5d55376d8 | 13,407 |
def get_icon_for_group(group):
"""Get the icon for an AOVGroup."""
# Group has a custom icon path so use. it.
if group.icon is not None:
return QtGui.QIcon(group.icon)
if isinstance(group, IntrinsicAOVGroup):
return QtGui.QIcon(":ht/rsc/icons/aovs/intrinsic_group.png")
return QtGui... | 8e6ea6f22901bc715a7b6ce02c68ca633bf9fe00 | 13,408 |
def unix_to_windows_path(path_to_convert, drive_letter='C'):
"""
For a string representing a POSIX compatible path (usually
starting with either '~' or '/'), returns a string representing an
equivalent Windows compatible path together with a drive letter.
Parameters
----------
path_to_conve... | d3c23e2c19be4b81be135ae84760430be852da41 | 13,409 |
def recordview_create_values(
coll_id="testcoll", view_id="testview", update="RecordView", view_uri=None,
view_entity_type="annal:Test_default",
num_fields=4, field3_placement="small:0,12",
extra_field=None, extra_field_uri=None
):
"""
Entity values used when creating a ... | a4b057acefd8f3e7c35b8412f0f0986d0440ab7a | 13,410 |
import math
def calculateZ(f, t2, a0, a1, a2=0, a3=0):
""" given the frequency array and the filter coefficients,
return Z(s) as a np.array()
"""
s = np.array(f)*2*math.pi*1j ####################
z = (1 + s*t2)/(s*(a3*s**3 + a2*s**2 + a1*s + a0))
return z | 56b2d349d3c279006c85a9dc9b8742395f1a6114 | 13,411 |
def get_team_project_default_permissions(team, project):
"""
Return team role for given project.
"""
perms = get_perms(team, project)
return get_role(perms, project) or "" | e6c41a1cc56c7ae3e51950508fbc1c514b6ebf7d | 13,412 |
from Carbon.File import FSRef, FSGetResourceForkName
from Carbon.Files import fsRdPerm
from Carbon import Res
def readPlistFromResource(path, restype='plst', resid=0):
"""Read plst resource from the resource fork of path.
"""
fsRef = FSRef(path)
resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceFork... | 36d0387114d548d57f41351355c1fe5d948f70e3 | 13,413 |
def simple_satunet(
input_shape,
kernel=(2, 2),
num_classes=1,
activation="relu",
use_batch_norm=True,
dropout=0.1,
dropout_change_per_layer=0.0,
dropout_type="standard",
use_dropout_on_upsampling=False,
filters=8,
num_layers=4,
strides=(1, 1),
):
"""
Customisabl... | 1efdfb6dd15782543adb071b081b580ea78cb986 | 13,414 |
from datetime import datetime
def fracday2datetime(tdata):
"""
Takes an array of dates given in %Y%m%d.%f format and returns a
corresponding datetime object
"""
dates = [datetime.strptime(str(i).split(".")[0], "%Y%m%d").date()
for i in tdata]
frac_day = [i - np.floor(i) for i in t... | 03ca701317a6b80fd8c14eecddc84a380f16b3aa | 13,415 |
def train(ctx, cids, msday, meday, acquired):
"""Trains a random forest model for a set of chip ids
Args:
ctx: spark context
cids (sequence): sequence of chip ids [(x,y), (x1, y1), ...]
msday (int): ordinal day, beginning of training period
meday (int); ordinal day, end of train... | aa3abec936948277db2057047ebeb686eb7331a9 | 13,416 |
def flatten(iterable):
"""
Unpacks nested iterables into the root `iterable`.
Examples:
```python
from flashback.iterating import flatten
for item in flatten(["a", ["b", ["c", "d"]], "e"]):
print(item)
#=> "a"
#=> "b"
#=> "c"
#=> "d"
... | 8c47de3255906fb114a13ecfec4bf4a1204a0dfd | 13,417 |
def get_file_info(bucket, filename):
"""Returns information about stored file.
Arguments:
bucket: a bucket that contains the file.
filename: path to a file relative to bucket root.
Returns:
FileInfo object or None if no such file.
"""
try:
stat = cloudstorage.stat(
'/%s/%s' % (bucket... | f06c6c3f29cf15992d6880e6509b8ebe11d4288b | 13,418 |
import random
def generate_tree(depth, max_depth, max_args):
"""Generate tree-like equations.
Args:
depth: current depth of the node, int.
max_depth: maximum depth of the tree, int.
max_args: maximum number of arguments per operator, int.
Returns:
The root node of a tree structure.
"""
if ... | df8c968444d86658d2d6f09fb836b39119998790 | 13,419 |
import os
def create_experiment(body): # noqa: E501
"""create a experiment
instantiate/start experiment # noqa: E501
:param body: Experiment Object
:type body: dict | bytes
:rtype: ApiResponse
"""
if connexion.request.is_json:
req = Experiment.from_dict(connexion.request.get_js... | bcebee7bcc8b33857311fd8231136c1983f35061 | 13,420 |
def Pow_sca(x_e, c_e, g, R0, R1, omega, epM):
"""Calculate the power scattered by an annulus
with a 'circling' electron as exciting source inside and
an electron moving on a slightly curved trajectory outside (vertical)
The trajectory of the electron derives from a straight vertical
trajectory in th... | aab79a2653428354d88ada4ded683d8eead6dd1e | 13,421 |
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_i... | 6da7916c0c74c4a9c58a91a5920d32ed8e3bbdf5 | 13,422 |
def index():
"""Render upload page."""
log_cmd('Requested upload.index', 'green')
return render_template('upload.html',
page_title='Upload',
local_css='upload.css',
) | 478f970f54a0c66443fbbfa24f44c86622e0e07f | 13,423 |
import tempfile
import json
import tarfile
import os
def pin_rsconnect(data, pin_name, pretty_pin_name, connect_server, api_key):
"""
Make a pin on RStudio Connect.
Parameters:
data: any object that has a to_json method (eg. pandas DataFrame)
pin_name (str): name of pin, only alphanumer... | 8f3fdc29988c1cbc6ceec7c201591502d791e69c | 13,424 |
import tqdm
def partial_to_full(dic1, dic2):
"""This function relates partial curves to full curves, according to the distances between them
The inputs are two dictionaries"""
C = []
D = []
F = []
# Calculate the closest full curve for all the partial curves under
# evaluation
for i i... | 31229ba4715e7241b205b81a207aae6e8290b93e | 13,425 |
import random
def _sample(probabilities, population_size):
"""Return a random population, drawn with regard to a set of probabilities"""
population = []
for _ in range(population_size):
solution = []
for probability in probabilities:
# probability of 1.0: always 1
#... | ac781075f8437ea02b2dde3b241c21685c259e0c | 13,426 |
def nodal_scoping(node_ids, server = None):
"""Helper function to create a specific ``ansys.dpf.core.Scoping``
associated to a mesh.
Parameters
----------
node_ids : List of int
server : server.DPFServer, optional
Server with channel connected to the remote or local instance. When... | a8587a2027326e1c88088fac85a54879f28267d6 | 13,427 |
import json
def user_active(request):
"""Prevents auto logout by updating the session's last active time"""
# If auto logout is disabled, just return an empty body.
if not settings.AUTO_LOGOUT_SECONDS:
return HttpResponse(json.dumps({}), content_type="application/json", status=200)
last_activ... | 332dd45457ab099a2775587dd357f5ccf9d663f7 | 13,428 |
def decode_labels(labels):
"""Validate labels."""
labels_decode = []
for label in labels:
if not isinstance(label, str):
if isinstance(label, int):
label = str(label)
else:
label = label.decode('utf-8').replace('"', '')
labels_decode... | 36b8b10af2cd2868ab1923ccd1e620ccf815d91a | 13,429 |
def indent(text, num=2):
"""Indent a piece of text."""
lines = text.splitlines()
return '\n'.join(indent_iterable(lines, num=num)) | 04b547210463f50c0ddc7ee76547fea199e71bdc | 13,430 |
import random
def random_lever_value(lever_name):
"""Moves a given lever (lever_name) to a random position between 1 and 3.9"""
rand_val = random.randint(10, 39)/10 # Generate random value between 1 and 3.9
return move_lever([lever_name], [round(rand_val, 2)], costs = True) | c39781752b3defe164ad5d451932a71c99d95046 | 13,431 |
def back(update, context):
"""Кнопка назад."""
user = get_user_or_raise(update.effective_user.id)
update.message.reply_text(
messages.MAIN_MENU_MESSAGE, reply_markup=get_start_keyboard(user)
)
return ConversationHandler.END | 827070b4bcefad57afc8847f96a404a9272a0f7b | 13,432 |
def get_norm_residuals(vecs, word):
"""
computes normalized residuals of vectors with respect to a word
Args:
vecs (ndarray):
word (ndarray):
Returns:
tuple : (rvecs_n, rvec_flag)
CommandLine:
python -m ibeis.algo.hots.smk.smk_residuals --test-get_norm_residuals
... | 8514f203907732c2d3175bf25f2803c93166687a | 13,433 |
def user_closed_ticket(request):
"""
Returns all closed tickets opened by user
:return: JsonResponse
"""
columns = _no_priority
if settings.SIMPLE_USER_SHOW_PRIORITY:
columns = _ticket_columns
ticket_list = Ticket.objects.filter(created_by=request.user,
... | 61c2be90937c4d8892dc8756428e3b191adc6d55 | 13,434 |
def review_lock_status(review_id):
"""
return status of review included trials (locked = T or F)
@param review_id: pmid of review
@return: boolean
"""
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor()
cur.execute(
"SELECT included_complete FROM systematic_reviews WHERE re... | 452731857800ac45c5cbbb7e158223e3055e807d | 13,435 |
def get_placekey_from_address(street_address:str, city:str, state:str, postal_code:str, iso_country_code:str='US',
placekey_api_key: str = None) -> str:
"""
Look up the full Placekey for a given address string.
:param street_address: Street address with suite, floor, or apartm... | 0f3f911bb66a30138b8b293455d348f618e11486 | 13,436 |
import os
import time
async def upload_image(
request: Request,
file: UploadFile = File(...)
):
"""
upload image(jpg/jpeg/png/gif) to server and store locally
:return: upload result
"""
save_file_path = os.path.join(os.getcwd().split("app")[0], r"app/static/images")
# pic_uuid... | 4df0841998ffb12cce5ad6fdb4df23f594a57d16 | 13,437 |
from pathlib import Path
def _path_to_str(var):
"""Make sure var is a string or Path, return string representation."""
if not isinstance(var, (Path, str)):
raise ValueError("All path parameters must be either strings or "
"pathlib.Path objects. Found type %s." % type(var))
... | c5ae3ed06be31de3220b5400966866ccda29b9fc | 13,438 |
def netconf_edit_config(task: Task, config: str, target: str = "running") -> Result:
"""
Edit configuration of device using Netconf
Arguments:
config: Configuration snippet to apply
target: Target configuration store
Examples:
Simple example::
> nr.run(task=netcon... | 9862199c65ecbdc9eb037a181e5783eb911f76a1 | 13,439 |
def _cve_id_field_name():
""" Key name for a solr field that contains cve_id
"""
return "cve_id" | 68ca6f2585804e63198a20d3f174836a0cbb0841 | 13,440 |
def mapRuntime(dataFrame1, dataFrame2):
"""
Add the scraped runtimes of the titles in the viewing activity dataframe
Parameters:
dataFrame1: string
The name of the dataFrame to which the user wants to add the runtime
dataFrame2: string
The name of the dataFrame ... | 61d4af72c51e61c6f0077b960e4002dd7d272ad8 | 13,441 |
def get_circ_center_2pts_r(p1, p2, r):
"""
Find the centers of the two circles that share two points p1/p2 and a radius.
From algorithm at http://mathforum.org/library/drmath/view/53027.html. Adapted from version at
https://rosettacode.org/wiki/Circles_of_given_radius_through_two_points#Python.
:p... | 5ad9abe858721ad94c5d16cc8ed617dabe9f3336 | 13,442 |
def crext_MaxFragmentLength(length_exponent):
"""Create a MaxFragmentLength extension.
Allowed lengths are 2^9, 2^10, 2^11, 2^12. (TLS default is 2^14)
`length_exponent` should be 9, 10, 11, or 12, otherwise the extension will
contain an illegal value.
"""
maxlen = (length_exponent-8).to_bytes(1... | 0078d372440dbe4914675efd004b4fb60f73a6d8 | 13,443 |
import torch
def perform_intervention(intervention, model, effect_types=('indirect', 'direct')):
"""Perform intervention and return results for specified effects"""
x = intervention.base_strings_tok[0] # E.g. The doctor asked the nurse a question. She
x_alt = intervention.base_strings_tok[1] # E.g. The ... | 3fae717923adda6d4b08c424c24600d578961a2a | 13,444 |
def nice_size(
self: complex,
unit: str = 'bytes',
long: bool = False,
lower: bool = False,
precision: int = 2,
sep: str = '-',
omissions: list = 'mono deca hecto'.split(),
):
"""
This should behave well on int subclasses
"""
mag = magnitude(self, omissions)
precision = s... | 1361f17e98ce4d5c6f9c094b8a4f1a9e7cf3035b | 13,445 |
from .core.observable.fromcallback import _from_callback
from typing import Callable
from typing import Optional
import typing
def from_callback(func: Callable,
mapper: Optional[typing.Mapper] = None
) -> Callable[[], Observable]:
"""Converts a callback function to an observabl... | b93900f480d5dd851d8e45c00627590ad89fd24c | 13,446 |
import re
def EVLAUVFITS(inUV, filename, outDisk, err, compress=False, \
exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \
include=[], headHi=False, logfile=""):
"""
Write UV data as FITS file
Write a UV data set as a FITAB format file
History writ... | 98de4f1422be2281eca539b9c372e8d0b9980aeb | 13,447 |
def form_cleaner(querydict):
"""
Hacky way to transform form data into readable data by the model constructor
:param querydict: QueryDict
:return: dict
"""
r = dict(querydict.copy())
# Delete the CRSF Token
del r['csrfmiddlewaretoken']
for key in list(r):
# Take first element... | 83d61f028748132803555da85f0afe0215be2edd | 13,448 |
def has_1080p(manifest):
"""Return True if any of the video tracks in manifest have a 1080p profile
available, else False"""
return any(video['width'] >= 1920
for video in manifest['videoTracks'][0]['downloadables']) | f187ff7fd8f304c0cfe600c4bed8e809c4c5e105 | 13,449 |
def visualize_table(filename: str, table: str) -> bool:
"""
Formats the contents of a db table using the texttable package
:param filename: .db file name (String)
:param table: Name of the table to plot (String)
:return: Bool
"""
conn, cursor = get_connection(filename)
table_element... | d7ab8125353ac0550a704ba208a8095f82125294 | 13,450 |
def extractIsekaiMahou(item):
"""
# Isekai Mahou Translations!
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Isekai Mahou Chapter' in item['title'] and 'Release' in item['title']:
return buildReleaseMes... | 8537e5d9374c38aa0218d380013e98c4bfe6eabb | 13,451 |
def delete_version_from_file(fname, par, ctype=gu.PIXEL_MASK, vers=None, cmt=None, verb=False) :
"""Delete specified version from calibration constants.
Parameters
- fname : full path to the hdf5 file
- par : psana.Event | psana.Env | float - tsec event time
- ctype : gu.CTYPE - enumerat... | 2f5e6d180457f140c8195e358ffa6afbae8a227d | 13,452 |
import os
def get_filename(filePath):
"""get filename without file extension from file path
"""
absFilePath = os.path.abspath(filePath)
return os.path.basename(os.path.splitext(absFilePath)[0]) | e9ccddf29f38f88ccd65764a2914689611b142e8 | 13,453 |
from typing import List
from typing import Tuple
import io
def create_midi_file(notes: List[Tuple[int, int]]) -> io.BytesIO:
"""Create a MIDI file from the given list of notes.
Notes are played with piano instrument.
"""
byte_stream = io.BytesIO()
mid = mido.MidiFile()
track = mido.MidiTrack... | 1f9443df11f08a76c9d5c472d025fe92f3d459af | 13,454 |
async def get_programs(request: Request) -> Response:
"""
description: Get a list of all programs
responses:
200:
description: A list of programs.
"""
ow: "OpenWater" = request.app.ow
return ToDictJSONResponse([p.to_dict() for p in ow.programs.store.all]) | d4a16ec19ba4e095c0479a43f2ef191e9dae84f5 | 13,455 |
def create_dataframe(dictionary_to_convert, cols):
"""
From a Dictionary which is passed, and the desired column to create, this function
returns a Dataframe.
"""
dataframe_converted = pd.DataFrame.from_dict(dictionary_to_convert, orient='index', columns = cols)
dataframe_converted = dataframe_convert... | 4f2ad388cd9a12a6aee55e974320c8b7ac7f95a7 | 13,456 |
def br_candidates(data, br_remaining, commit):
"""Find candidates not yet included to be added to br(r,*)
Given the list of remaining, that is not yet taken into account
bug fixes, split this list into part that has been created (fixed)
before creation time of given bug report, and those that were
... | 4885a6b894fbed140db2f6da6f84daba481bf2ef | 13,457 |
import pandas
def aggregate_dataframe(mails_per_sender, datetimes_per_sender):
"""Engineer features and aggregate them in a dataframes.
:param dict mails_per_sender: A dictionary with email counts for each sender
:param dict datetimes_per_sender: A dictionary with datetime objects for
each sender
... | a584d72fdb2df9148b5ff6a6fe907c8f09b26234 | 13,458 |
def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs):
"""Create the test databases.
This function is a copy of the Django setup_databases with one addition.
A Tenant object is created and saved when setting up the database.
"""
test_database... | fc47c571c40f56f6dabc96bd04e270e874b99d6b | 13,459 |
import sys
def about_view(request):
"""
This view gives information about the version and software we have loaded.
"""
evaluation = get_session_evaluation(request.session)
definitions = evaluation.definitions
system_info = mathics_system_info(definitions)
return render(
request,
... | c2d3a8d1c640a3ad6bd7b955e745c288aea87049 | 13,460 |
import os
def is_trace_directory(path: str) -> bool:
"""
Check recursively if a path is a trace directory.
:param path: the path to check
:return: `True` if it is a trace directory, `False` otherwise
"""
path = os.path.expanduser(path)
if not os.path.isdir(path):
return False
... | d0f0a7ef323072196e1b007d88c94de0576d4137 | 13,461 |
def traj2points(traj, npoints, OS):
"""
Transform spoke trajectory to point trajectory
Args:
traj: Trajectory with shape [nspokes, 3]
npoints: Number of readout points along spokes
OS: Oversampling
Returns:
array: Trajectory with shape [nspokes, npoints, 3]
"""
... | f411b91e86943f7ae03f52cf3d6b1005299902ba | 13,462 |
import re
import os
def parse_headings(raw_contents, file_):
"""Parse contents looking for headings. Return a tuple with number
of TOC elements, the TOC fragment and the number of warnings."""
# Remove code blocks
parsable_contents = re.sub(r"```[\s\S]+?```", "", raw_contents)
# Parse H1,H2,H3
... | 9569ba74878852ad95598ef42bb66d3df89c09c8 | 13,463 |
import os
def current_umask():
"""Get the current umask which involves having to set it temporarily."""
mask = os.umask(0)
os.umask(mask)
return mask | ef5ee2405241f880b44b8d6abb56bee4a1e04512 | 13,464 |
def model_variable(name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
constraint=None,
trainable=True,
collections=None,
**kwargs):
"""
Get or cr... | 7c717234fca10163708abf19057e68124b8fe3e8 | 13,465 |
def default_k_pattern(n_pattern):
""" the default number of pattern divisions for crossvalidation
minimum number of patterns is 3*k_pattern. Thus for n_pattern <=9 this
returns 2. From there it grows gradually until 5 groups are made for 40
patterns. From this point onwards the number of groups is kept ... | 60d083ffed24987882fa8074d99e37d06748eaf3 | 13,466 |
def resize_basinData():
"""
read in global data and make the new bt with same length
this step can be elimated if we are using ibtracks in the future CHAZ development
"""
basinName = ['atl','wnp','enp','ni','sh']
nd = 0
for iib in range(0,len(basinName),1):
ib = basin... | f80892b79cbe12f00daa0918ccf1ac579c90193d | 13,467 |
def _cast_wf(wf):
"""Cast wf to a list of ints"""
if not isinstance(wf, list):
if str(type(wf)) == "<class 'numpy.ndarray'>":
# see https://stackoverflow.com/questions/2060628/reading-wav-files-in-python
wf = wf.tolist() # list(wf) does not convert int16 to int
else:
... | cf2bf853b3ac021777a65d5323de6990d8dc4c5c | 13,468 |
import string
import os
def encoded_path(root, identifiers, extension = ".enc", depth = 3, digest = True):
"""generate a unique file-accessible path from the given list of identifiers
starting at the given root directory."""
ident = string.join(identifiers, "_")
if digest:
ident = sha.new(ide... | 16c9b810ca98e5fc2c48ce403f7af83e40066a08 | 13,469 |
def centralize_scene(points):
"""In-place centralize a whole scene"""
assert points.ndim == 2 and points.shape[1] >= 3
points[:, 0:2] -= points[:, 0:2].mean(0)
points[:, 2] -= points[:, 2].min(0)
return points | 3bdbbe5e3e9c1383852afd15910bb23a68e75506 | 13,470 |
def ms(val):
""" Turn a float value into milliseconds as an integer. """
return int(val * 1000) | 97f7d736ead998014a2026a430bf3f0c54042010 | 13,471 |
def render_doc(stig_rule, deployer_notes):
"""Generate documentation RST for each STIG configuration."""
template = JINJA_ENV.get_template('template_doc_rhel7.j2')
return template.render(
rule=stig_rule,
notes=deployer_notes
) | 97167c23b7b9550bac9f8722ac9f9baed21e060e | 13,472 |
def official_evaluate(reference_csv_path, prediction_csv_path):
"""Evaluate metrics with official SED toolbox.
Args:
reference_csv_path: str
prediction_csv_path: str
"""
reference_event_list = sed_eval.io.load_event_list(reference_csv_path,
delimiter='\t', csv_header=False,
... | 718da1a97cb73e382b45c43432f4b991eab93732 | 13,473 |
from pathlib import Path
import yaml
def get_notebooks():
"""Read `notebooks.yaml` info."""
path = Path("tutorials") / "notebooks.yaml"
with path.open() as fh:
return yaml.safe_load(fh) | 232ffc1820f29eddc9ded118b69ea8e6857b00c9 | 13,474 |
def getSimData(startDate, endDate, region):
""" Get all boundary condition data needed for a simulation run
Args:
startDate (string): Start date DD.MM.YYYY
(start time is hard coded to 00:00)
endDate (string): End date DD.MM.YYYY
(end day is... | 65e7c3a18194eeac4781d57c412cbb079c1078ba | 13,475 |
def get_dag_path(pipeline, module=None):
"""
Gets the DAG path.
:@param pipeline: The Airflow Variable key that has the config.
:@type pipeline: str.
:@param module: The module that belongs to the pipeline.
:@type module: str.
:@return: The DAG path of the pipeline.
"""
if module is... | 4b0a9e5d9692d3c2477e23cb4ba988c589fb9b96 | 13,476 |
def blow_up(polygon):
"""Takes a ``polygon`` as input and adds pixels to it according to the following rule. Consider the line between two
adjacent pixels in the polygon (i.e., if connected via an egde). Then the method adds additional equidistand pixels
lying on that line (if the value is double, convert t... | c48005af11b8e1982aa45218159169acca0bd145 | 13,477 |
from typing import Optional
import time
def x_sogs_raw(
s: SigningKey,
B: PublicKey,
method: str,
full_path: str,
body: Optional[bytes] = None,
*,
b64_nonce: bool = True,
blinded: bool = False,
timestamp_off: int = 0,
):
"""
Calculates X-SOGS-* headers.
Returns 4 eleme... | 6184f7f719c8d1e9e8e14fef56a65cd1d87f9f4f | 13,478 |
import json
def get_param(param, content, num=0):
"""
在内容中获取某一参数的值
:param param: 从接口返回值中要提取的参数
:param content: 接口返回值
:param num: 返回值中存在list时,取指定第几个
:return: 返回非变量的提取参数值
"""
param_val = None
if "." in param:
patt = param.split('.')
param_val = httprunner_extract(cont... | d912c3ee22c223b4f9a91dc4817fc54a79139c20 | 13,479 |
def make_thebig_df_from_data(strat_df_list, strat_names):
"""Joins strategy data frames into a single df - **The Big DF** -
Signature of The Big DF:
df(strategy, sim_prefix, exec, node)[metrics]
"""
thebig_df = pd.concat(strat_df_list, axis=0, keys=strat_names)
thebig_df.index.set_names("strate... | 8ce67464a18fde5e81e0c8fd0c2a2d7ea016730e | 13,480 |
from datetime import datetime
def first_weekday_date(date):
"""
Filter - returns the date of the first weekday for the date
Usage (in template):
{{ some_date|first_weekday_date }}
"""
week_start = date - datetime.timedelta(days=date.weekday())
return week_start.date() | 8c7466040bff9e1924dbe365b92d796afe976fed | 13,481 |
def isLto():
"""*bool* = "--lto" """
return options.lto | ada2d688b1fe84fbcbb585c28e9d6251cce3dcd9 | 13,482 |
def runtime():
"""Get the CumulusCI runtime for the current working directory."""
init_logger()
return CliRuntime() | e4c3ed275f08cc7b982550714fa5c66c78ed1aa4 | 13,483 |
def order_json_objects(obj):
"""
Recusively orders all elemts in a Json object.
Source:
https://stackoverflow.com/questions/25851183/how-to-compare-two-json-objects-with-the-same-elements-in-a-different-order-equa
"""
if isinstance(obj, dict):
return sorted((k, order_json_objects(v)) for... | 5a0459d227b0a98c536290e3e72b76424d29820c | 13,484 |
def CalculatePEOEVSA(mol, bins=None):
"""
#################################################################
MOE-type descriptors using partial charges and surface
area contributions.
chgBins=[-.3,-.25,-.20,-.15,-.10,-.05,0,.05,.10,.15,.20,.25,.30]
You can specify your own bins to compute som... | 2b51c65f70b93bee80be5eba740319ab53eeb992 | 13,485 |
def install_pyheif_from_pip() -> int:
"""
Install the python module pyheif from PIP.
Assumes required libraries already installed
:return: return code from pip
"""
print("Installing Python support for HEIF / HEIC...")
cmd = make_pip_command(
'install {} -U --disable-pip-version-che... | b4d9a2d8d08e9e6dde4ac828dd34dfc93dd6ca02 | 13,486 |
def adjust_mlb_names(mlb_id, fname, lname):
"""
Adjusts a prospect's first and last name (fname, lname) given their mlb.com player_id for better usage in matching to the professional_prospects table.
"""
player_mapper = {
}
qry = """SELECT wrong_name
, right_fname
, right_lname
FROM... | 2570cd47e3875e1c621f6b4c7c8659c6edca1d6e | 13,487 |
from typing import Callable
from typing import Any
def all_predicates(*predicates: Callable[[Any], bool]) -> Callable[[Any], bool]:
"""Takes a set of predicates and returns a function that takes an entity
and checks if it satisfies all the predicates.
>>> even_and_prime = all_predicates(is_even, is_prime... | b531e848e3a24851c5bc756beae46bdd14311b1f | 13,488 |
def centered_rand(l):
"""Sample from U(-l, l)"""
return l*(2.*np.random.rand()-1.) | f8cc1a8c6ad190b53061e1e83a410aa5cdcf26ed | 13,489 |
import torch
def compute_rays_length(rays_d):
"""Compute ray length.
Args:
rays_d: [R, 3] float tensor. Ray directions.
Returns:
rays_length: [R, 1] float tensor. Ray lengths.
"""
rays_length = torch.norm(rays_d, dim=-1, keepdim=True) # [N_rays, 1]
return rays_length | 9b43f9ea79708a690282a04eec65dbabf4a7ae36 | 13,490 |
import itertools
def _repeat_elements(arr, n):
"""
Repeats the elements int the input array, e.g.
[1, 2, 3] -> [1, 1, 1, 2, 2, 2, 3, 3, 3]
"""
ret = list(itertools.chain(*[list(itertools.repeat(elem, n)) for elem in arr]))
return ret | 95cf8ebb75505d2704cf957cdd709b8fa735973a | 13,491 |
def get_neighbors_table(embeddings, method, ntrees=None):
"""
This is a factory method for cosine distance nearest neighbor methods.
Args:
embeddings (ndarray): The embeddings to index
method (string): The nearest neighbor method to use
ntrees (int): number of trees for annoy
Returns:
Nearest ne... | ee665e8332bf0f9b4c2e1ed38cf8b328a10cfc9b | 13,492 |
def _compute_positional_encoding(
attention_type,
position_encoding_layer,
hidden_size,
batch_size,
total_length,
seq_length,
clamp_length,
bi_data,
dtype=tf.float32):
"""Computes the relative position encoding.
Args:
attention_type: str, the attention type. Can be "uni" (di... | fe7a87510745aa2c4b7b5f9e3225464d32e4a00e | 13,493 |
def _get_instance_id(instance_list, identity):
"""
Return instance UUID by name or ID, if found.
"""
for i in instance_list.items:
if identity in (i.properties.name, i.id):
return i.id
return None | f466e10028e9b84f23bd4ace1f02ad8f792517ee | 13,494 |
import os
def DBConnect(dwhName=None):
"""
Parameters
----------
dwhName :
Default value = None)
Returns
-------
"""
conn = mysql.connect(host=os.getenv('DBT_MYSQL_HOST'), user="root",
database=dwhName, buffered=True)
cur = conn.cursor()
prin... | abab780180b35b4e5062072c38a1dfa2eb23e666 | 13,495 |
def isPageWatched(user, trunk):
"""Is the page being watched by the user?"""
result = (models.Subscription.all().
filter('user =', user).
filter('trunk =', trunk).
filter('method !=', models.Subscription.METH_MEH))
return result.count(1) != 0 | 07335b32e11ef275a8c23281e295ed175b2b5854 | 13,496 |
def encode(number, base):
"""Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= ... | d430b98af798b298b855b0573bf63e5ff9e1eeb9 | 13,497 |
def _parse_constants():
"""Read the code in St7API and parse out the constants."""
def is_int(x):
try:
_ = int(x)
return True
except ValueError:
return False
with open(St7API.__file__) as f_st7api:
current_comment = None
seen_comments = ... | ca3c10b1eda6d46f86e21f318b960781b8875cc3 | 13,498 |
def verify_outcome(msg, prefix, lista):
"""
Compare message to list of claims: values.
:param prefix: prefix string
:param lista: list of claims=value
:return: list of possible strings
"""
assert msg.startswith(prefix)
qsl = ["{}={}".format(k, v[0]) for k, v in parse_qs(msg[len(prefix) ... | dd24e16c3029c911b939af4a50f4c7c7a71c8722 | 13,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.