content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import glob
def find_exp_parameters(cfg, logger):
""" Extracts experimental parameters. """
hemi, space = cfg['hemi'], cfg['space']
space_idf = f'hemi-{hemi}*.func.gii' if 'fs' in space else 'desc-preproc_bold.nii.gz'
# Use all possible participants if not provided
if cfg['subject'] is None:
... | a72a4c84cc1660005c31ecf65978c07cc5795420 | 3,631,618 |
def onroot_vc(t, y, solver):
"""
onroot function to reset the solver back at the start, but keep the current
velocity as long as the time is less than a given amount
"""
if t > 28: # we have found 4 interruption points, so we stop
return 1
solver.reinit_IC(t, [Y0, y[1]])
return 0 | aaabfcc4f06bd48fa2dd8858ffbec4b7d01e886f | 3,631,620 |
def _only_one_selected(*args):
"""Test if only one item is True."""
return sum(args) == 1 | 9966cc7c2cde16c689f29ba2add80b2cddce56e7 | 3,631,621 |
import re
def get_org_files(rcfile):
"""Get a list of org files from a 'vimrc' file."""
with open(rcfile, 'r') as vimrc:
data = vimrc.read()
orgfiles = re.search(r'org_agenda_files\s=.*?\[.*?\]', data, re.DOTALL).group()
orgfiles = orgfiles.split('[')[1].split(', ')
orgfiles = [slugify(x) ... | 0ca189535490a56b986060ab2634597aa40c1442 | 3,631,622 |
from typing import Iterator
from typing import List
def build_uncertainty_calibrator(
calibration_method: str,
uncertainty_method: str,
regression_calibrator_metric: str,
interval_percentile: int,
calibration_data: MoleculeDataset,
calibration_data_loader: MoleculeDataLoader,
models: Itera... | fe71921c0dfda06405101b2d5acdd514b5235ddc | 3,631,625 |
def generate_new_diversity_plots(otu_table_fs, gg_f, mapping_f,
mapping_category='Sample_Type',
min_num_samples=11,
category_values_to_exclude=None,
verbose=False):
"""Will exclude 'NA... | 02632d4e22c5c4740ebb536e182f7bb24820c170 | 3,631,626 |
def tile_data3d(data,(lentZ,lentY,lentX)):
"""
Tile sparky data into 1D numpy array
Parameters:
* data Three-dimensional data array
* lentZ Z (w1) dimention tile size
* lentY Y (w2) dimention tile size
* lentX X (w3) dimention tile size
Returns 1D numpy array of floats
... | 9544fe1ac4a42588bc143d6aaf55be31d382b34e | 3,631,627 |
import scipy
def sparse_to_vector(vector: scipy.sparse.spmatrix):
"""
Converts one dimensional sparse matrix to a vector array to allow more features.
:param vector: Vector as a sparse matrix (x,1) or (1,x).
:return: Vector as an one dimensional array (x,).
"""
return np.ravel(vector.toarray()... | 43fd27f48eea91754d95f86a631024a8b07a1a86 | 3,631,629 |
def uncentered_operator(X, func, center=None, fill=None, **kwargs):
"""Only apply the operator on a centered patch
In some cases, for example symmetry, an operator might not make
sense outside of a centered box. This operator only updates
the portion of `X` inside the centered region.
Parameters
... | f166e16ea7e0438c8af5e28a86afd71c4ec375f1 | 3,631,630 |
def _get_range_and_pstring(variable, mean_cube, tropopause=False):
"""Get range for color bar and print string."""
if variable == "Air Temperature":
print_var = "Temperature [K]"
set_range = np.linspace(180, 230, 21)
elif variable == "Geopotential Height":
print_var = "Geopotential H... | ce3370929d490ae3636d5959a6e9b6ecbfe61110 | 3,631,631 |
def merge_storage(df, cons, prod, stor):
"""Merge positve storage in consumption and negative part in the production
"""
_df = df.copy()
assert not _df.isnull().values.any(), 'Include NaN values'
_df[prod] = _df[prod] - _df[stor].clip(upper=0)
_df[cons] = _df[cons] + _df[stor].clip(lower=0)
... | 28daaf07ecd6a83259388020e044017415a93201 | 3,631,632 |
from calendar import isleap
from datetime import datetime
def numeric_date(dt=None):
"""
Convert datetime object to the numeric date.
The numeric date format is YYYY.F, where F is the fraction of the year passed
Parameters
----------
dt: datetime.datetime, None
date of to be convert... | 1a369bb8824db3f885b1af269f0d86eba5103769 | 3,631,634 |
def specific_clean_cell_lst():
"""Clean a list of cells - column cells"""
# List of strings
col_cells = request.json["cells"]
col_type = request.json["coltype"]
clean_cells = fix_specific(col_cells, col_type)
return clean_cells | e61e17dc311516bed179cde6a4b9cecaab4420de | 3,631,635 |
def compress_sym(sym_expanded, make_symmetric=True):
"""Compress symmetric matrix to a vector.
Similar to scipy.spatial.squareform, but also contains the
diagonal.
Parameters
----------
sym_expanded : nd-array, shape (size, size)
Input matrix to compress.
make_symmetric : bool (de... | f2d5b7ce91c18ae3730feda002cdcc76ad0540e7 | 3,631,636 |
def get_cc_biz_id_by_app(fta_application_id):
"""
通过fta_application_id获取cc_id
"""
app = session.query(AlarmApplication).filter_by(
app_id=fta_application_id,
is_deleted=False,
is_enabled=True).first()
if app:
return app.cc_biz_id
else:
return None | 597bd8dd170c42d19166e9db64c80bf490fb7a2d | 3,631,637 |
from pathlib import Path
def get_csv_filename(folder="zips"):
"""
Returns the Path of the csv-file stored in zips-folder
"""
csvs = [f for f in Path(folder).iterdir() if f.suffix == ".csv"]
if len(csvs) >= 1:
return csvs[0]
else:
logger.error(f"CSV-file missing")
raise ... | d7e811ef15174d29c9514c2eeaa853e9da4996e8 | 3,631,638 |
import random
import string
def generate_random_id(start: str = ""):
"""
Generates a random alphabetic id.
"""
result = "".join(random.SystemRandom().choices(string.ascii_lowercase, k=16))
if start:
result = "-".join([start, result])
return result | f818ecf7ba4296a3ad010ef20bc5e286036bb56d | 3,631,639 |
def add_supplementary_xml(element: etree, config: dict) -> etree:
"""Add arbitrary xml from configuration object to xml
Args:
element (etree): original xml document
config (dict): standard ReadAlong-Studio configuration
Returns:
etree: xml with supplemental markup
"""
if "x... | 2b554a5de0b43731c75ccd7bf311591a3b51001d | 3,631,640 |
def get_client_names(worksheet) -> list:
"""Get list of client names from Excel worksheet."""
num_rows = worksheet.max_row
names = []
for i in range(2, num_rows+1):
cell_obj = worksheet.cell(row=i, column=1)
if cell_obj.value not in names:
names.append(cell_obj.value)
r... | 6da6e52ed10e84ae79119c511e063114bb61b334 | 3,631,641 |
def as_json(dictionary):
"""
Object hook used in order to create the right object reading a JSON.
:param dictionary: Dict, Dictionary to analyze.
:return: The right object represented in the JSON.
"""
if "first_name" in dictionary:
return User(**dictionary)
elif "update_id" in dictio... | ed5f386e3c37a363cbec0e026960628d827462a4 | 3,631,642 |
def coefficient_map(cv: xr.DataArray) -> xr.DataArray:
"""
Return the coefficient map
:param cv: cost volume
:type cv: xarray.Dataset, with the data variables cost_volume 3D xarray.DataArray (row, col, disp)
:return: the coefficient map
:rtype : 2D DataArray (row, col)
"""
row = cv.coor... | 32179fff71635283394226ffac2ee9c0ba7f0f3d | 3,631,643 |
def transpose(a, axes=None):
"""
Reverse or permute the axes of an array; returns the modified array.
For an array a with two axes, transpose(a) gives the matrix transpose.
Parameters
----------
a : array_like
Input array.
axes : tuple or list of ints, optional
If specified... | d51bc442e71f52c08b38cff98275540528e178be | 3,631,644 |
def post_token():
"""
<url>/notifications/api/PushToken
Get Device Tokens for notifications
"""
token = request.json.get('token')
deviceId = request.json.get('deviceId')
user = User.query.filter_by(token=token).first()
device = DevicesNotificationHandlers.query.filter_by(user_id=user.i... | 3e287f339500c02e91e5a6512878178686ec3a22 | 3,631,645 |
from datetime import datetime
import pytz
def get_timestamp() -> str:
"""
Получение текущей временной метки
"""
return datetime.datetime.now(pytz.utc).strftime('%Y.%m.%d %H:%M:%S %z').strip() | 093b2275d5dc1381eb69a3b845702715e5b8281f | 3,631,646 |
from brambox.boxes.annotations import Annotation
def as_anno(class_id, x_center, y_center, w, h, Win, Hin):
"""
Construct an BramBox annotation using the basic YOLO box format
"""
anno = Annotation()
anno.class_id = class_id
anno.x_top_left = (x_center - w / 2) * Win
anno.y_top_left = (y_c... | e46f6b626bf500da0b2c63a4d093ad392e9a9b3a | 3,631,647 |
def parse_testcase_xml(testcase):
"""
Flatten fields of interest from a TestCase XML element into a dict,
where anything not found is None
"""
# We need to emit only Unicode things, but we may get str or Unicode
# depending on if the parser thinks we have UTF-8 or ASCII data in a field.
... | e93d629f0953cecd30ce4a7241a8f6a1db76fb06 | 3,631,648 |
def build_coco_results(dataset, image_ids, rois, class_ids, scores):
"""Arrange results to match COCO specs in http://cocodataset.org/#format
rois: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
image_ids: [num_instances]
class_ids: [num_instances]
scores: (optional) confidence sc... | ac25c6e6a4ed45b976ff06369edaa13c8f5fcdb7 | 3,631,649 |
import requests
def get_instance_ip(compute_url, instance_id, token):
""" Retrieve the IPs of the running instance """
url = "%s/servers/%s/ips" % (compute_url, instance_id)
headers = {"X-Auth-Token": "%s" % token, "Content-type": "application/json"}
curl = requests.get(url=url, headers=headers)
... | 224e916f574869023e540d6a4913acd7541c7942 | 3,631,650 |
def _domain_map(z, satu, mapType=0):
"""domain color the array `z`, with the mapping
type `mapType`, using saturation `s`. Currently
there is only one domain coloring type
"""
h = _hue(z)
s = satu*_np.ones_like(h, _np.float)
v = _absolute_map(_np.absolute(z))
hsv_map = _np.dstack((h, s, ... | a422d2b463a97afdcae18f820f2ac7462f54ce91 | 3,631,651 |
from typing import Callable
def provider(provided_dependency_name: _Name = None,
**named_dependencies: _Name) -> Callable[[_ProviderMethod], _ProviderMethod]:
"""
Method decorator for instance provider methods in a module class. The provider method can take
parameters representing dependencie... | 52ef1a7a65b93b498ecfbb1b3173effc91de8e67 | 3,631,652 |
def _num_to_words(num):
"""
Turkish converter
Params:
num(int/long): number to be converted
Returns:
wordString
"""
units = ['', u'bir', u'iki', u'üç', u'dört', u'beş', u'altı', u'yedi', u'sekiz', u'dokuz']
teens = ['', u'onbir', u'oniki', u'onüç', u'ondört', u'onbeş', u'on... | 14adb62d17f2089127ca9b90f1d884063c028adf | 3,631,653 |
def get_vehicle_txn(session, vehicle_id):
"""
For when you just want a single vehicle.
Arguments:
session {.Session} -- The active session for the database connection.
vehicle_id {String} -- The vehicle's `id` column.
Returns:
{dict} or {None} -- Contains vehicle information fo... | 5f7f3c773e40f567a060015f2c8e5c043b6cb1f5 | 3,631,654 |
import six
def slugify(value):
"""
Slugify a string (even if it contains non-ASCII chars)
"""
# Re-map some strings to avoid important characters being stripped. Eg
# remap 'c++' to 'cpp' otherwise it will become 'c'.
for k, v in settings.OSCAR_SLUG_MAP.items():
value = value.replace(... | 53273bd3f6ae2418736a22a2780581d1974dc92b | 3,631,655 |
def upper(value: str): # Only one argument.
"""Converts a string into all uppercase"""
return value.upper() | 8ec4c4ed284bc8d823e356db7749a4c98a00b194 | 3,631,656 |
from typing import Dict
from typing import List
def _create_sorted_hash_list(data: Dict, hash_function: str) -> List[Dict]:
"""Create a sorted sha256 hash list."""
out = []
for obj in data:
hash = _create_json_hash(obj, hash_function=hash_function)
out.append(hash)
out.sort()
retur... | 2efbac4652bf2db975513610956445c932543d11 | 3,631,657 |
def disease_function_subset(ipa, network_dir, printing=False):
"""
Returns a disease subset of functions. A function is considered a
disease if its lowercase name is the same as its class and its name is
not a function category. Build must be run first
"""
disease_names = set()
for function ... | 83370f5dd6a6245d4fc2dc988c43beec110a3f48 | 3,631,658 |
import torch
def map_tensor(x, func):
"""
Apply function @func to torch.Tensor objects in a nested dictionary or
list or tuple.
Args:
x (dict or list or tuple): a possibly nested dictionary or list or tuple
func (function): function to apply to each tensor
Returns:
y (dic... | 38675f836fcb462946e03054b74051e7ccea882e | 3,631,659 |
def xor(a,b):
""" XOR two strings of same length"""
assert len(a) == len(b)
x = []
for i in range(len(a)):
x.append( chr(ord(a[i])^ord(b[i])))
return ''.join(x) | cbe3d32883dc5516821711181c7f5d52194d89de | 3,631,661 |
def wmts2twmsbox_scale(scale_denominator, col, row):
"""
Returns TWMS equivalent bounding box based on TILECOL and TILEROW.
Arguments:
scale_denominator -- WMTS scale denominator value from getCapabilities.
col -- WMTS TILECOL value.
row -- WMTS TILEROW value.
"""
print ... | 9660f5a1b3b9eecf5623d70c9b32861ab2e8dd88 | 3,631,662 |
import hashlib
import yaml
def get_hash(x, length=16):
"""Return hash of x."""
return hashlib.sha224(yaml.dump(dict(key=x)).encode()).hexdigest()[:length] | e13c278ef649e2d8c213580d5ccc27ae64d72027 | 3,631,663 |
def make_unhealthy():
"""Sets the server to simulate an 'unhealthy' status."""
global _is_healthy
_is_healthy = False
template = render_template('index.html',
hostname=gethostname(),
zone=_get_zone(),
template=... | c379b14b1a924bc81c31b74a322d6ddde67421d8 | 3,631,664 |
def filtreDonner(liste) :
"""
Fonction qui va filtrer les donner.
Cette fonction va filtrer les donners inutiles mot trop frequent ...
param : liste[string] -> liste chaine de caractere a filtrer
return : liste[string] -> liste chaine de caractere filtrer.
"""
return liste | b7e5f04a6645895a16c44f3f477ecc9d9a8ecef1 | 3,631,665 |
def get_problem_set(dataset,LABELNAME,labels,i2s):
"""Aggregate labels and associated article/domain information by chosen classification task
Arguments
- dataset: a list of article text (the corpus)
- LABELNAME: a string given by user input identifying the classification task
- labels: a dict ... | 3f65f75e1d8fcde54babd5d236dc179955fb3fe7 | 3,631,667 |
def hello_world(text: str) -> str:
"""Print and return input."""
print(text)
return text | 7bfcb8e9cfccdf5fad8c702f97f6b7c4e56c7682 | 3,631,668 |
def NestedGroupKFold(model, X, y, parameter_grid, groups, class_weights, scorer=make_scorer(accuracy_score),
inner_cv=GroupKFold(n_splits=4), outer_cv=GroupKFold(n_splits=4)):
"""
Implements a nested version of GroupKFold cross-validation using GridSearchCV to evaluate models
that nee... | 7fec0ff05ee002212432cb6fee414013ba079e6d | 3,631,669 |
def create_vespa_query(query, text_processor, number_videos):
"""
Create the body of a Vespa query.
:param query: a string representing the query.
:param text_processor: an instance of `TextProcessor` to convert string to embedding.
:param number_videos: Number of videos to return.
:return: bod... | b5d5ead2b31244220a41474758b463910e9d8e9a | 3,631,670 |
def _thumb_from_pixel_clusters(images, mask, h, w, use_distance_from_centroid=False):
""" Alternate implementation. Results are sharper, but noisier """
# 6-color
# colors = np.array([[1, 0, 1, 0], [1, 0, 0, 0], [1, 1, 0, 0],
# [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0]],
# ... | a91440006ac42208ffaca71f6889f5b7ca1c9dcf | 3,631,671 |
def get_rtClock():
"""
Instanziiert ein Real Time Clock Objekt
"""
return rtc.SDL_DS3231() | 9a854aba4e6986f7ed56fb058a368ad629d5c3e1 | 3,631,672 |
def create_draft(service, user_id, message_body):
"""Create and insert a draft email. Print the returned draft's message and id.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message_bo... | 6ea595383349b74d5265b569b25a6e10b9748c6c | 3,631,673 |
def analyze_files(file_list):
"""return info for each file in a list that
if it passed in analyzedir? passed in basedir? the results are the same?"""
result = map(lambda f: (f,)+analyze(f, analyzedir, basedir), file_list)
return result | bd8be9c6a9047921670546eea5667c312e5fe26d | 3,631,674 |
from . import default_logger
import time
def profiling(func):
"""Decorator to mark a function for profiling. The time and memory usage will be recorded and printed.
Example:
.. highlight:: python
.. code-block:: python
@profiling
def foo():
print(1)
"""
@wraps(... | 36c83e39743336be49436f4cfcc8891040288f54 | 3,631,675 |
import psutil
import math
def find_no_of_workers(maxworkers, sys_share=0):
"""
Find the optimal number of workers for MP such that system does not crash.
Parameters
----------
maxworkers : Int. Maximum number of workers allowed.
Returns
-------
workers : Int. Workers used.
sys_sh... | ebb5140d6099ef6600a2373a12e18747ccdaddbd | 3,631,676 |
from typing import Callable
from typing import Dict
from typing import Any
import tqdm
from typing import Literal
def from_rdflib(
graph: Graph,
literal_cleaning_func: Callable = None,
kg_name: str = None,
multi_value: Callable = None,
) -> KG:
"""Create forayer knowledge graph object from rdflib ... | a3dae2f4586603de9a5b52c45715591c31d386fc | 3,631,677 |
def video_player(obj):
"""
Receives object with 'video' FileField and returns HTML5 player.
"""
return {'object': obj} | 197c16e2ff16777634cfad327c08df571481ed09 | 3,631,678 |
def wait_for(scope, prompt):
"""
Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True | 10c95350b4c2aa4ad8fe9bce040efc461f461ca0 | 3,631,679 |
def render_list_categories():
"""
METHOD=GET.
Renders Category Page.
"""
categories = session.query(Category).order_by(asc(Category.name)).all()
return render_template('categories/list.html', categories=categories) | 45cb527a9188f10957e276952bf56ebd1b2b59ae | 3,631,682 |
import time
def perform_install(pspec, is_upgrade=False, force=False, quiet=False):
"""
Args:
pspec (PackageSpec): Package spec to install
is_upgrade (bool): If True, intent is an upgrade (not a new install)
force (bool): If True, check latest version even if recently checked
q... | 557deda9249bb0b117f3cc820d3d6d8009988940 | 3,631,683 |
import re
def tokens_to_str(message, section='body'):
""" Takes one section of a message as specified by key param and
returns it in string format to be joined with other messages
for summarization, printing, id creation (future).
"""
body = message[section]
new_mess = ''
if isins... | 4b8f57060dfe110a2a0e2c767a73966cc1d5abdb | 3,631,684 |
def azip(*aiterables):
"""async version of izip with parallel iteration"""
return _azip(*aiterables, fillvalue=None, stop_any=True) | 8b296a1775ee54d0a1d44997b3dd7682a8da434f | 3,631,685 |
def collect_data(
bids_dir,
participant_label,
bids_validate=True,
bids_filters=None,
):
"""
Uses pybids to retrieve the input data for a given participant
Examples
--------
>>> bids_root, _ = collect_data(str(datadir / 'ds054'), '100185',
... bids_va... | 5f654e4fb6b145e7ad34e238b1ad9e992e426b6e | 3,631,686 |
def filter_features(input_features, **kwargs):
"""
Args:
input_features: A Geojson feature collection
Returns:
A json of two geojson feature collections: passed and failed
"""
if type(input_features) is DictType:
if input_features.get("features"):
return iterate... | 69c1f517b8344a6a493d41228a4e249eb385aaab | 3,631,687 |
import functools
def polygon_wrapper(func):
"""
Wrapper function to perform the setup and teardown of polygon
attributes before and after creating the polygon.
Keyword arguments:
func (function) -- the function to draw the polygon.
"""
@functools.wraps(func)
def draw_polygon(self... | 76056e41c36a2c15dcb8a2e05cc4ec4c1beb68dc | 3,631,688 |
def compose_base_find_query(user_id: str, administrator: bool, groups: list):
"""
Compose a query for filtering reference search results based on user read rights.
:param user_id: the id of the user requesting the search
:param administrator: the administrator flag of the user requesting the search
... | 2f398930603093ddc59e0c6ba4956e7d46a7758d | 3,631,689 |
def test_prevent_links():
"""Returning None from any callback should remove links or prevent them
from being created."""
def no_new_links(attrs, new=False):
if new:
return None
return attrs
def no_old_links(attrs, new=False):
if not new:
return None
... | ad78f384621d301d1ce8c7339f4648bf2517c7f9 | 3,631,690 |
def intersection (l, r) :
"""Compute intersection of lists `l` and `r`.
>>> intersection (range (4), range (2,5))
[2, 3]
"""
r_set = set (r)
return [x for x in l if x in r_set] | 36d7003587204814b6e09ec093f2a6715e87a500 | 3,631,691 |
def filter_df_on_ncases(df, case_id_glue="case:concept:name", max_no_cases=1000):
"""
Filter a dataframe keeping only the specified maximum number of cases
Parameters
-----------
df
Dataframe
case_id_glue
Case ID column in the CSV
max_no_cases
Maximum number of cases... | 5f8532ebe465d7b80934b35ef8d3925217f4e355 | 3,631,692 |
def welcome():
"""List all available api routes."""
return (
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | fd95f362d1e39ac6485e97ee0a77d318f3011bb8 | 3,631,693 |
def decode(s):
"""doc me"""
for encoding in "utf-8-sig", "utf-16":
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode("latin-1") | 40ce76e5067e591eb1e433f18c4d574a7235ab4e | 3,631,695 |
def Quantum_Vibrational_S(Temperature, wavenumbers):
"""
Funciton to calculate the quantum vibrational entropy at a given temperature
**Required Inputs
Temperature = single temperature in Kelvin to determine the vibrational entropy (does not work at 0 K)
wavenumbers = array of wavenumber (in order w... | be0b760db66651ff95bcb1614d17573bbfa80941 | 3,631,696 |
def _open(full_path, state, year, variety, database='SID'):
"""Returns a handle using python's builtin open() function; however, it
will skip past any non-content rows as specified within.
This is necessary because HCUP files very occasionally have bonus
content, typically a data use notice, and it... | b7a236433122a051abc913f34112b4250908b508 | 3,631,697 |
def summon(self: Client, entity: str, pos: Vec3 = None,
nbt: dict = None) -> str:
"""Summons an entity."""
return self.run('summon', entity, pos, nbt) | 651adcb3f0ec1e8d1efef0ba79bfe1f4e208c3f9 | 3,631,698 |
def get_inner_html(node):
"""Gets the inner HTML of a node, including tags."""
children = ''.join(etree.tostring(e).decode('utf-8') for e in node)
if node.text is None:
return children
return node.text + children | 467af19497a12744851ddadbb6fbf138cf846809 | 3,631,699 |
def remove_whitespace(s):
"""Remove excess whitespace including newlines from string
"""
words = s.split() # Split on whitespace
return ' '.join(words) | 7d9e7b15ba101f00412565b42c260e8bc29ac49a | 3,631,700 |
def get_first_group (match):
"""
Retrieves the first group from the match object.
"""
return match.group(1) | d4103989a7fbd55e40600d391b51dfb93053ed8f | 3,631,701 |
from typing import Dict
from typing import Tuple
from typing import Any
def plot_from_region_frames(
frames: Dict[str, pd.DataFrame],
variable: str,
binning: Tuple[int, float, float],
region_label: str,
logy: bool = False,
legend_kw : Dict[str, Any] = None,
) -> Tuple[plt.Figure, plt.Axes, plt... | 3a0fe727d7160a0ed203bd0431e8ca8329259f27 | 3,631,702 |
from unittest.mock import patch
async def init_integration(hass, co2_sensor=True) -> MockConfigEntry:
"""Set up the Nettigo Air Monitor integration in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
title="10.10.2.3",
unique_id="aa:bb:cc:dd:ee:ff",
data={"host": "10.... | 5e56cfd160499cc9c6164f231fe21cdcd2e41596 | 3,631,703 |
def decode(ciphered_text: str) -> str:
"""
Decode Atbash cipher
:param ciphered_text: Atbash cipher
:return: decoded text
"""
return ''.join(replace_char(char) for char in ciphered_text
if char in LOWERCASE or char in DIGITS) | ff70504009ab45a0de476e7d8fcb139785f3590a | 3,631,704 |
def text(label, default=None):
"""
@brief prompt and read a single line of input from a user
@retval string input from user
"""
display = label
if( default ):
display += " (default: " + str(default) + ")"
input = raw_input( display + ": " )
if input == '' and default:
i... | 0676596272a13607beae0b4f4ca289be61601834 | 3,631,705 |
def update_reservation(reservation, updatedSpots, comments):
"""
Update the reservation with the new spots needed
"""
newSpots = updatedSpots - reservation.seats_needed
reservation.seats_needed = updatedSpots
reservation.note=comments
db.session.commit()
flash("Reservation updated.")
... | eea612b228c7d3b66690b735cde76d26df964b3a | 3,631,706 |
def qc_freq(species, geom, natom, atom, mult, charge, index=-1, high_level = 0):
"""
Creates a frequency input and runs it.
index: >=0 for sampling, each job will get numbered with index
"""
if index == -1:
job = str(species.chemid) + '_fr'
else:
job = str(species.c... | 26f9bd91f2c688ab687363011661dd816ac250ff | 3,631,707 |
from datetime import datetime
def sample_to_timed_points(model, size):
"""As :func:`sample` but return in :class:`open_cp.data.TimedPoints`.
"""
t = [datetime.datetime(2017,1,1)] * size
pts = sample(model, size)
assert pts.shape == (size, 2)
return open_cp.data.TimedPoints.from_coords(t, *pts.... | 11775060c76efdf6cfe31cd7efe3a09d562c888a | 3,631,708 |
def _per_image_standardization(image):
"""
:param image: image numpy array
:return:
"""
num_compare = 1
for dim in image.shape:
num_compare = np.multiply(num_compare, dim)
_standardization = (image - np.mean(image)) / max(np.std(image), 1 / num_compare)
return _standardization | 18461f97a91c1cad2156606b67c7a5f732587b1f | 3,631,709 |
import torch
def unflatten_parameters(params, example, device):
"""Unflatten parameters.
:args params: parameters as a single 1D np array
:args example: generator of parameters (as returned by module.parameters()),
used to reshape params
:args device: where to store unflattened parameters
... | f321c536bcbfada2e2cd254ecffaf5b0b9573472 | 3,631,710 |
def pattern_to_regex(pattern):
"""
Convert the CODEOWNERS path pattern into a regular expression string.
"""
orig_pattern = pattern # for printing errors later
# Replicates the logic from normalize_pattern function in Gitlab ee/lib/gitlab/code_owners/file.rb:
if not pattern.startswith('/'):
... | 8b82ad2efa9e47028a7419dcef72fb9c6b3741ba | 3,631,711 |
def unit2uniform(x, vmin, vmax):
"""
mapping from uniform distribution on parameter space
to uniform distribution on unit hypercube
"""
return vmin + (vmax - vmin) * x | 2765db219dfda5debd5f8957c0ad9c0b44335f89 | 3,631,713 |
def extractHachidoriTranslations(item):
"""
Parser for 'Hachidori Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Charging Magic with a Smile' in item['tags']:
return buildReleaseMessageWithT... | f596e40b65fa1c92b74bcf8e83ea4b32ccad5124 | 3,631,715 |
def _tvgp_qvgp_optim_setup():
"""Creates a VGP model and a matched tVGP model"""
time_points, observations, kernel, noise_variance = _setup()
input_data = (
tf.constant(time_points),
tf.constant((observations > 0.5).astype(float)),
)
likelihood = Bernoulli()
tvgp = t_VGP(
... | 95578fceaa5206d6318c6045a521681d268a1e7d | 3,631,717 |
def get_average_rate(**options):
"""
gets average imdb rate of all movies.
:rtype: float
"""
return movies_stat_services.get_average_rate() | c32af301d3e2f789a68e5b179d78324b7205cbaa | 3,631,718 |
def _uint_to_le(val, length):
"""Returns a byte array that represents an unsigned integer in little-endian format.
Args:
val: Unsigned integer to convert.
length: Number of bytes.
Returns:
A byte array of ``length`` bytes that represents ``val`` in little-endian format.
"""
retur... | 54e765e7b3772c6e2e6dc4c7e6de48d034b9d4b5 | 3,631,719 |
import torch
def batch_to_patches(x, patch_size, patches_per_image):
"""
:param x: torch tensor with images in batch (batsize, numchannels, height, width)
:param patch_size: size of patch
:param patches_per_image:
:return:
"""
device = x.device
assert(x.dim()... | 200ea8d893d660e981608ddd1276679b3765ee01 | 3,631,721 |
import json
def parse_json(json_data, category):
"""
Parses the <json_data> from intermediate value.
Args:
json_data (str): A string of data to process in JSON format.
category (str): The category ('all' / 'spam' / 'ham') to extract data from.
Returns:
(status_code, data), wh... | bc56ddf35d3551f43b2bd5644a6337d288d6af52 | 3,631,722 |
def get_dset_size(shape_json, typesize):
""" Return the size of the dataspace. For
any unlimited dimensions, assume a value of 1.
(so the return size will be the absolute minimum)
"""
if shape_json is None or shape_json["class"] == 'H5S_NULL':
return None
if shape_json["class"] ... | 82e0cf9041a81ed6f9d2195502ca7f21f557164d | 3,631,723 |
from typing import List
def check_shapes(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
"""
Analog of :func:`check_agency` for ``feed.shapes``.
"""
table = "shapes"
problems = []
# Preliminary checks
if feed.shapes is None:
return problems
... | 2c22c674f19f2e711fc337cd9c734e300e94b2ad | 3,631,724 |
def get_help_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "OPM Status Help"
speech_output = "To begin, ask o. p. m. status an acceptable question. For example, " \
"Is the gov... | 8c1fea3cbb575dee9a80dd8b8e0351b90f837b4c | 3,631,725 |
import random
def mm_clustering(sampler, state, float_names, fixed_df, total_df_names, fit_scale, runprops, obsdf,geo_obj_pos, best_llhoods, backend, pool, mm_likelihood, ndim, moveset, const = 50, lag = 10, max_prune_frac = 0.9):
"""
Determines if walkers in the ensemble are lost and removes them. Replacing them
... | 724159d78948b57ca1fbc06974b6728b24144ffe | 3,631,726 |
def off_diagonal_min(A):
"""Returns the minimum of the off diagonal elements
Args:
A (jax.numpy.ndarray): A real 2D matrix
Returns:
(float): The smallest off-diagonal element in A
"""
off_diagonal_entries = off_diagonal_elements(A)
return jnp.min(off_diagonal_entries) | 0b05e7d2b091538cd4ca95624faaa347cae5401f | 3,631,727 |
def cli_cosmosdb_sql_stored_procedure_create_update(client,
resource_group_name,
account_name,
database_name,
co... | 4dbeccf559f32cb10762081706d98602a9f8f646 | 3,631,728 |
def create(box=None,n=None,nr=None,nc=None,sr=1,sc=1,cr=None,cc=None,const=None) :
"""
Creates a new HDU
"""
if box is not None:
nr=box.nrow()
nc=box.ncol()
sc=box.xmin
sr=box.ymin
else :
if nr is None and nc is None :
try :
nr=n
... | 298802654b7f5a5572f4d59c0c3ab30a2c2af6e7 | 3,631,729 |
def gcd(num1, num2):
"""Return Greatest Common Divisor"""
# Euclidean Algorithm for GCD
a = max([num1, num2])
b = min([num1, num2])
while b != 0:
mod = a % b
a = b
b = mod
return a | 36c788d44a4aafaaf000963a7c5e1b80fa6f64f5 | 3,631,730 |
from typing import List
from typing import Dict
from typing import Any
def read_params_from_config(config: dict, _root_name: str = "") -> List[NamedPyParam]:
"""Reads params from the nested python dictionary.
Args:
config: a python dictionary with params definitions
_root_name: used internall... | bfdd3de4977bcd2ad09ec52fbdccdd77ed685d09 | 3,631,731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.