content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _date_index(config):
"""Returns a pandas.DatetimeIndex for the given config, based on the values of
the options daily, monthly, year, month, day, dayofyear, latest, all, and
median.
For a median config, the base index is a single leap year; otherwise, the
base index is a date index from the beg... | 6ac045bfd5c977414ecdb76795c06c477cf680df | 41,100 |
import os
import warnings
def get_key(dotenv_path, key_to_get):
"""
Gets the value of a given key from the given .env
If the .env path given doesn't exist, fails
"""
key_to_get = str(key_to_get)
if not os.path.exists(dotenv_path):
warnings.warn("can't read %s - it doesn't exist." % do... | f4828cd60b406f8df1f5e1ab3e7a1b4acc561dbf | 41,101 |
def secret_exponent_to_wif(secret_exp, compressed=True, is_test=False):
"""Convert a secret exponent (correspdong to a private key) to WIF format."""
d = private_byte_prefix(is_test) + to_bytes_32(secret_exp)
if compressed: d += b'\01'
return b2a_hashed_base58(d) | 8ac254b3dd650ab26d5be2ea0c889bba7cf930c7 | 41,102 |
def create_host(ec2_conn, ipa_client, image_id, count, domain,
secgroup_ids, instance_type, subnet, disk,
instance_vars, role=None, instance_profile=None,
hostgroups=None, hostname=None, ip_address=None,
eni=None, key=None, tags=None, spot=False,
... | 3d2147940ad4f9023fe7b59f27aed8dd0f300324 | 41,103 |
import os
def extractAll(fname, notwilight=True):
""" extra data on all exposures from surveysim output
no cosmics split adds 20% to margin
total BGS time: 2839 hours
total BGS minus twilight: 2372
assuming 7.5 deg^2 per field
assumiong 68% open-dome fraction
"""
total_hours = 2839
... | 8492b885723ad2b9bb318838890cba156605d822 | 41,104 |
def check_new_labels_var(self, labels_df):
"""Check the new annotations labels, then set the labels_df index"""
if labels_df is None or labels_df.empty:
return
labels_df.index = self.get_var_index()
if labels_df.index.name is None:
labels_df.index.name = "index"
# all labels must h... | 600945f3049569417b9493e1e370e3e8ac4191dd | 41,105 |
def ajax_delete_widget(request):
""" Delete single widget """
if request.is_ajax():
if request.method == 'POST':
widget_id = request.POST.get('widget_id', 0)
if widget_id:
delete_widget(widget_id)
return HttpResponse(simplejson.dumps({'status':'succes... | d62fd59849c324f824f6c1acd4c0a8d222ffab13 | 41,106 |
from pathlib import Path
async def post_pack_response(repo_path: Path, pack_type: str) -> Response:
"""
Make the response for handling exchange pack responses,
uses 'BODY_TIMEOUT' for a timeout of a request.
A matching route should be: '/<repo_name>.git/<pack_type>'.
:param repo_path: Path t... | c5ed0b8635c2c4a1cb0fa4c5ea1188f627a47737 | 41,107 |
def api_login_view(request):
"""
Login a user based on some credentials.
POST with HTTPS: args that correspond to credentials passed to the authentication backends.
"""
if request.method != 'POST':
return render_error(request, __ERROR_NOT_ALLOWED, 405)
if not request.is_secure() and not... | daac02f70fd926fd0526a43eb43cf4b80eb69cd4 | 41,108 |
def get_geocoder_normalized_addr(address, addr_keys=ADDRESS_KEYS):
# type: (Union[Mapping, str], Optional[Sequence]) -> dict
"""Get geocoder normalized address parsed to dict with addr_keys.
:param address: string or dict-like containing address data
:param addr_keys: optional list of address keys. sta... | b0c97f01b12fd80865f6c9722778f2775508f845 | 41,109 |
from typing import Dict
from typing import Union
from typing import List
import csv
def _read_csv(filepath: str, kwargs: Dict) -> Union[List, Dict]:
"""See documentation of mpu.io.read."""
if "delimiter" not in kwargs:
kwargs["delimiter"] = ","
if "quotechar" not in kwargs:
kwargs["quotech... | dfc91fa4c9516a2f33d0e7d43124eaa78b434dc6 | 41,110 |
import torch
def bbox_iou(box1, box2, x1y1x2y2=True):
"""
计算IOU
"""
if not x1y1x2y2:
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, b... | e492d3d98629f926d5de1627b563c25a6a99404d | 41,111 |
import os
def tsdb_query(query, profile):
"""Perform a query using the tsdb commandline program. The query
argument to this function is used as the value of the tsdb -query
argument and the profile argument to this function is used as the
value of the tsdb -home argument."""
env = dict(os.environ)... | 09d6a1f6799b299a1bdfc790b72a9d59c2b94855 | 41,112 |
def points_extraction(images, nx, ny):
"""
perform the extraction of object points and image points
:param images: list of images
:param nx: the number of inside corners in x
:param ny: the number of inside corners in y
:return: object points, image points and retvalues
"""
# Arrays to ... | c03520814d5599f0794bcce99da55862c5f3c3ca | 41,113 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding `Profile` object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_avatar = Profile.objects.get(pk=instance.pk).avatar
except Profile... | f78b78e106effaa04b67c2d23aab95ac89eb0c83 | 41,114 |
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = User.query.filter_by(username=username).first()
return rv.user_id if rv else None | d0a096f72ed0175238fcbd5756f5f70b3ae8f990 | 41,115 |
def clean_toc(toc: str) -> str:
"""Each line in `toc` has 6 unnecessary spaces, so get rid of them"""
lines = toc.splitlines()
return "\n".join(line[6:] for line in lines) | 40a22200d04c12865e4bffae9cdd3bdc4ea827be | 41,116 |
def separate_means_and_sigma(O: np.ndarray, D: int):
"""
Retreive means and sigma from the outputted O matrix of
emission probabilities
"""
flat_sigma = O[D:]
assert len(flat_sigma) == D*(D + 1) // 2
return O[:D], flat_sigma | 73727c2884ddea1fcecfb3753a0757190ee2d573 | 41,117 |
import pickle
def pickle_load(file_path):
""" data = pickle_load(file_path)
Load data from a pickle dump file
inputs:
file_path: str, path of the pickle file
output:
data: python object
"""
with open(file_path, 'rb') as file_ptr:
data = pickle.load(file_ptr)
r... | c9112881facc7a6a135893168fa9abf63309b392 | 41,118 |
import json
async def account_add(request : VueRequest):
"""
添加用户的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
username = req... | 58773e7424a666142c0e01d45bef14602d3a9163 | 41,119 |
import socket
def port_available(port):
"""
Check is port sent available currently.
:return: {Tuple}
"""
status = False
error = {}
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
try:
s.bind(('0.0.0.0', port))
status = True
exce... | 9a9b6daf94d6515f4358db5f557ea4d967a8a048 | 41,120 |
def vtk_points_to_polyline(vtk_points):
"""
creates a polyline, creating lines along point path
:param vtk_points:
:return:
"""
lines = vtk.vtkCellArray()
for k in range(vtk_points.GetNumberOfPoints() - 1):
line = vtk.vtkLine()
line.GetPointIds().SetId(0, k)
line.Ge... | f89296565ffa01acacb033dca38bc7ba82cb2b29 | 41,121 |
def getLayerThicknesses(vessel):
"""returns a dataframe with thicknesses of each layer along the whole vessel"""
thicknesses = []
columns = ['lay{}_{:04.1f}'.format(i, angle) for i, angle in enumerate(getAnglesFromVessel(vessel))]
for layerNumber in range(vessel.getNumberOfLayers()):
vesselLayer... | 84a9e80045b9c3c23ef0d8121c7e95b5187259c5 | 41,122 |
from typing import List
def get_transcription_files_by_dataset(
dataset: str, transcription_folder: str
) -> List[str]:
"""return paths of transcriptions from the given data set and the path of all of transcriptions"""
train_set = get_data_list(f"splits/{dataset}")
transcription_train_set = list(
... | e2a32614995c92706139a0a2c9d385b97918fb2f | 41,123 |
def versiontuple(v):
"""Return the version as a tuple for easy comparison."""
return tuple(int(x) for x in v.split(".")) | 422d49818e2d6d34d0591c1c450d0c92b7fabc82 | 41,124 |
def validate_aliases(aliases):
"""Checks that each alias remains unique when converted to a valid filename."""
return len(set(get_valid_filename(s) for s in aliases)) == len(aliases) | fb866cfdc5c3f45c790468850a25aaa793659099 | 41,125 |
def apps(app_id=None):
"""Returns marathon apps together with corresponding tasks
:param str app_id: application id
"""
marathon_addresses = _addresses()
return _apps(marathon_addresses, app_id) | f99bd8ecdea5292a27e1092b4e5f64bea3e4102a | 41,126 |
import re
def find_checksum(s):
"""Accepts a manifest-style filename and returns the embedded
checksum string, or None if no such string could be found."""
m = re.search(r"\b([a-z0-9]{32})\b", s, flags=re.IGNORECASE)
md5 = m.group(1).lower() if m else None
return md5 | f0d9735833e257a3f133d2d51b01775e35408755 | 41,127 |
def data_null_check(df):
"""Prints out nulls of dataframe into a nice data frame format"""
if type(df) == pd.core.frame.DataFrame:
return df.isnull().sum() | 5d18797d032799af30dca27f73f52946417c909c | 41,128 |
def sum_up_nums(*nums):
"""(int or float) -> int or float
Adds up as many numbers(separate arguments) as the caller can supply.
Returns the sum of <*nums>
"""
cntr = 0 # Init sum zero
for num in nums:
cntr += num
return cntr | 8ed03f16d624ea24a90a20d42df30328b119edd7 | 41,129 |
from typing import Tuple
from typing import List
def _generate_random_example_for_one_session_and_one_marker(
rng: np.random.Generator,
) -> Tuple[List[EventMetaData], List[int]]:
"""Generates a random marker extraction result for a single session and marker.
Args:
rng: a random number generator
... | 4a770cd86de5ebab472492689f77ecc7d2e9dae3 | 41,130 |
def real_rowcol_in_hunk(hunk, relative_rowcol):
# type: (str, RowCol) -> Optional[RowCol]
"""Translate relative to absolute row, col pair"""
hunk_lines = split_hunk(hunk)
if not hunk_lines:
return None
row_in_hunk, col = relative_rowcol
# If the user is on the header line ('@@ ..') pre... | 72968d95a52129e657e2f6565a99b4dc66381e98 | 41,131 |
def load_mrs_rsrf_file( filename ):
"""
Reads RSRF parameters from binary FITS table.
"""
# Read the RSRF data from file
try:
hdulist = pyfits.open(filename)
fits_hdr_prim = hdulist[0].header
fits_hdr_ext = hdulist[1].header
#fitsdata = hdulist[1].data[0]
... | 6af68cdeb2cc525ff7678767f91cf49d127b6092 | 41,132 |
import json
def recipe(index):
"""
Return (GET) or delete (DELETE) one recipe
"""
try:
if request.method == 'GET':
return Response(
json.dumps(recipebook.recipes[index].to_json_dict()),
mimetype="application/json")
elif request.method... | 54787a5d0bdbec04ec76224090c41351e1b28ae0 | 41,133 |
def eval_numerical_gradient_blobs(f, inputs, output, h=1e-5):
"""
Compute numeric gradients for a function that operates on input
and output blobs.
We assume that f accepts several input blobs as arguments, followed by a blob
into which outputs will be written. For example, f might be called like this:
... | 6ce997d621df7915eb2f49ae747c0983ea7255e3 | 41,134 |
from re import S
def poly_half_gcdex(f, g, *symbols):
"""Half extended Euclidean algorithm.
Efficiently computes gcd(f, g) and one of the coefficients
in extended Euclidean algorithm. Formally, given univariate
polynomials f and g over an Euclidean domain, computes s
and h, such that... | 69c7c45480b0b59f32f89491fe3149959fbc2b90 | 41,135 |
def find_message(file_content):
"""Implmentation for Part 1."""
point_system = LightPointSystem(_parse_entry(entry)
for entry in file_content)
total_area = point_system.get_area()
seconds = 0
while True:
point_system.step_forward()
new_area = poin... | 6c25b2b6712bba70c68a717424a227041e137571 | 41,136 |
import collections
def get_convert_rgb_channels(channels_info):
"""Get first available RGB(A) group from channels info.
## Examples
```
# Ideal situation
channels_info: {
"R": ...,
"G": ...,
"B": ...,
"A": ...
}
```
Result will be `("R", "G", "B", "A")`... | b2764811c3b929c51a6b4e9f735163c8aeb4abca | 41,137 |
def create_choice(question, choice_text ):
"""
Creates a choice for question.
"""
return Choice.objects.create(question=question, choice_text=choice_text) | 6a5e91eebeb7b13d04fee392d614b848e465a8f6 | 41,138 |
def GenerateTests():
"""Generate all tests."""
filelist = []
ii = 0
for iTarget in range(len(_TARGETS)):
for iFilter in range(len(_FILTERS)):
for iFunc in range(len(_COMPARE_FUNCS)):
item = _TARGETS[iTarget] + '_' + _FILTERS[iFilter] + '_' + _COMPARE_FUNCS[iFunc]
filename = GenerateFil... | 27d462c5a5adc5c6a1255fa51f46f1e04d338a03 | 41,139 |
def get_expts(context, expts):
"""Takes an expts list and returns a space separated list of expts."""
return '"' + ' '.join([expt['name'] for expt in expts]) + '"' | 76cd216662a6f7a248b70351f79b52e3c47871aa | 41,140 |
from datetime import datetime
def to_timestamp(obj: datetime) -> int:
"""
秒值
"""
return int(obj.timestamp()) | df4ed5659c96887b7d2b56c82c6431281f39ed0d | 41,141 |
def make_model(model_type, dataset, from_logits=False):
"""Builds a model.
XXX: from_logits=True is incompatible with expected gradient length.
"""
model = MODELS[model_type](dataset, to_proba=not from_logits)
loss = keras.losses.CategoricalCrossentropy(from_logits=from_logits)
# XXX doesn't st... | 165331bd10e5842e7943a189fff26439064af7ad | 41,142 |
def create_filename(last_element):
"""
For a given file, returns its name without the extension.
:param last_element: str, file name
:return: str, file name without extension
"""
return last_element[:-4] | 3faaf647ed6e3c765321efb396b2806e7ef9ddf9 | 41,143 |
def ajax_popular_environment_external(request, form_acess, client):
"""
Method to call popular_environment_shared when use by external way
"""
return facade.popular_environment_shared(request, client) | 6d8922477162364f6b3725f7802dc80d57a21e99 | 41,144 |
def cyclic_learning_rate(learning_rate, global_step, max_lr, step_size=10,
mode='tri', name='CyclicLearningRate'):
""" This function varies the learning rate between the
minimum (learning_rate) and the maximum (max_lr).
It returns the decayed learning rate.
Parameters
-----... | 01447dd8979d480c1e36aca9f8842f4919e7bfd5 | 41,145 |
import yaml
def fetch_local_config(default, config=None):
"""
Returns the content of a yml config file as a hash
Parameters:
- default: default file name to look for
- config: override with this file name instead. (optional)
Note: the pattern of using config is intended to make using this with
OptionsP... | 41639c401c6d33940b6098abaef9b26086615f74 | 41,146 |
def detect_lang(text, hint_language=None, best_effort=False,
all_details=False, return_score=False,
logger=None):
"""
Detect language of the text using pycld2
Parameters
----------
text : string
Text to detect language for.
all_details : bool, optional
... | 3fce5f07fe3d50750a7f763f0b676dfb3113f168 | 41,147 |
import time
import os
def generateCropRowsLinesAll(cfgLinesGenerator):
"""
generateCropRowsLinesAll.
:param cfgLinesGenerator: (Array) config lines generator array.
:returns None: None.
"""
tilesDirName = cfgLinesGenerator[0]
meanAngleFitElipseContours = cfgLinesGenerator[1]
pixelSizeValu... | 89784f8e27fa20166cfbd97dc45871c458c4dc91 | 41,148 |
from typing import Union
def is_number(value: Union[int, str]) -> bool:
"""
Is thing a number
"""
return isinstance(value, int) or (isinstance(value, str) and value.isnumeric()) | e69de261a45398eb970c00e9a5997a615c6fc7e6 | 41,149 |
import psutil
def getCpuUsage():
"""Find and return CPU Usage
Returns:
int -- Cpu Usage
"""
cpuUsage = psutil.cpu_percent()
return int(cpuUsage) | 3e063117731c0810fbb9a4faafee4c7299e5e2c4 | 41,150 |
def e_step(sigma,X, mask_var, mask_samp,n_ul = 0):
"""
E step for MTL algorithm.
"""
n = X.shape[0]
n_tr = np.size(np.where(mask_samp == False)[0])-n_ul
mask_var_c = ((mask_var+1)%2).astype(bool)
mask_samp_c = ((mask_samp+1)%2).astype(bool)
if n_ul>0:
mask_samp_c[0:n_ul] =... | d324f082f7b8e491620246e524976c9567f982a7 | 41,151 |
import os
def chain_submission(gromosXX_bin_dir: str, in_imd_path: str, simSystem:Simulation_System,
out_dir_path: str, out_prefix: str,
chain_job_repetitions: int, slave_script: str,
job_submission_system: _SubmissionSystem, jobname: str, nmpi: int,
... | 4f0fe824ca5cd9e9ab06558f2aa791efbf55717e | 41,152 |
def composite_coordinates_dictionary(dictified_values):
"""A dictionnary will be populated (or updated) with values from the
'dictified_values' dictionnary
Parameters
----------
dictified_values :
A dictionary of Sentinel-1 values
coordinates_dictionary :
A dictionnary matching... | cd80fc6ddaa20669eb84380659272ecea92a678c | 41,153 |
def fruit_flow_through_fruit_development_stage(jth: int, number_Fruits, sum_canopy_t, last_24_canopy_t):
"""
Equation 9.31
number_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * fruit_flow_inhibition_rate * number_fruit_j
Returns: fruit flow through fruit development s... | f3a22ed089e9146c2cc05b1816a5806520936b43 | 41,154 |
def normalization(vector):
"""
Normalize scores in this vector
"""
x = vector[vector>0]
beta = x.quantile(0.9)
updated_vector = vector/beta
return updated_vector | dfe403e8ec73ca3fab5492ce42a6390f1963f840 | 41,155 |
def integer_repr(bin_str, fixed_width=False):
"""integer_repr(bin_str, fixed_width=False)
Converts a binary representation to its integer number.
Examples
--------
>>> integer_repr(b'11')
3
>>> integer_repr(b'-11')
-3
>>> integer_repr(b'0011')
3
The two's complement is re... | cb1906cba79bfc33e259666b9de05be8048bb47b | 41,156 |
def emu(Omh2, ns, s8, fR0, n, z):
"""Returns the emulator prediction of Boost in power spectrum, for a redshift between 0 < z < 49
Parameters
----------
Omh2: float
Physical matter density parameter (O_m h^2) in range [0.12, 0.15]. Here h = 0.67, a constant in the emulator design
ns: floa... | a622982145fdd28a6935203c8f485da7d7fa58a6 | 41,157 |
def lp_visual(lp: LP,
basic_sol: bool = True,
show_basis: bool = True,) -> plt.Figure:
"""Render a figure visualizing the geometry of an LP's feasible region.
Args:
lp (LP): LP whose feasible region is visualized.
basic_sol (bool): True if the entire BFS is shown. De... | a6e2643dfd598046524fe0c1db87dbdc09de186f | 41,158 |
def _cofactor(M, i, j, method="berkowitz"):
"""Calculate the cofactor of an element.
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
"lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matr... | 9b87fae84e5b37303d5a606ac333b1a9e976934d | 41,159 |
def separateResults(parallelResults, numThreads):
"""
Routine for separate each quality metric vector
Parameters
----------
parallelResults: A tuple of quality of metrics, return of performCalc
numThreads: 1D Numpy array
-------
Return:
A tuple of 3D Numpy Array
[itera... | a0ab4810291bd1841dff3d3425ea529fa7247f5a | 41,160 |
import os
import sqlite3
def get_default_db():
"""Get the default database for the crawler.
Returns:
DB API v2 compliant connection to the crawler's default database.
"""
parent_dir = os.path.dirname(os.path.realpath(__file__))
loc = os.path.join(parent_dir, 'articles.db')
return sqli... | 77c589ecb51379fff937c84579e8a30313352b29 | 41,161 |
def _add_path(root_path, relative_path):
"""Add another level to an LDAP path.
eg,
_add_path('LDAP://DC=gb,DC=vo,DC=local', "cn=Users")
=> "LDAP://cn=users,DC=gb,DC=vo,DC=local"
"""
protocol = u("LDAP://")
if relative_path.startswith(protocol):
return relative_path
... | ad03442214f1611617b6dd28b1cd319b7d0f805c | 41,162 |
def merge_scenarios_with_paths(scenarios):
"""
This will merge ScenarioWithPaths objects and return a ScenarioWithPaths
objects which has the power generation vectors from all scenarios as well
as the paths from all scenarios. We assume independence across the
scenarios.
Args:
scenarios... | 1daa4d428709f1e7c1956ad27888228abec45801 | 41,163 |
def adaptive_threshold(image: np.ndarray) -> np.ndarray:
"""
Wrapper for OpenCV's adaptive threshold algorithm.
Parameters
----------
image : numpy.ndarray
Image as numpy array
Returns
-------
numpy.ndarray
Binarized image using adaptive threshold.
Contribute
-... | fc716fd04a8ea2cdcbebeca7fc51a7987bc14a6b | 41,164 |
def quaternionInverse(*args):
"""
quaternionInverse(Quaternion pQua, Quaternion pQuaOut)
quaternionInverse(Quaternion pQua) -> Quaternion
"""
return _almath.quaternionInverse(*args) | ff90abd6931659a4a23b89f351e75d75fbe3f1ff | 41,165 |
import inspect
import itertools
import functools
def get_common_base(cls_list):
"""
Get the most derived common base class of classes in ``cls_list``.
"""
# MRO in which "object" will appear first
def rev_mro(cls):
return reversed(inspect.getmro(cls))
def common(cls1, cls2):
#... | a100f6259f773b0304fa67b7fd364ab4801db707 | 41,166 |
import os
def dispatch_repl_commands(command):
"""Execute system commands entered in the repl.
System commands are all commands starting with "!".
"""
if command.startswith('!'):
os.system(command[1:])
return True
return False | 96b7f7783c8579b2717fef2a160094bf2e7dc86e | 41,167 |
from operator import eq
def l_inverse(L, check=False, verbose=False):
"""invert L (lower triangular, 1 on diagonal)
"""
m, n = L.shape
assert m==n
L1 = identity(m)
# Work forwards
for i in range(m):
#u = L1[:, i]
assert L[i, i] == 1
for j in range(i+1, m):
... | a5daa3fe776c6bac75d56d818fbf3ab88e3be0c2 | 41,168 |
def simplify_numpy_dtype(dtype):
"""Given a numpy dtype, write out the type as string
Args:
dtype (numpy.dtype): Type
Returns:
(string) name as a simple string
"""
kind = dtype.kind
if kind == "b":
return "boolean"
elif kind == "i" or kind == "u":
return "in... | c2370b2a08e58c9614ca43e3f14864782eef4100 | 41,169 |
import time
import re
def model_predict(year, month, day, country, dev=DEV, verbose=True):
"""
make predictions
"""
## start timer for runtime
time_start = time.time()
## load data
datasets = engineer_features(training=False, dev=dev, verbose=verbose)
## load models
... | 6ef8d43f68003ce5e85a8c6a6ca4980f2c321f24 | 41,170 |
import json
def form2(req, key, slug):
"""
Show the bookmarklet form.
"""
s = good_session(key)
if not s:
return redirect('bookmarklet:form1', slug=slug)
data = json.loads(s.data)
scholar_url = data['scholar_url']
doi = data['doi']
event = OAEvent.objects.get(id=data['even... | 455c15831dcd17abdc6017997b403b9eaa621b2a | 41,171 |
def GetNetworkPerformanceConfig(args, client):
"""Get NetworkPerformanceConfig message for the instance."""
network_perf_args = getattr(args, 'network_performance_configs', [])
network_perf_configs = client.messages.NetworkPerformanceConfig()
for config in network_perf_args:
total_tier = config.get('total... | 2b2f0773fb01b7bbcda30af38d03ed845331f10c | 41,172 |
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001,
power=0.75, init_lr=0.001):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (1 + gamma * iter_num) ** (- power)
i = 0
for param_group in optimizer.param_groups:
param_g... | e3876633b34bc8e2135f9e8d82e64e8bba42a6da | 41,173 |
def OpenFace(openface_features, PID, EXP):
"""
Tidy up OpenFace features in pandas data.frame to be stored in sqlite
database:
- Participant and experiment identifiers are added as columns
- Underscores in column names are removed, because sqlite does not like
underscores in column names.
... | 684e74c159a3551e3fd6d9a80b134c2474759056 | 41,174 |
def auth(function):
"""Wrapper checking if the user is logged in."""
@wraps(function)
def wrapper(*args, **kwargs):
testing = app.config.get('TESTING')
if (session.get('users') and session.get('logged_in')) or testing:
return function(*args, **kwargs)
return redirect(FLOW... | 26bb3d97bbe56a632f4d97c5b45c87e2022a5719 | 41,175 |
def svd_solve(A, b=None, w_cut=1e-10):
"""
This function solves the system of equations Ax=b by calculating the
inverse of A using the SVD method: x=A^(-1)*b; A^(-1)=V*S^(-1)*U'
Inputs:
A: 2D array of dimensions nxm (n>=m)
b: 1D array of dimensions n
w_cut: cut-off frequency for ... | fdf153836cba3ff5a618797505fbbb221fe29237 | 41,176 |
import re
def get_bootstrap_game(self, default_game='SamplesProject'):
"""
:param self: Context
:param default_game: Default game to set to if we cannot read bootstrap.cfg.
:return: Name of the game enabled in bootstrap.cfg
"""
game = default_game
project_folder_node = ge... | 0f58438de8cfe18dcab446b68d9c178df03c8c87 | 41,177 |
def check_issue(name, checks, controls):
"""
Checks if a certain RWT issue needs to be suggested.
Returns: list
"""
rwt = []
is_issue = False
total_reasons = []
total_offenders = []
for check in checks:
for control in controls:
if control != []:
f... | 7e16b5d7fe2e674a4e91ccec70ca6a5f47784c49 | 41,178 |
def create_training_instances(all_tokens, vocab_words, max_seq_length, rng):
"""Create `TrainingInstance`s from raw text."""
rng.shuffle(all_tokens)
instances = []
print('Process of "create_training_instances"')
for tokens in all_tokens:
instances.append(create_instances_from_sentence(token... | c94b588aa0a5b8d9c1a8dd9be203d62d6acbe060 | 41,179 |
def get_binary_result(probs):
"""
将预测结果转化为二分类结果
Args:
probs: 预测结果
Return:
binary_result: 二分类结果
"""
binary_result = []
for i in range(len(probs)):
if float(probs[i][0]) > 0.5:
binary_result.append(1)
elif float(probs[i][0]) < 0.5:
binary... | df0375b05abe2807a1568133f8ed0aa4a5fe3736 | 41,180 |
def _find_open_boundary_neighbors(neighbors, open_boundary_nodes):
"""Array of booleans that indicate if a neighbor is an open boundary."""
open_boundary_neighbors = neighbors[:, open_boundary_nodes]
is_open_boundary_neighbor = np.in1d(open_boundary_neighbors, open_boundary_nodes)
is_open_boundary_neigh... | a2705c964d11bda3d1784f5356f44090a1cf2e62 | 41,181 |
from datetime import datetime
def _boto3_now():
"""Get a ``datetime`` that's compatible with :py:mod:`boto3`.
These are always UTC time, with time zone ``dateutil.tz.tzutc()``.
"""
if tzutc is None:
raise ImportError(
'You must install dateutil to get boto3-compatible datetimes')
... | 509fdca72c6ceea1b3e2723d5446f41a8e72c9ec | 41,182 |
def pass_trigger(evt):
"""
# HLT_QuadJet40_IsoPFTau40
if (evt.run<165970 ) | ((evt.run>166782 & evt.run<171050)):
if evt.HLT_QuadJet40_IsoPFTau40 == 1:
return True
else:
return False
# HLT_QuadJet45_IsoPFTau45
elif ((evt.run>=165970) & (evt.run<=166782)) | ((... | cd64eae12ce723f29f77d89bb544024605c1e830 | 41,183 |
def ricker(t,ts,fsavg):
"""
Ricker Pulse
@param t time vector
@param ts temporal delay
@param fsavg pulse width parameter
@return Output signal vector
"""
a = fsavg*pi*(t-ts)
a2 = a*a
return ((1.0-2.0*a2)*np.exp(-a2)) | cf21218b114940dbfae2bc4d016757f0c83722a4 | 41,184 |
def read_avgint(dismod_file):
"""Read average integrand cases, translating to locations and covariates."""
avgint = dismod_file.avgint
with_integrand = avgint.assign(integrand=avgint.integrand_id.apply(lambda x: IntegrandEnum(x).name))
with_location = with_integrand.merge(dismod_file.node, on="node_id",... | 8964b5cf997b566d245aadbabef5ddf924ee74b6 | 41,185 |
def extendedMeasurementReport():
"""EXTENDED MEASUREMENT REPORT Section 9.1.52"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x36) # 00110110
c = ExtendedMeasurementResults()
packet = a / b / c
return packet | a08b6afa7fb60a800ee9ca9848d575ce2222c216 | 41,186 |
def part1(data):
"""
>>> part1(read_input())
6916
"""
twos = 0
threes = 0
for label in data:
if has_count(label, 2):
twos += 1
if has_count(label, 3):
threes += 1
return twos * threes | af4a5a5a971eafce264d4132b79df035c2153c38 | 41,187 |
def f_whist_jeu_real(request, record_id):
""" Saisie du réalisé 0 1 2 """
crudy = Crudy(request, APP_NAME)
obj = get_object_or_404(WhistJeu, id=record_id)
title = "Réalisé de %s" % (obj.participant.joueur.pseudo.upper())
if obj.pari > 1:
crudy.message = "**%s**, combien de plis as-tu réalisé... | d59a15550ce9539b97750f31e1db343f583033e2 | 41,188 |
def expected_min(x, m):
"""Compute unbiased estimator of expected ``min(x[1:m])`` on a data set.
Parameters
----------
x : :class:`numpy:numpy.ndarray` of shape (n,)
Data set we would like expected ``min(x[1:m])`` on. Require ``len(x) >= 1``.
m : `int` or :class:`numpy:numpy.ndarray` with d... | c0aef9a8123f625194665aec88b034adaa59ef49 | 41,189 |
def _load_transforms():
"""
Load the transform pairs into the module level variable for later lookup.
Returns
-------
:class:`dict`
"""
return {
f: (globals().get(f), globals().get("inverse_{}".format(f)))
for f in globals().keys()
if "inverse_{}".format(f) in global... | 45ef7c50aee54e6daa344809e603f7abf7bbe836 | 41,190 |
def scalarclip(polydata, arrayname, scalarvalue, insideout=True,
ispointdata=True):
"""Clip vtkPolyData returning regions with value of array above a
specified value."""
clipper = vtk.vtkClipPolyData()
clipper.SetInput(polydata)
if ispointdata: # array is pointdata
clipper.Se... | 912e5aaf1c911e61e39526f0e688f52fcfc4edd2 | 41,191 |
import copy
def deep_merge_dict(base, priority):
"""Recursively merges the two given dicts into a single dict.
Treating base as the the initial point of the resulting merged dict,
and considering the nested dictionaries as trees, they are merged os:
1. Every path to every leaf in priority would be re... | 5c527f45d4ddee00f1e905b09165bcd3551412f6 | 41,192 |
def class_oneshot(X, y, clmod, testsize = .2, randomstate=2342, score_method = 'AUC'):
"""
Store test measures from one-shot classification methods.
Input: design matrix, X,
response vector, y,
a classification model, clmod,
size of test set, testsize,
random num... | d9e0428f16c9f7abe5d3ef1fbf1c287b0610837e | 41,193 |
def _BuildUpgradeCandidateList(location_ref,
image_version_id,
python_version,
release_track=base.ReleaseTrack.GA):
"""Builds a list of eligible image version upgrades."""
image_version_service = image_version_api_util.Imag... | 46c6d2b753cba78cefe21d4f1e718c30dfa004e6 | 41,194 |
def pointer_gamut_visual_response():
"""
Returns a *Pointer's Gamut* visual response.
Returns
-------
Response
*Pointer's Gamut* visual response.
"""
args = request.args
json_data = pointer_gamut_visual(
colourspace_model=args.get('colourspaceModel', COLOURSPACE_MODEL),... | a6498ac6aa38ae559cfb5a98e3d671aa8ff5403d | 41,195 |
import string
def change(new_input):
"""Translate the string."""
new = '' # final translation
extras = 'efmnoprt' # multi instance cases
valid_non_letters = f'{string.punctuation} '
fail = 'Invalid input.'
count = 0 # number length count
i = 0 # index for iterating through message
... | 21386bc469dc46f34d854f941d4ba2b6942b4742 | 41,196 |
def max_pool(data_in, x, y):
"""Maxpool layer wrapper"""
return tf.nn.max_pool2d(data_in, ksize=[1, x, y, 1], strides=[1, x, y, 1], padding='SAME') | f2005362fe6b96eb74fd6a7d05b7e88d3acdfd75 | 41,197 |
def parse_proxy_line(line: bytes | bytearray) -> tuple[ProxyDict, int]:
"""
Parses the given line (string or sequence of bytes) for the client IP
and other fields passed through the proxy protocol.
This returns a tuple with elements as follows:
(1) Dictionary with the parsed IP addresses
(2) In... | c6d9664377721502bb7c6b6162a34048b087052d | 41,198 |
import tempfile
import uu
import time
import pathlib
def overhead():
"""Run a macrospin example for 1 ps through ``mumax3c`` and directly and
return the difference in run times.
Returns
-------
float
The time difference (overhead) between running mumax3 though ``mumax3c``
and directl... | 3b8a6575ee5021b62841e4f6acb282495efd3170 | 41,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.