content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def vector_to_dictionary(vector, layers):
"""
Convert the parameter vector of a model into a dictionary used by the model
Arguments:
vector -- one-dimensional vector in orders: "W1", "W2", "WL", "b1", "b2", "bL"
layers -- list of (n_uints, activations) pairs that define network structure,... | 33f628463546892ae8127cad25bda1e7ae19a78a | 54,700 |
import re
def prettify_soup(soup: bs4.BeautifulSoup) -> str:
"""Generate an HTML string of a BeautifulSoup paper document that is slightly more readable
than simply calling str(soup).
Args:
soup (bs4.BeautifulSoup): Paper soup
Returns:
str: HTML (UTF-8 encoded)
"""
# Only ins... | 9d472bc0f3b9fb887404c01a9ec9b53c6ac4d0d5 | 54,701 |
def compute_vanderwaals(traj_frag_molid, frame_idx, index_to_label, sele_id, VDW_EPSILON, VDW_RES_DIFF):
"""
Compute all vanderwaals interactions in a frame of simulation
Parameters
----------
traj_frag_molid: int
Identifier to simulation fragment in VMD
frame_idx: int
Frame num... | 05749204946124e87f8413d2bd1845c93cb568b8 | 54,702 |
def load_text(filepath):
"""Loads text from a file and returns it as a string.
Args:
filepath (str): The path to the file to be loaded.
Returns:
text (str): The text loaded from the file.
Examples
--------
>>> load_text('text.txt')
"""
with open(filepath, encoding='utf... | 66a925216a33f8b9e7abab4b7ada6ad2716cefd6 | 54,703 |
def f_call_one_optional_kwd(a, /, *, b=2):
"""
>>> f_call_one_optional_kwd(1)
(1, 2)
>>> f_call_one_optional_kwd(1, b=3)
(1, 3)
"""
return (a,b) | 4bcbc58d90f093775c4f52dcdfce0d0deb5d6686 | 54,704 |
import requests
import json
def send_post_request(url, data: dict = None, **kwargs) -> dict:
"""
发起post请求
:param url: 请求目标地址
:param data: 请求参数
:param kwargs:
:return:
"""
try:
resp_dict = requests.post(url, data=json.dumps(data), **kwargs).json()
except Exception as e:
... | 95de52e6005e7f00078a6e682512450a0367ee70 | 54,705 |
def _data_type_filter(x, y):
"""Filter data types into acceptable format."""
if HAS_DASK:
x = extract_dask_data(x)
if y is not None:
y = extract_dask_labels(y)
if HAS_PANDAS:
x = extract_pandas_data(x)
if y is not None:
y = extract_pandas_labels(y)
return x, y | de9bf7141d82655a4c202d8baed80cecb1ac94aa | 54,706 |
def area(int_pts, num_of_inter):
"""area"""
area_val = 0.0
for i in range(num_of_inter - 2):
area_val += abs(trangle_area(int_pts[:2], int_pts[2 * i + 2:2 * i + 4],
int_pts[2 * i + 4:2 * i + 6]))
return area_val | 78519de4802bbd76c376af1e2bec71ed106eca34 | 54,707 |
def unique(it):
"""Return a list of unique elements in the iterable, preserving the order.
Usage::
>>> unique([None, "spam", 2, "spam", "A", "spam", "spam", "eggs", "spam"])
[None, 'spam', 2, 'A', 'eggs']
"""
seen = set()
ret = []
for elm in it:
if elm not in seen:
... | 8e182467eb8179c2b9168470f8b683710ad37b56 | 54,708 |
def _quaternionAdd(quat0, quat1):
""" Multiplies 2 lists of quaternions
"""
# Find the maximum indices to use for clipping purposes
max0, max1 = quat0.shape[0]-1, quat1.shape[0]-1
maxsize = max(max0, max1) + 1
quat = np.empty((maxsize,4))
for ii in range(maxsize):
index0 = min(ii, ... | f3124f38955d728efbe8e9b467a7164e8024b888 | 54,709 |
from numpy import where
def image_numbers(logfile,name="",repeat_count=[]):
"""Select a subset of a dataset based on critria, such a file name and repeat counts
logfile: table object, must have attributes "file",Temperature","Delay"
name: part of the image filname, e.g. "_offWT"
repeat_count: e.g. [["... | e4ed486792eab4091016599ec09cf3a219df14b2 | 54,710 |
from pathlib import Path
import argparse
def valid_file(path):
"""Helper method for parse_args to convert to Path and verify if the file path exists.
Args:
path: path to file from parse_args()
Returns:
The absolute path of the given file path if it exists
Raises:
argparse.Ar... | e6420eb8c5c59951ef47eb236caa69c886f93b00 | 54,711 |
import scipy
def optimize_epsilon(data_train, labels_train, data_test, labels_test, num_markers, method='centers', fixed_parameters={}, bounds=[(0.2 , 10)], x0=[1], max_fun_evaluations=20, n_experiments=5, clf=None, hierarchy=False, verbose=True):
"""
Finds the optimal value of epsilon using scipy.optimize.du... | d8089bf5059bbcb3b1650ea3adcf24a39365c3e4 | 54,712 |
def census_vip_call(*, resp, **_):
"""
Convert response for calling url to pandas dataframe,
begin parsing df into FBA format
:param resp: df, response from url call
:return: pandas dataframe of original source data
"""
# Convert response to dataframe
df = pd.read_excel(resp.content,
... | c7e63b569b317cc9bdae2eb6064fea437ac03f49 | 54,713 |
def model_field_slugify(
model_class,
instance,
string,
filter_keys=None,
exclude_keys=None,
slug_field='slug'):
"""Slugify string based on another string and saves slug in model"""
if str(string).lower() in reserved_slugs:
raise ReservedSlugException('Es... | 1520deee2a8ba5b2cb78372c5f00ab63306f0e0c | 54,714 |
def create_read_fmt(read_id: str) -> str:
"""create a bitstruct format for any given read it up to 512 bits"""
if len(read_id) > 64:
raise ValueError("Read ID is too large")
padding = 512 - len(read_id)*8
r_fmt = "t{0}p{1}".format(len(read_id)*8, padding)
return r_fmt + ("u3" * 150) + ("u6" ... | f7319ffc62b55859ed8af3e6b7e044d9481f7384 | 54,715 |
import gc
import os
def penMarksFeatures(MF, prefix='', input=[], whole_image=True, output=[]):
"""Obtain coordinates of the pixels at the edge of the penmarks from the tile frames in both pre- and post-MALDI
microscopy datasets using matlab implementation of the SURF algorithm.
Args:
MF (str): p... | e94c28c65fd322c36343b934284cc0e46e20c67e | 54,716 |
from robosuite.controllers import ALL_CONTROLLERS
import os
import json
def load_controller_config(custom_fpath=None, default_controller=None):
"""
Utility function that loads the desired controller and returns the loaded configuration as a dict
If @default_controller is specified, any value inputted to ... | 587ff2e2a430e1b1754e8bf39632dbf379540dad | 54,717 |
from typing import Optional
import tempfile
from pathlib import Path
def get_job_log_file(run: Run, index: Optional[int] = None) -> str:
"""
Reads the job log file (70_driver_log.txt or std_log.txt) of the given job. If an index is provided, get
the matching file from a multi-node job.
:return: The co... | 5675a9e08a499cd99c765e1e76009c0ad3cbdc55 | 54,718 |
import warnings
from typing import cast
def _is_compatible(program: Loop, min_len: int, quantum: int, sample_rate: TimeType) -> _CompatibilityLevel:
""" check whether program loop is compatible with awg requirements
possible reasons for incompatibility:
program shorter than minimum length
... | 38cc5f639b54bbfc5602d4f5e3c25909a9a06014 | 54,719 |
def get_data_for_tpu(tpu_name, economic_dataframe, marry_dataframe, edu_dataframe, population_dataframe):
"""
:param tpu_name: the name of the tpu
:param economic_dataframe: the dataframe contains median income and employment rate
:param marry_dataframe: the dataframe which saves the marrital status
... | fe71fd15fab28684f848b80e68746fe1e3a73f51 | 54,720 |
def gridaspoints(*arrs):
"""Creates an N-dimensional grid form arrs and returns grid points sequence
of point coordinate pairs
"""
# there is a small gotcha here.
# with the convention following the 2013-08-30 sprint in Potsdam it was
# agreed upon that arrays should have shapes (...,z,y,x) simi... | ba907705965bf9f432d127126c784eb5b1c84873 | 54,721 |
def download_powermeter_csv(agent):
"""
Method to download a CSV list of mains sensor readings for all configured power meters and panels
**parameters**
:param agent: An agent instance from the device where the pmc data should be downloaded
:return: returns the pmc data in csv format
**Exampl... | d1c2b10ca89de98fd029388882e91b2264c0d235 | 54,722 |
def get_learner(case, *args, **kwargs):
"""Generator function for test"""
data = Data(*args, is_learner=True, **kwargs)
p = getattr(data.indexer, 'partitions', 1)
X, y = data.get_data((12, 4), 2)
(F, wf), (H, wh) = data.ground_truth(X, y, p)
data.indexer.fit(X)
learner, transformer = Estima... | 104317d0a5e7daf0272178b54595c33068fb844c | 54,723 |
import yaml
import sys
import os
def read_backend_config(config_file):
"""Parse YAML configuration file
Parameters
----------
config_file : str
path to the ramp-backend YAML configuration file
Returns
-------
config : dict
dictionary with RAMP database configuration info
... | a965a577f55714770d6de850e3875b0db77a2ace | 54,724 |
import async_timeout
import asyncio
import shlex
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up System Bridge from a config entry."""
client = Bridge(
BridgeClient(aiohttp_client.async_get_clientsession(hass)),
f"http://{entry.data[CONF_HOST]}:{entry.data[CONF... | 471ef1b3703515bcb32292783ebb2171939dffe2 | 54,725 |
def cleaned(cls):
"""Call individual cleaning methods and collect all of their ValidationErrors
Purpose:
This decorator allows you to write individual methods that do some
validation or cleaning without having to worry about collecting all
of their ValidationErrors together into a list ... | d502bfb2070d6a5578a5d7bb502383513f816ee0 | 54,726 |
import sys
import os
import logging
def jedi_epc_server(
address='localhost',
port=0,
port_file=sys.stdout,
sys_path=[],
virtual_env=[],
sys_path_append=[],
debugger=None,
log_traceback=None,
):
"""Start EPC server.
:type log_settings: LogSettin... | 8ec90c3c550389ad6bc09f4065a400741c64e144 | 54,727 |
def check_framescene(scene, frame, cameras, quality, check_green_frames,
check_empty_frame, min_nbr_people):
"""
Checks a frame for all cameras in one scene.
Returns True if all frame is good.
Returns False if any frame was bad.
"""
for camera in cameras:
bad, ids = ... | 05843c8b022fae658076232be709d295dd42cd84 | 54,728 |
def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id):
"""
Gets an onset_front and an offset_front such that they both occupy at least some of the same
frequency channels, then returns the portion of each that overlaps with the other.
"""
# Get the... | 14314dc10d896807a3d10ef57a1a4abaab28de5c | 54,729 |
import os
def create(req, sock, client, server, cfg):
"""
:param req: ``.message.Request`` 请求
:param sock: client sock
:param client: client addr, e.g. ``('127.0.0.1', 10000)``
:param server: server sock, e.g. ``('127.0.0.1', 8000)``
"""
resp = Response(req, sock, cfg)
# set initial e... | 3864f3b8246591b0d7340cf44d6851cb6b65157b | 54,730 |
import statistics
def time_formatted(event:str, mode:str, t: float, dnf: bool=False) -> str:
""" Reverses parse_time """
if t == statistics.DNF:
return "DNF" if dnf else ""
if event in ["3x3x3 Fewest Moves", "3x3x3 Multi-Blind"]:
if event == "3x3x3 Fewest Moves" and mode == "average":
... | fb39e88e3e790b2338288cc31f4e6b0c7e9b299c | 54,731 |
from re import T
import numpy
def tsum(x: T.Tensor, axis: int=None, keepdims: bool=False) -> T.FloatingPoint:
"""
Return the sum of the elements of a tensor along the specified axis.
Args:
x: A float or tensor.
axis (optional): The axis for taking the sum.
keepdims (optional): If ... | a8004051ed0258396366e075bd5b4f3cdebcdd5d | 54,732 |
def ask_multi_choices(prompt="Add to choices : ", choices_list=[], to_save="s", to_quit="q"):
"""Collect multi choices from list
Keyword Arguments:
prompt {str} -- the question method (default: {"Add to choices : "})
choices_list {list} -- the available options (default: {[]})
to_sa... | 0ece08fd561b770445af1e9a778f3dbaf0c1ba6a | 54,733 |
def DtypeToType(dtype):
"""Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum."""
if dtype.char in np.typecodes['AllFloat']:
return GetFeatureStatsProtoDef().FLOAT
elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or
np.issubdtype(dtype, np.datetime64) or
np.i... | b448192a2bd50cf1b45a29c3f29e1be53c4cab08 | 54,734 |
def register_prelu_func(graph):
"""Register Prelu op with function def, this is need for importing graph_def
with unregistered Prelu op.
Args:
graph: A tf.Graph object to insert prelu function into.
"""
# Create a function for Prelu op
@function.Defun(tf.float32, tf.float32, func_name='Prelu')
def pr... | 6884288e62489e8e27f1b9bf7aac911c13f005c4 | 54,735 |
def _parseSteps(raw_steps, lang=None):
"""
:type raw_steps: Iterable[dict]
:param lang: (Optional) Descriptor of the language to query the step,
without any specification of encoding or modifiers.
:type lang: str | None
:rtype: Iterable[TutorialStep]
"""
def getI18nStringForStepKey(... | 7a9b2cc7cf3c805d38db6c1ae21ea20062ba7ca4 | 54,736 |
def legendre_P(n,x):
"""
Returns the Legendre polynomial of the first kind for integers
`n > -1`.
REFERENCE:
- AS 22.5.35 page 779.
EXAMPLES::
sage: P.<t> = QQ[]
sage: legendre_P(2,t)
3/2*t^2 - 1/2
sage: legendre_P(3, 1.1)
1.67750000000000
sage... | 45b60b0ad5874a3bf54e83cad6037e72e8f363fd | 54,737 |
def spawn_dates_times(df, spawn_dates=True, spawn_times=False):
"""
Build date/times column from a timeseries dataframe
:param df: (pd.DataFrame) - dataframe with datetime index
:param spawn_dates: (boolean) - whether to spawn year, month, day cols
:param spawn_times: (boolean) - whether to spawn h... | ee58b5117d65fa3f217b16973dcdc06918c5474b | 54,738 |
def parse_date(string, format=None):
"""
:type string: str
:type format: NoneType or str
:rtype: NoneType or date
"""
if format is None:
formats = FORMATS
else:
formats = [format]
for f in formats:
try:
return dt.datetime.strptime(string, f).date()
except ValueError:
pass
return None | 7282d401ba0ab2e2243c7c4ad990136ad80d2ee3 | 54,739 |
from typing import List
def impurity_of_split_rec(points: List[DataPoint], split: float) -> float:
"""
Recursive method wrapper to split the data points into two arrays based on the split point provided and return the gini impurity measure for that split point.
"""
print("Printing split: {}".format(sp... | c3232595b4f1168472e3444939e57f5744a0b6da | 54,740 |
import ctypes
def GetConsoleOriginalTitle() -> str:
"""
GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.
"""
if IsNT6orHigher:
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.kernel32.GetConsoleOriginalT... | 55900e0280253860b95a20acd2551f61a831d61d | 54,741 |
from re import U
def build_train_mf(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, scope="mfec",
alpha=1.0, beta=1.0, theta=1.0, latent_dim=32, ib=True, reuse=None):
"""Creates the train function:
Parameters
----------
make_obs_ph: str -> tf.placeh... | 8c0b943fb70b0bc1e4db750f6b82edb5d134c780 | 54,742 |
import multiprocessing
import glob
import os
import collections
from datetime import datetime
def _batch_into_watershed_subsets(
watershed_root_dir, degree_separation, done_token_path,
watershed_subset=None):
"""Construct geospatially adjacent subsets.
Breaks watersheds up into geospatially s... | 559fb2a9f64cae7127cacbfb78f6e46cabead521 | 54,743 |
def connection():
"""
Function that provide the SQL connection to be uses by the ORM.
Returns
-------
(bool, SQL connection object)
The first element of the tuple indicates whether the connection is to be closed after every query. The second
element should provide an SQL connection ... | 65b0122a0cc7b57ab553ac85a6db576e3d242de6 | 54,744 |
def mergeinput_preprocess_duo(df1, df2):
""" Merge 2 data frames into one for full analysis.
Output will be two form: long form and wide form
long form: simply add 2 df on top of each other
wide form: each row represents a request coordinate with result from both run. -> calculate ED
relevant cols f... | 9967be2ec1ccae8d6462c5c01f63d8641b523759 | 54,745 |
def mbeans(query=None):
"""
Returns a list of all the available MBeans in the server. The optional
query parameter will filter the list by objectname
"""
return server.getQueryMBeans(ObjectName(query), None) | 3ad2ed5b36196b55deeefa51ab7968b009b523de | 54,746 |
def is_decimal_dtype(obj):
"""Check whether an array-like or dtype is of the decimal dtype.
Parameters
----------
obj : array-like or dtype
The array-like or dtype to check.
Returns
-------
bool
Whether or not the array-like or dtype is of the decimal dtype.
"""
ret... | c2151eb94ff9aebd6694aa679d1cfcc75f08133f | 54,747 |
def calculate_F1(max, compensate = 0, threshold = 0.5):
"""
Args:
max (M,N)
return:
AP,TP,FP,FN,precision,recall,F1
"""
if compensate < 0:
compensate = 0
TP = 0
FP = 0
FN = 0
for i in range(len(max)):
if max[i] > threshold:
TP = TP + 1
... | 6aab529bbf1837472f0d711997b31fca0fcc3eee | 54,748 |
import time
def runtime(X, y, model_generator, method_name):
""" Runtime (sec / 1k samples)
transform = "negate_log"
sort_order = 2
"""
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
for i in range(3):
... | 6cbb4a7e773f3c5dafcaf43aa6106be59dc4b87f | 54,749 |
def get_mask(json_data, microplate_names):
"""Return wrapper for numpy array."""
return ControlMask(json_data, microplate_names) | d18fc86c9189b80f550d55646d8f2b94f924fe4d | 54,750 |
def utc2sec(*utc):
"""Convert list composed of year,month,day,hour,minute,second [,microsec]
:param utc: list of year,month,day,hour,minute,second
:returns: number of seconds since the epoch 0001-01-01
"""
utc2=list(utc)
if len(utc)<7:
utc2.append(0)
return int(utc2micro(*utc2)/10*... | 41b6469087414a8c210125b52060745f2cbaf380 | 54,751 |
import subprocess
import logging
def subprocess_run(subprocessCMD, shell=False):
"""
Run a subprocess command, passed by dict of arguments. Executes by default with shell=False, and then logging STDOUT and STDERR
"""
procCall = subprocess.run(subprocessCMD,stdout=subprocess.PIPE,stderr=subprocess.PIPE... | 2a2307e133a83a5ec0c8abb100f39635242429e8 | 54,752 |
def scale_sample(xy_sample,grid):
""" This function is used to apply the shifts and scaling to the sample. """
sample = xy_sample.copy()
if grid.dim == 2:
sample[:,2] = sample[:,2] + grid.shifts[0]*sample[:,0] + grid.shifts[1]*sample[:,1]
sample[:,0] = sample[:,0]/grid.b0
sample... | 3f0ae32f198ec75d112ff7d36ea2505dcd75dbea | 54,753 |
def radius_aperture(info_dict):
""" Compute the radius of the aperture
Parameters
----------
info_dict: dictionary
wavelength: float
wavelength in angstrom
Returns
--------
aperture: float
radius of the aperture in arcsec
"""
if info_dict["psf_type"] == "gaussi... | d5055e6bdb3b5fd519ac2b96941a0338bc547b0c | 54,754 |
from pathlib import Path
def find_file(filename):
"""
Finds a file in the directory that has the same name
as the parameter <filename>. If the file does not exist,
the directory is searched for <filename.*> instead, and if
only one match is found, that particular filename is returned.
"""
... | 4915739f11221f566a7fc6f381fc29bf30426908 | 54,755 |
def FermiDirac(Ef, EJ, T):
"""
Returns the Fermi-Dirac probability distribution, given the crystal's
Fermi energy, the temperature and the energy where the distribution values
is required.
Args:
| Ef: Fermi energy in J
| EJ: Energy in J
| T : Temperature in K
Returns:
... | 1e8fbfc0a9ef704340810f2b085afe3543f61356 | 54,756 |
def glXQueryVersion(dpy):
"""
dpy - Display*
return - bool, int, int: support, major, minor"""
major = Numeric.zeros(1, Numeric.Int32)
minor = Numeric.zeros(1, Numeric.Int32)
res = _glxlib.glXQueryVersion(dpy, major, minor)
return res, major[0], minor[0] | 28798bc9371bffd959025190af17b3d29cdd8a0b | 54,757 |
import numpy as np
from grizli.aws import db
import os
def reset_failed_assoc(failed_status='status != 2', reset=True, remove_files=True):
"""
Reset failed visits
"""
failed_assoc = db.SQL(f"""SELECT * FROM assoc_table
WHERE {failed_status}""")
if rese... | d580954dd5aa65b140b230ce8c9d669d782d2b27 | 54,758 |
import random
def get_message_data():
"""Default valid message data."""
return {
'message': '''
-----BEGIN PGP MESSAGE-----
Version: Keybase OpenPGP v2.0.8
Comment: https://keybase.io/crypto
wcBMA6Uvn0xuUMOaAQf/bGf4y9ZfKChSOAJs4M5V7K3nDC2p/sUNcfy8FzoIl9VE
j2vT3bMZsaT3cJkQMfABqWgzq8VlQjRP1/m+bBX4jRUYV... | 1e715936bcdd133a981403e6b523bd623e806b1b | 54,759 |
def usgs_kyanite_parse(*, df_list, source, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to fl... | 25536570a06fffe43d36d4f62a0ff0a2ee98863d | 54,760 |
from typing import List
def prepare_element(sample_nist_component_def: component.ComponentDefinition):
"""Prepare a target element for remove tests."""
element = Element(sample_nist_component_def)
parties: List[common.Party] = []
parties.append(
common.Party(**{
'uuid': 'ff47836c-... | 08570b86e8eaf7c510c9b5cafa0071b3fe90edb9 | 54,761 |
import torch
def flow_warp_tensor(mask, flow, coord=None):
"""
:param mask: 1xCxHxW
:param flow: HxWx2
:return:
"""
if coord is None:
shape = mask.shape[-2:]
coord = torch.ones(shape).cuda().long()
coord = torch.nonzero(coord).float()
flow = flow2coord(flow, coord)
flow = flow.unsqueeze(0... | 0ff2ed886f5224708cdb8ee4f0129b952bb2de3e | 54,762 |
import os
def filter_filename(dirname, include=[], exclude=[], array_id=None):
"""Filter filename in a directory"""
def get_array_id(filename):
array_id = filename.split("_")[-2]
try:
array_id = eval(array_id)
except:
pass
return array_id
filename_co... | 309eabb4c7e3b25e11bafd66a0cdc9a91169ad08 | 54,763 |
def get_filestore(config):
"""Returns the correct filestore based on the platform in |config|.
Raises an exception if there is no correct filestore for the platform."""
# TODO(metzman): Force specifying of filestore.
if config.platform == config.Platform.EXTERNAL_GITHUB:
return filestore.github_actions.Gith... | 3964858f3cdf9b562dd7a77540a905d292dfb028 | 54,764 |
def neighborhood_ambulance_combinations(neighborhoods, total_ambulance):
"""
This function returns all possible combinatios for neighborhoods and
the number of ambulances they hold.
Inputs:
neighborhoods (Array of string) neighborhood names that contains ambulance stations
total_ambula... | 2e640ab8c089dc61e650978d7da1201f0032540b | 54,765 |
def get_number_of_desktops():
"""
Returns the number of virtual desktops.
:return: The number of desktops.
:rtype: util.PropertyCookieSingle (CARDINAL/32)
"""
cook = util.get_property(root, '_NET_NUMBER_OF_DESKTOPS')
return util.PropertyCookieSingle(cook) | 4899628116bac58fbeb23f5f9fddb248115e4cef | 54,766 |
def scalar_to_array(input_x):
"""
Converts a scalar to a `Tensor`.
Args:
input_x (Union[int, float]): The input is a scalar. Only constant value is allowed.
Returns:
Tensor. 0-D Tensor and the content is the input.
Raises:
TypeError: If `input_x` is neither int nor float.
... | d7923256a1908df9f1633ebe946a871ad7a6bcbe | 54,767 |
import json
import requests
def handle_action():
"""Handle a response when a user clicks a button from Wizzy in Slack"""
event_data = json.loads(request.form["payload"])
user = event_data['user']['id']
# if channel empty, it's a shortcut
if event_data.get('channel') is None:
# shortcut - g... | cb54f430e4e3317af658ef1068d893f4798a7c0e | 54,768 |
from typing import List
import copy
def calc_permutation_matrix(
system_order: List[int], size_list: List[int]
) -> np.ndarray:
"""calculate permutation matrix.
permutation matrix can reorder the system order to [0, 1,..., n].
Parameters
----------
system_order : List[int]
system_ord... | 6544e03cb1febde14c15ad5fa6ac2c425dabec0a | 54,769 |
def interface(agents, envrionment, steps):
"""
Agents-Environment Interface. Let the agents interact.
Parameters
----------
agents : iterable of agents
envrionment : envrionment
steps : int (Number of interaction steps)
"""
def allagentinteract(obs, rews):
actions = []
... | 61d137c33db85afca506a1a84efadf77eab23802 | 54,770 |
import random
def cvt_horizontal_flip(
sample_input: Dataset, sample_output: Dataset, probability: float = 0.5
) -> Dataset:
"""Converts the sample_input dataset to horizontal flips in sample_output dataset.
Args:
sample_input: input dataset passed to generate output dataset.
sample_outpu... | 2f15e5ed3aae75bda360f17f95e7722b70bb0bbc | 54,771 |
def search():
"""Display search options"""
return render_template("search.html") | 97193ebb2820b33f038a5f027caa5bde6889a788 | 54,772 |
def get_client_setting(setting: str, cid: str) -> ClientSetting:
"""Return client setting based on setting name and cid."""
for client_setting in get_setting(setting).clients:
if client_setting.cid == cid:
return client_setting
raise ClientSettingNotFound() | e6292699c4a741541dede631fc1f5b42cbb744ec | 54,773 |
def between(x, min, max, exclude_max=UNSET) -> ProcessBuilder:
"""
Between comparison
:param x: The value to check.
:param min: Lower boundary (inclusive) to check against.
:param max: Upper boundary (inclusive) to check against.
:param exclude_max: Exclude the upper boundary `max` if set to `t... | 72417a83c8196b32a4c3838ec6e0b9b21c94d050 | 54,774 |
def parse_description(issue):
"""
:param issue: Issue object.
:return: ROGA type: (a string that should be listeria/salmonella/vtec - otherwise they'll get others later.
seq_ids: List of seqIDs which will later be written to file and used in ROGA report generation.
"""
# Take whatever i... | 13ea063546a327dd94eff1fca8f03d9ea7ea1476 | 54,775 |
def feedback(data: FeedbackData) -> str:
"""
Pass the request data as FeedbackData object,
as this can be customised in the model.py file to adapt based
on deployed model to make predictions
Parameters:
data: Parse the request body data based on your model schema and
pass this to pred... | cdfbe44e46c82282488f4d57d818b27c0279f488 | 54,776 |
def get_dataset(id_):
"""특정 dataset에 대한 정보 반환
Args:
id_ (int): dataset ID
Returns:
_type_: _description_
"""
result_json = {"datasetName": "", "image_metadata": []}
query = Dataset.query.filter_by(id=id_).first()
result_json["datasetName"] = query.name
query = ImageM... | 135b45947ebe604ee71d579c5aa9b373f9d8048f | 54,777 |
def test_metathesis(word, anagram):
""" Tests if a word and an anagram are a metathesis pair
This is only true if the words are I. Anagrams II. Differ in two places
"""
count = 0
for para in zip(word, anagram):
if para[0] != para[1]:
count += 1
return count == 2 | c26090d92b526ce7d2a84138e4248c884a19f5bc | 54,778 |
from aac.plugins import (
gen_json,
gen_plugin,
gen_protobuf,
gen_design_doc,
gen_gherkin_behaviors,
gen_plant_uml,
specifications,
)
def get_plugin_manager() -> PluginManager:
"""
Gets the plugin manager and automatically registers internal plugins.
... | 8a8bc92205bf2334c41332e2f6a337fc0709a634 | 54,779 |
def get_token(username, password):
"""Returns a new token for login credentials."""
payload = {'username': username, 'password': password}
key = username + password # simple key
token = jwt.encode(payload, key, algorithm='HS256')
# Convert bytes to string
token = token.decode('utf-8')
# Sto... | 2abef9d55fb96fcc9567b934d1dccd55e29e3c96 | 54,780 |
def standardize(ds, dim="time"):
"""Standardize Dataset/DataArray
.. math::
\\frac{x - \\mu_{x}}{\\sigma_{x}}
Args:
ds (xarray object): Dataset or DataArray with variable(s) to standardize.
dim (optional str): Which dimension to standardize over (default 'time').
Returns:
... | 99de2a60e340a7ad451daec27aad028485d4aa59 | 54,781 |
import warnings
def predict(model, image_files, resize=False, show_image=True, cloud=None):
"""Predict using an model in a local or GCS directory (offline), or a deployed model (online).
Args:
model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies
a deployed mod... | 5cc4e7667032243448ab5b871c7728967698702b | 54,782 |
import sys
def retrieve_past_timestamps(ref_timestamp, streams_stamps, prev_timestamp=0):
""" get timestamps between two annotated frames.
Parameters
----------
ref_timestamp :
The timestamp of the annotated image.
streams_stamps :
Timestamps dict of the whole sequence
prev_timestamp :
Th... | 12b5918a1273129c603f4287102677d26946c202 | 54,783 |
import six
def topics_offset_distance(
kafka_client,
group,
topics,
offset_storage='zookeeper',
):
"""Get the distance a group_id is from the current latest offset
for topics.
If the group is unkown to kafka it's assumed to be an offset 0. All other
errors will not be caught.
Thi... | d6f1ded7f609d86726b88eba494fec5fdc264e7d | 54,784 |
def get_first_meeting_day_num(days: str):
""" Returns the number representing the day of first meeting of the week
:param days:str: Days field of WebReg list, example: "MWF"
"""
day_nums = get_day_nums(days)
first_day_num = day_nums[0]
return first_day_num | f86f2832ea7cec4356b1aae60a7a1ac17573fc35 | 54,785 |
from typing import Any
from datetime import datetime
def post_search(netid: str, client: ShrunkClient, req: Any) -> Any:
"""``POST /api/search``
Execute a search query. Request format:
.. code-block:: json
{
"query?": "string",
"set": {
"set": "'user' | 'shared' | 'a... | a4d59bed2aee578d14fee1ecdb84d4e036c0d0b9 | 54,786 |
import smtplib
def os_error():
"""Operating system error. AKA EnvironmentError / IOError."""
try:
smtplib.SMTP('localhost:a_port')
except OSError:
return "bad port number" | 2b99d466f04369ab98bdb40c7a3417dd8c089744 | 54,787 |
import requests
import os
import random
def select_random_hashtag():
"""
Returns a random hashtag from the latest posts or travel if none was found
"""
r = requests.get('https://api.instagram.com/v1/users/self/media/recent?access_token={}'.format(os.environ['ACCESS_TOKEN']))
if r.status_code == 20... | 914ebd4af4ec1ce92d0b5325ca1cd9dc007ccf3d | 54,788 |
def multivariate_potential(ptset2, meanvec, covmat):
"""
Vectorised evaluation of multivariate Gaussian pdf.
Args:
ptset: shape (N, d)
mean: shape (d,)
covar: shape (d,)
Raises:
AssertionError: if ptset, mean and covar have not consistent shape
Returns:
resul... | 226c0958c9fd835c93ce33a3f42cd1abea62eba0 | 54,789 |
import os
import urllib
import json
def test_apigateway_invoke_localhost_with_path(
cfn_client, deploy_cfn_template, stepfunctions_client
):
"""tests the same as above but with the "generic" localhost version of invoking the apigateway"""
deploy_result = deploy_cfn_template(
template_path=os.path.... | 3bda9d20ad656cba16af958432912a6996afdaf6 | 54,790 |
def restart(backend):
"""Restart the running server from an async test function.
This fixture deals with possible differences between the environment of the
test function and that of the server.
"""
async def restart(server):
await backend.run_in_threadpool(AsyncioBackend().run, server.res... | 518af91d3ebf1bd88f2faae1a06215dd6d67d9cf | 54,791 |
def colinterp(a,x) :
"""Interpolates colors"""
l = len(a)-1
i = min(l, max(0, int (x * l)))
(u,v) = a[i:i+2,:]
return u - (u-v) * ((x * l) % 1.0) | 278eb403e220fee139a73ed6f764df93b6366bc9 | 54,792 |
def accepted_content_type(f):
"""
Check if the requested content type is application/json.
"""
def decorator(*args, **kwargs):
if request.content_type != 'application/json':
raise ServiceException('Content type must be application/json', 400)
return f(*args, **kwargs)
r... | 5b0bcde03e4dc204ca95dd685b0715680f502633 | 54,793 |
import requests
def get_articles_html(url_articles: str) -> str:
"""Wraps HTTP requests.get for testibility
Parameters
----------
url_articles : str
Articles URL
Returns
-------
str
HTML page of articles
"""
articles_html = requests.get(
url_articles, head... | 4fcbf397d4986eed19a3528dde99cb5a81581a10 | 54,794 |
def ei_merit(X, surrogate, fX, XX=None, dtol=0):
"""Compute the expected improvement merit function.
:param X: Points where to compute EI, of size n x dim
:type X: numpy.array
:param surrogate: Surrogate model object, must implement predict_std
:type surrogate: object
:param fX: Values at previ... | e53d35f93b7aeb5fca6c34e70ababb7812b78fc5 | 54,795 |
import soundfile as sf
from pathlib import Path
from typing import Optional
from typing import List
import logging
def load_audio(
path: Path,
channel: Optional[int] = None,
mmap: bool = False,
channel_names: List[str] = ["left", "right"],
) -> MultiTrack:
"""load waveform from file"""
multiTr... | bd853eb4fef33aad63a0267c5bb63ba91d457d3b | 54,796 |
def render_robots_meta_tag(context):
"""
Returns the robots meta tag.
"""
request = context['request']
robots_indexing = None
robots_following = None
# Prevent indexing any unwanted domains (e.g. staging).
if context.request.get_host() in settings.META_TAGGER_ROBOTS_DOMAIN_WHITELIST:
... | 018084102031ca13a36f2563c6f05d810045432e | 54,797 |
from typing import Dict
def search(search_string)->Dict:
"""
API to search "search_string" in the stored documents
:param search_string: search string provided by the user
:type search_string: str
:return: returns results i.e. return list of documents that are closest match to the search string
... | 588960333a7140ad51ffc577741f9102e90d082f | 54,798 |
def convert_lang_code(code):
"""
Map a language code to the canonical one that ConceptNet 5 uses, using the
'langcodes' library.
"""
return str(langcodes.get(code)) | 0da05bd40e6758038c28c3d585744d2ed63fe6f7 | 54,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.