content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def filterSignal(mriSignal, acqTime, timePhysioRegrid, valuesPhysioRegrid, cardiacPeriod, freqDetection='temporal'):
"""
Define function to apply last 2 steps (breathing frequencies filtering and final smoothing) in one single call
:param mriSignal:
:param acqTime:
:param timePhysioRegrid:
:pa... | f762f3037254852c4a40c2ea703542f739001d13 | 40,740 |
def write_string(val: str) -> bytes:
"""Returns the OSC string equivalent of the given python string.
Raises:
- BuildError if the string could not be encoded.
"""
try:
dgram = val.encode('utf-8') # Default, but better be explicit.
except (UnicodeEncodeError, AttributeError) as e:
... | 3e0ca5db6203b9ff27d46b805f0b3cb2f2f7e77a | 40,741 |
def split_in_columns(message=message):
"""Split the message by newline (\n) and join it together on '|'
(pipe), return the obtained output"""
pipe = "|"
message_split = message.split("\n")
message_join = pipe.join(message_split)
return message_join | e0d05c9418f10c87d61ed5fcf4dd366fa77c6d5d | 40,742 |
def detail(container: str):
"""
Inspect a container on Azure Blob Storage
"""
# Get container info
container_client = service_client.get_container_client(
container=container)
container = container_client.get_container_properties()
# Get the blobs inside this container
blobs =... | 588044011c086469ae79f89289214647422d689c | 40,743 |
from datetime import datetime
import shutil
def sync_cp_dump(server, args_array, **kwargs):
"""Function: sync_cp_dump
Description: Locks the database and then copies the database files to a
destination directory.
Arguments:
(input) server -> Database server instance.
(input) a... | f33aee9b22ed0f17dd00e8212218a79bec72ed1c | 40,744 |
import PIL
def create_image (width, height, color='white'):
"""
Creates an empty image.
:param width: image width
:param height: image height
:param color: background color
:return: the image
"""
image = PIL.Image.new("RGBA", (width, height), color)
return image | 77cae1dc440d97e6d4fb46eab3cd270e07223289 | 40,745 |
def convert_image_resize1d(attrs, inputs, tinfos, desired_layouts):
"""Convert Layout pass registration for image resize1d op.
Parameters
----------
attrs : tvm.ir.Attrs
Attributes of current resize op
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
ti... | d2c455ce931cd95887803a9f7271a239acbe4523 | 40,746 |
import json
def index(metadata_context: BaseContext = Provide[ApplicationContainer.context_factory]):
"""Handler for base level URI for the features endpoint.
Supports GET and POST methods for interacting."""
if request.method == constants.HTTP_GET:
with metadata_context.get_session() as session:
... | 098cab3df8f0754ccf0025205d3b56c0328ce66f | 40,747 |
def select_area(ds, lon, lat, g_step=0.25):
"""
Select data for given location or rectangular area from dataset.
In case data for a single location is requested, the nearest data point
for which weather data is given is returned.
Parameters
-----------
ds : xarray.Dataset
Dataset w... | 4760ebdfd0b580403ea2f0e3214f23e9b4806f1d | 40,748 |
def get_ordered_dataset(file_pattern, blocks_only=True, shuffle=True):
"""Given a file pattern,return the dataset contained.
If specified, shuffle the dataset group-wise.
:param blocks_only: whether to only use records with 'is_extracted_block' == True
:type blocks_only: bool
:param file_pattern: t... | 3cbd08e1d3ef72ed13a5605804b757512107f8de | 40,750 |
def build_vxlan_header(encapsulation_header, ethernet_header):
"""
Build NSH header with underlying ethernet header
:param encapsulation_header: VXLAN or GRE NSH header
:type encapsulation_header: `:class:nsh.common.VXLANGPE|GREHEADER`
:param base_header: base NSH header
:type base_header: `:cl... | 304c0d4f4ac06d11073195695a6750507471b7eb | 40,751 |
from typing import OrderedDict
def _new_obj(original_function):
"""Decorator to deepcopy unaltered states into new object
Parameters
----------
original_function : callable
Callable must return None or a Mapping with some or all of
_state_attrs defined.
Returns
-------
ne... | c7e9de3b1dbc6f415c8df87c4feaaefae383c59b | 40,752 |
import logging
def Aggregate_median_SABV(rnaseq):
"""Compute median TPM by gene+tissue+sex."""
logging.info("=== Aggregate_median_SABV:")
logging.info(f"Aggregate_median_SABV IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}")
rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "TPM"]].groupby(by=["ENS... | 99689df7058f9d0d96bae1672076ccca50c11aee | 40,753 |
from typing import Dict
from typing import Any
def is_similar_except_in_shape(
definition_or_instance_1: Dict[str, Any],
definition_or_instance_2: Dict[str, Any],
only_x_dimension: bool = False
) -> bool:
"""Return whether the two given objects are similar in color
(material category) and size (di... | cda59f51908ed76dca8ddf356236a8516e86b174 | 40,754 |
import requests
def simpleapi():
"""Cross-Microservice call"""
url = getservice(APP.node, "simple-api")
key = requests.get(url + "/simple-api/version", timeout=1)
return (key.text, 200) | 62b7cbecfb30e03c1ec0ac3386aa46c29b37a73c | 40,756 |
def mac_address(name, value):
"""Validate that the value represents a MAC address
:param name: Name of the argument
:param value: A string value representing a MAC address
:returns: The value as a normalized MAC address, or None if value is None
:raises: InvalidParameterValue if the value is not a ... | b1d7f49a8032986af06b5aef8e3da9d6a5210b32 | 40,757 |
def total_dist_from_point(data: CachingDataStructure, start_point: tuple,
max_prop_level: int = INF) -> tuple:
"""
For some CachingDataType, it calculates the distance in linear
space for all different propagation levels. Returns a tuple of three
arrays; (1) an array of propaga... | cfd8d1985554db2f38d1a4c8fcca8e8ad3991404 | 40,758 |
def compute_curve(labels, predictions, num_thresholds=None, weights=None):
""" Compute precision-recall curve data by labels and predictions.
Args:
labels (numpy.ndarray or list): Binary labels for each element.
predictions (numpy.ndarray or list): The probability that an element be
... | d0079807c8f46c9399342f17b642da6c38f563fa | 40,759 |
def _split_series(df, series_id, target, by='quantiles', cuts=5, split_col='Cluster'):
"""
Split series into clusters by rank or quantile of average target value
by: str
Rank or quantiles
cuts: int
Number of clusters
split_col: str
Name of new column
Returns:
-----... | 05e5536b4d0b853801c1612aeff6d9dba5f889b7 | 40,761 |
def content_disposition_filename(filename):
"""
Sanitize a file name to be used in the Content-Disposition HTTP
header.
Even if the standard is quite permissive in terms of
characters, there are a lot of edge cases that are not supported by
different browsers.
See http://greenbytes.de/tech/t... | de0c584adef10430a374983d5d8db74e79515e90 | 40,763 |
import json
def new_query(event, *args):
"""Add new query session <kind of deprecated>
Args:
url: review/{review_id}/query
body:
"search" <search dict (wrapper/input_format.py)>
Returns:
{
"review": review object,
"new_query_id": ne... | fdc3d890fd8e01d293ec4c1ed5d1e5a02c30d199 | 40,764 |
def update(gen, test: dict, context: dict, event):
"""
:param gen: 一个generator对象
:param test: 传入的本次测试配置(来自config.yaml)
:param context: 测试运行时的上下文,包括当前空闲线程、时间等信息
:param event: 事件,通常是一个op
:return: gen2: 通过该次调用传入的generator的状态得到了更新,返回更新后的generator
"""
if gen is None:
return None
... | 14492f840f966c2fb9049840586dd0bd26502a9b | 40,766 |
import time
def get_time_at(time_in=None, time_at=None, out_fmt="%Y-%m-%dT%H:%M:%S"):
"""
Return the time in human readable format for a future event that may occur
in ``time_in`` time, or at ``time_at``.
"""
dt = get_timestamp_at(time_in=time_in, time_at=time_at)
return time.strftime(out_fmt,... | ea84f08a0a4a72f8d9408932a07117c4fff7d41d | 40,768 |
def synchronized(lock):
"""
Synchronization decorator.
"""
def wrap(f):
def new_function(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
lock.release()
return new_function
return wrap | 99e04c15bd141bd7d4e131eb0e5de6f5c73f347c | 40,769 |
def make_snippet(snippets, location):
"""Makes a colored html snippet."""
output = "<br>".join(sentence.replace(
location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets)
return output | 57bebb05df3ae34b45f57e589f6b105425609b8c | 40,770 |
def read_data(filenames, mode):
"""
The main function to read all the back calculated files
Parameters
----------
filenames: dict
This parameter is a dictionary of properties with their relative path to the data file.
mode: str
This parameter must be one of the following:
... | 3c1bebf165fdedb52b55207c56e7a5f9fe88de81 | 40,771 |
def is_identity(mat, eps=None):
"""Checks if a matrix is an identity matrix.
If the input is not even square, ``False`` is returned.
Args:
mat (numpy.ndarray): Input matrix.
eps (float, optional): Numerical tolerance for equality. ``None``
means ``np.finfo(mat.dtype).eps``.
... | 98b00c3492056c4f7bf0a53d6a15017c03d32dbe | 40,772 |
def connect_to_db_via_ssh(ssh_info, db_info):
"""
Connects to a remote PostgreSQL db, via SSH tunnel.
Args:
ssh_info (obj): All ssh connection info.
db_info (obj): All db related connection info.
Returns:
:class:`psycopg2.extensions.connection`: Live connection suitable for que... | 64e9048bd2b301bcfcd162b87a4d637076909746 | 40,774 |
def kid_2():
"""Return a second JWT key ID to use for tests."""
return "test-keypair-2" | c1bbe824ee90470c17ac62cbc3096cff4e3ddb1a | 40,775 |
import torch
def cosine_sim(x1, x2, dim=-1, eps=1e-8):
"""Returns cosine similarity between x1 and x2, computed along dim."""
w12 = torch.sum(x1 * x2, dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze() | bdc2ba499ed4b0293d999b8e0d01a8c1972a98ba | 40,777 |
def overlap(b4_reg, b7_reg, sep):
"""
function to find ds9 ellipse regions that match or overlap between band 4 and band 7
"""
# define some other little functions
def match_function(c, c_array, sep):
""" c would be a single band 4 dust region
c_array would be array of the band 7 regions
"""
# find wher... | 7b85c46ecc849ec75a59ef8f0bb1f8b7932bfd3c | 40,778 |
from typing import Optional
from typing import Any
from typing import Tuple
def tile_array_2d(array: np.ndarray, tile_size: int, channels_first: Optional[bool] = True,
**pad_kwargs: Any) -> Tuple[np.ndarray, np.ndarray]:
"""Split an image array into square non-overlapping tiles.
The array w... | 3d1e94435e4d846b8e77c58a0f1dd5af56ac764d | 40,779 |
from src.praxxis.sqlite import connection
def get_filenames(ruleset_db, rule):
"""returns a list of all filenames for a rule in a ruleset"""
conn = connection.create_connection(ruleset_db)
cur = conn.cursor()
list_filenames = 'SELECT Filename FROM "Filenames" WHERE Rule = ?'
cur.execute(list... | 519932300fd8f11afe5465964a08c7e7352378a0 | 40,780 |
def toy_features():
"""
Generate a sample feature dataframe with one column that isn't a
feature.
"""
feat = pd.DataFrame({"A": [1, 2, 3],
"B": [4, 5, 6],
"C": [7, 8, 9],
"D": ["a", "b", "c"]})
return (feat, feat.loc[:, ... | d72a7a54767dfb5a415662982e97e1ae92ec1ab3 | 40,781 |
def cube_px_resampling(array, scale, imlib='opencv', interpolation='bicubic',
scale_y=None, scale_x=None):
""" Wrapper of frame_px_resample() for resampling the frames of a cube with
a single scale. Useful when we need to upsample (upsacaling) or downsample
(pixel binning) a set of f... | d9c5c2a7c64b3f053e2302e134163b557065e81d | 40,782 |
def move_items_back(garbages):
"""
Moves the items/garbage backwards according to the speed the background is moving.
Args:
garbages(list): A list containing the garbage rects
Returns:
garbages(list): A list containing the garbage rects
"""
for garbage_rect in garbages: # Loop... | 9ffd28c7503d0216b67419009dac6ff432f3b100 | 40,784 |
def optimize(inputs, output, sizes):
"""
Produces an optimization path similar to the greedy strategy
:func:`opt_einsum.paths.greedy`. This optimizer is cheaper and less
accurate than the default ``opt_einsum`` optimizer.
:param list inputs: A list of input shapes. These can be strings or sets or
... | f9052884859534782854d996e836681890aded0e | 40,785 |
from typing import List
def variation(inlist:List(float))->float:
"""
Returns the coefficient of variation, as defined in CRC Standard
Probability and Statistics, p.6.
Usage: lvariation(inlist)
"""
return 100.0*variability.samplestdev(inlist)/float(central_tendency.mean(inlist)) | e2abb6394131851a9e4354db7e6569b1020cc28c | 40,786 |
def process_zdr_column(procstatus, dscfg, radar_list=None):
"""
Detects ZDR columns
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Accepted Config... | 2565aebec15ee19a03b904f7cf42d3b8ca63cd5c | 40,787 |
import re
def _mask_pattern(dirty: str):
"""
Masks out known sensitive data from string.
Parameters
----------
dirty : str
Input that may contain sensitive information.
Returns
-------
str
Output with any known sensitive information masked out.
"""
# DB credenti... | b75ae1e6ea128628dd9b11fadb38e4cbcfe59775 | 40,788 |
def cleanString(currentString):
""" Remove extra spaces and final punctuation from string.
"""
cleanstring = currentString.strip()
cleanerString = removePunctuationField(cleanstring)
return cleanerString | 37a44fa1a5b042590803bac4ef12a4dab153273a | 40,789 |
import re
def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall("filename=(.+)", cd)
if len(fname) == 0:
return None
return fname[0] | 3c516b0e7bfe2adfd05922a221d5919823177bd7 | 40,790 |
import urllib
def redirect_view(request, url):
"""
Redirect all requests that come here to an API call with a view parameter.
"""
dest = '/api/%.1f/%s' % (legacy_api.CURRENT_VERSION,
urllib.quote(url.encode('utf-8')))
dest = get_url_prefix().fix(dest)
return HttpR... | cad47b547257f8b2c58fe6a66120467ee2b2c656 | 40,791 |
def arch_matches(arch, alias):
"""
Check if given arch `arch` matches the other arch `alias`. This is most
useful for the complex any-* rules.
"""
if arch == alias:
return True
if arch == 'all' or arch == 'source':
# These pseudo-arches does not match any wildcards or aliases
... | 308e3fbe90aedfd0d089444875d459bc850b8496 | 40,792 |
import numpy
def calc_m_q_inv_m(m, q, flag_m: bool = False, flag_q: bool = False):
"""
q is quadratic form q_11, q_22, q_33, q_12, q_13, q_23
m is matrix m_11, m_12, m_13, m_21, m_22, m_23, m_31, m_32, m_33
Output is matrix o
"""
m_11, m_12, m_13 = m[0], m[1], m[2]
m_21, m_22, m_23 ... | 0875a6f0889232d1ceb558cde4e77130c405f86f | 40,793 |
def divisors(n):
"""
Returns a list of all positive integer divisors of the nonzero
integer n.
INPUT:
- ``n`` - the element
EXAMPLES::
sage: divisors(-3)
[1, 3]
sage: divisors(6)
[1, 2, 3, 6]
sage: divisors(28)
[1, 2, 4, 7, 14, 28]
s... | ca33ab9b15f2fc422a5a2b0c5a392144b4ac8ccd | 40,794 |
def list_to_hash(lst):
"""Convert a flat list of key value pairs to a hash"""
return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)}; | 44e3ce2e919a6e0f0cd605e6b712ff738949c457 | 40,795 |
from typing import Union
from typing import Tuple
def get_multiparm_instance_indices(
parm: Union[hou.Parm, hou.ParmTuple], instance_index: bool = False
) -> Tuple[int, ...]:
"""Get the multiparm instance indices for this parameter tuple.
If this parameter tuple is part of a multiparm, then its index in ... | e4e3c42b3c2f57c2bf2f4df4766b26e7ac2880cb | 40,796 |
def first_time(series, value, window=None):
""":func:`aggfunc` to:
- Return the first index where the
series == value
- If no such index is found
+inf is returned
:param series: Input Time Series data
:type series: :mod:`pandas.Series`
:param window: A tuple indicating a time win... | cf4788b9c34089da21f2839fb7517718467e17a7 | 40,797 |
from typing import Union
from typing import List
from textwrap import dedent
import torch
def prepare_filter_triples(
mapped_triples: MappedTriples,
additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None,
) -> MappedTriples:
"""Prepare the filter triples from the evaluation trip... | 999afbbe5d4016778dbd44f00b5c1ddb7eb2fc3b | 40,798 |
def create():
"""
Progress can be added to any/all goal(s) displayed.
"""
goals = fetch_goals()
if request.method == "POST":
data_id = request.form.getlist("id")
data_progress = request.form.getlist("progress")
data_quality = request.form.getlist("grade")
data = {... | ca2d15e27bcc692b64d7436cb045060e68065da4 | 40,799 |
def load_bikeshare(data_path=FIXTURES):
"""
Downloads the 'bikeshare' dataset, saving it to the output
path specified and returns the data.
"""
# name of the dataset
name = 'bikeshare'
data = load_numpy(name, data_path=data_path)
return data | 5c2799eb19718c670687e8a0b4669463f71bca66 | 40,800 |
def svn_wc_add_lock(*args):
"""svn_wc_add_lock(char const * path, svn_lock_t lock, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t"""
return _wc.svn_wc_add_lock(*args) | 3b5ad14ac99aad49b19050e3707078b38b781f88 | 40,801 |
def contains_non_ascii_unicode(s):
"""Determine whether the Unicode string 's' contains non-ASCII code-points."""
# Surely there must be a better way to do this? There's nothing I can see in
# the stdlib 'unicodedata' module:
# http://docs.python.org/library/unicodedata.html
#
# Note that list comprehens... | 138d3c298598603f2d0dc24518bbea46a4f8b7e6 | 40,802 |
def build_profile_information(user):
"""
Returns a dictionary containing information relevant to an user's
profile.
Override this function to add additional information to an user's
profile.
"""
context = {}
context['user'] = user
up_votes = Vote.objects.filter(user = use... | 2bc58d6bdcadff44328d50c7edf6ad33ac33e7c0 | 40,803 |
def __remove_duplicate_chars(string_input, string_replace):
"""
Remove duplicate chars from a string.
"""
while (string_replace * 2) in string_input:
string_input = \
string_input.replace((string_replace * 2), string_replace)
return string_input | 6302bf225fcd5cde822e0640eb7b2c44dcc93fc8 | 40,804 |
def clean_data(df):
"""Split the categories column to 36 individual columns and convert their values to 0 / 1.
Drop the original categories column.
Drop duplicated rows.
Args:
df: the dataset
Returns:
DataFrame: the cleaned dataset
"""
# split categories into separate c... | eeeed21b10419f2c3402abecc0710556db979c6c | 40,806 |
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year):
"""Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database."""
formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthd... | 1b4eff67a4073505f9f693f63db6f7c32646bd53 | 40,807 |
from datetime import datetime
import uuid
def pow_json_serializer(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
#serial = obj.isoformat()
serial = obj.strftime(twittercomments.config.myapp["date_format"])
return serial
... | f400b6297b8fb8047c367839fe7be878ab9c9c20 | 40,808 |
def scale_poscar(path_poscar,scale=(1,1,1),tol=1e-2):
"""Create larger/smaller cell from a given POSCAR.
- **Parameters**
- path_poscar: Path/to/POSCAR or `poscar` data object.
- scale: Tuple of three values along (a,b,c) vectors. int or float values. If number of sites are not as expected in ou... | 45edf5f79acdd25cc8da8037c461008796a294af | 40,809 |
import math
def normal_distribution(x: float) -> float:
"""
標準正規分布
f(x) = (1/sqrt(2pi))exp(-x^2/2)
"""
# 係数
coefficient = 1 / math.sqrt(2 * math.pi)
# 指数
exponent = math.exp(-(x ** 2) / 2)
# 標準正規分布
return coefficient * exponent | 2ee740674ddf2a7b95d507aedf1f5453a75f31f1 | 40,810 |
from datetime import datetime
def jd_from_datetime_utc(datetime_utc=None):
""" Converts a UTC datetime to Julian date. Imported from photrix (E. Dose).
:param datetime_utc: date and time (in UTC) to convert [python datetime object]
:return: Julian date corresponding to date and time [float].
"""
... | b97a9a6efc4f0783b9c06ca622987d9ccb1ef023 | 40,811 |
def reanalyze_callers(*args):
"""reanalyze_callers(ea_t ea, bool noret)"""
return _idaapi.reanalyze_callers(*args) | 2a20f6c3cbd5298867bd7c1ef6546659e89d0933 | 40,812 |
def parallel(*layers):
"""Combinator for composing layers in parallel.
The layer resulting from this combinator is often used with the `FanOut` and
`FanInSum`/`FanInConcat` layers. Based on `jax.experimental.stax.parallel`.
Args:
:layers: a sequence of layers, each an `(init_fn, apply_fn, kernel_fn)`
... | 77cd0f635433c35d0e5fa94ec9e156b7266ef9fe | 40,813 |
def get_datastore_identifier(datastore):
"""Revieve the NAA identifiers for the requested datastore object.
Args:
ds(vim.Datastore): Datastore object that the NAA is needed for.
Returns:
naa_ids(set): Returns a set of NAA(s) associated with the datastore.
"""
# The variable 'device... | f1386a789376da4cfab8a75cc769f2b45aece0f9 | 40,814 |
def get_coeff_eq3(hybrid_category):
"""係数d,e,f
Args:
hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分
Returns:
tuple: 式(3)における係数 d,e,f
"""
if hybrid_category == '区分1':
return get_table_g_3()[0][0], get_table_g_3()[1][0], get_table_g_3()[2][0]
elif hybrid_category == '区分2'... | 0cbfd8e8861f8dc0bde1e78b078631c8837811d9 | 40,816 |
def bw2sdtrf(bwvol):
"""
computes the signed distance transform from the surface between the
binary True/False elements of logical bwvol
Note: the distance transform on either side of the surface will be +1/-1
- i.e. there are no voxels for which the dst should be 0.
Runtime: currently the funct... | 485cd4852d362073211e05c47cdbec209b0ea47e | 40,817 |
def kzInterp(data_stack_in, kz_stack_in, kz0, pol_name):
"""
It generates a synthetic SLC stack of acquisitions by interpolating the
original stack of SLC data_stack defined over the kz axis specified by
kz_stack in correspondence of the desired phase-to-height.
Parameters
----------
da... | 1dc73c33c947a87f035311e520c3b9ec914c53bd | 40,818 |
def handler(event, context):
"""
This function fetches content from mysql RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("select * from package")
for row in cur:
item_count += 1
logger.info(row)
return "selected %d items from RDS p... | fd0f00ff86c1e5b775470e00b0ef58098819fdb6 | 40,819 |
def _map_ragged_tensor_impl(root, root_path,
paths,
operation,
is_repeated, dtype,
new_field_name
):
"""Maps a ragged tensor.
Args:
root: the root of the expression.
ro... | 855582254900bc85e857b63f1264e769348971a6 | 40,820 |
def ceil(number) -> int:
"""
>>> import math
>>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567]
>>> all(math.ceil(num) == ceil(num) for num in numbers)
True
"""
return int(number) if number - int(number) <= 0 else int(number) + 1 | 20c3f5cf56cd149e00a76e368729a76012b24375 | 40,821 |
def update_activity_link_parent_child(data):
"""Update exchange activity links from parent to child (i.e. the current) dataset.
Correct an error in ecoinvent master data production.
In a few cases, an exchange in a child dataset includes an ``activityLink``
to the parent dataset, from which the datase... | f4a1b30449d31e163ff0c7f72f38606b30877e4d | 40,822 |
def get_all_areas():
"""Get a dictionary with all findable areas
"""
return sattools.ptc.get_all_areas(["satpy", "fcitools"]) | 150eb0d983c119fcc2af0ea039d567eb85351da5 | 40,823 |
def is_valid_unique_product_ids(document: dict) -> bool:
"""Temporary implementation of rule for unique product ids."""
prod_ids = []
for path in uni_pro_ids.CONDITION_JMES_PATHS:
pids = jmespath.search(path, document)
if pids is not None:
prod_ids.extend(pids)
probe = jmespa... | 3172c68bed4ab500c3db737492f00fdd0d2070e6 | 40,824 |
import bigflow.transform_impls.pipe
def pipe(pvalue, command, **options):
"""
对于给定的PCollection/PTable,返回通过command处理后的PCollection
Args:
pvalue (PCollection/PTable): 输入
command: 命令行
**options: 可配置选项
type: pipe类型,目前支持streaming和bistreaming,默认为streaming
buffer_size: 缓存大小(单条... | 6a883e8689d0f3b6ecdf23983aba9ff709f0fbec | 40,825 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/temp_stats_start/yyyy-mm-dd<br/>"
f"/api/v1.0/temp_stats_start_end/yyyy-mm-dd/yyyy-... | f8b1ae7435e220103d0013ab930804bc1be928c3 | 40,826 |
import re
def remove_strange_chars(text):
"""Remove funky characters that don't belong in a URL."""
return re.sub(STRANGE_CHAR_PATTERN, "", text) | 608caf15156b9c2bb4ffa977fa1e80394079bc16 | 40,827 |
def build_projection_operator(l_x, n_dir=None, l_det=None, subpix=1,
offset=0, pixels_mask=None):
"""
Compute the tomography design matrix.
Parameters
----------
l_x : int
linear size of image array
n_dir : int, default l_x
number of angles at whi... | 170f1ed9fc69cee4edc65aef5f3bc0e79b018022 | 40,830 |
def check_permissions(accountid, command):
"""
Checks The Permission To Player To Executive Command
Parameters:
accountid : str
command : str
Returns:
Boolean
"""
roles = pdata.get_roles()
if is_server(accountid):
return True
for role in roles:
if accountid in roles[role]["ids"] and "ALL" in ro... | 09df6a860a953c240bac65c9f7f99438f6c334c3 | 40,831 |
def train(model, train_loader, optimizer, criterion, step):
"""
train one epoch
"""
for batch in train_loader:
step += 1
optimizer.zero_grad()
left_img = batch['left'].to(device)
right_img = batch['right'].to(device)
target_disp = batch['disp'].to(device)
... | 43fed9483ab7c9a78eb9f1addef0f44be4f335ec | 40,832 |
def get_group_followers(group, ignore_permission=False):
"""Returns a list of group member Contacts owned by the members."""
if not ignore_permission:
assert_group_permission(group, 'Group Permission denied')
if not group.is_group:
return []
return _get_follower_contacts(group.user_id... | b4b787d503c5e0625574d3fc7858570ec47556a1 | 40,833 |
import librosa
def getCensFeatures(XAudio, Fs, hopSize, squareRoot = False):
"""
Wrap around librosa to compute CENs features
:param XAudio: A flat array of raw audio samples
:param Fs: Sample rate
:param hopSize: Hop size between STFT windows
:param squareRoot: Do square root compression?
... | 94cfb7f12c19192faada1e63309921309b641957 | 40,834 |
def comet_magnitude_power_law(h=10., n=4., delta=1., r=1.):
"""The conventional power-law formula to predict a comet's brightness.
Parameters
----------
h : float
Absolute magnitude.
n : float
Activity parameter.
delta : float
Comet's geocentric distance in AU.
r : f... | 962c67e8f2a6e7ebf95307f5284fecddac3afef2 | 40,835 |
from typing import Literal
def setFilterType(filter_type : Literal[0, 1]):
"""
Set Filter Type (1 byte)
filter_type:
- 0 = FILTER_INCLUSIVE
- 1 = FILTER_EXCLUSIVE
Used for:
- RP1210_Set_J1708_Filter_Type (24)
- RP1210_Set_J1939_Filter_Type (25)
- RP1210_Set_CAN_Filter_Type (26)
... | cb0412e82db0efdc29b2b9f1e5ccbb77acabe1f9 | 40,837 |
def nrms(data_fit, data_true):
"""
Normalized root mean square error.
See: https://nl.mathworks.com/help/ident/ref/goodnessoffit.html
"""
# root_mean_squared_error = np.mean(np.linalg.norm(data_fit - data_true, axis=0), dtype=numpy.float16) # RMSE
# normalization_factor = 2 * np.linalg.norm(da... | ee93497c64b0d8a8e7d7c94287277ddaf60bb5f8 | 40,838 |
def test_from_file_decorator(tmp_path):
""" Test the from_file decorator. """
# create a temp yaml file
yaml_content = """
---
get:
summary: Hello
operationId: hello
responses:
200:
content:
application/json:
schema:
type:... | ee8042214e68181b2c3d569c115a4c37c98cb766 | 40,840 |
import hashlib
import hmac
def assert_dg_hash(
dg_file: bytes, data_group_hash_values: bytes, hash_alg: str, dg_number_bytes: bytes
) -> bool:
"""
Calculate the hash over the DG file and compare that in the EF.SOD.
"""
dg_number = int.from_bytes(dg_number_bytes, byteorder="big")
# Only hashes ... | 5448cd5a8df7a7aee85030100571c5e919980245 | 40,841 |
def isPlayerValid(player_id):
"""
check whether player id is valid in the DB
"""
try:
Player.objects.get(id=player_id)
except Player.DoesNotExist:
return False
else:
return True | 4c45a400ca61434d420fa2ef7a417ebde543400b | 40,842 |
def str_format(s, *args, **kwargs):
"""Return a formatted version of S, using substitutions from args and kwargs.
(Roughly matches the functionality of str.format but ensures compatibility with Python 2.5)
"""
args = list(args)
x = 0
while x < len(s):
# Skip non-start token characters... | addf11c8390c52da7b0f2886d2298bab66a50e49 | 40,843 |
def __private_function_example():
"""This is a private function example, which is indicated by the leading
under scores.
:return: tmp_bool"""
tmp_bool = True
return tmp_bool | be8d0309dc3a52d4f128e2e113046c1c79efe457 | 40,844 |
from sage.functions.other import log_gamma
def _sympysage_lgamma(self):
"""
EXAMPLES::
sage: from sympy import Symbol, loggamma
sage: assert log_gamma(x)._sympy_() == loggamma(Symbol('x'))
sage: assert log_gamma(x) == loggamma(Symbol('x'))._sage_()
"""
return log_gamma(self.ar... | cde661ce3a3dd2da3968c5048b9ee1fa0ee36cde | 40,845 |
import raylab
import functools
def initialize_raylab(func):
"""Wrap cli to register raylab's algorithms and environments."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
raylab.register_all()
return func(*args, **kwargs)
return wrapped | 3c4f00c662fad9954ecdb09119368bb02d72d03f | 40,846 |
async def pessoa_projeto_edit(
request: Request,
pessoa_projeto_id: int,
pessoa_projeto: PessoaProjetoEdit,
db=Depends(get_db),
pessoa=Depends(get_current_active_pessoa),
):
"""
Update pessoa_projeto
"""
return await edit_pessoa_projeto(db, pessoa_projeto_id, pessoa_projeto, pessoa) | bd611aa8fb726a5d97d75d534d53f92e02e8e943 | 40,847 |
def ingest(
dtype, shape, colors, data_split, get_buffer, get_local_colors=None
):
"""
Construct a single-column Table backed by a collection of buffers
distributed across the machine.
Each buffer is assumed to cover a disjoint dense subset of a rectangular
n-dimensional domain, and is identifi... | 1459e6e275060a0d29c718dd552012937c6ebb96 | 40,848 |
from typing import Any
def described_as(description: str, matcher: Matcher[Any], *values) -> Matcher[Any]:
"""Adds custom failure description to a given matcher.
:param description: Overrides the matcher's description.
:param matcher: The matcher to satisfy.
:param value1,...: Optional comma-separate... | 8ccbaa6afe48b4c6ef62399f1f9de5dfcd16de14 | 40,849 |
import jinja2
def _render_json_dict_jinja(json_dict):
"""Render jinja-templated choice variables in cookiecutter.json dictionary
.. note::
This function only modifies dictionary values that are strings containing
double curly bracket jinja variables such as '{{ varname }}'. All other
di... | fefb867d9da47ab4ef0e5f7fdf628f6d91516517 | 40,850 |
from typing import Tuple
from typing import Callable
from typing import Any
def get_random_noise() -> Tuple[Callable[..., Any], int]:
"""Get a random noise augmentation."""
f, (a, b) = choice(NOISE) # noqa S311
return f, choice(range(a, b + 1)) | d0114f66b1e4b91f2ab213d152e0c96f82196590 | 40,852 |
from typing import Iterable
def any_true(iterable) -> bool:
"""Recursive version of the all() function"""
for element in iterable:
if isinstance(element, Iterable):
if not any_true(element):
return True
elif element:
return True
return False | 67b4ea1e3c9da9c92a2ed8a26f346d67825e62fd | 40,853 |
from datetime import datetime
import pycountry
import logging
def load_jhu_data():
"""Wrap load_jhu_data_raw, to make data more useful."""
# vaccine data (from owid)
vac_data = load_owid_vaccinations_data_raw()
country_to_date_to_vac_data = {}
for country_data in vac_data:
country_alpha_3... | 164222f4596f91df4e93125e1e549d24f802851f | 40,854 |
def PrintStartTime(printString):
"""
Print the current time since execution and a msg (printString)
"""
endTime = time.time() - startTime
print str(int(endTime)) + ' s: ' + printString + ' .......'
return endTime | 17ad1c55e3943b36b1a6b9fcefa5deb0bce668a1 | 40,855 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.