content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_target_group_with_type_color_and_workspace(tg_type, color, workspace):
"""
Récupère un target group ayant un type et une couleur précise
:param tg_type: Type recherché
:type tg_type: str
:param color: Couleur recherché
:type color: str
:param workspace: Workspace
:type work... | 74baf63ee309201f4b15462380f8fb3f8024ce23 | 43,870 |
def resource_path(level = 2):
"""Return a resource path calculated from the caller's stack.
"""
return get_resource_path(level + 1) | be93c9e3202bdd447d5305534e479d01997f7f0f | 43,871 |
def split_residue_id(atom):
"""Takes an atom and splits its het ID into components.
:param Atom atom: the atom to read.
:rtype: ``tuple``"""
if atom.het:
id = atom.het.id.split(".")[-1]
num = "".join([c for c in id if c.isdigit()])
insert = "".join([c for c in id if c.isalpha()... | 7340c24dc1ef982fd0a3772764a02d7c8fd30126 | 43,872 |
from typing import Union
def get_latest_education(education_history: list[Education]) -> Union[Education, HigherEducation, None]:
"""
Currently we presume that the education history passed in is ordered,
we can add in sorting here by attendance date if we need to in the
future
"""
if len(educa... | f89688a8f0a846326fb48877f964fe35d20d53a0 | 43,873 |
def get_model(controller, name):
""" List information for model
Arguments:
name: model name
controller: name of controller to work in
Returns:
Dictionary of model information
"""
models = get_models(controller)['models']
for m in models:
if m['short-name'] == name:
... | c4af45535cc1470ce0c25397af98eaea8e6ae574 | 43,875 |
def transform_coord(y_coordMat, x_coordMat, rotationCenter, transformVect):
""" Transform x-y coordinate (y_mat & x_mat) by transformVect | round to int | return rotated y & x coord as vector"""
""" y_mat and x_mat are the coord to be rotated | rotationCenter [y;x] or [y;x;phi] are the centre of rotation by the... | 89c28fd7f5f60b20f99952538eedda89546c5b14 | 43,876 |
import numpy as np
def pvs(t):
"""
Saturation vapor pressure as a function of tempetature
t [°C]
"""
T = t + 273.15 # [K] Temperature
# pws(T) [Pa] saturation pressure over liquid water
# for temp range [0 200] °C eq. (6)
C8 = -5.800_220_6e3
C9 = 1.391_499_3e0
C10 = -4.864... | 8ba1aced4669753cca0ff2332bc2bd7ad5ad7814 | 43,877 |
def enumerate_bonds(mol):
"""
A helper function for calling Molecule.enumerate_bonds
First, get the Kekulized molecule (get the Kekule version with alternating single and double bonds if the molecule
is aromatic), since we don't have implementation for aromatic bond additivity corrections
"""
mo... | 5b2e1aad49fa9eebd7b67a442c59e8edcb295bf4 | 43,879 |
def _build_link_str(frame_info: Traceback) -> str:
"""
Build the clickable link string for a frame info object.
"""
return f'{INDENT}File "{frame_info.filename}", line {frame_info.lineno}, in {frame_info.function}' | e6781b17fbf19c82b05282c33935a7fd1849d843 | 43,880 |
def save_output_node(out):
"""
This calcfunction saves the out dict in the db
"""
out_wc = out.clone()
return out_wc | 7f89752332c023558dfb2ea7774231e1c1eeab99 | 43,881 |
def inject_spectrum(model, snr=100, dt=1, res=50, planet_params={}):
"""
Inject the synthetic model into chromatic Rainbow
Parameters
----------
model : synthetic_planet
Synthetic planet object with wavelength-varying limb-darkening coefficients, as defined in generate_spectrum_ld
r_sta... | 6f910a85c85ea7dc59bfd3ac1b27692e29a4a88f | 43,882 |
import numbers
def l2_regularizer(scale, name='l2_regularizer'):
"""Returns a function that can be used to apply L2 regularization to weights.
Small values of L2 can help prevent overfitting the training data.
Args:
scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
name: An optional na... | 58f5e48b9af5a5d7ddf3217a68262e441677cd24 | 43,883 |
def cal_fdp_power(selected, non_zero_index, r_index=False):
""" Calculate power and False Discovery Proportion
Parameters
----------
selected: list index (in R format) of selected non-null variables
non_zero_index: true index of non-null variables
r_index : True if the index is taken from rpy2 ... | 5e14b19c95ec0bc465c6ea6c98606768f00ee49e | 43,884 |
def _serialize_dictionary_value(value, charset) :
""" Serialize dictionary value """
error_code = Error(errOk)
if value is None :
return error_code, NULL_STRING
result = "{"
comma = ""
for key, child_value in sorted(
value.value.items(),
key = lambda value: (value[1].order_number, value[0])... | 888f344dc12afa42f2f7054bc62958a7915c82a3 | 43,885 |
def _create_types_map(sqltypes):
"""Take a types module and utilising the `dir` function create a
mapping from the string value of that attribute to the SQLAlchemy
type instance.
"""
sql_types_map = {
item.lower(): getattr(sqltypes, item)
for item in dir(sqltypes)
if item[0].... | 69a3902663eadc70050acc0c1869fcb86a2a6384 | 43,886 |
def discuss(topic) :
"""Discuss a topic with the user and return their response.
Ask if the user likes the topic and why.
Parameters:
topic (str): The topic under discussion.
Return:
str: Response to the question of why they like the topic.
"""
like = input("Do you like " + to... | 854dcb744440b98fbbeb763e9ae0a866afb5d7d0 | 43,887 |
def sigmoid(x):
"""
sigmoid function
:param x:
:return:
"""
return 1.0/(1.0+np.exp(-x)) | 6e147229a6b527bff1e0976abde0f472ea60ab84 | 43,888 |
def numba_update_portability_matrix(
portability_matrix, r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g
):
"""
updating the probability matrix
"""
for a, b, c, d, e in zip(r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g):
portability_matrix[a, b, c, d, e] = 1
return portability_matrix | 138a55af650ab98d1ff4d991b5f81e6f709148c8 | 43,889 |
def _sin(t: 'Tensor') -> 'Tensor':
"""
Also see:
---------
:param t:
:return:
"""
data = np.sin(t.data)
requires_grad = t.requires_grad
if requires_grad:
def grad_fn(grad: np.ndarray) -> np.ndarray:
return grad * np.cos(t.data)
depends_on = [Dependency(... | 968f95788758d56414206859e48daa3ef5b4b080 | 43,890 |
def confirm(prompt, default=False):
"""Give a yes/no prompt with the default letter (y or n) presented as uppercase"""
if default:
prompt += " [Y/n] "
else:
prompt += " [y/N] "
response = None
while response is None:
raw_input = input(prompt)
if raw_input == "":
... | 5d33b6f1116b7c7cf134afcd4c6749f183abb5d7 | 43,891 |
def get_ssa(net, blob_versions=None):
"""
Given a net, return a structure containing the version of each input and
output blob used by each operator.
Args:
net: either a Net or a NetDef
blob_versions: (optional) map with current version number for given
... | e800cd02d46302790dd1c96aebc7170f590f56de | 43,893 |
def band_dos_element_spd_spin_polarized(
band_folder,
dos_folder,
element_spd_dict,
output='band_dos_element_spd_sp.png',
scale_factor=5,
color_list=None,
legend=True,
linewidth=0.75,
band_color='black',
unprojected_band_color='gray',
unprojected_linewidth=0.6,
figsize=(8... | a07b4efe8f4cb297abe618217dbc8785f3fc5428 | 43,894 |
def get_redirect_target():
""" Returns the redirect target. """
for target in request.args.get('next'), request.referrer:
if not target:
continue
elif is_safe_url(target):
return target | 9c715bb77a670f15a8c10acaf29efbe99ab245af | 43,895 |
from typing import Callable
import functools
def construct_schedule(
name: str,
**kwargs,
) -> Callable[[chex.Numeric], chex.Array]:
"""Constructs the actual schedule from its name and extra kwargs."""
if name == "fixed":
return functools.partial(fixed_schedule, **kwargs)
elif name == "imagenet_sgd"... | c1bb57b08af3aa47078d58f831118d76cce455f6 | 43,896 |
from typing import IO
from datetime import datetime
def set_month_year(io: IO, user_selected_moth_year: str) -> tuple[int, int]:
"""
Produce Month/Year combination to filter calendar by
:param io: instance of IO object
:param user_selected_moth_year: string containing user-selected combination of Mont... | f3dc4cb2b043e0eacadd54d43b771f0571176195 | 43,897 |
def dump_to_writer(writer, resources, resource_type=None, fields=None):
"""
Dump resources to a CSV writer interface.
The interface should expose the :py:class:`csv.writer` interface.
:type writer: :py:class:`csv.writer`
:param writer: Writer object
:param fields: List of fields to write
:... | 6824ca0ddbb893c41be335237d4d88e9de4c0c9f | 43,898 |
def find_author(name, authors):
""" Find the author with the provided name, in the list of authors"""
for author in authors:
if author.name == name: return author
raise ValueError('Author', name, 'not found.') | dd47f0ecf8574d68a0ce9b5e94dff19b58f5887a | 43,899 |
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 |
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 |
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 |
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 |
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 |
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 |
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 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 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 |
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 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 |
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 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 |
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 |
from pathlib import Path
def nf_dir() -> Path:
"""Root directory for `jax3d/nerfstatic/`."""
return j3d_dir() / 'nerfstatic' | aff2737627d5bec1c760c857533df938b1ed4596 | 43,985 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.