content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def IAM_calc(ang_target,IAM_type,file_loc):
"""
This IAM is calculated with a table of many known IAM for specific angles
and computes a linear interpolation between two known angles for unknown angles.
"""
ang_target=abs(ang_target)
IAM_raw = np.loadtxt(file_loc, delimiter=",")
... | 5f11bc007305a797553997f39ca004590d00414d | 43,900 |
def _format_resolution_output(path, project, folderpath, entity_name, result):
"""
:param path: Path to the object that required resolution; propagated from
command-line
:type path: string
:param project: The potential project the entity belongs to
:type project: string
:param f... | 6e060f0eea2809e9b2f561d31fcb217334c5d4c7 | 43,901 |
from typing import OrderedDict
def find_corr_vars(correlation_dataframe,corr_limit = 0.70):
"""
This returns a dictionary of counts of each variable and how many vars it is correlated to in the dataframe
"""
flatten = lambda l: [item for sublist in l for item in sublist]
flatten_items = lambda dic... | 16ad89af3bb9073b704d1382247450999288f046 | 43,902 |
def removeblanklines(astr):
"""remove the blank lines in astr"""
lines = astr.splitlines()
lines = [line for line in lines if line.strip() != ""]
return "\n".join(lines) | fa4e04ca1b9cc643782af9363b5e6e6405a2b56d | 43,903 |
def image_filtering(img_array):
"""Put each object in the image into seperate image, returns list of images """
objects_array = []
object_ids = set(np.unique(img_array))
object_ids -= {0}
for object_id in object_ids:
obj_array = np.where(img_array == object_id, img_array, 0)
objects_... | 5c5d12028193bdbaa09d93a00731b9be04af70ab | 43,904 |
def get_system_settings(clear_metadata=True, exclude_locals=None):
"""System settings with applied studio overrides."""
default_values = get_default_settings()[SYSTEM_SETTINGS_KEY]
studio_values = get_studio_system_settings_overrides()
result = apply_overrides(default_values, studio_values)
# Clear... | 1f23f776293cbc61c8e014e701b1fba4d2b9fdad | 43,905 |
from typing import Callable
def resolve_average_callable(
averaging_method: [str, Callable[[np.ndarray], np.ndarray]]
) -> Callable[[np.ndarray], np.ndarray]:
"""Resolve a string or callable to a averaging callable.
Parameters
----------
averaging_method: str or Callable, defaults = 'mean'
... | 8d0f4e37d9e12ec85f3d223ea7b414d9ef5a91b8 | 43,906 |
def printChapterE(self, section):
"""
"""
output = []
#if self.FAxial == 'COMPRESSION':
#
output.append(" "+"\n")
output.append("_______________________________________________________________________________________"+"\n")
output.append(" "+"\n")
output.append(" F... | 9cd8ab3004864dd571f9853b9dc5554ebbb1b538 | 43,907 |
import re
def CheckEmailFormat(email: str) -> bool:
"""
Emailアドレスのフォーマットをチェックする。
ask him
"""
regex = r'^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if(re.search(regex, email)):
# print("Valid Email")
return True
else:
# print("Invalid Email")
return False | 042afa1e96934e11211bfff2b6e492768c7c5f50 | 43,908 |
import inspect
def datadriven(**testcases):
"""
You should decorate tests with datadriven if you want to pass data to them
(and have them called multiple times).
For example, declaring a test method like this:
@datadriven(
dataA=Args(paramA="foo"),
dataB=Args("hello", p... | 26602f7ddbe464ffde5812b61642d1b604335245 | 43,909 |
def version():
"""Returns the version number of the plugin manager.
Returns:
str
"""
return VERSION | 25361d6289153c355ed7a8c286c5725ce52f5b58 | 43,910 |
def AccountMoveVolumes(account_name,
account_id,
volume_names,
volume_ids,
volume_prefix,
volume_regex,
volume_count,
source_account,
so... | 491fbada3b61f95f20b16bc9bbb469af227b15fb | 43,911 |
import codecs
import re
def parse_notes(filename):
"""Build a Node list from the note text file"""
with codecs.open(filename, "r", "utf8") as file:
lines = file.readlines()
valid_line_regex = re.compile(r"^ *(il. ?)?~?\d+")
move_regex = re.compile(
r"((?:[KQBNR][a-h]?[1-8]?|[a-h])?x?[a... | 5de68eea9441505dcacf17257d568bfdb7b0b0be | 43,912 |
import matplotlib.pyplot as plt
from datetime import datetime
import numpy as np
from pylab import rcParams
def get_history_file_n(folderlist, param, nyears):
"""
Exhibits a graphic with the production of the group of researchers.
The 'production' is defined according to the parameters inserted.
Args... | 31eb5f079a48d44e2641e7eb6f0af0d64c4c039e | 43,913 |
def get_spark_memory_config(memory=SparkDefault.MEMORY):
"""
Assemble memory configuration for a Spark session
:param memory: string with memory configuration for spark
:return: memory configuration
"""
if not memory:
return ()
memory = memory.split(",")
if len(memory) != 3:
... | 55749da638dd7748bef2364484acb8bdf46c9056 | 43,914 |
def to_type(cls):
"""
Cast the data to a specific type
Parameters
----------
cls : class object
The class to cast the object to
"""
return lambda _, value: cls(value) | 3ae4daac59db30ce988adf55bc4f7f9e15822361 | 43,915 |
def post_save(sender, instance, raw, created, using, update_fields, **kwargs):
"""https://docs.djangoproject.com/es/1.10/ref/signals/#post-save"""
try:
if not should_audit(instance):
return False
# new created obj
if created:
event_type = CRUDEvent.CREATE
... | 3abc94a7f0510afeca026ac58cc92ac213134863 | 43,916 |
def tuneModel(grid, x_train, y_train, n_iter=3, cv=3, random_state=42, n_jobs = -1):
"""
Implements randomized parameter search for Random Forest models.
Parameters
----------
grid: dict
dictionary with list of possible values for each parameter
that should be tuned
x_train: li... | 7531ff31e8bfea247e954a4e1af7c0c73b250a2d | 43,917 |
import hashlib
def md5_key(chrom, start, end, ref, alt, assembly):
"""Generate a md5 key representing uniquely the variant
Accepts:
chrom(str): chromosome
start(int): variant start
end(int): variant end
ref(str): references bases
alt(str): alternative bases
ass... | 64db55c0075d063aeec500f97700ec769840cc4f | 43,918 |
import re
import json
import logging
def convert_xml_to_json(xml_filename, output_filename):
"""Create a JSON file based on XML assessment data.
Parameters
----------
xml_filename : str
The name of the source XML assessment data file.
output_filename : str
The name of the target ... | 1947e4e112f32cfe7173f6026d629459f7e1a21f | 43,919 |
import pickle
def load_object_with_pickle(file_name: str) -> object:
"""Loads a object easily be using pickle module.
Args:
file_name (str): file_name.pkl
Returns:
object (object): Any PyAbsorp object.
"""
__endswith_pkl_check(file_name)
try:
with open(file_name, "wb"... | 144dfab05bc1dd9eeec0c5bd7a0e3343d4403b35 | 43,920 |
def _roll_cube_data(cube, shift, axis):
"""Roll a cube data on specified axis."""
cube.data = np.roll(cube.data, shift, axis=axis)
return cube | 726b8d65607049d26474edf29236beb1a5de9d97 | 43,921 |
def _dataset_version(path, name):
"""Get the version of the dataset."""
ver_fname = op.join(path, 'version.txt')
if op.exists(ver_fname):
with open(ver_fname, 'r') as fid:
version = fid.readline().strip() # version is on first line
else:
# Sample dataset versioning was intro... | a49f302abb94f5cafc38f231a67257add4d17579 | 43,922 |
import code
from operator import sub
def main():
"""Generates markdown file"""
client = carla.Client('127.0.0.1', 2000)
client.set_timeout(2.0)
world = client.get_world()
bp_dict = {}
blueprints = [bp for bp in world.get_blueprint_library().filter('*')] # Returns list of all blueprints
b... | 30874097ceb1b2a788d2ed3195cf779dc8c98bf0 | 43,923 |
import math
def acf(x, max_lag):
"""
Autocorrelation function transform, currently calculated using standard
stats method. We could use inverse of power spectrum, especially given we
already have found it, worth testing for speed and correctness. HOWEVER,
for long series, it may not give much bene... | 4c93fdf024ce0ed7453795ac339863b29082ce86 | 43,924 |
def _missing_ids(vba, pcode_ids, verbose=False):
"""
See if there are any function names or variables that appear in
the p-code that do not appear in the decompressed VBA source code.
vba - (str) The decompressed VBA source code.
pcode_ids - (set) The IDs defined in the p-code.
return - (floa... | 86dfb5abf8bd9c24078adbed60f6428872ee1ae4 | 43,925 |
def get_staking_transaction_by_hash(tx_hash, endpoint=_default_endpoint, timeout=_default_timeout) -> dict:
"""
Get staking transaction by hash
Parameters
----------
tx_hash: str
Hash of staking transaction to fetch
endpoint: :obj:`str`, optional
Endpoint to send request to
... | ea075dd89fcfcc421474d172816e003349985133 | 43,926 |
def make_wrap_words(length, sep=','):
"""Returng wrap words function."""
return lambda words: wrap_words(words, length, sep) | 6dab7101dff089a4dc48839bcbeabdb8578b572a | 43,927 |
import ast
def parse_assignments_expressions(code):
"""Parse a code block composed of variable assignments.
Args:
code: Multiline string representing Python code
Returns: Dict <variable_name>: <(variable_type, variable_value)>
"""
variables = dict()
tree = ast.parse(code)
for blo... | 9eb57bf2a59e0b0d46fd222c1407ce2fab07368b | 43,928 |
import random
def hearing_test():
"""
Determines if the user is eligible to take the hearing test (i.e. has not exceeded `MAX_HEARING_TEST_ATTEMPTS`, and
then renders the hearing test, which consists of the assessor counting the tones in two audio files.
If caqe.settings.HEARING_TEST_REJECTION_ENABLE... | ddf6ae2a693333a9c7721abe942947dc9aae63a1 | 43,929 |
import importlib
def load_cdk_app(cdk_app_path, cdk_app_name):
"""
Load a CDK app from a folder path (dynamically)
:param cdk_app_path: The full path of the CDK app to load
:param cdk_app_name: The module path (starting from cdk_app_path) to find the function returning synth()
:return:
"""
... | 485a6c3bb79045d71fc3452904f86471c2b97a63 | 43,930 |
def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
... | 1f42de3797f31fdef0a873b6f50a919323085e98 | 43,931 |
def get_pod_memory_usage_range(cluster_id, namespace, pod_name_list, start, end, bk_biz_id=None):
"""获取CPU总使用率
start, end单位为毫秒,和数据平台保持一致
"""
step = (end - start) // 60
pod_name_list = "|".join(pod_name_list)
porm_query = f"""
sum by (pod_name) (container_memory_working_set_bytes{{cluste... | e0230c1106d2f567337b662414490e1b3767e8af | 43,932 |
def is_isotropic(self, p):
"""
Checks if Q is isotropic over the p-adic numbers `Q_p`.
INPUT:
`p` -- a prime number > 0
OUTPUT:
boolean
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1])
sage: Q.is_isotropic(2)
False
sage: Q.is_isotropic(3)
... | eae5ef191dd3e0716bb95ae89dd15b0bdb7d033a | 43,933 |
import warnings
import scipy
def floquet_markov_mesolve(
R, rho0, tlist, e_ops, options=None, floquet_basis=True,
f_modes_0=None, f_modes_table_t=None, f_energies=None, T=None,
):
"""
Solve the dynamics for the system using the Floquet-Markov master equation.
.. note::
It is important to... | 611b5e90d4152927f0567f463cd56e847ecd0c16 | 43,934 |
def build_query(filters, page):
"""
Construye el query de búsqueda a partir de los filtros.
"""
return filters.buildQuery().order_by('nombre') | 2cebff5cfed09948e6828dcb4d59d51c08e93544 | 43,935 |
def _get_storage_api(retry_params, account_id=None):
"""Returns storage_api instance for API methods.
Args:
retry_params: An instance of api_utils.RetryParams.
account_id: Internal-use only.
Returns:
A storage_api instance to handle urlfetch work to GCS.
On dev appserver, this instance by defaul... | 1e2d6abc1f910da89ea13a79f6210e1cb2244886 | 43,936 |
from typing import Tuple
from typing import Any
import codecs
import sys
def io_wrapper(io_str: str, mode: str) -> Tuple[bool, Any]:
"""
Wrapper for IO stream
Args:
io_str: "-" or file name
mode: IO mode
"""
if io_str != "-":
std = False
stream = codecs.open(io_str,... | 4ba03243754490b75e8cf66dbb0f40b450d6d10f | 43,937 |
def get_algo_invalidate_solved_values(board: Board):
"""
simple invalidator: iterate through rows, cols, packages and invalidate already-solved candidates
"""
def invalidate_solved_values():
for unit in board.get_all_houses():
unit.invalidate_solved_values()
board.validate_co... | 345ceb9edbe4079ad50ba42d6cfe00f2bffc351d | 43,938 |
def query_parse(field_key_map: FieldKeyMap, **kwargs):
"""
将查询条件转化为 filterByFormula
records.filter(title="hello", subtitle="world") => '{title}="hello" AND {subtitle}="world"'
1. 通过 filter 和 get 参数查询到的只能转化为 and 条件。
"""
query_str = ""
for k, v in kwargs.items():
if query_str:
... | 1eb372ab954aeb5c99cf08b1e25064815c521cde | 43,939 |
def thrown_showers_per_ebin(sim_list, log_energy_bins=None):
"""Calculate the number of thrown showers in each energy bin
Parameters
----------
sim_list : array_like
Sequence of simulation dataset numbers.
log_energy_bins : array_like or None, optional
Log energy bins to use (defaul... | 848dbd0def4bbfb45933bf1b25d4d24354d3b63b | 43,940 |
import requests
import logging
def _request_youtube(method, url, env, params=None, headers=None, json=None):
"""Perform a YouTube Reporting API request.
This function refreshes the access token if necessary.
"""
request_fn = {"DELETE": requests.delete, "GET": requests.get, "POST": requests.post}
... | e3df7a6fe2cd61f728179bb83f6fa800e75700e7 | 43,941 |
def faceBlobSalientBasedOnAverageValue(value, salientLabelValue):
"""Deprecated"""
# the face is considered salient if 50% of pixels or more are marked salient
if value > (0.5 * salientLabelValue):
return True # bright green
# if the face is not salient:
else:
return False | 7a1f7d46e1cd251a80ebf8f7405dde58d108fdd8 | 43,942 |
from pathlib import Path
import os
import requests
def download(url, force_download=False):
""" Downloads given URL and saves a local file"""
cur_dir = Path(__file__).absolute().parent
DATA_DIR = os.path.join(cur_dir, 'data')
if not os.path.exists(DATA_DIR):
print('[i] create following folder... | b44b284446e84b4a1c07e1ef95066c40a33f4227 | 43,943 |
def find_field(child, field_name: str, tag_root: str) -> str:
""" Fetch specific fields of the child nodes of current the XML node.
Args:
child (object): child of node that may have field = field_name.
field_name (str): name of field of XML node.
tag_root (str): start of tag of each XML... | b520ebf1a00c6287650cb4438425d3d38640c14c | 43,944 |
def rmse(predictions, targets):
""" RMSE function
Args:
predictions (1-d array of float): Predicted values.
targets (1-d array of float): Observed values.
"""
return np.sqrt(((predictions - targets) ** 2).mean()) | b468e43271813dea75468d2da5bd36711092fd7c | 43,945 |
import base64
def base64_encode_nifti(image):
"""Returns base64 encoded string of the specified image.
Parameters
----------
image : nibabel.Nifti2Image
image to be encoded.
Returns
-------
str
base64 encoded string of the image.
"""
encoded_image = base64.encodeb... | 5e3758089240d8840c1cb1828ab908dead3b4b7c | 43,946 |
def get_token(auth_url, username, password):
"""
Authenticate user and return generated token
auth_url: Url to be used for BDSE
Username: Username for BDSE
Password: Password for the user
"""
buf = cStringIO.StringIO()
curl = pycurl.Curl()
curl.setopt(curl.URL, auth_u... | e897775ff01ecda5692b9026352d88c571c8c440 | 43,947 |
def compare_configs(fn1, fn2):
"""compare two ini files
"""
result = []
gen1 = sort_inifile(fn1)
gen2 = sort_inifile(fn2)
def gen_next(gen):
"generator to get next item from file"
eof = False
try:
sect, opt, val = next(gen)
except StopIteration:
... | 1d2f69e6f5c8fb03d537f16e67d68345f6863408 | 43,948 |
import logging
def tf_build_varying_top_k_mask_4d_op(input_tensor, k_max, batch_size, h, w, input_area, ranking_mask):
"""Build varying top K mask."""
batch_h_w_size = batch_size * h * w
logging.debug('encoding shape = (%s, %s, %s, %s)',
batch_size, h, w, input_area)
# Find the "winners". Th... | bfc32b8c3eeaf990fd225a5a6dfabba3c30ad403 | 43,949 |
from datetime import datetime
from typing import Tuple
def resolve_parameter_name(
parameter_name: str,
obs_date: datetime,
) -> Tuple[str, str, str]:
"""
Resolves a ``parameter_name`` into a dictionary that contains
information about which archive the parameter can be obtained
from, using whi... | fef8b5b7c0e7bc9726b4ef1648cacea901870600 | 43,950 |
import os
import json
import traceback
import shutil
from datetime import datetime
def publish_dataset(prod_dir, dataset_file, job, ctx):
"""Publish a dataset. Track metrics."""
# get job info
job_dir = job["job_info"]["job_dir"]
time_start_iso = job["job_info"]["time_start"]
context_file = job["... | 2badaef1a2fda1c9d3a1e0a30e389f84a1425ff3 | 43,951 |
import numpy
def calc_array_manifold_f(fbinX, fftlen, samplerate, delays, half_band_shift):
"""
Calculate one (conjugate) array manifold vector for each frequancy bin or subband.
"""
chan_num = len(delays)
Delta_f = samplerate / float(fftlen)
J = (0+1j)
fftlen2 = fftlen / 2
if half_ba... | 26005e6c831e4a04052f6beed86bc861a97eb522 | 43,952 |
def get_network_interface(interface='default'):
"""
Returns the network interface which contains addr, broadcasts, and netmask elements
:param interface: The interface name to check, default grabs
"""
# Get the default gateway
gws = netifaces.gateways()
LOGGER.debug("gws: {}".format(gws))
... | eabef72b1f03cee5c9d377c44dc6cadd815fa202 | 43,953 |
def build_g_suite_service(service, version, credentials):
"""
Builds a Google API Resource Client.
:param service: The service to get a client for.
:type service: str
:param version: The version of the service to get a client for.
:type version: str
:param credentials: The credentials used t... | 8dd8d7e729878252916b3b4fcdd9d5c0a127f297 | 43,954 |
import functools
def resnet_v1_beta(inputs,
blocks,
num_classes=None,
is_training=None,
global_pool=True,
output_stride=None,
root_block_fn=None,
reuse=None,
scope=No... | da69e17b0831df30a3f9436567e760810d129546 | 43,955 |
def get_resize(image, scale):
""" resizes image according to scale"""
if isinstance(scale, int):
if image.shape[0] % scale != 0 or image.shape[1] % scale != 0:
return 1, None
if image.shape[0] < scale or image.shape[1] < scale:
return 2, None
arrays = []
... | f75718a298bfd9ae5fd851ad20c65631ff34cf0f | 43,956 |
from typing import List
import base64
def parse_saml_response_to_roles(saml_response: str) -> List[str]:
"""
Parses a SAML response to a list of role,saml-provider pairs
:param saml_response: the SAML response to parse
:return: a list of role,saml-provider pairs
"""
roles = []
root = Elem... | b339c61de4565611ba149cf0b2d6fe5428fae1fc | 43,957 |
import numpy
def rotate(p, angle, center=(0, 0)):
"""
Rotates given point around specified center.
Args:
p: (float, float)
Point to rotate.
angle: float
Angle in radians.
center: (float, float)
Center of rotation.
"""
... | 41b95c1b4162ad9ebacc2250c293e33daaa8a526 | 43,958 |
def pendulum(integrator_type, num_samples, num_parts, T_max, dt, srate, noise_std, seed):
"""simple pendulum"""
def hamiltonian_fn(coords):
q, p = np.split(coords, 2)
H = 9 * (1 - cos(q)) + p ** 2 / 2
return H
def dynamics_fn(coords):
dcoords = autograd.grad(hamiltonian_fn)... | af884b72e5b4eb96819878f16dc38e948cb4d6c2 | 43,959 |
from typing import Union
def historical_volatility(maven_asset_code: str, price_type: str,
currency: str, period_start: list,
period_end: list,
lambda_factor: Union[None, float] = None
) -> dict:
"""
:param... | ac70a372641f8c8ab2ef3fc6e5f63857183c59e0 | 43,960 |
import tempfile
import os
def _merge_clips(clips, dryrun):
"""
ffmpeg plays nicely when the files that are to be concatenated
are written to a text file, and the file is passed to ffmpeg
the new file is written to temp
:param [] clips: list of movie clips to be concatenated
:param bool dryru... | 81d6e83014359ec9bcba99b4ccbc3248875e2fa6 | 43,961 |
from re import T
def cos(x):
"""Elementwise cosine """
return T.cos(x) | 6bd1a0eb07da39450754ce20b0da2112c79d3b71 | 43,962 |
def authenticate(url="ws://localhost:8776", session_key=None, print_callback=print, **kwargs):
"""
Connect to a telekinesis server and call the authenticate method at the entrypoint
url: string - url of the telekinesis Broker. example: "wss://telekinesis.cloud"
session_key: string ... | b3314b86fbbfe1d11f08c3b63f985d469ffc55e7 | 43,963 |
from datetime import datetime
def get_inconsistent_resources(context):
"""Get a list of inconsistent resources.
:returns: A list of objects which the revision number from the
ovn_revision_number and standardattributes tables differs.
"""
sort_order = sa.case(value=ovn_models.OVNRevision... | d148400a0211de31b70fd323f8c00eda666b7a0f | 43,964 |
import sys
def ustr(obj):
""" Python 2 and 3 utility method that converts an obj to unicode in python 2 and to a str object in python 3"""
if sys.version_info[0] == 2:
# If we are getting a string, then do an explicit decode
# else, just call the unicode method of the object
if type(ob... | 0b30e580fa931723afae872ec238ea49fd80700a | 43,965 |
import json
def ChangePasswordView(request):
"""
Set new password for the user.
"""
post_data = json.loads(request.body)
username = post_data['username']
token = post_data['token']
password = post_data['password']
try:
user = User.objects.get(username=username)
if defa... | 8a79547fefb4f3a6cf4d1ec7c6554a7b48dbd04d | 43,966 |
def pure_water_density_tanaka(t, a5=0.999974950):
"""Equation according Tanaka, M., et. al; Recommended table for the density of water between 0 C and 40 C based on
recent experimental reports, Metrologia, 2001, 38, 301-309
:param t: water temperature (°C)
:param a5: density of SMOW water under one atm... | 27bcc12f8f9089cf8307d72ba784675bbcd5036a | 43,967 |
def collect_multi_single(ilist, fmt, fmt_dc):
"""Collect camera arrays from multiple files.
Parameters
----------
ilist: sequence
Sequence which elements are formatted into `fmt` and `fmt_dc` to
get paths to measurement files.
fmt : str
Format string for bright frame.
fm... | 0a19ebbb7b69b58ca3f89e86392ac937dcfb02fb | 43,968 |
def create_credentials(view_password, account, login_name, pass_word):
"""
Function to create a new credential
"""
new_credential = Credential(view_password, account, login_name, pass_word)
return new_credential | 6c56437ab3240cf8512b66fa48e2d0ff9dfa3fed | 43,969 |
import os
def latest_checkpoint(root_output_dir):
"""Get the latest checkpoint dirname, which is in the format of `ckpt_1`.
Args:
root_output_dir: The directory where all checkpoints stored.
Returns:
Dirname of the lastest checkpoint.
"""
checkpoints = tf.io.gfile.glob(os.path.join(root_output_dir... | 22b44126b8cf93d4209f7dc39f9682b06a6e9569 | 43,970 |
def menu(request):
"""餐廳的菜單.
有菜名、價格、說明以及會不會辣。
"""
food1 = {
'name': '番茄炒蛋',
'price': 60,
'comment': '好吃',
'is_spicy': False
}
food2 = {
'name': '番茄炒蛋',
'price': 60,
'comment': '好吃',
'is_spicy': False
}
foods = [food1, food2... | 430ee4e66672bea41355dcc76decf504ce7aea02 | 43,971 |
from pathlib import Path
import pickle
def load_trained_model(fname: str):
"""
Loads a saved ModelData object from file.
Args:
fname (str): Complete path to the file.
Returns: A ModelData object containing the model, list of titles, list of
authors, list of genres, list of summaries,... | 3bdfa3f090fa5efcd54b17bd47a0cd4ea57e1c4a | 43,972 |
import urllib
import requests
import json
def weather_old(city):
""" 百度天气
"""
try:
city_name = urllib.parse.quote(city.encode('utf-8'))
url_str = f'http://api.map.baidu.com/telematics/v3/weather?location={city_name}&ak={KEY1}&output=json'
response = requests.get(url_str)
da... | 47754e3b33e85fadae5185eeff3911f544dd2fb2 | 43,973 |
def lock_prefix():
"""
Will prefix locks with a Unicode Character 'KEY' (U+1F511)
if the user's stdout supports it
"""
if is_unicode_supported():
return u'\U0001F511 ' # Extra spaces are intentional
return '' | a5b99bffdd74f8ac22dfc1c77faf821af571ed44 | 43,974 |
def identity_belief(reference: dict) -> dict:
"""
Returns an identity function for the beliefs.
This is so that we can debug more easily. Therefore, does almost nothing
but replace values with 1.0 in a data structure.
Parameters
----------
reference : dict
A single reference metada... | f67561beb1c5e95b7e2127e1f33a0a1785036b6e | 43,975 |
def map2arr(iterator, return_np_array=True, check_nones=True):
"""Function to cast result from `map` to a tuple of stacked results
By default, this returns numpy arrays. Automatically checks if the map object is a tuple, and if not, just one object is returned (instead of a tuple). Be warned, this does not wor... | f6d37e0d6b2152a4eef0349bb7d86c64502c1c61 | 43,976 |
def resolve(item):
"""
Get a non-ambiguous string for each item. If it's uncertain, pick a word,
even if it's just THE. This lets us at least try a sort order, although
uncertain answers may be out of place.
"""
if isinstance(item, RegexClue):
return item.resolve()
else:
retu... | 964f587dee725c1e1572d2c3c134cdb2a6c8eee6 | 43,977 |
import yaml
def get_twitter():
""" Twitterインスタンスを取得する """
tw_cfg = yaml.load(open(".tokens"), Loader=yaml.SafeLoader)
oauth = OAuth(
tw_cfg['ACCESS_TOKEN'], tw_cfg['ACCESS_TOKEN_SECRET'],
tw_cfg['CONSUMER_KEY'], tw_cfg['CONSUMER_SECRET'])
tw = Twitter(auth=oauth)
return tw | 9750e7c9710446a24b62582195188359a2ecdc21 | 43,978 |
def elina_texpr0_array_is_interval_polyfrac(texpr_array, size):
"""
Test if an ElinaTexpr0Array is polynomial fraction with possibly interval coefficients, but no rounding.
Parameters
----------
texpr_array : ElinaTexpr0Array
ElinaTexpr0Array that needs to be tested.
size : c_size_t
... | cb48e8f12d294e420f392803a7d3bcc72da86705 | 43,979 |
def get_client_config(app_config, data_adaptor):
"""
Return the configuration as required by the /config REST route
"""
server_config = app_config.server_config
dataset_config = data_adaptor.dataset_config
annotation = dataset_config.user_annotations
auth = server_config.auth
# FIXME T... | babae5cec310383dd0233da0837694f8842f6f80 | 43,980 |
import select
def if_mkl_v1(if_true, if_false = []):
"""Returns `if_true` if MKL-DNN v1.x is used.
Shorthand for select()'ing on whether we're building with
MKL-DNN v1.x open source library only, without depending on MKL binary form.
Returns a select statement which evaluates to if_true if we're bui... | d49aed5ebb68f47111d8057a73454059dd8a31a0 | 43,981 |
def generate_hostfile(map_, file):
"""
generate hostfile base on map_
"""
for node in map_:
print('node-{}.simgrid.org'.format(node), file=file)
file.flush()
return file.name | 76de14bfec5e94ddbce4e29fbcaee844f566b086 | 43,982 |
import uuid
import json
def home(request):
"""
Controller for the app home page.
POST requests can be receieved from the CUAHSI HydroClient when exporting data to
HydroShare. These requests include a form describing the reference data exported
from the HydroClient workspace, but should not inclu... | 9a8a6c1aba716703e9cadeec86124c47dda2fae1 | 43,983 |
import traceback
def run(path='', code=None, rootdir=CURDIR, options=None):
"""Run code checkers with given params.
:param path: (str) A file's path.
:param code: (str) A code source
:return errors: list of dictionaries with error's information
"""
errors = []
fileconfig = dict()
lin... | fd6a02b1a3c070ad607defe0062c47e5122b888d | 43,984 |
from pathlib import Path
def nf_dir() -> Path:
"""Root directory for `jax3d/nerfstatic/`."""
return j3d_dir() / 'nerfstatic' | aff2737627d5bec1c760c857533df938b1ed4596 | 43,985 |
import os
def publish(request):
"""
Publish page: Simply render the publish form if the request method is GET, or actually publishes (create or modify)
a blog if the request method if POST.
Note that creating and modifying requires different permissions.
"""
# The permission authenticating par... | aadc2e93f4dcb9a60ade0b504599aba62142c0f1 | 43,986 |
def _populate():
"""Returns a list of sql commands to setup the DB for the fetch tests."""
populate = [
# NOTE NO GOOD using format to bind data
"insert into {} values ('{}')".format(
TABLE1, s)
for s in SAMPLES
]
return populate | c32d13fdae459f2fdcda66ea14bf856278924f99 | 43,987 |
def x2(samples):
"""Get F = <x_j^2>
Args:
samples (array_like): [N_samples, N_x] array of samples
Returns:
feature (array_like): [N_samples, 1] feature
grad_feature (array_like): [N_samples, 1, N_x] gradient of the feature
"""
Nx = samples.shape[-1]
Feature = np.sum(sam... | 6319ca23e8a6b61b93053f192aa6133d190ff04d | 43,988 |
def get_birthday_of_contact_day(p_birthday_of_contact_month):
"""Saves the Day of Birth of the Contact. Error Checking is Performed to Determine Validity"""
birthday_of_contact_day = input("Birthday Day | Enter Your Contact's Birthday Day as DD, ex: Type 01 For the First or 15 For the Fifteenth, Then Press Ent... | 2760c1ef43003779f92736ad0f641f1a506e54c1 | 43,989 |
def svds(A, k=6, ncv=None, tol=0, which='LM', v0=None,
maxiter=None, return_singular_vectors=True):
"""Compute the largest k singular values/vectors for a sparse matrix.
Parameters
----------
A : {sparse matrix, LinearOperator}
Array to compute the SVD on, of shape (M, N)
k : int, ... | 51fa68fdcd712303c2da1c5a6670cfb818ed0662 | 43,990 |
import typing
import asyncio
def sync(
awaitable: typing.Awaitable,
event_loop: typing.Optional[asyncio.events.AbstractEventLoop] = None,
):
"""
Run an awaitable synchronously. Good for calling asyncio code from sync Python.
The usage is as follows:
.. highlight:: python
.. code-block:: ... | 4fda68c3132564d9c6620fe8e4c1cfac401528a6 | 43,991 |
def get_plane_infos(p1: np.ndarray, p2:np.ndarray, p3:np.ndarray):
"""Returns the informations of a plane from a 3d region points
Args:
pos (np.ndarray): [description]
ori (np.ndarray): [description]
Returns:
tuple: p, e1, e2, n where p is the reference position of the plane, e1,e2... | c0ef5923e62a56595c7455ee34488e487c6c28ae | 43,992 |
import math
def check_float(a, b, precision=1e-4):
"""
check float data
Args:
a(list): input_data1
b(list): input_data2
precision(float): precision for checking diff for a and b
Returns:
bool
"""
def __adjust_data(num):
if num == 0.0:
return... | 240c4dac3228669592317e44b69f19d436a1c17d | 43,993 |
def icosahedron_nodes_calculator(order):
"""Calculate the number of nodes
corresponding to the order of an icosahedron graph
Args:
order (int): order of an icosahedron graph
Returns:
int: number of nodes in icosahedron sampling for that order
"""
nodes = 10 * (4 ** order) + 2
... | eccea98ec5da3fae748c3505af4689dfe6f47b73 | 43,994 |
def evaluateW(trials_1, trials_2):
"""
Evaluate the spatial filter of the CSP algorithm
Parameters
----------
trials_1 : numpy 3D-matrix
Trials matrix of class 1. The dimensions must be trials x channel x samples
trials_2 : numpy 3D-matrix
Trials matrix of class 2. The dimension... | 6afa58a3bd90f4801276fbefb7dacb4a3b4b469a | 43,995 |
def list_publicIP(apiclient, **kwargs):
"""List all Public IPs matching criteria"""
cmd = listPublicIpAddresses.listPublicIpAddressesCmd()
[setattr(cmd, k, v) for k, v in list(kwargs.items())]
return(apiclient.listPublicIpAddresses(cmd)) | ef47b964a1fcdaaa2d02dae733fc5d7c77553d27 | 43,996 |
def parse_mhdr(mhdr):
"""
MHDR parser
mhdr: 1 byte.
7 6 5 | 4 3 2 | 1 0
MType | RFU | Major
"""
# MHDR parser.
def get_mtype_cmd(mtype):
return {
"000": "Join Request",
"001": "Join Accept",
"010": "Unconfirmed Data Up",
... | a3a57c7b2cde3146e97b9d60cd548f95737d7a5f | 43,997 |
def per_device_batch_size(batch_size, num_gpus):
"""For multi-gpu, batch-size must be a multiple of the number of GPUs.
Note that this should eventually be handled by DistributionStrategies
directly. Multi-GPU support is currently experimental, however,
so doing the work here until that feature is in place.
... | 7311347685bed527a832e17c13cf4d8ac9fa4005 | 43,998 |
def log_loss(y_true, y_prob):
"""Compute Logistic loss for classification.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like of float, shape = (n_samples, n_classes)
Predicted probabilities, as returned by a class... | 6f4f44fbf2e2197116e71fcab979ab0aeb6627cb | 43,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.