content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calculate_transit_duration_in_days(t, period, transit_times, duration):
"""Return estimate for transit duration in days"""
# Difference between (time series duration / period) and epochs
transit_duration_in_days_raw = (
duration * calculate_stretch(t, period, transit_times) * period
)
... | f894b1e2ea4957e5139015574e4378fe26a6e81d | 45,700 |
def profile(request, user_id):
"""
Function that enables one to see their profile
"""
title = "Profile"
profile = Profile.objects.get(user_id=user_id)
biz = Business.objects.filter(user_id=user_id).all()
hood = Neighbour.objects.filter(user_id=user_id).all()
users = User.objects.get(id=u... | ed7fbbe1389d6fb924a626fb3368fc97be4c67b5 | 45,701 |
def get_binomial_filter_1d(size):
"""
This produces a 1d spatial filter with binomial coefficients
"""
assert size > 1
kernel = np.array([0.5, 0.5])
for i in range(size - 2):
kernel = convolve(np.array([0.5, 0.5]), kernel)
return kernel | 653cf1082dc346488ae12217e674d65fa6a933f8 | 45,702 |
import socket
def get_hostname() -> str:
"""
Get the current hostname, or fall back to localhost.
"""
try:
return socket.getfqdn()
except:
return 'localhost' | c53bd9fae0fbbae0c0b4f84e64064d7bfd2fd61e | 45,703 |
def format_design_table(designs: pd.DataFrame,
minimum_detectable_iroas: float,
minimum_lift_in_response_metric: float = 10.0,
minimum_revenue_covered_by_treatment: float = 5.0):
"""Formats a table with the output designs.
Args:
designs: t... | e6f8b963fe85479edab40860f7f0c3784cb324bf | 45,704 |
def SerializeEntries(entries):
"""Serializes given triplets of python and wire values and a descriptor."""
output = []
for python_format, wire_format, type_descriptor in entries:
if wire_format is None or (python_format and
type_descriptor.IsDirty(python_format)):
wire_fo... | fe89382e2be003bd6dce25b973d8bd3ad403c492 | 45,705 |
from typing import List
from typing import Tuple
def get_anilist(username: str, **vars) -> List[Tuple[int,str]]:
"""
Gets an anilist list with a username.
"""
measure = Measure()
raw = get_raw_anilist(username, **vars)
data = sort_anilist(raw)
logger.info(f'[get] Got data from anilist in {... | de341a40857491a00c6f9721f0bad6a20774d993 | 45,706 |
def get_metadata_wikidata(person_complete_name):
"""
Get birth date, gender and nationality (expressed with country name) for the given person
:param person_complete_name: Person you are interested in
:return:
"""
entities_ids = get_wikidata_entities(person_complete_name)
person_metadata = {... | 781583cd3e73fb55259ad4204884207a058ff774 | 45,707 |
def evaluate_general(
result_paths, interactions_paths, events_paths, metrics,
x_axis_name, x_axis_type,
group_key, group_key_name_func, sort_keyfunc=None,
xticks=[],
K=10):
"""
Return a 3D table
group_key: the legend part
metrics: the y axis
x_axis_name, sort... | d049aa6d3c5d77ef973ec7c88805884f1dc6e25c | 45,708 |
def _get_group_discount_offer(basket, balance, group_items, num_items_offer, price_offer):
"""
Update the balance and the basket for a Group discount offer.
"""
group_items = [item for item in group_items if item in basket]
offers_sold = sum([basket[item] for item in group_items])//num_items_offer... | 509470fccb8a3d41a2e2e69129f186e06db261ef | 45,709 |
def calculate_acc(mode: enums.GameMode, osu_score: dict, exclude_misses: bool = False):
""" Calculate the accuracy using formulas from https://osu.ppy.sh/wiki/Accuracy """
# Parse data from the score: 50s, 100s, 300s, misses, katu and geki
keys = ("count_300", "count_100", "count_50", "count_miss", "count_k... | 1aadd86d25a5123a857f258de0f411c2385b4d89 | 45,710 |
def softmax_kernel_transformation(data,
is_query,
projection_matrix=None,
numerical_stabilizer=0.000001):
"""Computes random features for the softmax kernel using FAVOR+ mechanism.
Computes random features for the... | 08f6ebb58d12e16c5a9b3ef8db1d8f241a1c186e | 45,711 |
from typing import List
from typing import Sequence
from typing import Tuple
def global_bspline_interpolation_first_derivatives(
fit_points: List[Vec3],
derivatives: List[Vec3],
degree: int,
t_vector: Sequence[float]) -> Tuple[List[Vec3], List[float]]:
"""
Interpolate the contr... | 8325c3858da5fd13878d5859c554868862a0aa11 | 45,712 |
from datetime import datetime
import os
def dashboard(request):
"""
Render HTML for dashboard/metrics view.
"""
# Datasets
dataset_count = Dataset.objects.all().count()
datasets_without_descriptions = [(unquote(dataset['name']), dataset['slug']) for dataset in Dataset.objects.filter(descripti... | d2e5dc4953845f9250caadc790fe4e8e0dbe96f5 | 45,713 |
import csv
def read_csv_as_list_dict(filename, separator, quote):
"""
Inputs:
filename - name of CSV file
separator - character that separates fields
quote - character used to optionally quote fields
Output:
Returns a list of dictionaries where each item in the list
corr... | 2946b19a246d35761bfce4502209404f70ad70ee | 45,714 |
def _getname(node: Node):
"""Get mpiexec name for forward and frechet."""
if node.step is not None:
return f"_it{node.iter:05d}_ls{node.step:05d}"
else:
return f"_it{node.iter:05d}" | 1fd3c02f4a4d8aa79482a54271a41d74970275c3 | 45,715 |
def get_plugin(plugin_name):
"""
_get_plugin_
Get the deploy plugin requested from the factory
"""
factory = pluggage.registry.get_factory(
'deploy',
load_modules=['cirrus.plugins.deployers']
)
return factory(plugin_name) | 91de511d884e460a587de909379e3b8b68b677e1 | 45,716 |
import socket
import subprocess
import json
def get_instance_identification():
"""
Gets an identifier for an instance. Gets EC2 instanceId if possible, else local hostname
"""
instance_id = socket.gethostname()
try:
# "special tactics" for getting instance data inside EC2
instance... | 13528289a0db7337e3b7c074b617906f3ad23dbf | 45,717 |
import logging
def shift_display_orders(at_display_order):
"""
shift the display order in hpo_site_id_mappings_table when a new HPO is to be added.
:param at_display_order: index where the display order
:return:
"""
q = SHIFT_HPO_SITE_DISPLAY_ORDER.format(
display_order=at_display_orde... | 478f386cf6f7288ba6afa5f67c693f4e37067855 | 45,718 |
def calculate_postrior_GP(lmbda_q2, mu_omega_int_points, kappa_X, mu_omega_X,
kappa_int_points, num_integration_points, T, Kss_inv, noise,
ks_X, ks_int_points):
"""
This method calculates the mean and the covariance of the GP in the inducing points.
:param... | f3c6699a27e6c33b4a8e0f9415c567f1e08e4220 | 45,719 |
def get_species_list(request):
"""
Get list of distinct species labels
"""
species = models.ImageSet.objects.order_by().values_list('species', flat=True).distinct()
return Response(sorted(list(species))) | 73de7f3118e9434a0d718663ce3fc2313df16979 | 45,720 |
def encode(value):
"""
Encode Swarm.
:param bytes value: a decoded content
:return: the encoded content
:rtype: str
"""
mhash = multihash.encode(multihash.from_hex_string(value), 'keccak-256')
return make_cid(1, 'swarm-manifest', mhash).buffer | f6310d3e02e7a432461a32e886af42df28264896 | 45,721 |
import logging
def process_raw_data(raw_data_filepath: str, processed_data_filepath: str) -> None:
"""
Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
raw_data = pd.read_csv(ra... | e2b88d5585f732315fcae45fa67be45d887fab03 | 45,722 |
import http
from bs4 import BeautifulSoup
import os
def scrape(web_url, pdf, pg_no):
"""
Web scraping logic
"""
try:
page = urllib2.urlopen(web_url, timeout=200)
except http.client.RemoteDisconnected:
print("Error 404: {} not found.".format(web_url))
return 0
soup ... | 52fad7c1ae7a11156e9711d74d4f5f37a6e231a5 | 45,723 |
def _get_best_corrs(pvals_file):
"""extract sig motifs
"""
with h5py.File(pvals_file, "r") as hf:
keys = sorted(hf["pvals"].keys())
for key_idx in range(len(keys)):
key = "pvals/{}/correlations".format(keys[key_idx])
# get hgnc_ids and corr values
with h5py.File(pvals_f... | d421792a62dfae440795ee35a6f46900bbb37b81 | 45,724 |
def l2_regularization(params):
"""Computes l2 regularization term for parameters."""
return jax.tree_util.tree_reduce(op.add, l2_norm(params)) | 2075debec96d14c34ac9f2a67c799c18597a5efb | 45,725 |
import os
import sys
def load(dpath):
"""
Loads data from directory.
Arguments:
dpath -- directory
Returns:
train_set_x_orig -- train set features
train_set_y_orig -- train set labels
test_set_x_orig -- train set features
test_set_y_orig -- test set labels
classes -- list of ... | cc04b92aaad93fd192844ab82812bea9d25642de | 45,726 |
from ..datasets import fetch_fermi_extended_sources
from ..data import SpectralCube
def _extended_image(catalog, reference_cube):
"""Reprojects and adds extended source images to a larger survey image.
"""
# This import is here instead of at the top to avoid an ImportError
# due to circular dependenci... | c823987639b90ef3e91e01a48ae19a95fdbc29eb | 45,727 |
def _read_epoch_encoder_file(metadata):
"""
Read in epochs from the ``epoch_encoder_file`` in ``metadata`` and return a
dataframe.
"""
if metadata.get('epoch_encoder_file', None) is None:
return None
else:
# data types for each column in the file
dtypes = {
... | 0f0356a6aec1640c6a35f73d7d08f479176470a0 | 45,728 |
from datetime import datetime
def get_submission_data_from_pushshift(raw_submission):
"""Creates a submission object from a Pushshift Submission JSON
Parameters:
raw_submission (dict): Pushshift Submission instance
Returns:
dict: object with information about a submission, like body, author or... | 0fa00524408623127d32fb6db89398285953ec9b | 45,729 |
def google_webResults(input):
"""
google_webResults
"""
return google_webResults_soup(input) | b9402f3b6c3c183101e75d4eeece0c5c5da8f79f | 45,730 |
def pyscv_refresh(*args):
"""
pyscv_refresh(py_this) -> bool
"""
return _ida_kernwin.pyscv_refresh(*args) | 2c4e9f081e2ae45c35db65ad7f86a153dbe31b16 | 45,731 |
def get_auth_header():
"""
Return the authentication header.
"""
return gazu.client.make_auth_header() | 04ba9abb2a54b8b1df1db7bc5ac0c944d10961b5 | 45,732 |
from typing import Any
from typing import List
def default_input_mapping(data: Any) -> List[Tensor]:
"""Finds all tensors in a (nested) collection that have the same batch size.
Args:
data: a tensor or a collection of tensors (tuple, list, dict, etc.).
Returns:
A list of all tensors with... | f1f2344cc3364f286a1ea1e19746854a3810c0b8 | 45,733 |
from datetime import datetime
def get_month_range(months=0, unbounded=False):
"""获取月的开始和结束时间.
:param unbounded: 开区间
"""
today = datetime.date.today()
year_diff = (today.month + months) // 12
end = today.replace(
month=(today.month + months) % 12 + 1,
year=today.year + year_d... | 1d7f3575c395433b2e632a1f135ddd063cee827c | 45,734 |
from typing import Dict
import pkgutil
import io
def _load_categories(filepath: str) -> Dict[str, str]:
"""Load data for domain category matching.
Args:
filepath: relative path to csv file containing domains and categories
Returns:
Dictionary mapping domains to categories
"""
data = pkgutil.get_da... | 25ec3c4808d4a9624112e277c0597c868a12572c | 45,735 |
def parse_data(format, need_shape=True, **kwargs):
"""An interface of data parser.
Args:
format (str): Data parser format.
need_shape (bool): Whether need shape attributes. Default: True.
Returns:
obj (dict): Parsed data.
Examples:
{'img_names': ['COCO_val2014... | 7690dfccf529e2eb849e6621b86636c76b489ad3 | 45,736 |
import time
def extract_waveforms(ephys_file, ts, ch, t=2.0, sr=30000, n_ch_probe=385, dtype='int16',
offset=0, car=True):
"""
Extracts spike waveforms from binary ephys data file, after (optionally)
common-average-referencing (CAR) spatial noise.
Parameters
----------
e... | 86aa702197a74547b867fe30dec272c3cd3108b4 | 45,737 |
def users_groups(user, user_lookup_field, **kwargs):
"""List all groups belonging to a user"""
user_obj = _okta_get("users", user,
search=f"profile.{user_lookup_field} eq \"{user}\"")
user_id = user_obj["id"]
rv = okta_manager.call_okta(f"/users/{user_id}/groups", REST.get)
rv.s... | b417b0c90251166b255688a32e58ec32ec7ce56b | 45,738 |
def _previousSibling(self):
"""
Return the previous sibling
NOTE: This is fairly inefficient. The reason that it has
to be done this way is because Text nodes are a subclass of
`unicode` which is an immutable object. This means that
we can't have two references to the same Text object (i.... | 5b6976232e8cc7f7925fcf95df093706968f76d8 | 45,739 |
def file_mapper(json_: dict) -> File:
"""
Maps the json file response into a File object.
:param json_: The json obtained from the endpoint call
:type json_: dict
:return: A File instance
:rtype: :class:`vdx_helper.models.File`
"""
return File(
file_hash=json_["file_hash"],
... | 8303a4d3fbc4c5de861d987293c0cd2d7293bc7c | 45,740 |
def will_boom(message: str) -> None:
"""
This task will indirectly raise an exception.
"""
return boom(message) | c38ad7b8459f2ea370e4bd2238ed7221c86f1499 | 45,741 |
def boolean(value):
"""
Translate the given value to a boolean object.
Example:
>>> boolean(True)
True
>>> boolean(0)
False
>>> boolean('false')
False
>>> boolean('yes')
True
"""
if isinstance(value, bool):
return value
... | 63035a67edb4945cdbe400139c7d2492d8dcfc6b | 45,742 |
def mppe_key_derivation_master_key(password_hash_hash, nt_response):
"""
RFC 3079 MPPE Key Derivation
3.4. Key Derivation Functions
GetMasterKey
:param password_hash_hash:
:param nt_response:
:return: master_key
"""
magic1 = "\x54\x68\x69\x73\x20\x69\x73\x20\x74\x68\x65\x20\x4d\x50\... | 3b39b57d917d70afef2c42069dec3bdd61a2eca5 | 45,743 |
def commutator (proc1, proc2):
"""Returns the commutator of A and B, i.e. [A, B], i.e. A * B * A^-1 * B^-1."""
return proc1 + proc2 + invert_moves(proc1) + invert_moves(proc2) | b87c58c863165f8098377e750d00cbfdf1828521 | 45,744 |
import threading
import multiprocessing
import asyncio
def test_PipeJsonRpcSendAsync_3():
"""
Put multiple messages to the loop at once. The should be processed one by one.
"""
n_calls = 0
lock = threading.Lock()
def method_handler1():
nonlocal n_calls
with lock:
n... | 7fa1ae208cd0f6c505ad6ed0a916a8e3c20f1e22 | 45,745 |
import csv
def readTsv(fileLines, d="\t"):
"""
convenience method for reading TSV file lines into csv.DictReader obj.
"""
reader = csv.DictReader(fileLines, delimiter=d)
return reader | 9da19510d787e393d6b00b9c0d64c405830ce5ce | 45,746 |
def dispatch_unit_scada(file):
"""Extract generator dispatch data
Params
------
file : bytes IO object
Zipped CSV file of given MMSDM table
Returns
-------
df : pandas DataFrame
MMSDM table in formatted pandas DataFrame
"""
# Columns to extract
... | 1bd2e0ceb3aac226973f88c9b9edefcd57e4df8c | 45,747 |
def _get_weights(Y, dist, weights):
"""Get the weights from an array of rankings and distances."""
sample_weight = get_weights(dist, weights)
# Assign a constant value if applying a uniform weighting
# to weigh the samples by the number of available classes
sample_weight = sample_weight if sample_w... | 9ef4f6d8d842bfec6370de1d33c3680dc848dca7 | 45,748 |
def credit(order_number, pnref=None, amt=None):
"""
Return funds that have been previously settled.
:order_number: Order number
:pnref: The PNREF of the authorization transaction to use. If not
specified, the order number is used to retrieve the appropriate transaction.
:amt: A custom ... | eb3c7063dda25d23ab6d2fbdc1859bd8d8771d69 | 45,749 |
import requests
import pprint
def get_location_data(location_list):
"""iterate through the list of locations and extract data from the API for each one. output the data in json format."""
location_data_json = {}
address = 'http://unlock.edina.ac.uk/ws/search?name=' # address of API
country_code = 'GB... | 6c3eebe16018dae1c58cc381e47cfa8311e32388 | 45,750 |
def request_string_selection(string_options, dlg_kind="livemodal",
dlg_klass=None, **selector_traits):
""" Dialog to select a string among a list of options.
Parameters
----------
string_options : list
List of string values to choose from. Passed as the `string_opti... | 6bf27044961f2e31f22562f7b5314046cbab0c0e | 45,751 |
import tarfile
import os
import json
import pickle
def extract_files(filename, file_type='target_files', tmp_folder=None, clean_tmp=False):
""" Read files from descriptor folder.
.. codeauthor:: Angelo Ziletti <angelo.ziletti@gmail.com>
"""
logger.debug('Loading file {0}'.format(filename))
if ... | 0adc55b9f05c3eb0c263bc1a0c138947a316fc24 | 45,752 |
def make_estimator(hparams):
"""Creates a TPU Estimator."""
generator = _get_generator(hparams)
discriminator = _get_discriminator(hparams)
if hparams.tpu_params.use_tpu_estimator:
config = est_lib.get_tpu_run_config_from_hparams(hparams)
return est_lib.get_tpu_estimator(generator, discriminator, hpara... | 333a13c400bca1a6b04701bcedc29a1fc064b494 | 45,753 |
import time
from re import I
def predict(model, data, batch, org_shape, rate, gpu):
"""
推論実行メイン部
[in] model: 推論実行に使用するモデル
[in] data: 分割(I.cnv.split)されたもの
[in] batch: バッチサイズ
[in] org_shape: 分割前のshape
[in] rate: 出力画像の拡大率
[in] gpu: GPU ID
[out] img: ... | 78e1391377cb0a3d38c3671ba2cf5c0fdf11faa6 | 45,754 |
from pathlib import Path
def _gen_bids_layout(
bids_dir,
derivatives,
pybids_database_dir,
pybids_reset_database,
pybids_config=None,
):
"""Create (or reindex) the BIDSLayout if one doesn't exist,
which is only saved if a database directory path is provided
"""
# Set db dir to Non... | 688c5979c97772c18230642964275805995dab5b | 45,755 |
import requests
from bs4 import BeautifulSoup
def grep_candidate_papers(url):
"""scrape first 10 papers and choose one
:param url:
:return: target paper information (title, writer, year, citations, url, paper_id, snippet)
"""
html_doc = requests.get(url).text
soup = BeautifulSoup(html_doc, "ht... | 3c70ad55ca335cba3f80af6192de3ea5b3d8ff40 | 45,756 |
import re
def friendly_filename(filename):
"""
Creates a 'friendly' filename based on the given filename. The
transformation process is as follows:
- Get everything after the last slash
- Remove the extension
- Convert slashes, underscores, bracket, pound to space
- Convert consecutive spa... | 54a2b65b8bcbc555cd203e72dc2a184b93e65aef | 45,757 |
def has_double_letters(string):
"""Tests if a string contains forbidden text"""
return check_for_contents(string, DOUBLE_LETTERS) | 1280676d72a4fa7125ace9e6474a8c95d1c9ef3a | 45,758 |
def preprocess_images_from_directory_val_separate(train_dir_path, test_dir_path,
val_dir_path,
label_mode, img_size, seed=45,
batch_size=32, val_split=0.2, ):
"""
... | 3635d279f9e8f6be1e910c494b9c2b55142e36f9 | 45,759 |
def transform_matrix_for_non_uniform_scale(
x_factor, y_factor, z_factor, allow_flipping=False, ret_inverse_matrix=False
):
"""
Create a transformation matrix that scales by the given factors along
`x`, `y`, and `z`.
Forward:
[[ s_0, 0, 0, 0 ],
[ 0, s_1, 0, 0 ],
[ ... | 8f9743d06aaafa1052b40fa3b0c210c068524956 | 45,760 |
def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
"""
Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
"""
with tf.variable_sco... | 68a9905a699d9240352d0660c158c4f19cb644ea | 45,761 |
import requests
def test_labels_added(repo, pull_num, labels, session):
"""
Test whether the labels were added correctly (permissions etc.)
:param repo: repository
:param pull_num: number of pull request
:param labels: labels that were added
:param session: open github session
... | d6365022069567f193820b93206f91b636ceb4fc | 45,762 |
from typing import Dict
from typing import Any
async def provider(cid: int) -> Dict[str, Any]:
"""获取漫画章节."""
link = f"https://www.manhuagui.com/comic/{cid}/"
async with HTTPClient() as client:
response = await client.get(link)
dom = PyQuery(response.text)
title = dom(".book-title h1").te... | 659dc81541a8cae9b1155ee8f5fdc491f44135f0 | 45,763 |
def causal_numerator(qs, ks, vs):
"""Computes not-normalized FAVOR causal attention A_{masked}V.
Args:
qs: query_prime tensor of the shape [L,B,H,M].
ks: key_prime tensor of the shape [L,B,H,M].
vs: value tensor of the shape [L,B,H,D].
Returns:
Not-normalized FAVOR causal attention A_{masked}V.
... | b5c3031a26583848b0e2f325475f79dbc6025f7a | 45,764 |
import subprocess
def _get_key_by_keyid(keyid):
"""Get a key via HTTPS from the Ubuntu keyserver.
Different key ID formats are supported by SKS keyservers (the longer ones
are more secure, see "dead beef attack" and https://evil32.com/). Since
HTTPS is used, if SSLBump-like HTTPS proxies are in place,... | 685d4229f03e985442445b95925032e5f98e8724 | 45,765 |
def token_to_char_offset(e, candidate_idx, token_idx):
"""Converts a token index to the char offset within the candidate."""
c = e["long_answer_candidates"][candidate_idx]
char_offset = 0
for i in range(c["start_token"], token_idx):
t = e["document_tokens"][i]
if not t["html_token"]:
token = t["to... | e638dbd7e184d6d14168f926a617d0ab8448f960 | 45,766 |
def FixedRateBondAddRedemption(builder, redemption):
"""This method is deprecated. Please switch to AddRedemption."""
return AddRedemption(builder, redemption) | 6b5176e77e4a984417f6b939a7cf989eef8ba0d3 | 45,767 |
def proto_dict(message,
including_default_value_fields=False,
preserving_proto_field_name=True):
"""Convert a proto message to a standard dict object"""
return json_format.MessageToDict(
message,
including_default_value_fields=including_default_value_fields,
... | 8ff6116c2d6e0812d2864394cf5a57c159da8e0f | 45,768 |
def get_arrow(delta):
"""Create glyphicon chevron
:param delta: change in rankings from previous week
:return: html code for arrow
"""
# Define html snippets to build arrow code
snu = ' <span class="text-success">'
snd = ' <span class="text-danger">'
ns = '</span>'
up = '<span cla... | f580890245f9b136c39994183d1811f10e796987 | 45,769 |
def GetHighlightColour():
"""Get the default highlight color
@return: wx.Colour
"""
if wx.Platform == '__WXMAC__':
if CARBON:
if hasattr(wx, 'MacThemeColour'):
color = wx.MacThemeColour(Carbon.Appearance.kThemeBrushFocusHighlight)
return color
... | 3b488ab64424ccf8348daa82d95e3d88365e2eb5 | 45,770 |
def different_ways_memoization(n):
"""Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def different_ways_memoization_helper(k):
if k < 0:
return 0
if d[k] == 0:
d[k] = differen... | e3d965e70904e6af150a45267c8b9ab95c903a9a | 45,771 |
def get_mask_voxels(mask):
"""
Compute x,y,z coordinates of a binary mask
Input:
- mask: binary mask
Output:
- list of tuples containing the (x,y,z) coordinate for each of the input voxels
"""
indices = np.stack(np.nonzero(mask), axis=1)
indices = [tuple(idx) for idx in indi... | 8bc4c88c59bc746025d1335ac975d8c5344f1967 | 45,772 |
def __virtual__():
"""
Only make this state available if the azurearm_resource module is available.
"""
if "azurearm_resource.resource_group_check_existence" in __salt__:
return __virtualname__
return (False, "azurearm_resource module could not be loaded") | 84a5de8e5d0297a29a01f3151aa46e0fd309b055 | 45,773 |
def video_list(request):
"""
*/entry/videos*
The entry interface's videos list. This view lists all videos,
their description, and allows you to click on them to view/edit the
video.
"""
message = ""
if request.GET.get('success') == 'true':
message = "Video deleted successfully... | 24bc5e5d8946dc02f2fa1ecab5ef37f4529a8901 | 45,774 |
def check_status(r: Response) -> Response:
"""Check the status code of a response and return it."""
if not r.status_code == codes.ok:
if r.url.startswith(BASE_ENDPOINT) and not r.json()["success"]:
errors = "\n".join(f"{err['code']}: {err['message']}" for err in r.json()["errors"])
... | c0a085f17602ebff4b2b5548d48104ca606477be | 45,775 |
def get_execution_platform(command, filename):
"""
<Purpose>
Returns the execution platform based on a best-guess approach using
the specified command, as well as the a file's extension. The
command takes precedence over the file extension. If the extension
is not recognized, then it will be assum... | ceb6afab191269b032bc6122978f630682cac9ca | 45,776 |
import io
def _binary_to_string_handle(handle):
"""Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE)."""
try:
# If this is a network handle from urllib,
# the HTTP headers may tell us the encoding.
encoding = handle.headers.get_content_charset()
except AttributeE... | 2f8f3a6c0c7e1518b10dd58084bc3daa7d2af7af | 45,777 |
import os
def read(path):
"""读取路径下的文件"""
user_id = os.environ.get("JUPYTERHUB_USER") or ""
if not path.startswith("/"):
path = rela2abs(path)
with get_engine().begin() as db:
src_file = get_file(
db,
user_id,
path,
True,
cryp... | 75b05798bfa354907a3c6b1461c0fc95f1095b20 | 45,778 |
import os
def get_cardlist_from_filename(filename) -> CardList:
""" Returns pandas database with parsed filename
File should contain list of cards with number and card names
"""
_, file_extension = os.path.splitext(filename)
if file_extension == '.cod':
cardlist = _parse_cod(filename)
... | b8624eee728fc129a1ab048749580662086d2c10 | 45,779 |
def list_of_combs(arr):
"""returns a list of all subsets of a list"""
combs = []
for i in range(0, len(arr) + 1):
listing = [list(x) for x in combinations(arr, i)]
combs.extend(listing)
return combs | 5e5fa48ebfe6aeb45a9477ff59daed1f5b95c7a9 | 45,780 |
import requests
def model_details(model_id):
"""
Summarize the model.
Parameters
----------
model_id: str
A valid id for a model in BiGG.
"""
response = requests.get(BASE_URL + "models/%s" % model_id)
response.raise_for_status()
return response.json() | ef69b637826aa1b64869cf65e2e50ef96aec2892 | 45,781 |
def appearance_app_templates(context, template_name):
"""
Fetch the app templates for the requested `template_name`, render it with
the current `request` from the `context`, and cache it for future use
unless the template has the no caching comment.
"""
result = []
for app in apps.get_app_c... | e3bb405c0b34a9efa740c17a4ed0af13fbae0c0a | 45,782 |
def unique_addons(addons_list):
"""Validate that an add-on is unique."""
single = set(addon[ATTR_SLUG] for addon in addons_list)
if len(single) != len(addons_list):
raise vol.Invalid("Invalid addon list on snapshot!")
return addons_list | 5968398235c0073134851070e2be3fbfaee42e6b | 45,783 |
def signals():
"""
Use this decorator to identify the enumeration within your observable class that defines the class' signals.
"""
# We need an inner function that actually adds the logger instance to the class.
def add_signals(cls):
# If the class doesn't already extend SignalsEnum...
... | 1e1987d0535f173a8ec8989ec2129dea842bd841 | 45,784 |
def mod(x):
"""
Devuelve el modulo del vector x
"""
s = 0
for c in x:
s += c**2
return sqrt(s) | 2b4146ee27e40e8de49410880cd3d96d4ef51917 | 45,785 |
def calculate_heat_capacity(thm_dstr, temp):
""" Calculate the Heat Capacity [Cp(T)] of a species using the
coefficients of its NASA polynomial
"""
cfts = _coefficients_for_specific_temperature(thm_dstr, temp)
if cfts is not None:
heat_capacity = (
cfts[0] +
(cft... | 7b744b6bdb63fcac3db09ddb731b13006bf47c7e | 45,786 |
from typing import Dict
async def get_provider_icons(mass: MusicAssistant) -> Dict[str, str]:
"""Get Provider icons as base64 strings."""
return {
prov.id: await get_provider_icon(prov.id)
for prov in mass.get_providers(include_unavailable=True)
} | 82418f057f45bd869a3cc8a9311a61dfd25a93dd | 45,787 |
def take(a, indices, axis=None, out=None, mode='raise'):
"""
Take elements from an array along an axis.
When axis is not None, this function does the same thing as "fancy"
indexing (indexing arrays using arrays); however, it can be easier to use
if you need elements along a given axis. A call such ... | 01093b9b44de0f78950f0f3b3a6ec50c683ff885 | 45,788 |
import tempfile
import subprocess
import json
from pathlib import Path
def _create_xclbin(mem_dict):
"""Create an XCLBIN file containing the specified memories
"""
with tempfile.TemporaryDirectory() as td:
td = Path(td)
(td / 'metadata.xml').write_text(BLANK_METADATA)
(td / 'mem.j... | fbd425099907097cd74a3ce86124eb6d121a4b99 | 45,789 |
import random
import string
def get_random_string():
""" generates a random string """
random_string = ''.join(
[random.choice(string.ascii_letters + string.digits) for n in range(32)]
)
return random_string | 1abcea093ded9a04bd7b35f29a0309452e72ab4d | 45,790 |
def calc_slope_components(dem, dx):
"""Calculate finite slopes."""
# sx,sy = calcFiniteDiffs(elevGrid,dx)
# calculates finite differences in X and Y direction using the
# 2nd order/centered difference method.
# Applies a boundary condition such that the size and location
# of the grids in is t... | 37405fb33b3a9d85bc5f19110304938dc6a92b8c | 45,791 |
def merge_neighbor_dims(x, axis=0):
"""Merge neighbor dimension of x, start by axis"""
if len(x.get_shape().as_list()) < axis + 2:
return x
shape = shape_list(x)
shape[axis] *= shape[axis+1]
shape.pop(axis+1)
return tf.reshape(x, shape) | c6d3a79ab13f9a36246804d927ad440323400751 | 45,792 |
def matrix_transpose(matrix):
"""
function to transpose a matrix
"""
return [[row[i] for row in matrix] for i in range(len(matrix[0]))] | bf2f2ba09a361f1cfd025b7f607e4f1a96705396 | 45,793 |
def from_xml(df, column):
"""
Takes a dataframe with XML-encoded bundles in the given column and returns
a Java RDD of Bundle records. Note this
RDD contains Bundle records that aren't serializable in Python,
so users should use this class as merely a parameter to other methods
in this module, l... | 0d1f4791c15f6f0aaebb843f99c90d038d1685b3 | 45,794 |
def has_s_dismantlable_vertex(graph):
"""Returns whether a graph has s-dismantlable vertices
Args:
graph (networkx.classes.graph.Graph): graph
Returns:
If the graph has dominated vertices, returns a list which only element
is the first s-dismantlable vertex. Otherwise, return False
... | a7a7df25218bd8e94b6431e28f2c62a0e168cbed | 45,795 |
import time
def evaluate(model, eval_fn, data_loader, batch_axis=0, max_steps=None, verbose=True, print_every=10):
"""Computes the loss and accuracy on the given dataset in test mode.
Example of how to use the evaluation function:
```
def my_eval_fn(model, x, y):
return evaluate_on_batch(... | e5313ec75f39f739aae27d51c27be90c9c87650c | 45,796 |
def from_auto_ml(model, shape=None, dtype="float32", func_name="transform"):
"""
Import scikit-learn model to Relay.
"""
try:
import sklearn # pylint: disable=unused-import
except ImportError as e:
raise ImportError("Unable to import scikit-learn which is required {}".format(e))
... | 373d474ec81d95235cb6edfa2767b8e4a675c7a0 | 45,797 |
import timeit
def con_str(image):
"""Doing contrast stretch and count the time for processing
Args:
image: input image data (should be ndarray)
returns:
img_str: image after contrast stretch
time_process: time for doing the processing
"""
start = timeit.default_timer()
... | 1b8b19edbe4021bfa09c269d8216a16c1287367f | 45,798 |
def text():
"""Returns text equivalent of the W3C text"""
return {
"@context": "http://www.w3.org/ns/anno.jsonld",
"type": "Annotation",
"body": {
"creator": "user",
"type": "TextualBody",
"value": "string"
},
"generator": {
... | 128e75331f178311738b472c1ad9f24a9689bdf4 | 45,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.