content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read():
"""Return the contents of the Windows Common Setup as a string"""
setup_in = open(PATH)
try:
return setup_in.read()
finally:
setup_in.close() | 212044cb72fab10ef030c0d26c2298a16b178e7e | 3,622,781 |
from typing import List
def longest_subarray(numbers: List[int], limit: int) -> int:
"""https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/"""
# monotone increasing queue with indices that could become the sliding window minimum
min_queue = deque()
... | 42fc854fd2362d359d144c247b54403fde1eb9ee | 3,622,782 |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_eleme... | 0551462066eb984c796ef7ee08d640e9bc4373e5 | 3,622,783 |
import torch
def project_to_2d(X, camera_params):
"""
Project 3D points to 2D using the Human3.6M camera projection function.
This is a differentiable and batched reimplementation of the original MATLAB script.
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_para... | 0727efaeecfa48540590461f7d9222c8e6071f6d | 3,622,784 |
import csv
def read_header_keywords_table(filepath):
""" Read a table of .fits keywords from a .csv file into a
HeaderKeywordList of HeaderKeyword objects.
:param filepath: The location of the .csv file containing the header
keyword table.
:type filepath: str
"""
# Op... | 0a3385e30eed06fbc1df12929fe3002be0bd4b50 | 3,622,785 |
from typing import List
def exists(bucket: str, key: str) -> bool:
"""Checks if there is an object in the object store with the given key
Args:
bucket (dict): Bucket containing data
key (str): Prefix for key in object store
Returns:
bool: True if exists in store
"""
# Get ... | 3918bffc09f26e392566452a34f72fd6ab30b141 | 3,622,787 |
def format_element_to_matlab_confusion_matrix(row, col, confusion_matrix):
"""
Return a string for the element on row, col location for
confusion_matrix to either
number of observation\npercentage of observations or
percentage_correct_classifications\npercentage_incorrect_classifications
per cla... | 5cba4be1a70a88d28ac558cb9de24c4f2befdfdb | 3,622,788 |
def add_lazy_nh4_pm25(d, dict_sum):
"""Calculates sum of particulate NH4.
Parameters
----------
d : xarray.Dataset
RRFS-CMAQ model data
Returns
-------
xarray.Dataset
RRFS-CMAQ model data including new NH4 calculation
"""
keys = _get_keys(d)
allvars = Series(di... | c0e6b4853824a137b48e8d072ac2eaae693a817e | 3,622,789 |
def record(episode,
episode_reward,
worker_idx,
global_ep_reward,
total_loss,
num_steps):
"""Helper function to store score and print statistics.
Arguments:
episode: Current episode
episode_reward: Reward accumulated over the current episode
... | c767352be49b63e9be046e7df6eedaf03a8061ad | 3,622,790 |
from scipy.spatial import cKDTree
from scipy.stats import entropy
def transform_cav2im3d_entropy(cavity_coords, grid_min, grid_shape, pharmaco):
"""
Takes coordinates of grid points and outputs an im3d for skimage
Uses entropy at 3A of pharmacophores as values to set the "greyscale"
"""
# First we simply the ph... | f8305ed08620716286b064ebfab1cb3ede9c1c7d | 3,622,791 |
def _normalize_title(key: str) -> str:
"""MediaWiki treats the first character of article names as upper-case."""
if not key: # Empty string
return ""
key = _normalize_spaces(key)
return key[0].upper() + key[1:] | 1e542d82f0a72e13bbfe89b5b56f13c01c1cba5c | 3,622,792 |
def n_coeffs_to_degree(n_coeffs):
"""what is degree if 2d polynomial has n_coeffs coefficients"""
delta_sqrt = int((8 * n_coeffs + 1.)**.5 + 0.5)
if delta_sqrt**2 != (8*n_coeffs+1.):
raise ValueError('Wrong input in n_coeffs_to_degree(): {:}'.format(n_coeffs))
return int((delta_sqrt - 3.) / 2. +... | 29a767668579d7a9d7c9c871cdb3168c7db3c6c1 | 3,622,793 |
def load():
"""Loads settings static configuration.
As the configuration is static and immutable, it is loaded only once from the disk.
Returns an instance of the `Settings` class.
"""
global _SETTINGS
if _SETTINGS is not None:
return _SETTINGS
s = _load_yaml(SUBSTRA_TESTS_CONFIG_... | 8e3a6fc4301e0263ef2a927b6286d134bb5b84c7 | 3,622,794 |
def modinv(a, b):
""" Returns x such that (x * a) (mod b) == 1
reference: https://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python
"""
g, x, _ = egcd(a, b)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % b | 6372a204dbdd840cb4e4b1d6f8b73b2cdc286d88 | 3,622,795 |
def keygen():
"""
Generate private and public keys for the "greased", bootstrappable encryption scheme.
The main idea here is that we want to minimize computation during decryption because it originally contains
an expensive modulus operation (c % p) that is too much for our somewhat homomorphic en... | 76093133a20deecc680c7c7b38f2a1bf09d7c7e4 | 3,622,796 |
def process_image(image_path):
"""
Given a path to a file, pre-process that image in preparation for making a prediction.
:param image_path: the path to the image file
:return: the image represented by a flattened numpy array
"""
im_transforms = TRANSFORM_TEST_VALIDATION
# Open image
im = Image.open(image_path... | 5005b66fe99e09ff79435b71cf2be899212b292c | 3,622,797 |
import hashlib
def checksum_md5(filename, blocksize=8192):
"""Calculate md5sum.
Parameters
----------
filename : str or pathlib.Path
input filename.
blocksize : int
MD5 has 128-byte digest blocks (default: 8192 is 128x64).
Returns
-------
md5 : str
calculated ... | 759c0c5cbc37ebe0cc85eb8156127308eff354bc | 3,622,798 |
from pyunifi.controller import Controller, APIError
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Unifi Controller."""
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
site_id = config.get(CONF_SITE_ID)
... | e99d6090d5c365dd96d632e76fa01197bcdd72e7 | 3,622,799 |
def proxyobj(bus, path, interface):
""" commodity to apply an interface to a proxy object """
obj = bus.get_object('org.bluez', path)
return dbus.Interface(obj, interface) | c715ed2cca3672cf019eb61df719052616a70dc6 | 3,622,800 |
def get_create_idea():
"""
Renvoie la vue pour créer une nouvelle Idée
:return:
"""
user = User.query.filter_by(id=session['uid']).first()
return render_template(
'create_idea.html',
title='Proposez une nouvelle idée de projet',
data={'user': user}
) | 7b8c0172ff820589f0f71cc251d7b6de6866e85f | 3,622,801 |
def scale_size(range=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None,
format=None):
"""
Scale for size.
Parameters
----------
range : list
The range of the mapped aesthetics result.
name : str
The name of the scale - u... | 9dab561b80c960bd0b12f765cbd68366dffcbd22 | 3,622,802 |
def conv2d(input,
num_filters,
filter_size,
stride=1,
padding=0,
dilation=1,
groups=None,
param_attr=None,
bias_attr=None,
use_cudnn=True,
act=None,
name=None,
data_format="NCHW"):
"""... | 4b1ab3485258dda44dc75d0bb92325676847ea12 | 3,622,803 |
def modifies(repo, subset, x):
"""``modifies(pattern)``
Changesets modifying files matched by pattern.
The pattern without explicit kind like ``glob:`` is expected to be
relative to the current directory and match against a file or a
directory.
"""
# i18n: "modifies" is a keyword
pat = ... | 9e70f258dbbb22ef2ebdd9ba30176f2421005a92 | 3,622,804 |
def normalize_volume_and_number(volume, number):
"""
Padroniza os valores de `volume` e `number`
Args:
volume (None or str): volume se aplicável
number (None or str): número se aplicável
Notas:
- se `number` é igual a `ahead`, equivale a `None`
- se `00`, equivale a ... | 1ec42912b942f6c1b7e22d2e64c4d842af100877 | 3,622,805 |
def multi_scale_like_flow(image, flow_ms):
"""
:param image: [batch, height, width, 3]
:param flow_ms: list of [batch, numsrc, height/scale, width/scale, 1]
:return: image_ms: list of [batch, height/scale, width/scale, 3]
"""
image_ms = []
for i, flow in enumerate(flow_ms):
batch, nu... | f8ced57511fd777c3d3fe3620e16b94bea059743 | 3,622,807 |
def pd_xlabels():
"""Create a DataFrame which uses the column labels as x-data."""
df = pd.DataFrame({"B": np.random.randint(0, 100, size=100)})
return df | 924ba89f50f8bad8d4106164067f4af7f733f6f6 | 3,622,808 |
def rotate(X,a=0):
"""Rotate around the origin a 2d matrix X by angle a in degrees"""
a = np.deg2rad(a) # Convert degrees to radians
return np.dot(X, [[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) | 272add751ff36272bfb5721833d6db6fa65fbe0f | 3,622,809 |
def __prepare_postcoder(directory: PathLike):
"""
Create an instance of PostCoder
Parameters
----------
directory: PathLike
The postalcode file directory.
If the file (ken_all.zip) doesn't exist, download it.
"""
postcoder = PostCoder.get_instance(directory)
return postc... | 0f9813343731b3a579ef643b3c40e5135b1d2398 | 3,622,810 |
def CalculateTransitionSolventAccessibility(ProteinSequence):
"""
###############################################################################################
A method used for calculating Transition descriptors based on SolventAccessibility
of AADs.
Usage:
result=CalculateTransitionSolve... | 448dd28b407b33d1d37eb8d0bbce40420bfb99ba | 3,622,811 |
def sSEZtoECEF(station_ecef:AbstractArray, sez:AbstractArray, conversion:str="geodetic") -> np.ndarray:
"""Compute the coordinates of an object in the topocentric frame of an
Earth-fixed frame
Args:
station_ecef (np.ndarray): Earth-fixed Cartesian station coordinates
sez (np.ndarray): SEZ c... | 17c3f7c0c421b017ca85529ff278651bc7065093 | 3,622,812 |
from onnx.helper import make_node
def convert_max(node, **kwargs):
"""Map MXNet's max operator attributes to onnx's ReduceMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = str(attrs.get("axis", 'None'))
axes = convert_string_to_list(mx... | cc1a809d02cfe92d88c7972b244007d878da7627 | 3,622,813 |
def tanimoto_sml(queryism, targetism):
"""
Returns the Tanimoto similarity between the two molecules in SMILES format.
"""
# no Unicode here
querymol = MolFromSmiles(str(queryism))
targetmol = MolFromSmiles(str(targetism))
if querymol and targetmol:
queryfp = RDKFingerprint(querymol... | c44ecbc5604d2cea0fa1aa0b000e571b7705356f | 3,622,816 |
from typing import List
from typing import Tuple
def style_close(style: List[Tuple[str, str]]) -> str:
"""
HTML tags to close a style.
>>> style = [
... ("font", 'color="red" size="32"'),
... ("b", ""),
... ("i", ""),
... ("u", ""),
... ]
>>> style_close(style)
... | 2043803e50230f139a6a60599b40c53461ed6ed8 | 3,622,817 |
def get_theta_hat_bw_imd_cm1(theta_star_bw_std):
"""制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(℃)(27b-1)
Args:
theta_star_bw_std(float): 標準条件の沸き上げ温度(
Returns:
float: 制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(
"""
# 制御モードがファーストモードの場合
return theta_star_bw_std | caf43cc7c9e17417e3b0096fe89e4a02d41dc0e6 | 3,622,819 |
def crossGeneAvg(genea, geneb):
"""
A crossover startegy where the two genes are averaged, with no cut point
12347 => 33334
54321 33334
Parameters
----------
genea : 1D numpy array
An 1D numpy array of genes.
geneb : 1D numpy array
An 1D numpy... | 83c3307c440da1e42c47d6b924cba7f975dd4d40 | 3,622,821 |
def _oauth_url():
"""Creates the URL handling OAuth redirects."""
return url_for('oauth', _external=True) | 7adda3aa7edfe1bbad286824d1dabb5cbaddc2ac | 3,622,822 |
def join_as_guest():
"""
Generates Valid Token for Guest Users
"""
_uuid = security.create_guest_uuid()
access_token, expires = security.create_access_token(
subject=_uuid,
is_guest_user=True,
expires_delta=timedelta(hours=settings.ACCESS_GUEST_TOKEN_EXPIRE_HOURS)
)
r... | 2f9f783ce234feb8da1f3ab15fee1052258850fc | 3,622,823 |
import xml
def getServosFromURDF():
""" Get servo parameters from URDF. """
try:
description = rospy.get_param("robot_description")
robot = xml.dom.minidom.parseString(description).getElementsByTagName('robot')[0]
joints = {}
# Find all non-fixed joints
for child in rob... | 61bd443911ded11a47f08148784ebe8b158101ba | 3,622,824 |
def test_check_logs(monkeypatch):
"""
.
"""
log1 = Log(
revision1="abc123", message="foo", status="log", utc_unix_timestamp=1611608732
)
log2 = Log(
revision1="abc123",
message="bar",
status="success",
utc_unix_timestamp=1611608732,
)
db_file = ge... | 936cd9c2c0e76c9c4c99d6ebde3ad2b7ea6bc38e | 3,622,825 |
from typing import Sequence
from typing import Literal
from typing import Any
def spacegroup_sunburst(
spacegroups: Sequence[int] | pd.DataFrame,
sgp_col: str = None,
show_values: Literal["value", "percent", False] = False,
**kwargs: Any,
) -> Figure:
"""Generate a sunburst plot with crystal syste... | 0a422bfe6dd415edc70bb2a3e535f3bc1a4819cf | 3,622,827 |
def how_many_arrows(tcol):
"""Determines the number of colors that have arrows on them.
Args:
tcol (list): A 2D array of the labeling that contains the colors
and arrows for each site.
Returns:
arrows (int): The number of arrows in the system.
n_species (int): The number ... | bd42ee81d9a085eeae5f06afb6c93eec7764e37f | 3,622,828 |
import re
def CreateKwargHandler(endpoints, f):
"""
Create methods which contains kwargs
and return the remaining endpoints to handle
"""
index = 0
# endpoints = ["/v2/users", "/v2/users/:id"]
remainEndpoints = []
while index < len(endpoints) - 1:
firstMatches = re.fi... | a805b8c2b1c1593e973fa0ac781fa780fa4a6d1a | 3,622,829 |
def get_grid_cells_position(shapes, aspect_ratio=16/9., dim=None):
""" Constructs a XY-grid based on the cells content shape.
This function generates the coordinates of every grid cell. The width and
height of every cell correspond to the largest width and the largest height
respectively. The grid dime... | 953f6af6989ef6032d11973fa662e631ec4d5271 | 3,622,830 |
def _detect_start_end(true_values):
"""From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times.
"""
... | d486bf0309882c4e1e330525cda5972d43802bfe | 3,622,831 |
def pow_many(power, *args):
"""
Функция складывает любое количество цифр и возводит результат в степень power (примеры использования ниже)
:param power: степень
:param args: любое количество цифр
:return: результат вычисления # True -> (1 + 2)**1
"""
rs = 0
for v in args:
rs +=... | da0404f24045f5818ffb2219153fccd9b864965b | 3,622,833 |
def register(request):
"""Summit registration form view
"""
class SummitForm(ModelForm):
class Meta:
model = SummitRegistration
SummitForm.base_fields['email'].label = 'Email address'
SummitForm.base_fields['phone'].label = 'Phone number'
SummitForm.base_fields['address'].l... | 11b3b774418f55be09132082d87a697b1c650cfd | 3,622,834 |
def _d_serialize_delper_switch_field(context, self, field, d_switch_variable, prefix):
"""
handle switch by calling _serialize() or _unpack(), depending on context
"""
# switch is handled by this function as a special case
param_fields, wire_fields, params = get_serialize_params(context, self)
f... | 632588f5b095496a7429a7c0b601adc3159a7744 | 3,622,835 |
import json
def generate_empty_conf_dict():
"""Generates an empty dictionary according to the conference template."""
with open(str(current_path) + "/confcrawler/ressources/conference_template.json", "r") as template:
return json.load(template) | a886ae77c42b55eaead3d68d990a98b0f6d411dc | 3,622,836 |
def lighr_head_model_fn(features, labels, mode, params):
"""Our model_fn for ResNet to be used with our Estimator."""
num_anchors_list = labels['num_anchors_list']
num_feature_layers = len(num_anchors_list)
shape = labels['targets'][-1]
if mode != tf.estimator.ModeKeys.TRAIN:
org_image = la... | 158f0263ee0221e806c9add2e3119e7cf543d085 | 3,622,837 |
def gaussianMI(x, y, constellation, M, dtype=tf.float64):
"""
Computes mutual information with Gaussian auxiliary channel assumption and constellation with uniform porbability distribution
x: (1, N), N normalized complex samples at the transmitter, where N is the batchSize/sampleSize
y: (1,... | e89ee7c36d19f1ae8e3e8ff66bd0d7d605976204 | 3,622,838 |
from datetime import datetime
def efun_get_jwt(mud: str, file: str) -> str:
"""
SYNOPSIS
string get_jwt(string mudname, string filename)
DESCRIPTION
Returns a JSON Web Token for accessing mudlib files
from the web.
This efun is only allowed to be called fr... | 0cd30ad2d3d14bd4ee6ce461a29cc0a0b2559a89 | 3,622,839 |
from bs4 import BeautifulSoup
import requests
def get_book_list():
"""Store information about the books in a list"""
wishlist = send_wishlist_request(f"https://www.bookdepository.com/wishlists/{WISH_LIST_CODE}")
if wishlist:
soup = BeautifulSoup(wishlist.content, "html.parser")
if not ver... | e6eb72c6687e852f4cc76c607c98cc10a12b62ad | 3,622,840 |
import shutil
def gunzip_merge(outfile, list_files):
"""
Merge gunzip files into final file
:param outfile: String for output file
:param list_files: List of files to merge
:type outfile: string
:type list_files: list
"""
list_files = list(list_files)
list_files.sort()
print ("\tMerging files into: "... | ae37753cc1f16d9fc4cb4cf50587e99ef045a938 | 3,622,841 |
def parse_id(method):
"""
Ensures the input experiment identifier is an experiment UUID string
Parameters
----------
method : function
An ONE method whose second arg is an experiment ID
Returns
-------
function
A wrapper function that parses the ID to the expected strin... | 94e3473b1cc5afa6278a1baba8d9849ff8f6b938 | 3,622,842 |
def shuffel_data(x, y, seed=None):
"""Random shuffle of the data"""
if seed:
np.random.seed(seed)
index = np.arange(x.shape[0])
np.random.shuffle(index)
return x[index], y[index] | 187100fc1b83ec78fca1f8912781aae75fdf4a6e | 3,622,843 |
def font_face(psname):
"""Return a Face tuple given a psname"""
fam = LIBRARY.parent_fam(psname)
for face in LIBRARY.list_fam(fam):
if face.psname == psname:
return face
notfound = 'Font: no matches for Postscript name "%s"'%basis
raise DeviceError(notfound) | b23421b33f565cc86c3ad22b395af707ca3e6f2b | 3,622,844 |
def modularity_density(
graph: nx.Graph, communities: object, lmbd: float = 0.5, **kwargs: dict
) -> object:
"""The modularity density is one of several propositions that envisioned to palliate the resolution limit issue of modularity based measures.
The idea of this metric is to include the information abo... | 085dfe9d03f92d98771521d07ecffb996b477461 | 3,622,846 |
def get_media_pool_clip_list_and_clip_name_list(project):
"""
Parametes
---------
project : Project
a Project instance
Returns
-------
clip_return_list : list
clip list
clip_name_list : list
clip name list
Examples
--------
>>> resolve, project_manag... | f69a67d1ae29e714bf8c153519b515238a93875d | 3,622,847 |
def get_instances():
"""returns array of instance names, array of corresponding n"""
data = np.genfromtxt('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str)
return data[:, 0], data[:, 1].astype(int) | 0d9d91d7b50d5c27be6ac77dff5aff6743e796bd | 3,622,848 |
def stac_catalogs_item(catalogs, item_id):
"""Fetch catalog's single features
---
tags:
- Data
description: |-
Fetch the feature with id `featureId` in the given catalog provided.
with `catalogs`.
parameters:
- name: catalogs
in: path
required: true
... | 90e7fda5481cb5cdc2b94d9165ead80b6c0a754b | 3,622,850 |
import zipfile
def _generate_zip_package(target, sources, sources_dir):
"""Generate a zip archive containing all of the source files. """
zip = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED)
manifest = _archive_package_sources(zip.write, sources, sources_dir)
zip.writestr(_PACKAGE_MANIFEST, '\n'.j... | fd16ea1ef48a37721e52d48cc5a9cd4eb8fc5cb0 | 3,622,852 |
from typing import List
import re
def match_phrases(phrases: List[str]):
"""
Compiles multiple phrases into a single predicate function that returns True if the input contain any of the
phrases surrounded by word boundaries.
"""
# escape regex metacharacters and ignore repeated whitespace in multi... | 0f1fb616060723285a124966b15fcc76659b363c | 3,622,853 |
def get_payment_request_with_payment_method(business_identifier: str = 'CP0001234', payment_method: str = 'CC'):
"""Return a payment request object."""
return {
'paymentInfo': {
'methodOfPayment': payment_method
},
'businessInfo': {
'businessIdentifier': business_... | c506f2750e0ffe5d1852116eab241e7e022d3b84 | 3,622,854 |
def empty_framework_version_warning(default_version, latest_version):
"""
Args:
default_version:
latest_version:
"""
msgs = [EMPTY_FRAMEWORK_VERSION_WARNING.format(default_version)]
if default_version != latest_version:
msgs.append(LATER_FRAMEWORK_VERSION_WARNING.format(lates... | d78f74087fe97b409b61d74bd26afc80749e6a79 | 3,622,855 |
def AddIamPolicyBinding(content_ref, member, role):
"""Adds iam policy binding request."""
policy = GetIamPolicy(content_ref)
iam_util.AddBindingToIamPolicy(
dataplex_api.GetMessageModule().GoogleIamV1Binding, policy, member, role)
return SetIamPolicy(content_ref, policy) | c135bd54654abcec1c95b995df0f1c09d3ca2805 | 3,622,856 |
def getLevelName(lvl):
"""
Return the textual representation of printing level 'lvl'. If the level is
one of the predefined levels (JOB, IMPORTANT, TERSE, NORMAL, VERBOSE) then
you get the corresponding string. If you have associated levels with names
using addLevelName then the name you have associ... | 9b60cefa53d6be0a0f40b456e569ad4df7babad8 | 3,622,857 |
def CIFAR100Config(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:return: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.ht... | 958052bf1db9b2f7a245f02a57832fa165fa1b4d | 3,622,858 |
def _get_cycle_factor_traversal(factor_size, num_frames):
"""
Cycles through the state space in a single cycle.
eg. num_indices=5, num_frames=7 returns: [0,1,3,4,3,2,1]
eg. num_indices=4, num_frames=7 returns: [0,1,2,3,2,2,0]
"""
grid = _get_interval_factor_traversal(factor_size=factor_size, num... | 5048d7d20a40b3d786dc9234735f9e5939ed0ba2 | 3,622,859 |
def get_links(text):
"""Extract all kind of links from text.
Ordanaty get arxivs, dois and urls from text.
Link of type doi and arxiv will never have same link,
but when extract urls, all of returned links will be
checked to ensure no repeat links.
Parameters
----------
text : text tha... | 10657f1cbe86f107df3c5f579df398777dd5f99b | 3,622,860 |
from typing import Optional
from typing import List
from enum import Enum
async def find_enums_by_topic(
topic_id: Optional[TopicId], principal_service: PrincipalService = Depends(get_console_principal)
) -> List[Enum]:
"""
find enumerations by given topic
"""
if is_blank(topic_id):
raise_400('Topic id is req... | 7cbd5baf247106f54c99a6fe16181ba29509f4be | 3,622,862 |
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
print(t1)
some_function()
t2 = time.time()
print(t2)
return "Time it took to run the function: " + str((t2 - t1)) ... | 7ff8cec2102f355d586d14e2e41c8a410beb5836 | 3,622,863 |
def all_close(x, y, msg, solver):
"""
Check to see if x and y are close
"""
try:
v = np.linalg.norm(x-y) <= 1.0e-03 * max([1, np.linalg.norm(x), np.linalg.norm(y)])
except:
print("""
check_failed
============
msg: %s
x: %s
y: %s
""" % (msg, x, y))
return False
v = v or np... | c7245e6b5a8cbc5b15d8180fd2a60e0ee281ac02 | 3,622,864 |
def term_matches(text, forms_list, options):
""" Counts the number of occurences of the words in forms_list in the text
The terms in forms_list can either be tokens or full terms. The
matching for tokens is contains and for full terms is equals.
"""
token_mode = options.get('token_mode', TM_TOKENS)
... | d40dffa610a2d6ecf210d2a27d6c9b3b5dfc9d73 | 3,622,865 |
def first_rows_close_as_set(a, b, k=None, rtol=1e-6, atol=1e-6):
"""Checks if first K entries of two lists are close, up to permutation.
Inputs to this assert are lists of items which can be compared via
numpy.allclose(...) and can be sorted.
Args:
a: list of items which can be compared via numpy.allclose... | 89b21b7653849fb4a24f61591f88b8896145db8b | 3,622,866 |
def process_categories(cat_path):
""" Returns the mapping between the identifier of a category in
Places365 and its corresponding name
Args:
cat_path: Path containing the information about the Places365
categories
"""
result = {}
with open(cat_path) as f:
lines = f.re... | f87741b990ee9ab9c8216112df73c7aa5bab8d49 | 3,622,870 |
def evalexpr(data, expr, exprvars=None, dtype=float):
""" evaluate expression based on the data and external variables
all np function can be used (log, exp, pi...)
Parameters
----------
data: dict or dict-like structure
data frame / dict-like structure containing named columns
exp... | 68deaceac6ae20ba178c28bd3046b31fb96e49fe | 3,622,871 |
def word_list_raw():
"""
Return the wordlist used for mnemonics.
"""
return """abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advi... | d85126435259c83dd481635c4d7940a5347ffe28 | 3,622,872 |
def _check_dthetapsi(
dtheta=None, psi=None,
extenthalf_psi=None, extenthalf_dtheta=None,
ntheta=None, npsi=None,
include_summit=None,
):
""" Return formatted dtheta and psi
They are returned with the same shape (at least 1d arrays)
They can be:
- 'envelop': if psi of dtheta = 'env... | 24c35d2c2ba8bb5dc888e7205e117ab8780b05e1 | 3,622,874 |
def find_beta_image_identifier(targetgrouparn):
"""Queries the tags on TargetGroups
Args:
targetgrouparn - Amazon ARN of the Target group that needs to be queried for the Tags
Returns:
identifier : tag key value of the target group , with KeyN... | 53185b64cbe7a05e85c36b19978344b700e5c9c0 | 3,622,875 |
import struct
def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLoca... | ae86bb1f3bc839053ca34c8bf2b4beb0af04aaee | 3,622,876 |
async def handle_post_projects(project: projects.schemas.project.ProjectCreate,
session: Session = Depends(session_scope)):
"""
Handles POST requests to /.
Parameters
----------
project : projects.schemas.project.ProjectCreate
session : sqlalchemy.orm.session.Sess... | efb943840c978976f3b8bd383df6c43bd4a946eb | 3,622,877 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = int(args.x_val) if args.x_val != 'None' else None
args.test_size = float(args.test_size)
# criterion (string)
# s... | 61438940cdc572b08ebd7ee0efe56cae65c1ddd7 | 3,622,878 |
def prequalification(request, step):
"""
View for rendering pre-qualification questions.
If user is not authenticated with BCeID, temporarily store user responses to session
"""
template = 'prequalification/step_%s.html' % step
if not request.user.is_authenticated:
responses_dict = get_... | b1d58d71776fbd05a80d451b2d7764825abaddd7 | 3,622,881 |
def _read_netcdf_coordinate_units(root):
"""Get units for coodinate values.
Parameters
----------
root : netcdf_file
A NetCDF file.
Returns
-------
tuple of str
Units for each coordinate.
"""
units = []
for coordinate_name in _AXIS_COORDINATE_NAMES:
try:... | 25c3fe5db696430cd9bbcb9f587ca8a5b968fac1 | 3,622,882 |
def check(_user_id):
"""
checks whether it is a check.
"""
_board = boards[_user_id]
return _board.is_check() | 1ce2e9862468fd167b7d7aa5e45ccfba8d788f5c | 3,622,883 |
def angle_to_pixels(angle, screenDist, screenW, screenXY):
"""
Calculate the number of pixels which equals a specified angle in visual
degrees, given parameters. Calculates the pixels based on the width of
the screen. If the pixels are not square, a separate conversion needs
to be done with the heig... | 2c65599e54af9d7555bb05260070c80f072483f2 | 3,622,884 |
import requests
def _delete_conn_info(self, switch, port, dir):
""" Deletes existed connection between ``port1`` and ``port2`` an the switch
``dir`` could be ``bi``,``in`` or ``out``
"""
cli = self._clients[switch]
ip = cli["ip"]
conn_port = cli["port"]
session = cli["session"]
... | eb5db24fb30ed09e09c7ad0b46a40ee28e99b802 | 3,622,886 |
from typing import List
def get_mask_for_tokens(tokens: List[str],
special_tokens: List[str] = []) -> List[int]:
"""Return a mask for a tokenized smiles, where atom tokens
are converted to 1 and other tokens to 0.
e.g. c1ccncc1 would give [1, 0, 1, 1, 1, 1, 1, 0]
Args:
... | 69b5757c294b9226987aa5e6643642e1b13c43d5 | 3,622,887 |
def fail_if_data_set_exists(zosmf_profile, dataset_name):
"""
Check whether data set exists and throw and exception if it does
"""
connection = {'plugin_profile': zosmf_profile}
files = Files(connection)
list_dsn = files.list_dsn(dataset_name)
if list_dsn['returnedRows'] == 0 :
retu... | baf7091527eaab2083fce89ca8be77183ef1d73b | 3,622,888 |
from pyoptsparse import Optimization
def snopt_opt(objfun, desvar, lb, ub, ncon=None, title=None, options=None,
sens='FD', jac=None):
"""
Find optimal values using SNOPT from pyoptsparse.
If SNOPT is not available, use other avaiilable optimizer. The desvar is an array of variables
name... | a53e7b8059104fb8aaef6f1f6ff0c40b526b4ee3 | 3,622,889 |
def yiq_to_web(yiq):
"""
Convert a YIQ color representation to a WEB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the
luma and chrominance.
:return: WEB r... | 2a8385bc86d5952b0ba386ead6692d71d3467e47 | 3,622,890 |
def post_processing(data, start, scaler_1, scaler_2, delta):
"""Post-processing"""
data = scaler_2.inverse_transform(data)
data = data * np.exp(0.5 * delta * data **2)
data = scaler_1.inverse_transform(data)
data = np.exp(data)
post_data = np.empty((data.shape[0], ))
post_data[0] = star... | 5d45cdce784d75600986efb68e0eb11b981accde | 3,622,891 |
def predict_accuracy(armas: tuple, sig: SwitchingArmaSignal) -> float:
""" Predict accuracy score from ARMA models.
Parameters
----------
armas
Pair of `Arma` models.
sig
Signal generated from the ARMA models.
Returns a predicted value for the expected accuracy score of... | 62e69fe7a751f26d040ca4b4a814ec11be0ebd30 | 3,622,892 |
def get_contours_inner_angles(contour):
"""
Given a closed contour, return a list of its inner angles in radians
:param contour: a 2D numpy array
:return: 1D numpy array of angles in radions
"""
# Unroll all points triplets to vectors
a = contour
b = np.tile(contour, reps=(2, 1))[1:1 + ... | 7c3811ab09a2523cf860ee1cd36883d0a95a0d78 | 3,622,893 |
def _get_year(obj):
"""
Get the year of the entry.
:param obj: year string object
:return: entry year or none if not valid value
"""
year = obj[0:4]
try:
year = int(year)
except ValueError:
year = None
return year | 6d3cbcc8759096ec3e798e90dc3a307b4a34b6ae | 3,622,894 |
def solve4y(x: float, m: float, b: float):
"""
y = m * x + b
"""
if m is np.nan:
return b
return m * x + b | ed56bdacc9c595e5c88bf86d1fb36479422f6ee7 | 3,622,895 |
def c2():
"""Compound CID 175."""
return Compound.from_cid(175) | 5d40c16a22ecee39530eb6b43d85e6e35b9f9387 | 3,622,897 |
import json
def create_user(request):
""" Creates a new user with specified settings
URL: /admin/Users/Create/
:param request:
:return:
"""
post = request.POST.dict()
username = post.get('username')
if username is None:
response = {'status':-1, 'status_message':'No userna... | d820f7381cb02d171fc770b6da96e491d3e7587a | 3,622,898 |
def hist_to_density_fullspace(counts, errs, bins, totalweight):
""" Normalize histogram to a unit integral density function
over total sum of event weights (not just the visible histogram range mass)
"""
norm = binwidth(bins) * totalweight
return counts/norm, errs/norm | 3b53b108326bd28f6649eabdc83238e92d4df856 | 3,622,900 |
def epochPoints(abf):
"""Return a list of time points where each epoch starts and ends."""
if abf.abfVersion["major"] == 1:
return []
position = int(abf.sweepPointCount/64)
epochPoints = [position]
for epochNumber, epochType in enumerate(abf._epochPerDacSection.nEpochType):
pointCoun... | 1eafc6a6cd7a3e68a5136ef6b92a4e7defae0648 | 3,622,901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.