content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def test_db_transaction_n1(monkeypatch):
"""Raise _DB_TRANSACTION_ATTEMPTS OperationalErrors to force a reconnection.
A cursor for each SQL statement should be returned in the order
the statement were submitted.
0. The first statement execution produce no results _DB_TRANSACTION_ATTEMPTS times (Operat... | 4dcb32f14d8a938765f4fde5375b6b686a6a5f5c | 3,639,254 |
import requests
from datetime import datetime
def fetch_status():
"""
解析サイト<https://redive.estertion.win> からクラバト情報を取ってくる
return
----
```
{
"cb_start": datetime,
"cb_end": datetime,
"cb_days": int
}
```
"""
# クラバト開催情報取得
r = requests.get(
"htt... | 683c9fe84bf346a1cce703063da8683d3469ccc2 | 3,639,255 |
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post(uuid, tapi_path_computation_routing_constraint=None): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post
creates tapi.path.computation.RoutingConstraint # noqa: E501
:p... | 7d56e6a544b2ac720aa311127aa5db9b3153a0c3 | 3,639,256 |
def A004086(i: int) -> int:
"""Digit reversal of i."""
result = 0
while i > 0:
unit = i % 10
result = result * 10 + unit
i = i // 10
return result | b0a65b7e203b7a92f7d6a1846888798c369ac869 | 3,639,257 |
def should_raise_sequencingerror(wait, nrep, jump_to, goto, num_elms):
"""
Function to tell us whether a SequencingError should be raised
"""
if wait not in [0, 1]:
return True
if nrep not in range(0, 16384):
return True
if jump_to not in range(-1, num_elms+1):
return Tru... | fc7c4bdb29cd5b90faec59a4f6705b920304aae0 | 3,639,258 |
from typing import Optional
from typing import Mapping
import functools
def add_task_with_sentinels(
task_name: str,
num_sentinels: Optional[int] = 1):
"""Adds sentinels to the inputs/outputs of a task.
Adds num_sentinels sentinels to the end of 'inputs' and at the beginning
of 'targets'. This is known... | 2d040f37d4346770e836c5a8b71b90c1acce9d1d | 3,639,259 |
def mk_llfdi(data_id, data): # measurement group 10
"""
transforms a k-llfdi.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json... | 42717f4d182b3df60e27f213c36278c894597ded | 3,639,261 |
def valid_distro(x):
"""
Validates that arg is a Distro type, and has
:param x:
:return:
"""
if not isinstance(x, Distro):
return False
result = True
for required in ["arch", "variant"]:
val = getattr(x, required)
if not isinstance(val, str):
result =... | 8fc68700a4d024b7ba756c186225ef22622db584 | 3,639,262 |
def encode(message):
"""
Кодирует строку в соответсвие с таблицей азбуки Морзе
>>> encode('MAI-PYTHON-2020') # doctest: +SKIP
'-- .- .. -....-
.--. -.-- - .... --- -. -....-
..--- ----- ..--- -----'
>>> encode('SOS')
'...
---
...'
>>> encode('МАИ-ПИТОН-2020') # doctest: +ELLI... | efa312c510738f89608af0febff3435b17235eb8 | 3,639,264 |
def get_group_to_elasticsearch_processor():
"""
This processor adds users from xform submissions that come in to the User Index if they don't exist in HQ
"""
return ElasticProcessor(
elasticsearch=get_es_new(),
index_info=GROUP_INDEX_INFO,
) | 12e9371282298c96968263e76d1d02848fc5dcb3 | 3,639,265 |
import torch
def loss_function(recon_x, x, mu, logvar, flattened_image_size = 1024):
"""
from https://github.com/pytorch/examples/blob/master/vae/main.py
"""
BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, flattened_image_size), reduction='sum')
# see Appendix B from VAE paper:
... | 73abe5c0944f646b4c9240fdb80e17cabf83a22d | 3,639,266 |
def remove_poly(values, poly_fit=0):
"""
Calculates best fit polynomial and removes it from the record
"""
x = np.linspace(0, 1.0, len(values))
cofs = np.polyfit(x, values, poly_fit)
y_cor = 0 * x
for co in range(len(cofs)):
mods = x ** (poly_fit - co)
y_cor += cofs[co] * mo... | 3699dcd3cae6021a5f2a0b4cad08882a4383d09c | 3,639,267 |
def generate_per_host_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id):
"""Generates infeed enqueue ops for per-host input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
hooks = []
with ops.device(device):
user_context = tpu_context.TPU... | a632fac96d555d3ce21d75183c00c6e7627ba5ac | 3,639,268 |
def SogouNews(*args, **kwargs):
""" Defines SogouNews datasets.
The labels includes:
- 0 : Sports
- 1 : Finance
- 2 : Entertainment
- 3 : Automobile
- 4 : Technology
Create supervised learning dataset: SogouNews
Separately returns the tra... | e10eaf10ba6e999d40a40f09f7e79b47eb5aa8a5 | 3,639,270 |
def add_volume (activity_cluster_df,
activity_counts):
"""Scales log of session counts of each activity and merges into activities dataframe
Parameters
----------
activity_cluster_df : dataframe
Pandas dataframe of activities, skipgrams features, and cluster la... | 1ea67909e2c48500ca2f022a3ae5ebcbe28da6c8 | 3,639,271 |
def polyadd(c1, c2):
"""
Add one polynomial to another.
Returns the sum of two polynomials `c1` + `c2`. The arguments are
sequences of coefficients from lowest order term to highest, i.e.,
[1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
Parameters
----------
c1, c2 : array_lik... | 0dc8327abf94126fca5bbcc836bc1c404c92148e | 3,639,274 |
def weighted_categorical_crossentropy(target, output, n_classes = 3, axis = None, from_logits=False):
"""Categorical crossentropy between an output tensor and a target tensor.
Automatically computes the class weights from the target image and uses
them to weight the cross entropy
# Arguments
target: A tensor of ... | e7fe2c583b4158afe5c04632c53402af1c64cc20 | 3,639,275 |
from django.conf import settings
def get_config(key, default):
"""
Get the dictionary "IMPROVED_PERMISSIONS_SETTINGS"
from the settings module.
Return "default" if "key" is not present in
the dictionary.
"""
config_dict = getattr(settings, 'IMPROVED_PERMISSIONS_SETTINGS', None)
if con... | 8e4d03b71f568e6c3450e6674d16624ae44181a8 | 3,639,276 |
def prefetched_iterator(query, chunk_size=2000):
"""
This is a prefetch_related-safe version of what iterator() should do.
It will sort and batch on the default django primary key
Args:
query (QuerySet): the django queryset to iterate
chunk_size (int): the size of each chunk to fetch
... | e8a8feeea8073161283018f19de742c9425e2f94 | 3,639,278 |
def dicom_strfname( names: tuple) -> str:
"""
doe john s -> dicome name (DOE^JOHN^S)
"""
return "^".join(names) | 864ad0d4c70c9bb4acbc65c92bf83a97415b9d35 | 3,639,280 |
import json
def plot_new_data(logger):
"""
Plots mixing ratio data, creating plot files and queueing the files for upload.
This will plot data, regardless of if there's any new data since it's not run continously.
:param logger: logging logger to record to
:return: bool, True if ran corrected, F... | 186b11d496c8b1097087f451e43d235b40d7a2ba | 3,639,281 |
def plot_graphs(graphs=compute_graphs()):
""" Affiche les graphes avec la bibliothèque networkx """
GF, Gf = graphs
pos = {1: (2, 1), 2: (4, 1), 3: (5, 2), 4: (4, 3), 5: (1, 3), 6: (1, 2), 7: (3, 4)}
plt.figure(1)
nx.draw_networkx_nodes(GF, pos, node_size=500)
nx.draw_networkx_labels(GF, pos)... | 4db21b3f5a823b5a7a17264a611435d2aa3825a4 | 3,639,282 |
def get_polygon_name(polygon):
"""Returns the name for a given polygon.
Since not all plygons store their name in the same field, we have to figure
out what type of polygon it is first, then reference the right field.
Args:
polygon: The polygon object to get the name from.
Returns:
The name for t... | da89efece12fbb27a5ceafef83b73ade392644cb | 3,639,283 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return redirect("/login")
# E... | 8699a3f0f162706c2e0a0ab9565b8b595cbb7574 | 3,639,284 |
from . import paval as pv
import configparser
def read_option(file_path, section, option, fallback=None):
"""
Parse config file and read out the value of a certain option.
"""
try:
# For details see the notice in the header
pv.path(file_path, "config", True, True)
pv.strin... | 6a9b839e36509630813c3cab5e45402b37377837 | 3,639,285 |
import json
def msg_to_json(msg: Msg) -> json.Data:
"""Convert message to json serializable data"""
return {'facility': msg.facility.name,
'severity': msg.severity.name,
'version': msg.version,
'timestamp': msg.timestamp,
'hostname': msg.hostname,
'a... | ee01821bdbcdcbe88f5c63f0a1f22d050814aa7f | 3,639,287 |
def get_direct_dependencies(definitions_by_node: Definitions, node: Node) -> Nodes:
"""Get direct dependencies of a node"""
dependencies = set([node])
def traverse_definition(definition: Definition):
"""Traverses a definition and adds them to the dependencies"""
for dependency in definition... | 6dfbfd9068ecc3759764b3542be62f270c45e4c1 | 3,639,288 |
def get_timeseries_metadata(request, file_type_id, series_id, resource_mode):
"""
Gets metadata html for the aggregation type (logical file type)
:param request:
:param file_type_id: id of the aggregation (logical file) object for which metadata in html
format is needed
:param series_id: if of ... | 056707f6bd1947dd227c61dccb99b4f9d46ce9c9 | 3,639,289 |
def standardize(tag):
"""Put an order-numbering ID3 tag into our standard form.
This function does nothing when applied to a non-order-numbering tag.
Args:
tag: A mutagen ID3 tag, which is modified in-place.
Returns:
A 2-tuple with the decoded version of the order string.
raises:
... | 66edb2f402e2781deaf39ae470b5f3c54411c1c3 | 3,639,290 |
def _count_objects(osm_pbf):
"""Count objects of each type in an .osm.pbf file."""
p = run(["osmium", "fileinfo", "-e", osm_pbf], stdout=PIPE, stderr=DEVNULL)
fileinfo = p.stdout.decode()
n_objects = {"nodes": 0, "ways": 0, "relations": 0}
for line in fileinfo.split("\n"):
for obj in n_objec... | f3792b457e3cc922b6df3cef69dfb4c8d00c68d9 | 3,639,291 |
def combine_multi_uncertainty(unc_lst):
"""Combines Uncertainty Values From More Than Two Sources"""
ur = 0
for i in range(len(unc_lst)):
ur += unc_lst[i] ** 2
ur = np.sqrt(float(ur))
return ur | 6f06afc7bda7d65b8534e7294411dbe5e499b755 | 3,639,292 |
def export_performance_df(
dataframe: pd.DataFrame, rule_name: str = None, second_df: pd.DataFrame = None, relationship: str = None
) -> pd.DataFrame:
"""
Function used to calculate portfolio performance for data after calculating a trading signal/rule and relationship.
"""
if rule_name is not None:... | e0587a658aab2e629bff7c307e5f1aaec63a80fe | 3,639,293 |
def attention(x, scope, n_head, n_timesteps):
"""
perform multi-head qkv dot-product attention and linear project result
"""
n_state = x.shape[-1].value
with tf.variable_scope(scope):
queries = conv1d(x, 'q', n_state)
keys = conv1d(x, 'k', n_state)
values = conv1d(x, 'v',... | 63456ce40c4e72339638f460a8138dcd143e7352 | 3,639,294 |
def std_ver_minor_inst_valid_possible(std_ver_minor_uninst_valid_possible): # pylint: disable=redefined-outer-name
"""Return an instantiated IATI Version Number."""
return iati.Version(std_ver_minor_uninst_valid_possible) | 9570918df11a63faf194da9db82aa4ea1745c920 | 3,639,295 |
def sequence_loss_by_example(logits, targets, weights,
average_across_timesteps=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits (per example).
Args:
logits: List of 2D Tensors of shape [batch_size x n... | adf8a063c6f41b41e174852466489f535c7e0761 | 3,639,296 |
def skip(line):
"""Returns true if line is all whitespace or shebang."""
stripped = line.lstrip()
return stripped == '' or stripped.startswith('#!') | 4ecfb9c0f2d497d52cc9d9e772e75d042cc0bcce | 3,639,297 |
def get_dss_client(deployment_stage: str):
"""
Returns appropriate DSSClient for deployment_stage.
"""
dss_env = MATRIX_ENV_TO_DSS_ENV[deployment_stage]
if dss_env == "prod":
swagger_url = "https://dss.data.humancellatlas.org/v1/swagger.json"
else:
swagger_url = f"https://dss.{ds... | 4e260b37c6f74261362cc10b77b3b28d1464d49d | 3,639,298 |
def bounce_off(bounce_obj_rect: Rect, bounce_obj_speed,
hit_obj_rect: Rect, hit_obj_speed):
"""
The alternative version of `bounce_off_ip`. The function returns the result
instead of updating the value of `bounce_obj_rect` and `bounce_obj_speed`.
@return A tuple (`new_bounce_obj_rect`, `new_bounce_... | 84b038c05f5820065293ba90b73497f0d1e7a7b9 | 3,639,299 |
def second(lst):
"""Same as first(nxt(lst)).
"""
return first(nxt(lst)) | aa49e089a06a4b3e7d781966d8b4f98b7fe15841 | 3,639,301 |
def gaussian_noise(height, width):
"""
Create a background with Gaussian noise (to mimic paper)
"""
# We create an all white image
image = np.ones((height, width)) * 255
# We add gaussian noise
cv2.randn(image, 235, 10)
return Image.fromarray(image).convert("RGBA") | 6243fde57b3e7415edc2024eebbe10f059b93a55 | 3,639,302 |
def draw_box(image, box, color):
"""Draw 3-pixel width bounding boxes on the given image array.
color: list of 3 int values for RGB.
"""
y1, x1, y2, x2 = box
image[y1:y1 + 1, x1:x2] = color
image[y2:y2 + 1, x1:(x2+1)] = color
image[y1:y2, x1:x1 + 1] = color
image[y1:y2, x2:x2 + 1] = colo... | 4d1e713c6cb6a3297b4f7d8ab9682205947770da | 3,639,303 |
def get_statuses_one_page(weibo_client, max_id=None):
"""获取一页发布的微博
"""
if max_id:
statuses = weibo_client.statuses.user_timeline.get(max_id=max_id)
else:
statuses = weibo_client.statuses.user_timeline.get()
return statuses | 4a214489aa5696c9683c9cfa96d79ee169135eb5 | 3,639,304 |
def do_nothing(ax):
"""Do not add any watermark."""
return ax | 6fbe32dc45ca1a945e1c45bf0319770c4d683397 | 3,639,305 |
def exec_lm_pipe(taskstr):
"""
Input: taskstr contains LM calls separated by ;
Used for execute config callback parameters (IRQs and BootHook)
"""
try:
# Handle config default empty value (do nothing)
if taskstr.startswith('n/a'):
return True
# Execute individual ... | 8854b5de0f408caf9292aecbcfa261744166e744 | 3,639,306 |
def term_size():
"""Print out a sequence of ANSI escape code which will report back the
size of the window.
"""
# ESC 7 - Save cursor position
# ESC 8 - Restore cursor position
# ESC [r - Enable scrolling for entire display
# ESC [row;colH - Move to cursor position
... | bc0b09163b48f821315f52c52b0a58b6b5fb977a | 3,639,307 |
def get_dashboard(request, project_id):
"""
Load Project Dashboard to display Latest Cost Estimate and List of Changes
"""
project = get_object_or_404(Project, id=project_id)
# required to determine permission of user,
# if not a project user then project owner
try:
project_user = P... | 36257741b2ef220d35e4593bd080a82b4cc743a0 | 3,639,308 |
def _scan_real_end_loop(bytecode, setuploop_inst):
"""Find the end of loop.
Return the instruction offset.
"""
start = setuploop_inst.next
end = start + setuploop_inst.arg
offset = start
depth = 0
while offset < end:
inst = bytecode[offset]
depth += inst.block_effect
... | 9cff8ab77563a871b86cdbb14236603ec58e04b6 | 3,639,309 |
def six_node_range_5_to_0_bst():
"""Six nodes covering range five to zero."""
b = BST([5, 4, 3, 2, 1, 0])
return b | 1afe6c613b03def6dc9d8aed41624e40180e5ae5 | 3,639,310 |
def IndividualsInAlphabeticOrder(filename):
"""Checks if the names are in alphabetic order"""
with open(filename, 'r') as f:
lines = f.readlines()
individual_header = '# Individuals:\n'
if individual_header in lines:
individual_authors = lines[lines.index(individual_header) + 1:]
sorted_auth... | 4753bbf41498373695f921555c8f01183dbb58dc | 3,639,311 |
import mxnet
from mxnet.gluon.data.vision import transforms
from PIL import Image
def preprocess_img_imagenet(img_path):
"""Preprocessing required for ImageNet classification.
Reference:
https://github.com/onnx/models/tree/master/vision/classification/vgg
"""
img = Image.open(img_path)
img ... | f181e3376f26ee14c6314a8a730e796eefb09e2e | 3,639,312 |
def create_lambertian(color):
"""
create a lambertion material
"""
material = bpy.data.materials.new(name="Lambertian")
material.use_nodes = True
nodes = material.node_tree.nodes
# remove principled
material.node_tree.nodes.remove(
material.node_tree.nodes.get('Principled BSDF')... | e291817853ec26d6767d8fd496ee5ced15ff87f2 | 3,639,313 |
def submission_view(request, locker_id, submission_id):
"""Displays an individual submission"""
submission = get_object_or_404(Submission, pk=submission_id)
newer = submission.newer()
newest = Submission.objects.newest(submission.locker)
if not newest:
newest = submission
oldest = Submis... | f473c7ad2c59dfd27a96fa4478f6b9652e740296 | 3,639,314 |
from pathlib import Path
def add_filename_suffix(file_path: str, suffix: str) -> str:
"""
Append a suffix at the filename (before the extension).
Args:
path: pathlib.Path The actual path object we would like to add a suffix
suffix: The suffix to add
Returns: path with suffix appended a... | 546bb95f694ee5d5cb26873428fcac8453df6a54 | 3,639,315 |
def list_dropdownTS(dic_df):
"""
input a dictionary containing what variables to use, and how to clean
the variables
It outputs a list with the possible pair solutions.
This function will populate a dropdown menu in the eventHandler function
"""
l_choice = []
for key_cat, value_cat in d... | fcd0474fa6941438cb39c63aa7605f1b776fd538 | 3,639,316 |
import itertools
import random
def get_voice_combinations(**kwargs):
"""
Gets k possible combinations of voices from a list of voice indexes. If k is None, it will return all possible
combinations. The combinations are of a minimum size min_n_voices_to_remove and a max size
max_n_voices_to_remove. Whe... | d3addbfe5023b5ee6e25f190c53b469593bb9ff4 | 3,639,317 |
def data(request):
"""This is a the main entry point to the Data tab."""
context = cache.get("data_tab_context")
if context is None:
context = data_context(request)
cache.set("data_tab_context", context, 29)
return render(request, "rundb/data/data.html", context) | 2763617afc7d865acaf3f0dcbf9190bd084ad5ae | 3,639,318 |
import typing
import pathlib
import pickle
def from_pickle(
filepath: typing.Union[str, pathlib.Path, typing.IO[bytes]]
) -> typing.Union[Categorization, HierarchicalCategorization]:
"""De-serialize Categorization or HierarchicalCategorization from a file written by
to_pickle.
Note that this uses the... | e268f8c1467965bbba47c65ebba5f021171fc6ce | 3,639,320 |
def recostruct(encoded, weights, bias):
"""
Reconstructor : Encoded -> Original
Not Functional
"""
weights.reverse()
for i,item in enumerate(weights):
encoded = encoded @ item.eval() + bias[i].eval()
return encoded | e17aeb6a819a6eec745c5dd811460049fa4a92cd | 3,639,321 |
import math
def get_file_dataset_from_trixel_id(CatName,index,NfilesinHDF,Verbose=True):#get_file_var_from_htmid in Eran's library
"""Description: given a catalog basename and the index of a trixel and the number of trixels in an HDF5 file,
create the trixel dataset name
Input :- ... | b9d0482780ae2a191175f1549513f46c047bb1cf | 3,639,322 |
def calc_element_column(NH, fmineral, atom, mineral, d2g=0.009):
"""
Calculate the column density of an element for a particular NH value,
assuming a dust-to-gas ratio (d2g) and the fraction of dust in that
particular mineral species (fmineral)
"""
dust_mass = NH * mp * d2g * fmineral # g cm^{-... | d1e24602e6d329132d59f300543f306502867fc1 | 3,639,323 |
def output_dot(sieve, column_labels=None, max_edges=None, filename='structure.dot'):
""" A network representation of the structure in Graphviz format. Units in the produced file
are in bits. Weight is the mutual information and tc is the total correlation.
"""
print """Compile by installing graphviz... | aa63e5ffb0bd1544f29391821db9ac49e690e3fe | 3,639,324 |
def projectSimplex_vec(v):
""" project vector v onto the probability simplex
Parameter
---------
v: shape(nVars,)
input vector
Returns
-------
w: shape(nVars,)
projection of v onto the probability simplex
"""
nVars = v.shape[0]
mu = np.sort(v,kind='quicksort')[:... | ace378ed84c61e05e04fdad23e3d97127e63df3a | 3,639,325 |
from typing import Collection
from typing import List
from typing import Sized
def render_list(something: Collection, threshold: int, tab: str) -> List[str]:
"""
Разложить список или что то подобное
"""
i = 1
sub_storage = []
order = '{:0' + str(len(str(len(something)))) + 'd}'
for eleme... | a7eb47df956fc4404bae6e29e75b280cd2b70cba | 3,639,326 |
from typing import Optional
from typing import List
from typing import Tuple
def combine_result(
intent_metrics: IntentMetrics,
entity_metrics: EntityMetrics,
response_selection_metrics: ResponseSelectionMetrics,
interpreter: Interpreter,
data: TrainingData,
intent_results: Optional[List[Inten... | 86942bbb30fe86fcd8e3453e7ac661b97832ec1a | 3,639,327 |
import jobtracker
def get_fns_for_jobid(jobid):
"""Given a job ID number, return a list of that job's data files.
Input:
jobid: The ID number from the job-tracker DB to get files for.
Output:
fns: A list of data files associated with the job ID.
"""
query... | ab867ec7b86981bfd06caf219b77fbb9410277ad | 3,639,328 |
def linear_schedule(initial_value: float):
"""
Linear learning rate schedule.
:param initial_value: Initial learning rate.
:return: schedule that computes
current learning rate depending on remaining progress
"""
def func(progress_remaining: float) -> float:
"""
Progress w... | afb0c9f050081f7e84728051535a899d9ece43f3 | 3,639,329 |
def download(os_list, software_list, dst):
"""
按软件列表下载其他部分
"""
if os_list is None:
os_list = []
arch = get_arch(os_list)
LOG.info('software arch is {0}'.format(arch))
results = {'ok': [], 'failed': []}
no_mindspore_list = [software for software in software_list if "MindSpore" no... | 9def81d5c1f127cab08add62a16df35c2a9dbc80 | 3,639,330 |
import hashlib
def get_hash_bin(shard, salt=b"", size=0, offset=0):
"""Get the hash of the shard.
Args:
shard: A file like object representing the shard.
salt: Optional salt to add as a prefix before hashing.
Returns: Hex digetst of ripemd160(sha256(salt + shard)).
"""
shard.see... | 94c399d41b56598e4ecac3f0c2d917a226e9e9db | 3,639,331 |
def boltzmann_statistic(
properties: ArrayLike1D,
energies: ArrayLike1D,
temperature: float = 298.15,
statistic: str = "avg",
) -> float:
"""Compute Boltzmann statistic.
Args:
properties: Conformer properties
energies: Conformer energies (a.u.)
temperature: Temperature (... | 5c5ea2d9ff43e9e068856d73f1e6bdc1f53c42b0 | 3,639,332 |
def _check_n_pca_components(ica, _n_pca_comp, verbose=None):
"""Aux function"""
if isinstance(_n_pca_comp, float):
_n_pca_comp = ((ica.pca_explained_variance_ /
ica.pca_explained_variance_.sum()).cumsum()
<= _n_pca_comp).sum()
logger.info('Selected %... | 1295de84f6054cac3072e2ba861c291cf71fdb72 | 3,639,333 |
def model_fn():
"""
Renvoie un modèle Inception3 avec la couche supérieure supprimée et les poids pré-entraînés sur imagenet diffusés.
"""
model = InceptionV3(
include_top=False, # Couche softmax de classification supprimée
weights='imagenet', # Poids pré-entraînés sur Imagenet
# input... | 3ee68e9874025d94cc1d73cf4857fecf6241e415 | 3,639,335 |
def find_correspondance_date(index, csv_file):
"""
The method returns the dates reported in the csv_file for the i-subject
:param index: index corresponding to the subject analysed
:param csv_file: csv file where all the information are listed
:return date
"""
return csv_f... | 915b9a493247f04fc1f62e614bc26b6c342783c8 | 3,639,336 |
def get_config(object_config_id):
"""
Returns current and previous config
:param object_config_id:
:type object_config_id: int
:return: Current and previous config in dictionary format
:rtype: dict
"""
fields = ('config', 'attr', 'date', 'description')
try:
object_config = O... | 5eb31025494dbcf17890f3ed9e7165232db9e087 | 3,639,337 |
import unicodedata
def normalize_to_ascii(char):
"""Strip a character from its accent and encode it to ASCII"""
return unicodedata.normalize("NFKD", char).encode("ascii", "ignore").lower() | 592e59ae10bb8f9a04dffc55bcc2a1a3cefb5e7e | 3,639,338 |
def verify_certificate_chain(certificate, intermediates, trusted_certs, logger):
"""
:param certificate: cryptography.x509.Certificate
:param intermediates: list of cryptography.x509.Certificate
:param trusted_certs: list of cryptography.x509.Certificate
Verify that the certificate is valid, accord... | 5d96fa38f22a74ae270af3ab35fc90274ed487e0 | 3,639,339 |
import json
def update_strip_chart_data(_n_intervals, acq_state, chart_data_json_str,
samples_to_display_val, active_channels):
"""
A callback function to update the chart data stored in the chartData HTML
div element. The chartData element is used to store the existing data
... | 67902561bc4d0cec2a1ac2f8d385a2accf4c03e9 | 3,639,340 |
import uuid
def genuuid():
"""Generate a random UUID4 string."""
return str(uuid.uuid4()) | c664a9bd45f0c00dedf196bb09a09c6cfaf0d54b | 3,639,341 |
def watsons_f(DI1, DI2):
"""
calculates Watson's F statistic (equation 11.16 in Essentials text book).
Parameters
_________
DI1 : nested array of [Dec,Inc] pairs
DI2 : nested array of [Dec,Inc] pairs
Returns
_______
F : Watson's F
Fcrit : critical value from F table
"""
... | db1f6be50657f4721aac4f800b7896afcbd71db7 | 3,639,342 |
def encode(integer_symbol, bit_count):
""" Returns an updated version of the given symbol list with the given symbol encoded into binary.
- `symbol_list` - the list onto which to encode the value.
- `integer_symbol` - the integer value to be encoded.
- `bit_count` - the number of bits from ... | fe8fb04245c053bb4387b0ac594a778df5bce22c | 3,639,343 |
def superkick(update, context):
"""Superkick a member from all rooms by replying to one of their messages with the /superkick command."""
bot = context.bot
user_id = update.message.from_user.id
boot_id = update.message.reply_to_message.from_user.id
username = update.message.reply_to_message.from_use... | 2a6550bb533a51cc8ebb79ca7f5cdbd214af4a5a | 3,639,344 |
import typing
from datetime import datetime
def encrypt_session(
signer: typing.Type[Fernet],
session_id: str,
current_time: typing.Optional[typing.Union[int, datetime]] = None,
) -> str:
"""An utility for generating a token from the passed session id.
:param signer: an instance of a fernet obje... | 9d924dcbc0abdf8facb31e256c5c67ccca3850be | 3,639,345 |
def construct_chargelst(nsingle):
"""
Makes list of lists containing Lin indices of the states for given charge.
Parameters
----------
nsingle : int
Number of single particle states.
Returns
-------
chargelst : list of lists
chargelst[charge] gives a list of state indic... | e94044566d0acc7106d34d142ed3579226706a65 | 3,639,346 |
import json
def parse(json_string):
"""Constructs the Protocol from the JSON text."""
try:
json_data = json.loads(json_string)
except:
raise ProtocolParseException('Error parsing JSON: %s' % json_string)
# construct the Avro Protocol object
return make_avpr_object(json_data) | f95854e8c0b8e49ec71e03ee8487f88f4687ebf0 | 3,639,347 |
def get_architecture(model_config: dict, feature_config: FeatureConfig, file_io):
"""
Return the architecture operation based on the model_config YAML specified
"""
architecture_key = model_config.get("architecture_key")
if architecture_key == ArchitectureKey.DNN:
return DNN(model_config, fe... | a7c58770a07c225ae79a03699639e19498d3a0c6 | 3,639,349 |
def get_properties_dict(serialized_file: str, sparql_file: str, repository: str, endpoint: str, endpoint_type: str,
limit: int = 1000) -> ResourceDictionary:
"""
Return a ResourceDictionary with the list of properties in the ontology
:param serialized_file: The file where the propert... | 3a31bd8b23cb7a940c6386225dd39a302f3d3f3a | 3,639,350 |
def get_duplicate_sample_ids(taxonomy_ids):
"""Get duplicate sample IDs from the taxonomy table.
It happens that some sample IDs are associated with more than taxon. Which
means that the same sample is two different species. This is a data entry
error and should be removed. Conversely, having more than... | c01315d6d51ec8e62a0f510944d724a18949aeb8 | 3,639,351 |
def get_settings_text(poll):
"""Compile the options text for this poll."""
text = []
locale = poll.user.locale
text.append(i18n.t('settings.poll_type',
locale=locale,
poll_type=translate_poll_type(poll.poll_type, locale)))
text.append(i18n.t('settings.l... | 24ef467070324dac6a8c698b791a1fe577a5d928 | 3,639,352 |
import functools
def pass_none(func):
"""
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
"""
@functools.wraps(func)
def wrapper(param, *args, **kwargs):
if param is not None:
return func(param, *args, **kwargs)
... | 2264ca5978485d8fc13377d17eb84ee522a040b9 | 3,639,354 |
def create_values_key(key):
"""Creates secondary key representing sparse values associated with key."""
return '_'.join([key, VALUES_SUFFIX]) | e8a70bc4ef84a7a62a9d8b8d915b9ddbc0990429 | 3,639,355 |
def make_mask(variable, **flags):
"""
Return a mask array, based on provided flags
For example:
make_mask(pqa, cloud_acca=False, cloud_fmask=False, land_obs=True)
OR
make_mask(pqa, **GOOD_PIXEL_FLAGS)
where GOOD_PIXEL_FLAGS is a dict of flag_name to True/False
:param variable:
... | fcdd7247359b5127d14a906298e20a05fd63b108 | 3,639,356 |
def _normalize_block_comments(content: str) -> str:
"""Add // to the beginning of all lines inside a /* */ block"""
comment_partitions = _partition_block_comments(content)
normalized_partitions = []
for partition in comment_partitions:
if isinstance(partition, Comment):
comment = pa... | 76c2c1d0b80cf40f647033aa8745058f1546076e | 3,639,357 |
from datetime import datetime
def check_holidays(date_start, modified_end_date, holidays):
"""
Here app check if holidays in dates of vacation or not.
If Yes - add days to vacation, if Not - end date unchangeable
"""
# first end date for check loop because end date move +1 for every weekend
da... | c2b8145f9963cd2679e238c2c378535eea2e08db | 3,639,358 |
from typing import Optional
from pathlib import Path
import platform
def get_local_ffmpeg() -> Optional[Path]:
"""
Get local ffmpeg binary path.
### Returns
- Path to ffmpeg binary or None if not found.
"""
ffmpeg_path = Path(
get_spotdl_path(), "ffmpeg" + ".exe" if platform.system()... | 2495a1153da32f3ffb21075172cd0fb82b7809ea | 3,639,360 |
def _water_vapor_pressure_difference(temp, wet_bulb_temp, vap_press, psych_const):
"""
Evaluate the psychrometric formula
e_l - (e_w - gamma * (T_a - T_w)).
Parameters
----------
temp : numeric
Air temperature (K).
wet_bulb_temp : numeric
Wet-bulb temperature (K).
... | cee814a44ae1736dc35f08984cdb15fe94576716 | 3,639,362 |
def _service_description_required(func):
"""
Decorator for checking whether the service description is available on a device's service.
"""
@wraps(func)
def wrapper(service, *args, **kwargs):
if service.description is None:
raise exceptions.NotRetrievedError('No service descrip... | 27b962616026ad3987d2c214138d903971e2461c | 3,639,363 |
def vector(*args):
"""
A single vector in any coordinate basis,
as a numpy array.
"""
return N.array(args) | 41da98ad36bff55fc4b71ce6b4e604262b2ecd1a | 3,639,364 |
def arcmin_to_deg(arcmin: float) -> float:
""" Convert arcmin to degree """
return arcmin / 60 | 9ef01181a319c0c48542ac57602bd7c17a7c1ced | 3,639,365 |
def soft_embedding_lookup(embedding, soft_ids):
"""Transforms soft ids (e.g., probability distribution over ids) into
embeddings, by mixing the embedding vectors with the soft weights.
Args:
embedding: A Tensor of shape `[num_classes] + embedding-dim` containing
the embedding vectors. E... | 4b831b8f23a226aac74c0bb3919e3c27bb57dc60 | 3,639,366 |
def param_11(i):
"""Returns parametrized Exp11Gate."""
return Exp11Gate(half_turns=i) | 5458c8a4e992bd38dbb114e9ae4c4bac8a86fc75 | 3,639,367 |
def resolve_link(db: Redis[bytes], address: hash_t) -> hash_t:
"""Resolve any link recursively."""
key = join(ARTEFACTS, address, "links_to")
link = db.get(key)
if link is None:
return address
else:
out = hash_t(link.decode())
return resolve_link(db, out) | b8087b2d015fc4b8515c35e437e609a935ccfcb2 | 3,639,368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.