content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def proxy(values=(0,), names=('constant',), types=('int8',)):
""" Create a proxy image with the given values, names and types
:param values: list of values for every band of the resulting image
:type values: list
:param names: list of names
:type names: list
:param types: list of band types. Op... | b57c4a625d8fa8c7a76bb0f1d2202e0e5cf2d41e | 13,375 |
import six
def _to_versions(raw_ls_remote_lines, version_join, tag_re, tag_filter_re):
"""Converts raw ls-remote output lines to a sorted (descending)
list of (Version, v_str, git_hash) objects.
This is used for source:git method to find latest version and git hash.
"""
ret = []
for line in raw_ls_remote... | 9113d26dbec144bbc72c89ca41935305a7321a18 | 13,376 |
def arraysum(x: int)->int:
"""
These function gives sum of all elements of list by iterating through loop and adding them.
Input: Integer
Output: Interger
"""
sum = 0
for i in x:
sum += i
return sum | aa14eaf4e2bb800ad5e61a63ab0bc17c56dbd86d | 13,377 |
def get_sensitivity_scores(model, features, top_n):
"""
Finds the sensitivity of each feature in features for model. Returns the top_n
feature names, features_top, alongside the sensitivity values, scores_top.
"""
# Get just the values of features
x_train = features.values
# Apply min max no... | a955c93691b09073be20fc65a2c6958a620f5548 | 13,378 |
def mad(data):
"""Median absolute deviation"""
m = np.median(np.abs(data - np.median(data)))
return m | 6b32901a94aca256736c1cb936c8b1c1794857d7 | 13,379 |
async def get_intents(current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches list of existing intents for particular bot
"""
return Response(data=mongo_processor.get_intents(current_user.get_bot())).dict() | 2a62bc579f6b392bc0038bf4f555941f764d456c | 13,380 |
def find_offset(
ax: Numbers, ay: Numbers, bx: Numbers, by: Numbers, upscale: bool = True
) -> float:
"""Finds value, by which the spectrum should be shifted along x-axis to best
overlap with the first spectrum. If resolution of spectra is not identical,
one of them will be interpolated to match resolut... | 64e0c13a16b3ead30227ab80398fea296674385d | 13,383 |
def And(*xs, simplify=True):
"""Expression conjunction (product, AND) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.and_(*xs)
if simplify:
y = y.simplify()
return _expr(y) | 5f25e8b2f37a4bbc077f10eee561936e41defefa | 13,384 |
def get_assignment_submissions(course_id, assignment_id):
""" return a list of submissions for an assignment """
return api.get_list('courses/{}/assignments/{}/submissions'.format(course_id, assignment_id)) | eb1a6143b551298efdb6c4181e2356d759c6fd6c | 13,385 |
def send_email(to, content=None, title=None, mail_from=None,
attach=None, cc=None, bcc=None, text=None, html=None, headers=None):
"""
:param to: 收件人,如 '[email protected]' 或 '[email protected], [email protected]' 或 ['[email protected], [email protected]']
:param content: 邮件内容,纯文本或HTML str
:param title:... | c68c4db3c96890d1e82f33666b69cd4e1ac4c116 | 13,386 |
def get_abbreviation(res_type, abbr):
"""
Returns abbreviation value from data set
@param res_type: Resource type (html, css, ...)
@type res_type: str
@param abbr: Abbreviation name
@type abbr: str
@return dict, None
"""
return get_settings_resource(res_type, abbr, 'abbreviations') | 91831f10fc2be1d7c7201b02e0d044939ce82e83 | 13,387 |
import time
def get_stock_list(month_before=12, trade_date='20200410', delta_price=(10, 200), total_mv=50, pe_ttm=(10, 200)):
"""
month_before : 获取n个月之前所有上市公司的股票列表,
默认为获取一年前上市公司股票列表
delta_price :用于剔除掉金额大于delta_price的股票,若为空则不剔除
TIPS : delta_price 和今天的股价进行比较
"""
... | 13f0dd7b31c297ea643ad42efb519a88907bbfd5 | 13,388 |
def dim_axis_label(dimensions, separator=', '):
"""
Returns an axis label for one or more dimensions.
"""
if not isinstance(dimensions, list): dimensions = [dimensions]
return separator.join([d.pprint_label for d in dimensions]) | f03e4eb02fc57890421bdcdaa0aea7d6541b8678 | 13,389 |
def get_random_idx(k: int, size: int) -> np.ndarray:
"""
Get `k` random values of a list of size `size`.
:param k: number or random values
:param size: total number of values
:return: list of `k` random values
"""
return (np.random.rand(k) * size).astype(int) | eedcc9953e878c9b475cc18666eb621de2811dbe | 13,390 |
from typing import Union
def fhir_search_path_meta_info(path: str) -> Union[tuple, NoneType]:
""" """
resource_type = path.split(".")[0]
properties = path.split(".")[1:]
model_cls = resource_type_to_resource_cls(resource_type)
result = None
for prop in properties:
for (
na... | 2117e9f09c401e2b027d3c3eb7347650eaa03582 | 13,392 |
def _is_camel_case_ab(s, index):
"""Determine if the index is at 'aB', which is the start of a camel token.
For example, with 'workAt', this function detects 'kA'."""
return index >= 1 and s[index - 1].islower() and s[index].isupper() | c21ec7d8aa7e786d1ea523106af6f9426fea01d8 | 13,393 |
def create_bulleted_tool_list(tools):
"""
Helper function that returns a text-based bulleted list of the given tools.
Args:
tools (OrderedDict): The tools whose names (the keys) will be added to the
text-based list.
Returns:
str: A bulleted list of tool names.
"""
r... | d75fb7793c019f2499b549c2af627bb2038876e7 | 13,395 |
def _c3_merge(sequences, cls, context):
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
Adapted from http://www.python.org/download/releases/2.3/mro/.
"""
result = []
while True:
sequences = [s for s in sequences if s] # purge empty sequences
if not sequence... | 6453f151fe227226f3fcbc29d4e5fffd800683cb | 13,396 |
def rgb2hex(rgb: tuple) -> str:
"""
Converts RGB tuple format to HEX string
:param rgb:
:return: hex string
"""
return '#%02x%02x%02x' % rgb | 1ecb1ca68fa3dbe7b58f74c2e50f76175e9a0c5a | 13,397 |
import warnings
def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance... | 2efd839b8ca8ea6fe7b26f645630beb78699a8ea | 13,398 |
def relu(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.relu"""
data, res = fd.args[0], fd.dest
num_dims = get_dims(data.comp)
args = data.comp.args
indices = ""
var_name = CHARACTER_I
for _ in range(num_dims):
indices += f'[{var_name}]'
... | 30eefb572f632e91993d715ecc70570d38030657 | 13,399 |
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 |
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 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 |
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 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 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 |
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 |
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 |
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 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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.