content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def complex_function(z):
"""
The complex function to plot. *You can write any function here*.
:param z: a numpy 2d array of complex numbers.
"""
return (z - 1) / (z + 1) | 242f6b84c50dedbbf28edf52c558d572ab4c6c85 | 3,620,446 |
def generate_lists(image_dir, subdir):
"""
80 images per class in total and 256 classes. Generate a list of lists. Each list contains 256*5 images.
:return: a list of lists. Each list contains 256*5 images.
"""
# last 20 images are for test.
index = range(1, 81, 1)
# np.random.shuffle(index... | cf3cf9ce7d950f431a161ffc75d6c1f0e0fc8a87 | 3,620,448 |
def get_embed(input_data, vocab_size, embed_dim):
"""
word embedding 输入.
:param input_data: 输入.
:param vocab_size: 总词语数.
:param embed_dim: w2v 维数
:return: Embedded input.
"""
#embedding 初始化,这边不采用预先训练的embeding,边训练边调参数
embedding = tf.Variable(tf.random_uniform((vocab_size,embed_dim),-... | 798e31d7a016e517ec933b55e97eb035e1755f7b | 3,620,449 |
import binascii
def encrypt(text, parola):
"""
Derives a 256-bit key using the PBKDF2 key derivation algorithm from the password. It uses a random
password derivation salt (128-bit). This salt should be stored in the output, together with the ciphertext,
because without it the decryption... | 94ca306d06c64b36facac38a9f44a403b86aadac | 3,620,450 |
def gList(question, items, returnsIndex):
"""
Returns an item or its index from a list based on user input.
:param question: String containing prompt to be displayed.
:param items: List of items of which user should choose from.
:param returnsIndex: Boolean indicating whether the function should return the item o... | b746338e62c29371e116738ef76b9cf176841259 | 3,620,451 |
import json
def _get_helper(json_expecting_func, **kwargs):
"""
Helper function used by several functions below
"""
try:
payload = json_expecting_func(**kwargs)
response, status_code, mimetype = json.dumps(payload), 200, "application/json"
except exceptions.BadRequest as exc:
... | 9ff97c5ae07d4f6e6d086813b5287199336c45be | 3,620,453 |
from typing import List
def hash_files(paths: List[str]):
"""
MD5 checksum a list of file paths
"""
return map(hash_file, paths) | 501347f2dc21e7c6e8b53f36c0df0e63b959166c | 3,620,454 |
def length_of_year(year):
""" the length of a day
:param year: The year you wuld like to know the length.
:returns: exact days. a day is longer then 365 days.
"""
return float(365.2564) if is_leap_year(year) else float(364.2564) | 516b46c92869ff520fbbb57aece371ea8176a86a | 3,620,457 |
def remove_hydrogens(mol):
"""Removes any hydrogens from the graph of a molecule.
This is a wrapper around rdkit.Chem.rdmolops.RemoveHs.
Parameters
----------
mol: rdkit.Chem.Mol
The molecule to be modified.
Returns
-------
mol: rdkit.Chem.Mol
A new molecule with the h... | 9b066b40485e3e7dcb5e31eb2bd692022d6b1cd1 | 3,620,458 |
import logging
import requests
def get_status(api_key=None, request_id=None, proxies=None, auth=None):
"""
Получить состояние активации:
http://sms-activate.ru/stubs/handler_api.php?api_key=$api_key&action=getStatus&id=$id
:param api_key: ключ API авторизации на сервисе
:param request_id: id актив... | bf07cd84dcce32a5d842ffe746624e6bf8781955 | 3,620,460 |
def match_event(event_type):
"""Return event type matcher."""
def matcher(func):
"""Add decorated function to list for event matching."""
func = add_skill_attributes(func)
func.matchers.append(
{"event_type": {
"type": event_type}})
return func
ret... | b0e9edf2e246418513c83c2e91101df34e714309 | 3,620,461 |
def fetch_data_for_date(record_date, site_id, data_dir):
"""
Download radar data for a given date and siteId from public S3 bucket
"""
files = []
bucket = S3.Bucket('noaa-nexrad-level2')
data_site_prefix = '{record_date}/{site_id}'.format(record_date=record_date, site_id=site_id)
for s3_obje... | 6d4213ff2f5d79095925062fca9b92e25680a44a | 3,620,462 |
def update_item_from_dict(table_name, key, dictionary, client):
"""
Update the item identified by `key` in the DynamoDB `table` by adding
all of the attributes in the `dictionary`.
Args:
table_name (str):
key (dict):
dictionary (dict):
client:
Returns:
dict
... | 333e74bb6f270cb794f6fe8da2de0ad9a40d3a9f | 3,620,463 |
def indirect_bp_names():
"""Return a list of valid Indirect Branch Predictor names."""
return _indirect_bp_classes.keys() | 21ea71889882fe61d5041f7390f41b08d5e04622 | 3,620,464 |
def device_action(device):
"""
Generates an actionable text for a :class:`~two_factor.plugins.phonenumber.models.PhoneDevice`.
Examples:
* Send text message to `+31 * ******58`
* Call number `+31 * ******58`
"""
assert device.__class__.__name__ == 'PhoneDevice'
number = mask_phone_numb... | f79c4ba89da7bf022d28e15507d091800915243b | 3,620,465 |
def main_app_url(module_scoped_container_getter):
""" Wait for the api from fastapi_main_app_main to become responsive """
return h.get_app_url(module_scoped_container_getter, "fastapi_main_app_main") | 5f228b31b37d3221038fa57764a447b727f9534a | 3,620,466 |
def _get_sign_array_1d(i: int, nsyms: int) -> Array:
"""Calculate array of nsyms signs that alternate every 2**i entries."""
sym_ints = jnp.arange(nsyms)
# The exponent below is simply a clever way to get the value of the i_spin-th bit
# of each integer in the sym_int array, to give us signs which alte... | 98f72eab66fb0ee8beb4735a8dfa2b387d61bcae | 3,620,467 |
def solve(lines):
"""Solve the problem."""
mem = dict()
mask = "X" * 36
for line in lines:
if line.startswith("mem"):
m = MEM_RE.match(line)
loc, val = [int(v) for v in m.groups()]
mem[loc] = apply_val_mask(mask, val)
elif line.startswith("mask"):
... | 875eb79467bfa98a7fa90cf2eb13fe3ff74faeae | 3,620,468 |
def _squash_unicode_in_bestrefs(bestrefs, localrefs):
"""Given bestrefs dictionariesy `bestrefs` and `localrefs`, make sure
there are no unicode strings anywhere in the keys or complex
values.
"""
refs = {}
for filetype, refname in bestrefs.items():
if isinstance(refname, tuple):
... | 50cc5fb89bfb329465e37bbbff469862181f1659 | 3,620,469 |
def enum(**enums):
"""Enable use of enums by utilizing types"""
return type('Enum', (), enums) | 0e9fd35df64ae775d2bf245c376cc0c9af06b4a6 | 3,620,470 |
import configparser
def create_arithmetictrainer_from_files(*files) -> Arithmetictrainer:
"""
Create a Arithmetictrainer from a configuration file.
"""
config_files = configparser.ConfigParser()
config_files.read(*files)
if len(config_files.sections()) == 0:
raise ValueError("Could not... | ad2a98d32372257a4e11886373a0403e395b7f5e | 3,620,471 |
def shrink(epsilon, x):
"""The shrinkage operator.
This implementation is intentionally slow but transparent as
to the mathematics.
Args:
epsilon: the shrinkage parameter (either a scalar or a vector)
x: the vector to shrink on
Returns:
The shrunk vector
"""
# try e... | a2e6f7c2692420dfbf33156a2ee0c29df70acebb | 3,620,472 |
def profiler_dtype_func(dtype, null=False):
"""
Return a function that check if a value match a datatype
:param dtype:
:param null:
:return:
"""
def _float(value):
if null is True:
return fastnumbers.isfloat(value, allow_nan=True) is True and fastnumbers.isint(value) is ... | e2e22020c4bc14b660d2d6ecfbd5f239175cd4f1 | 3,620,473 |
def stop(job_id, event, action, resource, _count):
"""App stop event type"""
job_name = '{}:event={}:action={}'.format(
resource, event, action
)
func_kwargs = dict(
job_id=job_id,
app_name=resource,
)
return job_name, func_kwargs | 56f1496c860396f76cee105e007803eb850ca679 | 3,620,474 |
def kurt(im):
"""Return kurtosis = mean((image-mode)/2)^4). """
mode = stats.mode(im, axis = None)[0][0]
z_score = (im-mode)/2
z_score = z_score**4
k = float(z_score.mean().values)
return k | 96c949167437ef43e31f4a96444ef4ffb6af6b4e | 3,620,475 |
def _format(str_lst, concise):
"""Format a string for printing.
Parameters
----------
str_lst : list of str
List containing all elements for the string, each element representing a line.
concise : bool, optional, default: False
Whether to print the report in a concise mode, or not.
... | da69e0682636f1bf5af02683a17849b0824dbcc3 | 3,620,476 |
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)] | ed85d5d1158e46109966b3c09f3d33d5acae8c98 | 3,620,477 |
from typing import Mapping
from typing import Set
from typing import Tuple
def get_chebi_role_to_children() -> Mapping[str, Set[Tuple[str, str]]]:
"""Get the ChEBI role to children mapping."""
df = get_filtered_relations_df('chebi', relation=has_role)
return multisetdict(
(role_id, ('chebi', chemi... | 583c28dbdd00a24df49d9b25d5e99a34de182cc0 | 3,620,478 |
def resample_solar_flux(solar_flux_file, sensor_waves, sensor_fwhms):
""" Resample solar flux to sensor wavelengths.
Arguments:
solar_flux_file: str
Solar flux filename.
sensor_waves: array
Sensor wavelengths.
sensor_fwhms: array
Sensor FWHMs.
Retu... | 307f4617926bb4b61d254b8f905666a315313376 | 3,620,479 |
def nexthop_is_local(next_hop):
"""
Check if next-hop points to the local interface.
Will be True for Connected and Local route strings on Cisco devices.
"""
interface_types = (
'Eth', 'Fast', 'Gig', 'Ten', 'Port',
'Serial', 'Vlan', 'Tunn', 'Loop', 'Null'
)
for type in interf... | fd74119d54998fafcb9400adaaa2c95b42671734 | 3,620,481 |
def mouse_body_geometry(beta,gamma,s,theta,phi):
"""
This function calculates the configuration of the mouse body
In this configureation, it has four free parameters: azimuth and elevation of the nose/hip
Returns the points, which define the model: center-points and radii
theta el is elevation of th... | 912125befcfa554aa53b1bb90dfbe531d8ca5ea0 | 3,620,482 |
def calculate_expval(xcoords, wfuncs):
"""
Calculates the expected values :math:`<x>` for the x-coordinate by
numerically calculating the integral
.. math::
\\int_{x_{min}}^{x_{max}} | \\psi (x) |^2 x dx
Args:
xcoords (1darray): Array containing the x-coordinates
wfuncs (nd... | 83a1aca725c03799d6c4f0b8c85f7c8d5364004d | 3,620,484 |
def generate_bbox(cls_map, reg, scale, threshold):
"""
得到对应原图的box坐标,分类分数,box偏移量
"""
# pnet大致将图像size缩小2倍
stride = 2
cellsize = 12
# 将置信度高的留下
t_index = np.where(cls_map > threshold)
# 没有人脸
if t_index[0].size == 0:
return np.array([])
# 偏移量
dx1, dy1, dx2, dy2 = [... | e9cb9b7b3b949bfb51c46c3f9a625a46286c1275 | 3,620,485 |
def logistic_expval(mu, tau):
"""
Expected value of logistic distribution.
"""
return mu | f6ac18144d5543d50c04f8e042bb8b5f8c8ea5ec | 3,620,486 |
def is_(var):
"""intuitive handling of variable truth value also for `numpy` arrays.
Return `True` for any non-empty container, otherwise the truth value of the
scalar `var`.
Caveat of the most unintuitive case: [0] evaluates to True, like [0, 0].
>>> import numpy as np
>>> from cma.utilities... | dd7be0e1535c6a616a1984b7d4b4cab3b03fbfbd | 3,620,487 |
def abs_load_diff(ilp_vars, x, y, vnfs, vims, dec_vars, types=['cpu', 'ram']):
"""
Calculating the actual load difference between two vims x and y.
"""
load_x = 0.0
load_y = 0.0
for res_type in types:
if res_type == 'cpu':
type_used = 'core_used'
type_tot = 'cor... | d8ba5c46de41becb001b0fcc2a94d78b6f5aa5c7 | 3,620,488 |
def facebook_auth_settings(request):
"""
Facebook Auth client side ID.
"""
context = {}
context['FACEBOOK_AUTH_ID'] = getattr(settings, 'SOCIAL_AUTH_FACEBOOK_KEY', '')
return context | 521a9caec5ad83c7398ae635c696ee3d5e6c6366 | 3,620,489 |
def keras_model_fn(hyperparameters):
"""keras_model_fn receives hyperparameters from the training job and returns a compiled keras model.
The model will be transformed into a TensorFlow Estimator before training and it will be saved in a
TensorFlow Serving SavedModel at the end of training.
Args:
... | 42009db35825ea915153b1ebfe726f19bb686d5d | 3,620,490 |
import re
import tarfile
import io
def _check_open_tarball(testcase, response):
"""
Check http-response headers and open tar ball from content.
"""
testcase.assertTrue(re.search(r'attachment;\s*filename="[^"]*.tar.gz"',
response['Content-Disposition']))
testcase.a... | ffa0aa59f102fffb3c11664ee5f486f424b6acd8 | 3,620,491 |
def square_shaper(x, y, side_length=1):
"""Shaper function for a square with a given side length.
Parameters
----------
x : float or array-like
x-component of the step.
y : float or array-like
y-component of the step.
side_length : float
Square side length.
Returns
... | 1ade17ad77035ef35ae88cda264e1e23978766f2 | 3,620,492 |
def make_non_pad_mask(lengths, xs=None, length_dim=-1):
"""
See https://github.com/espnet/espnet/blob/e962a3c609ad535cd7fb9649f9f9e9e0a2a27291/espnet/nets/pytorch_backend/nets_utils.py#L179
"""
return ~make_pad_mask(lengths, xs, length_dim) | 950d8af7559ff08c7bd55bb36b2fc95fc7bbc574 | 3,620,493 |
def to_nsec(val):
"""Returns value in nanoseconds if value is ROS time/duration, else value."""
return val.to_nsec() if isinstance(val, genpy.TVal) else val | b8c3d6d9f7662a89e5d48ff7cb4456adc84ebb5c | 3,620,494 |
import sqlite3
def prob14(cur: sqlite3.Cursor) -> pd.DataFrame:
"""Show the 1984 winners and subject ordered by subject and winner name;
but list Chemistry and Physics last.
The expression subject IN ('Chemistry','Physics') can be used as a value -
it will be 0 or 1.
Parameters
---------... | 83a52bff0bc5f50d5ac428d0c2b996cb4ee154ac | 3,620,495 |
def GetKDPPacketHeaderInt(request=0, is_reply=False, seq=0, length=0, key=0):
""" create a 64 bit number that could be saved as pkt_hdr_t
params:
request:int - 7 bit kdp_req_t request type
is_reply:bool - False => request, True => reply
seq: int - 8 sequence numb... | 7a56abb0f1ccbe1a7da1a9e0c6b70418e00ef0be | 3,620,497 |
import json
def save_items_list(drive_service, file_location):
"""
save cloud items list in a json file
:param file_location: location where file needs to be saved
:param drive_service: servive object for drive
:return: True if list successfully saved else false
"""
files = drive_service.f... | 9f5dc557bbbfa102bf4acfa3fb9af9014b229c83 | 3,620,499 |
import re
def dashifyHeadline(line):
"""
Takes a header line from a Markdown document and
returns a tuple of the
'#'-stripped version of the head line,
a string version for <a id=''></a> anchor tags,
and the level of the headline as integer.
E.g.,
>>> dashifyHeadline('### s... | fa168c52bf5ceb994b88347cc941f6c88742eead | 3,620,500 |
def check_game_has_finished(player, game):
"""
Checks if the game has finished
:param player: (Player object) Current player
:param game: current game being played
:return: (boolean) True if the game has finished, else False
"""
finished_game = False
# Check if game has finished
if ... | 07eef0bcffc1069c1679c492afa96b1f7e297e09 | 3,620,502 |
def nullspace_relative_norm(A, x, tol=1e-12):
"""Compute the ratio between the norm of components of `x` that are in the
nullspace of `A` and the norm of `x`.
Args:
A (torch.Tensor): A matrix.
x (torch.Tensor): A certain vector.
tol (float): The tolerance level for determining what ... | e9e190951ed91d6f08aa3f4ac8edd6d889df00d4 | 3,620,503 |
def get_filter(df, alt_list, mach_list, aos_list, aoa_list):
""" Get a dataframe filter for a set of parameters lists. """
filt = pd.Series(True, index=df.index)
if alt_list:
filt &= df["altitude"].isin(alt_list)
if mach_list:
filt &= df["machNumber"].isin(mach_list)
if aos_list:... | bf85eef9d6235016db64387903f60d291cdc7bdc | 3,620,504 |
import binascii
def inet_ntoa(address):
"""Convert a network format IPv6 address into text.
@param address: the binary address
@type address: string
@rtype: string
@raises ValueError: the address isn't 16 bytes long
"""
if len(address) != 16:
raise ValueError("IPv6 addresses are ... | 6aa8e3a2f04cc17ca12b6dc68282659d78c65e9a | 3,620,505 |
def parseOutputForAllowedKeys(ml, allowed_keys=None):
""" Parses the given vclient output, while accepting only
known (or allowed) keys.
Also handles void states, where line occur that are neither
a key nor a value.
"""
data = {}
# When explicit keys are defined, start in void mo... | 44d0cf0a72759fd8087b1df240a1d25d75ac99c0 | 3,620,506 |
def explore_run_save_data_path(run_data_path):
"""Save run data path
Save run data path for next load in run stage
:param run_data_path: str, represent result evaluate path
:return: bool, represent save result
"""
explore_run_inst.run_data_path = run_data_path
return True | c7e0bf601043ea41510b1f76276f174615f04d7e | 3,620,508 |
def add_alias(alias: str, id: str) -> bool:
"""
This function assigns a desired alias of the user to its id.
Parameters
----------
alias : str
The alias name of the user
id : str
The id of the user
Returns
-------
bool
True if new alias has been added, otherw... | 9318625f1a55a678003465fd62a050f23015c16f | 3,620,509 |
from typing import List
def multi_scale_retinex(image: np.ndarray, sigma_list: List) -> np.ndarray:
"""
Performs multi-scale retinex by wrapping single-scale retinex
Parameters
-----------------------------
image: np.ndarray,
Image to be enhanced
sigma_list: List
Recommended s... | a85ac8e0dc934ca792d15a2cd25c850f0093052f | 3,620,510 |
import json
def craft_unknown_asset_message(
username, emoji, channel, launch_time, cloud_provider, vps_name, tags
):
"""Function to craft a nicely formatted Slack message using blocks
for cloud assets not found in Ghostwriter.
"""
UNKNOWN_ASSET_MESSAGE = {
"username": username,
"i... | fea3e96b93bfaba8971680fd0af52eccd543e0f0 | 3,620,511 |
def nevow_adapter_resource(interceptors=v()):
"""
Create a Nevow ``IResource`` that executes a context and avoids as much
Nevow machinery as possible.
A ~`fugue.interceptors.nevow.nevow` interceptor will be attached to the
front of the queue to facilitate the interaction with Nevow.
"""
_im... | 4180e753d8118c2749f8e57840d46057c87ba1da | 3,620,512 |
def make_division_term_lookup() -> pd.DataFrame:
"""DataFrame giving salient keywords for each division.
Combines the two sources of salient terms.
"""
# Match trend terms to divisions (combining the two sources of salience data)
division_term_lookup1 = _division_term_lookup_v1()
division_ter... | 5f3bb4eff2db1c7bcc48f32a8cd98837c0f3cd51 | 3,620,513 |
def address_has_changed(instance) -> bool:
"""
Check that the newly saved address
is different from the already saved
"""
return (instance.address != get_user_model()
.objects.get(id=instance.id).address) | 06cea06faac7ee5f9e2d3cbe73e3984cc4b9107f | 3,620,514 |
import re
def condition(string: str) -> str:
"""Turn variable conditions into `if score`"""
def equal_int(match: re.Match) -> str:
groups = match.groups()
return f'score {groups[0]} __variable__ matches {groups[1]}'
string, success = re.subn(
f'^{Re.var}\s*(?:==|=)\s*{Re.integer}$'... | 9c2214a7b5020510a6f41c60459234111e7064f1 | 3,620,515 |
def tilted_L1(u, quantile=0.5):
"""
tilted_L1(u; quant) = quant * [u]_+ + (1 - quant) * [u]_
"""
return 0.5 * abs(u) + (quantile - 0.5) * u | ff7a3fe97d79e4c848797c79a2a7c14b449ad6b6 | 3,620,517 |
from rfpipe import source, search, reproduce, candidates
def prep_and_search(st, segment, data, indexprefix='new', returnsoltime=False):
""" Reproduces rfpipe.search.prep_and_search but calculates and
indexes noises.
"""
ret = source.data_prep(st, segment, data, returnsoltime=returnsoltime)
if r... | 795626ad0992c51dd1e94659381d15f4299813a2 | 3,620,519 |
def update_entity(id):
"""
Update a story from the provided json
:param intent_id:
:param json:
:return:
"""
json_data = loads(request.get_data())
entity = Entity.objects.get(id=ObjectId(id))
entity = update_document(entity, json_data)
entity.save()
return 'success', 200 | e7642a6bf50a26b7c4bcac018b5ea44f92f6d42d | 3,620,520 |
import random
def data_augmentation(original_samples, original_labels, original_groups, augmentation_factor=2, x_coord=0, y_coord=1, c_coord=2):
"""
Pass original_samples after interpolation as a constant shape of (n_samples, NUM_FRAMES, n_keypoints, xyc)
"""
org_num_samples, org_num_frames, org_num... | 2f06d34ddcdcd09901f74d976f3983d67266bd86 | 3,620,521 |
def get_sectors():
"""Get all sectors in Yahoo Finance data. [Source: Finance Database]
Returns
-------
list
List of possible sectors
"""
return fd.show_options("equities", "sectors") | f3f6c1c095ba8c59d5ae0f5ed77cf98ee352265a | 3,620,522 |
def getId(collection):
""" Get the ImageCollection id.
**CLIENT SIDE**
:type collection: ee.ImageCollection
:return: the collection's id
:rtype: str
"""
return collection.limit(0).getInfo()['id'] | ad08535eb838cfa4d7153efd476b6dac14d118bc | 3,620,523 |
def predict_batch(model, dataset_batcher: Batcher):
"""Predict the values using the given batcher
Parameters
----------
model: SKLearn model
dataset_batcher : Batcher
Returns
-------
np.array
Predictions array
"""
y_pred = []
for X, y in dataset_batcher:
y_... | 0ac39f2eac8f2b74c1e42d2408e7a35be5eba98b | 3,620,525 |
import shutil
def migrate_file_target(target: FileTarget, copy: bool = False) -> FileTarget:
"""Apply a move, or copy of the FileTarget from source to new destination."""
_ensure_target_directory(target.target_move_path)
target = _check_existing_target_file(target)
if target.file_path == target.targe... | 0f0d1d5819b430afc1ac57c8f0c33a288df7757e | 3,620,526 |
def bytes_to_human(size, digits=2, binary=True):
"""Convert a byte value to the largest (> 1.0) human readable size.
Args:
size (int): byte size value to be converted.
digits (int, optional): number of digits used to round the converted
value. Defaults to 2.
binary (bool, op... | 22367220a122e399658a0dd42b52083ccc29df6f | 3,620,527 |
import requests
import toml
def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str do... | 665ff032834d3bb501e1ff9a8591d54d6d3bb5a8 | 3,620,528 |
def parseReplyBlock(s):
"""Return a new ReplyBlock object for an encoded reply block.
Raise ParseError on failure.
"""
block, length = _parseReplyBlock(s)
if length > len(s):
raise ParseError("Misformatted reply block: extra data.")
return block | 18e750ad42aa8e1216722d837b95d803ea6a9dc6 | 3,620,529 |
def _validate_method(method, where):
"""Helper for get_params()"""
if method is None:
return None
if method not in ['signal', 'thread']:
raise ValueError('Invalid method %s from %s' % (method, where))
return method | dbf7194f50a43dc3fd944f8923ddfec5aed3bbe7 | 3,620,530 |
import yaml
from yaml import CLoader as Loader
from yaml import Loader
def load_yaml(s: Union[bytes, IO, IO[bytes], Text, IO[Text]]):
"""Load a Yaml document.
This is a helper function which tries to use the fast ``CLoader``
implementation and falls back to the native Python version on failure.
"""
... | 5b0a70cd9a1bcb2596c9fccaf6566f3968a5c5e1 | 3,620,531 |
def _get_specs_and_amplitude_traces(all_audio, fs, spec_params):
"""
Return spectrograms and amplitude traces given a list of audio.
Parameters
----------
all_audio : list of numpy.ndarray
List of audio.
fs : int
Audio samplerate
spec_params : dict
Contains keys `'nperseg'`, `'noverlap'`, `'min_freq'`, `'... | df12742968e3c0a75fff967c21a1738905dfce20 | 3,620,532 |
import pathlib
def parent(path: str) -> str:
"""Get path's parent
e.g
j.sals.fs.parent("/home/rafy/testing_make_dir/test1") -> '/home/rafy/testing_make_dir'
Args:
path (str): path to get its parent
Returns:
str: parent path.
"""
return str(pathlib.Path(path).parent) | 8ed409fde19dcd74d3fb2c169946680a0c46543b | 3,620,534 |
def slugify(text):
"""
Turn the text content of a header into a slug for use in an ID
"""
non_safe = [c for c in text if c in non_url_safe]
if non_safe:
for c in non_safe:
text = text.replace(c, '')
# Strip leading, trailing and multiple whitespace, convert remaining whitespa... | a70c896e83c135822dfebb53ced8525380c1d33d | 3,620,535 |
def _getText(nodelist):
""" returns collected and stripped text of textnodes among nodes in nodelist """
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc.strip() | 37548ebf34f0f26cc4166e95621ee1ec0f3a3f71 | 3,620,536 |
import re
def strip_html(text):
"""See http://stackoverflow.com/a/9662362"""
return re.sub('<[^<]+?>', '', text) | 94747883a5df06b70fb3513e82e610d981582bbb | 3,620,537 |
def from_json(json_data, key):
"""Extract values from JSON data.
:arg dict json_data: The JSON data
:arg str key: Key to get data for.
:Returns: The value of `key` from `json_data`, or None if `json_data`
does not contain `key`.
"""
if key in json_data:
return json_data[key]
... | 2e5a97176c771c1c363fd7fbf86d8bf7b598f4ab | 3,620,539 |
def weights_dask(weights):
"""
Weighting array by cosine of the latitude.
"""
return weights.chunk() | d1b4259b806665760506b43cf072ceb61fcb2d8d | 3,620,540 |
def is_not_json(bytestring):
"""
:param bytes bytestring: A candidate byte string to inspect.
:return bool: ``False`` if and only if ``bytestring`` is JSON encoded.
"""
try:
loads(bytestring)
except:
return True
return False | 5af6f6b901caf79a4f8dc2e1180f83824c579193 | 3,620,542 |
def get_ingredients():
"""Find all available ingredients.
Returns:
list(IngredientDto): A list of all ingredients.
"""
ingredient_entities = IngredientEntity.query.all()
return [ingredient_entity_to_dto(entity, entity.availability) for entity in ingredient_entities] | 57e01f9b9f59f2929bba1ea35fe311b2e38a6764 | 3,620,543 |
def add_stock(request):
"""
This view renders Create brand Page """
prod_obj = Product.objects.all()
if not request.user.is_viewer :
context = {
"title": "Create Stock",
"products": prod_obj
}
return render(request, 'add_stock.html',context)
else:
... | dbd2869d4b41ce014fec08a807d44c0e9d290dda | 3,620,544 |
def project(a):
""" De-homogenize vector """
return a[:-1] / float(a[-1]) | 68074a4fb9c5021f7e727654e699d823d093c3a6 | 3,620,545 |
def add_presentations_sheet(supervisor, modified_df):
"""Adding the Presentations sheet with all Presentations according to the talk order on the presentation day"""
src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx')
print("The available sheets in the xlsx file")
print(src_gradi... | b563e87a3080088c2c2fcc32db5234874a03edc6 | 3,620,546 |
def load_obj(filename: str, default_mtl='default_mtl', triangulate=False) -> WavefrontOBJ:
"""Reads a .obj file from disk and returns a WavefrontOBJ instance
Handles only very rudimentary reading and contains no error handling!
Does not handle:
- relative indexing
- subobjects or groups
- line... | 2a09fd8eb0aef78564d616d8b42e090c62ed73ac | 3,620,548 |
def get_car(shape):
"""Get car image as input."""
return get_img(shape, "car.JPEG", np.float32, should_scale=True) | 232522a6324b92db4b0b3f7031b0ef16a3d35b7d | 3,620,549 |
import select
def get_total(session, Model):
"""Should be made in a context manager"""
stmt = select(func.count(Model.id))
_total = session.execute(stmt)
total = _total.scalar()
return total | 1b9ade37da64ce5ca34b3a6da70c230768b5cb0b | 3,620,550 |
def temp_c_2_f(temp):
"""
translate Celsius to Fahrenheit
T(°F) = (T(°C) * 1.8) + 32
"""
tc = (Decimal("%s" % temp) * Decimal("1.8")) + 32
return tc | 3d5793d0f058378291ea8491a3f0cf9ffbdea18b | 3,620,551 |
def CLT2_ci(mean_log, std_log, n, ci=0.95):
""" Returns the error margin for the geometric mean based
on the central limit theorem and the t-statistics.
Parameters
----------
mean_log : scalar, float
the arithmetic mean of the log-transformed data
std_log : scalar, float
the st... | b55becf2f8ef3dddc77a057c3d4a78075f6b916e | 3,620,552 |
def coraldistancemap(edgemask,x_mesh,y_mesh):
""" Function generating an array with the minimum distances to a coral object
The edgemask object should be a boolean array with the same shape as the x- and y-meshes.
It is True where the edges of the coral objects are located and False everywhere else
"""
... | 02e31f0db1f9aa02a508ea1d55789334a2b27a04 | 3,620,554 |
def conditional_entropy(xs, ys, bx=0, by=0, b=2.0, local=False):
"""
Compute the (local) conditional entropy between two time series.
This function expects the **condition** to be the first argument.
The bases *bx* and *by* are inferred from their respective time series if
they are not pro... | 03487b0b67e78359650001495cbb8ad975e69a6c | 3,620,555 |
def screen_aos(mol, active_atoms, den_mat_a, ovlp, trunc_lambda):
"""Screen AOs for truncation"""
include = [False] * mol.nbas
active_aos = []
for shell in range(mol.nbas):
aos_in_shell = list(range(mol.ao_loc[shell], mol.ao_loc[shell + 1]))
if mol.bas_atom(shell) not in active_atoms: ... | b4856265441d1a51d09d3c261b39ec655cf202e4 | 3,620,556 |
def setup_decision_tree_classifier(training_data,
training_target,
testing_data,
features = "preprocessed",
method = "count",
ngrams=(1,1)):
... | 9beac2b60c6e57ef15c37f49485fca352921962b | 3,620,557 |
def find_nearest(data, target, align='start', max_time_diff=None):
"""Finds the index of the nearest row in `data` to `target` time.
Args:
* data (pd.Series or pd.DataFrame): if `align==back` then `data` must
have an `end` column.
* target (pd.Timeseries or timestamp)
* align (str): `... | 849fca02f6757aa4487e38fd5b551bc543046b56 | 3,620,559 |
def clipped_error(x):
"""
# Huber loss (delta = 1)
L(a) = if abs(a) < delta -> 0.5*a*a
else -> delta*(abs(a) - 0.5*delta)
"""
# function where return the coordination of the values which is meet for the condition
# where(condition, x, y) 根据condition返回x或y中的元素
return tf.... | 9cba0097c4f90a31ef7b6fb11e3df86a154b64a5 | 3,620,560 |
def _rotate_affine(affine, shape, rotation):
"""
Work in progress. Does not work yet.
:param affine:
:param shape:
:param rotation:
:return:
"""
assert_affine_is_diagonal(affine)
# center the image on (0, 0, 0)
temp_origin = (affine.diagonal()[:3] * np.asarray(shape)) / 2
tem... | 5b24fc2450150d3f8e31576c70b5ad3bc17ee0d7 | 3,620,561 |
import torch
def b_inv(b_mat):
"""
inverse function for 2x2 matrix
:param b_mat: [M, 2, 2]
:return: [M, 2, 2]
"""
b00 = b_mat[:, 0, 0]
b01 = b_mat[:, 0, 1]
b10 = b_mat[:, 1, 0]
b11 = b_mat[:, 1, 1]
det = (b00 * b11 - b01 * b10)
b00 = b00 / (det + eps)
b01 = b01 / (det +... | e3a282a8cd24be31ae377c6c54e97f9daaa4afcc | 3,620,562 |
def right_bit_shift(lhs, rhs, ctx):
"""Element ↳
(num, num) -> a << b
(str, num) -> a.rjust(b, " ")
(num, str) -> b.rjust(a, " ")
(str, str) -> a.rjust(len(b)-len(a), " ")
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: int(lhs) >> int(rhs),
(str, ... | 246a6287baf3ad1b80e4ad56c7d41116dc00fb00 | 3,620,563 |
def spell_check(text, spell):
"""Fix misspelled words"""
suggestions = spell.lookup_compound(text, 2)
if suggestions:
return suggestions[0].term
else:
return text | 6ada77bbc6d691fa0e650f27f9a1e09885e70c14 | 3,620,564 |
def get_favicon():
"""
Function used internally to send static files from the static
folder to the browser
内部使用send_static_file方法将静态文件夹中的图片数据发送到浏览器
"""
# 找到网站图片的静态资源并返回
return current_app.send_static_file("news/favicon.ico") | fd85af2ffb65e1f0118b4b92d087112455f4e7ac | 3,620,565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.