content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gather_inputs(headers, test_suites, inputs_class=Inputs):
"""Read the list of inputs to test psa_constant_names with."""
inputs = inputs_class()
for header in headers:
inputs.parse_header(header)
for test_cases in test_suites:
inputs.parse_test_cases(test_cases)
inputs.gather_arg... | 18300cab225f817a7a09f73e4b957713ee45d0c8 | 10,800 |
def key_create(adapter_id):
"""Creates a key using a certain adapter."""
adapter = get_adapter(adapter_id)
if not adapter:
return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)
if not adapter.do_verify(request.headers):
return outp... | ec07091f3bb96f469338643f36b63ade50de3205 | 10,801 |
def is_right(side1, side2, side3):
"""
Takes three side lengths and returns true if triangle is right
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: bool
"""
return False | 2d22bbc7d0d363b360f578002a6380a4ae5f5b63 | 10,802 |
def parser_electron_number(electron_line):
"""
function of parser for electron information
Args:
electron_line (str): line
Returns:
list: electron information
"""
electron_list = parser_split_line_by_length(electron_line.rstrip(), CPF_FORMAT["ELECTRON"]["length"], "int")
return electron_list | 3a444aa0cb062ea5cfaac3e7686ff762e42ebf4c | 10,803 |
def summary(t, rtol=1e-5, atol=1e-8):
"""
Parameters
----------
t
rtol
atol
Returns
-------
"""
deltas = np.diff(t)
if np.allclose(deltas, deltas[0], rtol, atol):
# constant time steps
return deltas[0], deltas, ''
# non-constant time steps!
unq... | 0f1a5a65d832be8db35b8bdf145e6240d6072f71 | 10,804 |
def masked_huber(input, target, lengths):
"""
Always mask the first (non-batch dimension) -> usually time
:param input:
:param target:
:param lengths:
:return:
"""
m = mask(input.shape, lengths, dim=1).float().to(input.device)
return F.smooth_l1_loss(input * m, target * m, reduction... | c4eab136b73ffc92034a217252ac290848f77982 | 10,805 |
def calcProbabilisticResiduals(
coords_actual,
coords_desired,
covariances_actual
):
"""
Calculate the probabilistic residual.
Parameters
----------
coords_actual : `~numpy.ndarray` (N, M)
Actual N coordinates in M dimensions.
coords_desired : `~numpy... | c5bdc4048d9fef2e6b40e3bc48c80e6f6e2fcca7 | 10,806 |
import re
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 elements only"'
the resulting list would be:
['Should', 'give', '3 el... | befb31949d4c52fac96765fd78bc1b9d644282ba | 10,807 |
def scheduler(epoch):
"""Generating learning rate value for a given epoch.
inputs:
epoch = number of current epoch
outputs:
learning_rate = float learning rate value
"""
if epoch < 100:
return 1e-3
elif epoch < 125:
return 1e-4
else:
return 1e-5 | 916cbc12ff76b8d022a96c89083b8bd2a3078c69 | 10,808 |
def external_search(query, feature_type, url):
""" Makes an external search request to a specified URL. The url will have the search
text appended to it. Returns geojson matches with extra data for the geocoder.
"""
logger.info("using external API for feature lookup: %s", url + query)
req = E... | f90ea54dd8036b4237a74dd398cf3f2698ab4d0f | 10,809 |
import os
def has_supervisor() -> bool:
"""Return true if supervisor is available."""
return "SUPERVISOR" in os.environ | 5af98347acfdcc50c1b4ca80e01597c584e3a45a | 10,810 |
from setuptools import setup
from distutils.core import setup
def setup(*args, **kwds):
"""
Compatibility wrapper.
"""
try:
except ImportError:
return setup(*args, **kwds) | 174fd60c91c661e9c104c2b62a4966097d4faa57 | 10,811 |
def joinpath(base, end):
"""Like Path.joinpath(), but ensures the result is inside `base`.
Should be used for user-supplied `end`.
"""
result = (base / end).resolve()
if base not in result.parents:
print(base, end, result)
raise ValueError(end)
return result | 1b4f5afcdca21ceb6e676385602dd07b252db3ad | 10,812 |
def multicolored_line_collection(x, y, z, colors):
""" Color a 2D line based on which state it is in
:param x: data x-axis values
:param y: data y-axis values
:param z: values that determine the color of each (x, y) pair
"""
nstates = colors.shape[0]
# come up with color map and normalizat... | 6d9438a58547d4be253ca2a505e05da259c73118 | 10,813 |
def foldr(fn,
elems,
initializer=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None):
"""foldr on the list of tensors unpacked from `elems` on dimension 0.
This foldr operator repeatedly applies the callable `fn` to a sequence
of... | db88c9a7e4690af92067801b5e8c42c587c59f12 | 10,814 |
def featurise_distances(diagram):
"""Create feature vector by distance-to-diagonal calculation.
Creates a feature vector by calculating distances to the diagonal
for every point in the diagram and returning a sorted vector. The
representation is *stable* but might not be discriminative.
Parameters... | 9c4f20be1deb2ed5073015939d48615f3b04c21b | 10,815 |
def resize(source, width=None, height=None, filter=None, radius=1,
wrapx=False, wrapy=False):
"""Create a new numpy image with the desired size.
Either width or height can be null, in which case its value
is inferred from the aspect ratio of the source image.
Filter can be HERMITE, TRIANGLE... | 08fdc077dcea013fd8b0be4a195a860e6d5291ec | 10,816 |
def load_and_classify_payload(config, service, entity, raw_record):
"""Return a loaded and classified payload."""
# prepare the payloads
payload = load_stream_payload(service, entity, raw_record)
payload = list(payload.pre_parse())[0]
classifier = StreamClassifier(config=config)
classifier.load... | 1931804b1535ba00b495879061492e25a43f91e8 | 10,817 |
def render_text(self, block: str, block_type: str, y: int) -> int:
"""
:param self: MarkdownRenderer
:param block: string of text
:param block_type: type of the text (e.g. headers, ordered/unordered lists, blockquotes, code etc)
:param y: y-coordinate to start rendering on
:return: y-coordina... | ed3e18d9988d612f911d9f6c647cbdf7dfbf7b07 | 10,818 |
def tvadam_reconstructor(dataset='ellipses', name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:return: TV reconstructor for the specified dataset
"""
try:
params = Params.load('{}_tvadam'.format(dataset))
standard_dataset = load_standard_dataset(dataset)
if name... | 0b69d0ce60f05dc522449af66f70ee655389e13c | 10,819 |
import re
def process_spf_data(res, data):
"""
This function will take the text info of a TXT or SPF record, extract the
IPv4, IPv6 addresses and ranges, request process include records and return
a list of IP Addresses for the records specified in the SPF Record.
"""
# Declare lists that will... | 537a59dd9091df35ac2502e8b03f87e625b74b76 | 10,820 |
def create_knight():
"""
Creates a new knight according to player input.
Checks the knights module for how many points are to spend,
and which attributes are available. It then asks the player
for a name for the knight and to spend their points on the
available attributes.
Returns:
... | 8feed9cd71b68868d14cd1bcfe14ff9291cf2abd | 10,821 |
async def get_bank_name(guild: discord.Guild = None) -> str:
"""Get the current bank name.
Parameters
----------
guild : `discord.Guild`, optional
The guild to get the bank name for (required if bank is
guild-specific).
Returns
-------
str
The bank's name.
Raises
... | 1e0e3f1a1de7925daf5810ac3bcc75508993a642 | 10,822 |
from typing import Optional
from typing import Dict
from typing import Any
import tempfile
def build_cli_lib(to_save_location: Optional[str] = None, render_kwargs: Optional[Dict[str, Any]] = None) -> str:
"""Create project-specific cli.fif lib"""
if not to_save_location:
to_save_location: str = tempf... | 0231433f94b129213de95ac50b406ede88860f23 | 10,823 |
def match(A, S, trueS):
"""Rearranges columns of S to best fit the components they likely represent (maximizes sum of correlations)"""
cov = np.cov(trueS, S)
k = S.shape[0]
corr = np.zeros([k, k])
for i in range(k):
for j in range(k):
corr[i][j] = cov[i + k][j] / np.sqrt(cov[i + ... | a0ec70ec768a1dfc610e8a5050d190a94266b307 | 10,824 |
def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the f... | f209cbc9ae9aa18fd22e320fdc96ba97690f8a7d | 10,825 |
def posts_completed(scraped_posts, limit):
"""Returns true if the amount of posts scraped from
profile has reached its limit.
"""
if len(scraped_posts) == limit:
return True
else:
return False | ff72474349a32f326b63b95070927c4b379be800 | 10,826 |
def mag(x):
"""Returns the absolute value squared of the input"""
return np.abs(x)**2 | bd081775a0b99e050287160cf3369faa819e20cf | 10,827 |
def get_zero_columns(matrix):
""" Returns a list of the columns which are all 0 """
rows = matrix.shape[0]
columns = matrix.shape[1]
result = []
for j in range(columns):
is_zero_column = True
for i in range(rows):
is_zero_column = is_zero_column and matrix[i, j] == 0.0
... | 35694592f4155f710e5ed3c2148a138591cd683f | 10,828 |
def traditional_constants_icr_equation_empty_fixed(fixed_params, X_col):
""" Traditional ICR equation with constants from ACE consensus """
a = 450
tdd = X_col[0]
return a / tdd | 2931e4b3592a94690d98b0cb4cb90f712ff4a449 | 10,829 |
def sort_completions_key(completion):
"""
sort completions according to their type
Args:
completion (jedi.api.classes.Completion): completion
Returns:
int: sorting order
"""
if completion.type == "function":
return 2
elif completion.type == "instance":
retur... | 7bf767d908c83c11dafa5e0fd694bbb31a98c404 | 10,830 |
def _is_git_url_mismatch(mismatch_item):
"""Returns whether the given mismatch item is for a GitHub URL."""
_, (required, _) = mismatch_item
return required.startswith('git') | b1c3cec3d8cf3c7d3ffa5c405522b1a08754223b | 10,831 |
def from_url(url, output_path=None, options=None):
"""
Convert file of files from URLs to PDF document
:param url: URL or list of URLs to be saved
:param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string
:param options: (optional) dict to configure pyp... | 8543410dcfba9d44adc8939f3dc8be702f5e922b | 10,832 |
from typing import Dict
def parse_wmic_output(wmic_output: str) -> Dict[str, str]:
"""Parse output of wmic query
See test cases.
@param wmic_output: Output from wmic tool
@return Dictionary with key/value from wmic"""
try:
non_blank_lines = [s for s in wmic_output.splitlines() if s]
... | bce5195c484cafc80ef1d1e26b7fb598c20718aa | 10,833 |
def parse_identifier(stream: TokenStream) -> expression.Identifier:
"""Read an identifier from the token stream.
<ident>.<ident>
<ident>["<ident>"]
<ident>["<ident>"].<ident>
<ident>[<ident --> int/str>]
<ident>[<ident>.<ident --> int/str>]
<ident>[<int>]
<ident>[<int>].<ident>
"""
... | 0679a112a841d90d51806d83cd381aad7632c77b | 10,834 |
from typing import List
def cubemap_projection_matrices(from_point: Vector3D, far_plane: float) -> List[np.ndarray]:
"""
Create the required Cubemap projection matrices.
This method is suitable for generating a Shadow Map.
Simply speaking, this method generates 6 different camera matrices from the c... | e576aceec831df8267bff1c4de3cb7f0a58c3be7 | 10,835 |
from win32com.shell import shellcon, shell
def loadOptionsFile():
"""Find the .buildbot/FILENAME file. Crawl from the current directory up
towards the root, and also look in ~/.buildbot . The first directory
that's owned by the user and has the file we're looking for wins. Windows
skips the owned-by-u... | 2674c6e37de32f673e4fb9aeb6bb11981bee23d0 | 10,836 |
def get_high_accuracy_voronoi_nodes(structure, rad_dict, probe_rad=0.1):
"""
Analyze the void space in the input structure using high accuracy
voronoi decomposition.
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictio... | 2f671f9c8a357bd82f364f767cd387fae2661979 | 10,837 |
def setUpBlobDetector():
"""
Configure parameters for a cv2 blob detector, and returns the detector.
"""
params = cv2.SimpleBlobDetector_Params()
params.minThreshold = 0
params.maxThreshold = 255
params.filterByArea = True
params.minArea = 1500
params.maxArea = 25000
params.f... | d311f46d9b87d759edae0f15583c66dc31f80602 | 10,838 |
def raise_keymap():
"""
! @ # $ % || ^ & * ( )
DEL ESC || PGDN PGUP PSCR
CAPS volup ENT reset || UP
voldn super shift space bspc|| alt ent LEFT DOWN RGHT
"""
lef... | 94beda8275f65f16353b12b22809138d0342f512 | 10,839 |
import click
from typing import cast
def sample_cmd() -> Command:
"""Useful for testing constraints against a variety of parameter kinds.
Parameters have names that should make easy to remember their "kind"
without the need for looking up this code."""
@cloup.command()
# Optional arguments
@cl... | c5a8ed369d910872e52ef080707c8f0ae7436487 | 10,840 |
import inspect
def get_linenos(obj):
"""Get an object’s line numbers in its source code file"""
try:
lines, start = inspect.getsourcelines(obj)
except TypeError: # obj is an attribute or None
return None, None
except OSError: # obj listing cannot be found
# This happens for m... | 248ad7e377995e03969d3f7e1ded88670d8b08ea | 10,841 |
import random
def create_solution_board(width=6, height=6):
"""Randomly generates a new board
with width by height size
"""
if type(width) != int or type(height) != int:
raise TypeError('Arguments must be int type')
boxes = width * height
if boxes % 2 != 0:
raise ValueError('... | 0b6e30d726cec61581d93c909761f80d739eb917 | 10,842 |
from pydft.poisson import _O_operator, _L_operator, _B_operator
def _getE(s,R,W,V = None):
"""The sum of the energies for the states present in the solution.
Args:
s (list of int): The number of samples points along each
basis vector.
R (numpy.ndarray): The basis vectors for the un... | 7759c68e5774f809cfac1038014144cabe5c9410 | 10,843 |
def get_gt_list(request):
""" This view returns the list of groundtruths associated to a user and a specific configuration of institute,
usecase and language.
.js files: InfoAboutConfiguration.js DownloadGT.js"""
groundTruths = 0
json_resp = {}
ins = request.GET.get('inst',None)
lang = re... | 46cb039c9811eac5a43c08776b59b8cef12c7133 | 10,844 |
from typing import Any
from typing import MutableMapping
from typing import Hashable
def to_dict(item: Any) -> MutableMapping[Hashable, Any]:
"""Converts 'item' to a MutableMapping.
Args:
item (Any): item to convert to a MutableMapping.
Raises:
TypeError: if 'item' is a type that is ... | c3ba483bde73a35ed036debcc4b87575b1c8b962 | 10,845 |
import copy
def node(*args, **kwargs):
"""
args[0] -- a XML tag
args[1:] -- an array of children to append to the newly created node
or if a unicode arg is supplied it will be used to make a text node
kwargs -- attributes
returns a xml.dom.minidom.Element
"""
blocked_attributes... | 2a0f9a953d07a114e0a426f4225fb3c5076513ee | 10,846 |
import subprocess
import plistlib
def get_volume_uuid(path: str) -> str:
"""Returns the volume UUID for the given path or None if not found"""
try:
output = subprocess.check_output(["diskutil", "info", "-plist", path])
plist = plistlib.loads(output)
return plist.get("VolumeUUID", None)... | d01d6a9232393013009d337a2b669e246e928b65 | 10,847 |
import math
def mylog10(x):
"""Return the base-10 logarithm of x."""
return math.log10(x) | d32113c16047175125e1b79c9ce0ea8822e4853c | 10,848 |
import numpy
def get_RGB_to_RGB_matrix(in_colorspace, out_colorspace, primaries_only=False):
"""Return RGB to RGB conversion matrix.
Args:
in_colorspace (str): input colorspace.
out_colorspace (str): output colorspace.
Kwargs:
primaries_only (bool): primaries matrix only, doesn't... | 6c864fc45d254c38bc00a381f55dc3d2ad80aa9a | 10,849 |
import re
import string
def normalize_string(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_... | 85a77dca1110460a1c445cc32f78cadb8c70ebd5 | 10,850 |
def sub_band_as_numpy(band, y_limits, data_type=None):
"""Read subsets of the dataset so that we don't hold the whole thing
in memory. It seems wasteful to reread parts, but GDAL keeps its own cache.
"""
data_type = data_type if data_type else INT32
y_size = y_limits[1] - y_limits[0]
LOGGER.debu... | d27ac1f5f54179f5240d8160774ca0f722948982 | 10,851 |
def full_reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None,
scheme=None, domain=None, subdomain=None):
"""
First, obtains the absolute path of the URL matching given
``viewname`` with its parameters.
Then, prepends the path with the scheme name and the authority
... | b061cdc1369af0c60b95da58f262563e5ea93aa3 | 10,852 |
def get_object_or_none(model_class, **kwargs):
"""Identical to get_object_or_404, except instead of returning Http404,
this returns None.
"""
try:
return model_class.objects.get(**kwargs)
except model_class.DoesNotExist:
return None | d74b84e9186d9fb4faabb7eaa70f53672665d304 | 10,853 |
def GenerateTests():
"""Generate all tests."""
filelist = []
for ii in range(len(_GROUPS)):
filename = GenerateFilename(_GROUPS[ii])
filelist.append(filename)
WriteTest(filename, ii, ii + 1)
return filelist | 1160454ae0fab7008051bf9d4f5d2b94a74888b9 | 10,854 |
def shift_df_generator(empty_df, day_lower_hr_lim, day_upper_hr_lim):
"""Generate day and night dataframe.
Parameters
----------
empty_df : DataFrame
A DataFrame with timestamp and 'Temperature (Celsius)' with all zeros.
day_lower_hr_lim : int
The lower hour limit that constitutes t... | cc8f3675d88dc920fd1762894c859cd93a523aab | 10,855 |
import json
import regex
def json_loads(data, handle=False):
"""
封装的json load
:param data:
:param handle: 补丁, False: 默认不特殊处理: True: 不走正则
:return:
"""
if handle:
return json.loads(data.strip())
return json.loads(regex.sub(r"\\\\", data.strip())) | 34156a594b203af041fba8da65601bb17da95a3e | 10,856 |
def elina_linexpr0_size(linexpr):
"""
Return the size of an ElinaLinexpr0.
Parameters
----------
linexpr : ElinaLinexpr0Ptr
Pointer to the ElinaLinexpr0 that needs to be checked for its size.
Returns
-------
size_linexpr = c_size_t
Size of the ElinaLinexpr0.
""... | b68a9874dd795876dae1ff2ffe3de98728e521a7 | 10,857 |
def _make_index(df, cols=META_IDX, unique=True):
"""Create an index from the columns/index of a dataframe or series"""
def _get_col(c):
try:
return df.index.get_level_values(c)
except KeyError:
return df[c]
index = list(zip(*[_get_col(col) for col in cols]))
if ... | 4356de2531f150c80bc364315ebf547fd345967f | 10,858 |
import json
def handler(event, context):
""" Lambda Handler.
Returns Hello World and the event and context objects
"""
print(event)
print(context)
return {
"body": json.dumps('Hello World!')
} | 561326fec784aa72a133b217f1e2cecaf12ec1ad | 10,859 |
from typing import List
def flatten_concat(tensors: List[tf.Tensor], batch_dims: int = 1) -> tf.Tensor:
"""Flatten given inputs and concatenate them."""
# tensors [(B, ...), (B, ...)]
flattened: List[tf.Tensor] = list() # [(B, X), (B, Y) ...]
for tensor in tensors:
final_dim = -1
if a... | 1a4b9bbf12f75aff43273a7f44c659b7afecdddc | 10,860 |
def analyze_friends (names,phones,all_areacodes,all_places):
"""
names: tuple of names
phones: tuple of phone numbers (cleaned)
all_areacodes: tuple of area codes (3char ints)
all_places: tuple of places
Goal: Print out how many friends you have and every unique state
"""
# For TES... | b90f938c9c019dc331c38cafb36d1a7e0cb3f83f | 10,861 |
def fast_autoregressive_predict_fn(context, seq_len):
"""Given a context, autoregressively generate the rest of a sine wave."""
core = hk.LSTM(32)
dense = hk.Linear(1)
state = core.initial_state(context.shape[0])
# Unroll over the context using `hk.dynamic_unroll`.
# As before, we `hk.BatchApply... | bf61799a8f34045cb214fd68095e1b9346fc797f | 10,862 |
def get_entities(corpus_name):
""" Load the dataset from the filesystem corresponding to corpus_name
(to see the list of allowed names, use utils.list_corpora() ), and extract
all annotated entities.
Returns a dict, in which each key is an entity type, which contains a list
of entity mentions in th... | 274d82c4d5ae978452aaa7cf3aae14a7b86b3030 | 10,863 |
def _reporthook(t):
"""``reporthook`` to use with ``urllib.request`` that prints the
process of the download.
Uses ``tqdm`` for progress bar.
**Reference:**
https://github.com/tqdm/tqdm
"""
last_b = [0]
def inner(b: int = 1, bsize: int = 1, tsize: int = None):
"""
... | 9a4d527ff0b964e4220db7a22a522657947e91cb | 10,864 |
def serial_rx(sysclk, reset_n, n_stop_bits_i, half_baud_rate_tick_i, baud_rate_tick_i, recieve_i, data_o, ready_o):
""" Serial
This module implements a reciever serial interface
Ports:
-----
sysclk: sysclk input
reset_n: reset input
half_baud_rate_tick_i: half baud rate tick
baud_rate_... | 62f215644004b61738db9fd249f28a4abc1391ea | 10,865 |
def zpad(x, l):
""" Left zero pad value `x` at least to length `l`.
>>> zpad('', 1)
'\x00'
>>> zpad('\xca\xfe', 4)
'\x00\x00\xca\xfe'
>>> zpad('\xff', 1)
'\xff'
>>> zpad('\xca\xfe', 2)
'\xca\xfe'
"""
return b'\x00' * max(0, l - len(x)) + x | 605aab22fa54f9df85397793c65d46dcf2ec3588 | 10,866 |
def clf2D_slope_intercept(coef=None, intercept=None, clf=None):
"""
Gets the slop an intercept for the separating hyperplane of a linear
classifier fit on a two dimensional dataset.
Parameters
----------
coef:
The classification normal vector.
intercept:
The classifier inte... | 9376c34a3836ee028c4b0497e1088ddd50bb1fc6 | 10,867 |
from pathlib import Path
import os
def _get_imgpaths(datasets: list, verbose=True):
""" get image paths
Args:
datasets (list): dataset names
verbose (bool, optional): . Defaults to True.
"""
img_paths = []
for dname in datasets:
img_dir = Path(dname.format(DATASETS_DIR=DAT... | 67de2541318f5348223bd79ceb0ab11e60d55f56 | 10,868 |
def build_driver_for_task(task):
"""Builds a composable driver for a given task.
Starts with a `BareDriver` object, and attaches implementations of the
various driver interfaces to it. They come from separate
driver factories and are configurable via the database.
:param task: The task containing ... | 5283b91e5a42fe7ebec20b91e0f1463abbc8b724 | 10,869 |
import torch
def evaluate(eval_model, criterion, ntokens, data_source, cnf):
"""
Evaluates the training loss of the given model
"""
eval_model.eval() # Turn on the evaluation mode
total_loss = 0.0
src_mask = generate_square_subsequent_mask(cnf.input_length).to(cnf.device)
with torch.no_gr... | 4570f5e7751683157ca8f3155052e484a1b3962e | 10,870 |
def km_to_meters(kilometers):
"""
(int or float) -> float
Takes a distance in kilometers and returns the distance in meters.
"""
return kilometers * 1000.0 | 33e40914c9d2b10009889ebfcbc543863a9ca363 | 10,871 |
from typing import List
from typing import Optional
from typing import Dict
from typing import Callable
from typing import Any
def build(plan: List[Step], instances_stock: Optional[Dict[Callable, Any]] = None):
""" Build instances dictionary from a plan """
instances_stock = instances_stock or {}
instance... | a1b3ecc98097d9a5d998cca1484b22a4b83124ca | 10,872 |
def make_module_spec(options, weight_file):
"""Makes a module spec.
Args:
options: LM hyperparameters.
weight_file: location of the hdf5 file with LM weights.
Returns:
A module spec object used for constructing a TF-Hub module.
"""
def module_fn():
"""Spec function for a ... | 2293f00186438a6cc3318be6a25ab5223b8e9a91 | 10,873 |
import math
def get_initial_scoreboard():
"""
Retrieve the initial scoreboard (first pages of global and student views).
If a user is logged in, the initial pages will instead be those on which
that user appears, and their group scoreboards will also be returned.
Returns: dict of scoreboard info... | 3e5998a0cc94a6c99ca58336ef0a350a4170240e | 10,874 |
async def resolve(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
tcp=False, source=None, raise_on_no_answer=True,
source_port=0, lifetime=None, search=None, backend=None):
"""Query nameservers asynchronously to find the answer to the question.
This is a convenienc... | 90a79f18d5c8887cbede733e7e05778ea78b36eb | 10,875 |
import re
def compare_xml(want, got):
"""Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison.
Based on http://codespeak.net/svn/lxml/trunk/s... | 6632c723c2461dcb34b7e4f0bca0b4d096b5def8 | 10,876 |
def _tf_equal(a, b):
"""Overload of "equal" for Tensors."""
return gen_math_ops.equal(a, b) | 899cff2abe9613d798fb59190c1860ef6a6599d7 | 10,877 |
def faq():
"""FAQ page for SciNet"""
return render_template("faq.html") | 67bbdcc713789f71b0506206ef8a4f2a56b3f1a1 | 10,878 |
def render_table(sheet, header, width, data, header_style, data_style, tt_id_style):
"""Рендерим страницу"""
# Render table header
for i in range(len(header)):
sheet.write(0, i, header[i], header_style)
sheet.col(i).width = width[i]
sheet.row(1).height = 2500
# Render table data
... | bc181ff96319daef3cad10e5072124a6c43172a6 | 10,879 |
def texsafe(value):
""" Returns a string with LaTeX special characters stripped/escaped out """
special = [
[ "\\xc5", 'A'], #'\\AA'
[ "\\xf6", 'o'],
[ "&", 'and'], #'\\"{o}'
]
for char in ['\\', '^', '~', '%', "'", '"']: # these mess up things
value = value.replace(char... | b40b60a34629f75dfdac298bd2937af52ef797b1 | 10,880 |
def match_against_host_software_profile(db_session, hostname, software_packages):
"""
Given a software package list, return an array of dictionaries indicating if the
software package matches any software package defined in the host software profile package list.
"""
results = []
system_option =... | 30a1bbf8a548a9578324a60aa3bc18998457671a | 10,881 |
from typing import Mapping
from typing import Any
def get_inputs_by_op(op: Op, store: Mapping[str, Any], copy_on_write: bool = False) -> Any:
"""Retrieve the necessary input data from the data dictionary in order to run an `op`.
Args:
op: The op to run.
store: The system's data dictionary to ... | 1f3ee5bfe98793c4e8002f2a7f7ea834bf0d93c0 | 10,882 |
from typing import Type
def finalize_post(func, store: Type['ParameterStore']):
"""Finalizes the store prior to executing the function
Parameters
----------
func : callable
The function to wrap.
store : ParameterStore
The parameter store to finalize.
Returns
-------
c... | 92195a0005b94dad7606609f99da4c824e39d5b1 | 10,883 |
def searchaftertext(filename, startterm, searchterm):
"""Start search after a certain text in a file"""
#print startterm
#print searchterm
startline = findLastString (filename, startterm)
searchtermfound = findLastString (filename, searchterm)
if searchtermfound > startline:
return True
... | 32adc5bebab42ac721c04c8f16bceea53f9e0d79 | 10,884 |
def vec_list_to_tensor(vec_list):
"""Convert list to vector tensor."""
return jnp.stack(vec_list, axis=-1) | 8e4dd60199c17dade87392f059412e00ae9defcc | 10,885 |
from datetime import datetime
def to_ecma_datetime_string(dt, default_timezone=local):
"""
Convert a python datetime into the string format defined by ECMA-262.
See ECMA international standard: ECMA-262 section 15.9.1.15
``assume_local_time`` if true will assume the date time is in local time if the... | bec3a52976552a0c0cc9ff5afde5bbf5578ff020 | 10,886 |
def _logfile_readme() -> str:
"""Returns a string containing a 'how to read this logfile' message.
Returns
-------
str
Returns a formatted paragraph-long message with tips on reading log file output.
"""
line1 = "Messages are displayed below in the format"
line2 = " <DATE> <TIME>... | 5e418b20df1ebb486d0b1c3ecf38d6c72ae8a5a7 | 10,887 |
def taxon_lookup(es, body, index, taxonomy_index_template, opts, return_type):
"""Query elasticsearch for a taxon."""
taxa = []
with tolog.DisableLogger():
res = es.search_template(body=body, index=index, rest_total_hits_as_int=True)
if "hits" in res and res["hits"]["total"] > 0:
if retu... | 52604947804581f633603d0728a68bc16f198503 | 10,888 |
async def get_south_services(request):
"""
Args:
request:
Returns:
list of all south services with tracked assets and readings count
:Example:
curl -X GET http://localhost:8081/fledge/south
"""
if 'cached' in request.query and request.query['cached'].lower() == ... | a134bcf3c899212afc4b805ddaa9a19db901578a | 10,889 |
def filter_bam_file(bamfile, chromosome, outfile):
"""
filter_bam_file uses samtools to read a <bamfile> and read only
the reads that are mapped to <chromosome>.
It saves the filtered reads into <outfile>.
"""
inputs = [bamfile]
outputs = [outfile]
options = {
'cores': 1,
... | 317e1283d4722483e4bc98080ef99abd9876d045 | 10,890 |
def import_teachers():
"""
Import the teachers from Moodle.
:return: Amount of imported users.
:rtype: int
"""
course_list = dict(Course.objects.values_list("courseId", "pk"))
teachers_list = parse_get_teachers(get_teachers(list(course_list.keys())))
teacher_group = create_auth_group()
... | 25b03c5b79d348171d23bce54a67ebbab2911440 | 10,891 |
def baryvel(dje, deq):
"""
Calculate helio- and barycentric velocity.
.. note:: The "JPL" option present in IDL is not provided here.
Parameters
----------
dje : float
Julian ephemeris date
deq : float
Epoch of mean equinox of helio- and barycentric velocity output.
... | 76f6dccceb697996541748704b293de6cfe77cf6 | 10,892 |
def uniform(low=0.0, high=1.0, size=None):
"""This function has the same `nlcpy.random.RandomState.uniform`
See Also
--------
nlcpy.random.RandomState.uniform : Draws samples from a uniform distribution.
"""
rs = generator._get_rand()
return rs.uniform(low, high, size=size) | 48de653a1721e5602eeefc2bf5182e0100759a31 | 10,893 |
def parse_time_interval(interval_str):
"""Convert a human-readable time interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are
us, ms, s.
Returns:
... | 4edbc180722ddb84f6f2fae1e9854db14571f2d3 | 10,894 |
def submatrix(M, x):
"""If x is an array of integer row/col numbers and M a matrix,
extract the submatrix which is the all x'th rows and cols.
i.e. A = submatrix(M,x) => A_ij = M_{x_i}{x_j}
"""
return M[np.ix_(x,x)] | ba3aab45b77d8f7462fd0f2a29c96fb573618d62 | 10,895 |
def inventory_report(products: list) -> str:
"""Gives a detailed report on created products"""
unique_names, average_price, average_weight, average_flam = _build_report_metrics(products)
report = f'''ACME CORPORATION OFFICIAL INVENTORY REPORT
Unique product names: {unique_names}
Average price: {ave... | 96080f5aff04ae8d8578be3940f756b471fdce48 | 10,896 |
def iou(a, b):
""" Calculates intersection over union (IOU) over two tuples """
(a_x1, a_y1), (a_x2, a_y2) = a
(b_x1, b_y1), (b_x2, b_y2) = b
a_area = (a_x2 - a_x1) * (a_y2 - a_y1)
b_area = (b_x2 - b_x1) * (b_y2 - b_y1)
dx = min(a_x2, b_x2) - max(a_x1, b_x1)
dy = min(a_y2, b_y2) - max(a... | 0e72d00a672c430cce69246cb7d7889ae41ae216 | 10,897 |
def svn_path_is_empty(*args):
"""svn_path_is_empty(char path) -> int"""
return _core.svn_path_is_empty(*args) | bf6db11940db6767c50a002104a528cf8c7a5363 | 10,898 |
import ast
import _pytest.assertion.rewrite
import argparse
import os
def main(args=None):
"""
CphdConsistency CLI tool. Prints results to stdout.
Parameters
----------
args: None|List[str]
List of CLI argument strings. If None use sys.argv
"""
parser = argparse.ArgumentParser(d... | 17b716b1060581d970b115230dc470bab0e307af | 10,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.