content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from xmodule.modulestore.store_utilities import DETACHED_XBLOCK_TYPES
def serialize_item(item):
"""
Args:
item: an XBlock
Returns:
fields: a dictionary of an XBlock's field names and values
block_type: the name of the XBlock's type (i.e. 'course'
or 'problem')
"""
... | 426e5e83644ca2f1a81491e7e0a65a67cca26f15 | 1,952 |
def gen_outfile_name(args):
"""Generate a name for the output file based on the input args.
Parameters
----------
args : argparse
argparse object to print
"""
return args.outfile + gen_identifier(args) | 6a91c26de3ae3ec39a2095434ccc18feb9fed699 | 1,953 |
def check_vg_tags(game_id):
"""Returns a user's tags."""
if game_id:
user_id = session.get('user_id')
user_query = VgTag.query.join(Tag).filter(Tag.user_id == user_id) # Only display user's tags for a specific game.
vg_tags = user_query.filter(VgTag.game_id == game_id).all()
... | 1eed3e9a58a21a79ae5502a67bde0c409af71785 | 1,954 |
def load_fits(path):
"""
load the fits file
Parameters
----------
path: string, location of the fits file
Output
------
data: numpy array, of stokes images in (row, col, wv, pol)
header: hdul header object, header of the fits file
"""
hdul_tmp = fits.open(f'{path}')
data = np.asarray(... | f0040e9ef3c8b2e7e4136f0ef7a7a2f9370a3653 | 1,955 |
def get_image_path(cfg,
metadata,
prefix='diag',
suffix='image',
metadata_id_list='default',):
"""
Produce a path to the final location of the image.
The cfg is the opened global config,
metadata is the metadata dictionairy (fo... | 0c725311db7b3290923f6206cb2bb4d382644e12 | 1,956 |
def ProjectNameToBinding(project_name, tag_value, location=None):
"""Returns the binding name given a project name and tag value.
Requires binding list permission.
Args:
project_name: project name provided, fully qualified resource name
tag_value: tag value to match the binding name to
location: reg... | 00966f8b74378b905fe5b3c4e5a6716a5d4f71bf | 1,957 |
def degrees_of_freedom(s1, s2, n1, n2):
"""
Compute the number of degrees of freedom using the Satterhwaite Formula
@param s1 The unbiased sample variance of the first sample
@param s2 The unbiased sample variance of the second sample
@param n1 Thu number of observations in the first sample
@pa... | 5f076e33584c61dca4410b7ed47feb0043ec97cb | 1,958 |
def get_range_to_list(range_str):
"""
Takes a range string (e.g. 123-125) and return the list
"""
start = int(range_str.split('-')[0])
end = int(range_str.split('-')[1])
if start > end:
print("Your range string is wrong, the start is larger than the end!", range_str)
return range(sta... | a88d9780ac2eba1d85ae70c1861f6a3c74991e5c | 1,960 |
import base64
def get_saml_assertion(server, session, access_token, id_token=None):
"""
Exchange access token to saml token to connect to VC
Sample can be found at
https://github.com/vmware/vsphere-automation-sdk-python/blob/master/samples/vsphere/oauth/exchange_access_id_token_for_saml.py
"""
... | 174400720340fb831d6a62728b48555db7349b95 | 1,961 |
import html
def display_value(id, value):
"""
Display a value in a selector-like style.
Parameters
----------
id: int
Id of the value to be displayed
"""
return html.div(
{
"class": "py-3 pl-3 w-full border-[1px] sm:w-[48%] md:w-[121px] bg-nav rounded-[3px] md:... | aeb3ceeeb8a2048beb8df7f5d3e6027d90df4739 | 1,963 |
def helmholtz_adjoint_double_layer_regular(
test_point, trial_points, test_normal, trial_normals, kernel_parameters
):
"""Helmholtz adjoint double layer for regular kernels."""
wavenumber_real = kernel_parameters[0]
wavenumber_imag = kernel_parameters[1]
npoints = trial_points.shape[1]
dtype = t... | 6b640e2b7b02e124d893452b8437bfdf6f4af1ec | 1,964 |
def crt(s):
"""
Solve the system given by x == v (mod k),
where (k, v) goes over all key-value pairs of the dictionary s.
"""
x, n = 0, 1
for q, r in s.items():
x += n * ((r-x) * inverse(n, q) % q)
n *= q
return x | 6bcd489f9096cb780c935dd30ea90663d91f854f | 1,966 |
def create_new_tf_session(**kwargs):
"""Get default session or create one with a given config"""
sess = tf.get_default_session()
if sess is None:
sess = make_session(**kwargs)
sess.__enter__()
assert tf.get_default_session()
return sess | 1520f330fe7939c997588cf3d8c63265610baa23 | 1,967 |
import typing
import re
def MaybeGetHexShaOfLastExportedCommit(
repo: git.Repo, head_ref: str = "HEAD") -> typing.List[str]:
"""The the SHA1 of the most recently exported commit.
Args:
repo: The repo to iterate over.
head_ref: The starting point for iteration, e.g. the commit closest to
head.
... | 1d6afe688567ffe245e9aabe753c90e6baf22bfe | 1,968 |
def get_inchi(ID):
"""This function accept UNIQUE-ID and return InChI string of a certain compound"""
inchi = df_cpd['INCHI'][ID]
return inchi | 2420a73c2a5e21348c6efde7cd6bcde0cc0c0c00 | 1,969 |
from typing import Optional
def pad_to_multiple(array: Array,
factor: int,
axis: int,
mode: Optional[str] = 'constant',
constant_values=0) -> Array:
"""Pads `array` on a given `axis` to be a multiple of `factor`.
Padding will be conc... | 5164e124dc270a47ef8f8b1512cdefe796904791 | 1,971 |
import math
def define_request(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
bounds_crs="EPSG:3005",
sortby=None,
pagesize=10000,
):
"""Define the getfeature request parameters required to download a dataset
References:
- http://www.opengeospatial.org/standards/wfs
-... | 215b39a606bfa7fc6736e8b2f61bf9c298412b36 | 1,973 |
from typing import List
from typing import Tuple
import torch
def get_bert_input(
examples: List[tuple],
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert input list to torch tensor.
Args:
examples: (input_id_list, )
Returns:
attention_mask, input_ids_tensor, token_typ... | 954d0990d5cd5f28d588c472f7d7d48ecc4b3eb2 | 1,974 |
import io
import traceback
def _format_exception(e: BaseException):
"""
Shamelessly stolen from stdlib's logging module.
"""
with io.StringIO() as sio:
traceback.print_exception(e.__class__, e, e.__traceback__, None, sio)
return sio.getvalue().strip() | d80f60634a9862ca282b1c7ccf63ae8e945ffdc9 | 1,975 |
import json
def batch_deploy(blueprint_id,
parent_deployments,
group_id=None,
new_deployment_ids=None,
inputs=None,
labels=None,
**_):
"""
Create deployments for a batch from a single blueprint.
:param bl... | 8128e39c94bfc15a5b75d3a88274720b52d8d900 | 1,976 |
import json
def compute_task_def(build, settings, fake_build):
"""Returns a swarming task definition for the |build|.
Args:
build (model.Build): the build to generate the task definition for.
build.proto.infra and build.proto.input.properties must be initialized.
settings (service_config_pb2.Setti... | 7071960148ed391b42a4b7ad1e4ed4e6d0c10713 | 1,977 |
def draw_bs_pairs(x, y, func, size=1):
"""Perform pairs bootstrap for replicates."""
# Set up array of indices to sample from: inds
inds = np.arange(len(x))
# Initialize replicates
bs_replicates = np.empty(size)
# Generate replicates
for i in range(size):
bs_inds = np.random.choice... | f0b05241f567570dd96ed97340d5075b8ccb5a7b | 1,979 |
def has_hole(feature):
"""
Detects the number of holes in a shapely polygon or multipolygon.
Parameters
----------
feature : shapely Polygon or Multipolygon
polygon to be analyzed for holes
Returns
-------
int
number of holes
"""
if feature.geom_typ... | e854d7a4902e66ec95479816662a145e184ee8af | 1,980 |
def linder_table(file=None, **kwargs):
"""Load Linder Model Table
Function to read in isochrone models from Linder et al. 2019.
Returns an astropy Table.
Parameters
----------
age : float
Age in Myr. If set to None, then an array of ages from the file
is used to generate dicti... | ff6b187009c8bbcef8ae604095c289429863907e | 1,981 |
def json_redirect(request, url, **kwargs):
"""
Returns a JSON response for redirecting to a new URL. This is very specific
to this project and depends on the JavaScript supporting the result that
is returned from this method.
"""
if not request.is_ajax():
raise PermissionDenied("Must be ... | 7fbafcfc400c733badc26fcb97bc3a61f4c49f74 | 1,982 |
def unauthenticatedClient():
"""Retorna um api client sem ninguém autenticado"""
return APIClient() | b821a7c1e11a398eee691ca43be54d5aca00d213 | 1,983 |
import re
def get_known_disk_attributes(model):
"""Get known NVMe/SMART attributes (model specific), returns str."""
known_attributes = KNOWN_DISK_ATTRIBUTES.copy()
# Apply model-specific data
for regex, data in KNOWN_DISK_MODELS.items():
if re.search(regex, model):
for attr, thresholds in data.ite... | 39ece3213996b201d1109d7787bcd8fed859235b | 1,985 |
def get_one_exemplar_per_class_proximity(proximity):
"""
unpack proximity object into X, y and random_state for picking exemplars.
----
Parameters
----
proximity : Proximity object
Proximity like object containing the X, y and random_state variables
required for picking exemplars... | eeb46d07a757d6b06432369f26f5f2391d9b14cd | 1,986 |
def annotation_layers(state):
"""Get all annotation layer names in the state
Parameters
----------
state : dict
Neuroglancer state as a JSON dict
Returns
-------
names : list
List of layer names
"""
return [l["name"] for l in state["layers"] if l["type"] == "annotat... | 98dee6b821fbfe2dd449859400c2166ba694025f | 1,987 |
def describe_bvals(bval_file) -> str:
"""Generate description of dMRI b-values."""
# Parse bval file
with open(bval_file, "r") as file_object:
raw_bvals = file_object.read().splitlines()
# Flatten list of space-separated values
bvals = [
item for sublist in [line.split(" ") for line ... | 1d19c71d9422a37f425c833df52d9b1936195660 | 1,988 |
def weight_update4(weights, x_white, bias1, lrate1, b_exp):
""" Update rule for infomax
This function recieves parameters to update W1
* Input
weights : unmixing matrix (must be a square matrix)
x_white: whitened data
bias1: current estimated bias
lrate1: current learning rate
b_exp : ex... | 6c2d5c6610724787b4e8c8fb42569265e4b13d76 | 1,989 |
def Dijkstra(graph, source):
"""
Dijkstra's algorithm for shortest path between two vertices on a graph.
Arguments
---------
graph -- directed graph; object of Graph class
source -- start vertex
>>> graph = Graph()
>>> graph.addVertex("A")
>>> conns = [ ("A", "B"), ("A", "C"), ("B"... | 9585c13c5504cdbff62494c2d5d97655c2281c34 | 1,990 |
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float:
"""Return an linearly annealed epsilon
Epsilon will decrease over time until it reaches `target_episode`
(epsilon)
|
max_e ---|\
| \
| \
| \
mi... | fab650085f271f1271025e23f260eb18e645a9ba | 1,991 |
import jsonschema
def ExtendWithDefault(validator_class):
"""Takes a validator and makes it set default values on properties.
Args:
validator_class: A class to add our overridden validators to
Returns:
A validator_class that will set default values
and ignore required fields
... | 42ab80b2c52e474a354589eb4c6041450cf23fd2 | 1,992 |
def coach_input_line(call, school, f):
"""
Returns a properly formatted line about a coach.
:param call: (String) The beginning of the line, includes the gender, sport, and school abbreviation.
:param school:(String) The longform name of the school.
:param f: (String) The input line from the user.
... | 762127ac058949af890c2ef7f19b924642cc4c39 | 1,993 |
def pad_seq(seq, max_length, PAD=0):
"""
:param seq: list of int,
:param max_length: int,
:return seq: list of int,
"""
seq += [PAD for i in range(max_length - len(seq))]
return seq | bb61677bc658e22b317e3d5fb10f7c85a84200d0 | 1,994 |
def complex_domain(spectrogram):
"""
Complex Domain.
Parameters
----------
spectrogram : :class:`Spectrogram` instance
:class:`Spectrogram` instance.
Returns
-------
complex_domain : numpy array
Complex domain onset detection function.
References
----------
... | 10248ca5bb291326018934d654b2fee6a8a972d0 | 1,995 |
import torch
def toOneHot(action_space, actions):
"""
If action_space is "Discrete", return a one hot vector, otherwise just return the same `actions` vector.
actions: [batch_size, 1] or [batch_size, n, 1]
If action space is continuous, just return the same action vector.
"""
# One hot encod... | bad47c1f55795d16bdcd67aac67b4ae40a40363c | 1,996 |
def find_triangle(n):
"""Find the first triangle number with N divisors."""
t, i = 1, 1
while True:
i += 1
t += i
if len(divisors(t)) > n:
return t | b74e0e8fd869b4d9a9ae1fe83299f32eaa848e9a | 1,997 |
import requests
def get_main_page_soup(home_url):
""" parse main page soup"""
user_agent= 'Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, ' \
'like Gecko) Chrome / 64.0.3282.140 Safari / 537.36 Edge / 18.17763 '
headers = {'User-agent':user_agent}
# request to ... | 6100fa9b669ee498dea354418b3816bbc46b3b26 | 1,998 |
def gen_task4() -> np.ndarray:
"""Task 4: main corner of a triangle."""
canv = blank_canvas()
r, c = np.random.randint(GRID-2, size=2, dtype=np.int8)
syms = rand_syms(6) # 6 symbols for triangle
# Which orientation? We'll create 4
rand = np.random.rand()
if rand < 0.25:
# top left
rows, cols = [r,... | d367af38a74fd57eb86d001103a1f8656b395209 | 1,999 |
def pytest_funcarg__testname(request):
"""
The testname as string, or ``None``, if no testname is known.
This is the parameter added by the test generation hook, or ``None`` if no
parameter was set, because test generation didn't add a call for this test.
"""
return getattr(request, 'param', No... | 87444cda36635b21c27d260835f96670d6b2d215 | 2,000 |
def notes_to_editor_view(notes):
"""Convert notes object content to more readble view
Args:
notes (list): list of note object
Returns:
list: list of note object
"""
for note in notes:
note.content = to_editor(note.content)
return notes | 44dfa40fb0bf3c5c3c2aafb2731583b6e13d8853 | 2,002 |
def normalization(arr, normalize_mode, norm_range = [0,1]):
"""
Helper function: Normalizes the image based on the specified mode and range
Args:
arr: numpy array
normalize_mode: either "whiten", "normalize_clip", or "normalize" representing the type of normalization to use
norm_rang... | 8400419db77c2f76ba63999ecae89eb3fbdfae6d | 2,003 |
def draw_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=0):
"""Visualizes a single binary mask."""
was_pil = isinstance(img, (Image.Image))
img = np.array(img)
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], ... | 047bfc2f26ed38c28ff31f46746542a5d56182c4 | 2,004 |
def build_md_page(page_info: parser.PageInfo) -> str:
"""Given a PageInfo object, return markdown for the page.
Args:
page_info: Must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or
`parser.ModulePageInfo`.
Returns:
Markdown for the page
Raises:
ValueError: if `page_info` is an i... | 86ed4f8e1b9b733f45e827c65b067295a9a2ff06 | 2,005 |
from typing import Optional
def transpose(data: NodeInput, input_order: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which transposes the data in the input tensor.
@param data: The input tensor to be transposed
@param input_order: Permutation of axes to be applied to the input tensor
... | bc84792893352cdd235efd9e33fdc53cadd6521f | 2,006 |
def find_opposite_reader(card_reader_list, find):
"""Returns the card reader on the opposite side of the door for the card reader in find"""
for c in card_reader_list:
if c.room_a == find.room_b and c.room_b == find.room_a:
return c
raise (Exception("No reader on opposite side found")) | 8a70b9b35174be62f3ca816f385b4c29a6ebebe8 | 2,007 |
def tag_from_clark(name):
"""Get a human-readable variant of the XML Clark notation tag ``name``.
For a given name using the XML Clark notation, return a human-readable
variant of the tag name for known namespaces. Otherwise, return the name as
is.
"""
match = CLARK_TAG_REGEX.match(name)
i... | 948ea17b017926353a37d2ceab031751146e445a | 2,008 |
def build_k_indices(y, k_fold, seed):
"""
Randomly partitions the indices of the data set into k groups
Args:
y: labels, used for indexing
k_fold: number of groups after the partitioning
seed: the random seed value
Returns:
k_indices: an array of k sub-indices that are ra... | 3d5684ef59bc1ac0abeca243c394499258be5b54 | 2,009 |
def get_parent(obj, default=_marker):
"""Returns the container the object was traversed via.
Returns None if the object is a containment root.
Raises TypeError if the object doesn't have enough context to get the
parent.
"""
if IRoot.providedBy(obj):
return None
parent = aq_parent(... | a6c53ddd4a8bfb81f211737edf1da12688a3f4e2 | 2,010 |
import numpy
def MRR(logits, target):
"""
Compute mean reciprocal rank.
:param logits: 2d array [batch_size x rel_docs_per_query]
:param target: 2d array [batch_size x rel_docs_per_query]
:return: mean reciprocal rank [a float value]
"""
assert logits.shape == target.shape
sorted, ind... | eb9249bf0e3942aeb01b148a0db28c3e5f9dd00a | 2,011 |
def range(starts,
limits=None,
deltas=1,
dtype=None,
name=None,
row_splits_dtype=dtypes.int64):
"""Returns a `RaggedTensor` containing the specified sequences of numbers.
Each row of the returned `RaggedTensor` contains a single sequence:
```python
ragged.rang... | 177c956844596b5125c288db8859a38ecf4e8b80 | 2,012 |
def ecef2enuv(u, v, w, lat0, lon0, deg=True):
"""
for VECTOR i.e. between two points
input
-----
x,y,z [meters] target ECEF location [0,Infinity)
"""
if deg:
lat0 = radians(lat0)
lon0 = radians(lon0)
t = cos(lon0) * u + sin(lon0) * v
... | b9b6adb9232407043927cdbc0c2cec4f0b9b50a2 | 2,013 |
def interpolate_ray_dist(ray_dists, order='spline'):
""" interpolate ray distances
:param [float] ray_dists:
:param str order: degree of interpolation
:return [float]:
>>> vals = np.sin(np.linspace(0, 2 * np.pi, 20)) * 10
>>> np.round(vals).astype(int).tolist()
[0, 3, 6, 8, 10, 10, 9, 7, 5... | f1ef1906fd2871e995355a7dd8818a946eefe1e3 | 2,014 |
def distance(left, right, pairwise=pairwise['prod'], distance_function=None):
"""
Calculate the distance between two *k*-mer profiles.
:arg left, right: Profiles to calculate distance
between.
:return: The distance between `left` and `right`.
:rtype: float
"""
if not distance_functio... | 1be9b2777cf58bf52e2e33d6c39ed3655edc2354 | 2,015 |
def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
"""recursively get all imported projects, their exported and
imported modules in a dictionary object:
project-1:
url: git-url (not valid for first, top-level project)
exports:
header-dirs: ... | 66c0d25d27559e6841bcfced49646f5a711bfeb3 | 2,016 |
from typing import Optional
from typing import Sequence
def get_database_cluster(name: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseClusterResult:
"""
Provides information on a ... | edc9d4e0264e90a1491a809c40e2cf2961699d80 | 2,017 |
def tesla_loadhook(h, *args, **kwargs):
"""
Converts a load hook into an application processor.
>>> app = auto_application()
>>> def f(*args, **kwargs): "something done before handling request"
...
>>> app.add_processor(loadhook(f, *args, **kwargs))
"""
def processor(han... | 65743cd9220ddef40294cde0f4f6566ae9235772 | 2,020 |
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): #pragma: no cover
"""
Force a string to be unicode.
If strings_only is True, don't convert (some) non-string-like objects.
Originally copied from the Django source code, further modifications have
been made.
Origina... | 61992707364bfbb3e714bb52005a417387f8d7de | 2,021 |
def extractYoloInfo(yolo_output_format_data):
""" Extract box, objectness, class from yolo output format data """
box = yolo_output_format_data[..., :6]
conf = yolo_output_format_data[..., 6:7]
category = yolo_output_format_data[..., 7:]
return box, conf, category | ff28a5ce5490c61722ca06b0e09b9bd85ee7e111 | 2,022 |
def bbox_diou(bboxes1, bboxes2):
"""
Complete IoU
@param bboxes1: (a, b, ..., 4)
@param bboxes2: (A, B, ..., 4)
x:X is 1:n or n:n or n:1
@return (max(a,A), max(b,B), ...)
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
... | f32e4a289f437494fd738c1128d6e7c7a8e02c7e | 2,023 |
def showp1rev(context, mapping):
"""Integer. The repository-local revision number of the changeset's
first parent, or -1 if the changeset has no parents. (DEPRECATED)"""
ctx = context.resource(mapping, b'ctx')
return ctx.p1().rev() | 2c843d5476a8e5b43fa8ac31351de633c5fa3d6c | 2,024 |
def erp_pretax(t,ma,st,ra,par):
""" early retirement pension (efterløn) pretax"""
# initialize
ERP = np.zeros(1)
# pre two year period
if par.T_erp <= t < par.T_two_year:
if ra == 1:
priv = priv_pension(ma,st,par)
ERP[:] = np.maximum(0,par.ERP_high - 0.6*0.05*np.max... | d9a3142236aa942f8c86db1c484e57e4fc7ee278 | 2,025 |
def add_missing_cmd(command_list):
"""Adds missing cmd tags to the given command list."""
# E.g.: given:
# ['a', '0', '0', '0', '0', '0', '0', '0',
# '0', '0', '0', '0', '0', '0', '0']
# Converts to:
# [['a', '0', '0', '0', '0', '0', '0', '0'],
# ['a', '0', '0', '0', '0', '0',... | 190884575d0110f06088b9be70008da56c279344 | 2,027 |
def replace_umlauts(s: str) -> str:
"""
Replace special symbols with the letters with umlauts (ä, ö and ü)
:param s: string with the special symbols (::)
:return: edited string
"""
out = s.replace('A::', 'Ä').replace('O::', 'Ö').replace('U::', 'Ü').replace('a::', 'ä').replace('o::', 'ö') \
... | 8fad1f1017a3fd860d7e32fd191dd060b75a7bb8 | 2,028 |
def bandstructure_flow(workdir, scf_input, nscf_input, dos_inputs=None, manager=None, flow_class=Flow, allocate=True):
"""
Build a :class:`Flow` for band structure calculations.
Args:
workdir: Working directory.
scf_input: Input for the GS SCF run.
nscf_input: Input for the NSCF run... | f3515fdfa8c719c8b91a8f76a04d468e545d6f23 | 2,029 |
def resnet_50(num_classes, data_format='channels_first', pruning_method=None):
"""Returns the ResNet model for a given size and number of output classes."""
return resnet_50_generator(
block_fn=bottleneck_block_,
lst_layers=[3, 4, 6, 3],
num_classes=num_classes,
pruning_method=pruning_method... | 4962f9a4cf4aaaf0052941279c8156e29b2cb639 | 2,031 |
import json
import base64
def read_amuselabs_data(s):
"""
Read in an amuselabs string, return a dictionary of data
"""
# Data might be base64'd or not
try:
data = json.loads(s)
except json.JSONDecodeError:
s1 = base64.b64decode(s)
data = json.loads(s1)
ret = {}
... | f9c2fb2807d1003261bec7b58e4ba025aac65a6a | 2,032 |
def calinski_harabasz(dataset_values:DatasetValues):
"""Calinski, T.; Harabasz, J. (1974). A dendrite method for cluster analysis.
Communications in Statistics - Theory and Methods, v.3, n.1, p.1�27.
The objective is maximize value [0, +Inf]"""
if dataset_values.K == 1:
return 0
re... | c8231971350d22d1067056c53838f0536ae03e77 | 2,033 |
from re import IGNORECASE
def parse_version(version):
"""
input version string of the form:
'Major.Minor.Patch+CommitHash'
like:
'0.1.5+95ffef4'
------ or ------
'0.1.0'
returns version_info tuple of the form:
(major,... | cc9b326e498991092a494458d4f98cce7bbb28f9 | 2,034 |
def _location_sensitive_score(W_query, W_fil, W_keys):
"""Impelements Bahdanau-style (cumulative) scoring function.
This attention is described in:
J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben-
gio, “Attention-based models for speech recognition,” in Ad-
vances in Neural Info... | f3daa106f6ac819ef5037a221e2cd768d6810642 | 2,035 |
def get_streamdecks():
"""
Retrieves all connected streamdecks
"""
streamdecks = DeviceManager().enumerate()
return streamdecks | f649fe4404ec6be71cdb4f9cd5805738e1d0b823 | 2,036 |
import six
def clean_string(text):
"""
Remove Lucene reserved characters from query string
"""
if isinstance(text, six.string_types):
return text.translate(UNI_SPECIAL_CHARS).strip()
return text.translate(None, STR_SPECIAL_CHARS).strip() | 5387d76d4dc47997eac751538670cc426d854449 | 2,037 |
def convert_single_example(example_index, example, label_size, max_seq_length,
tokenizer, max_qa_length):
"""Loads a data file into a list of `InputBatch`s."""
# RACE is a multiple choice task. To perform this task using AlBERT,
# we will use the formatting proposed in "Improving Langu... | 385f5f2801a41e0216e8a8c22d089e986bb55588 | 2,038 |
from typing import Tuple
from typing import Optional
def _single_optimal_block(x: NDArray) -> Tuple[float, float]:
"""
Compute the optimal window length for a single series
Parameters
----------
x : ndarray
The data to use in the optimal window estimation
Returns
-------
stat... | 7de0221ddc654d4f9e8ddd56d65f688c096a7784 | 2,040 |
def predict(params, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
... | c647114ad415b2ae6c75f2fe2e207bf279775131 | 2,041 |
def response(request):
"""
返回相应对象
:param request:
:return:
"""
json_str = '{"name": "张三", "age": 18}' # 整体是个字符串
response = HttpResponse(json_str,
content_type="application/json",
status=200)
response["dev"] = "aGrass0825" # 向响应头中添加内容
... | a44b35682ff8f5de168711730a10056653319512 | 2,042 |
def nest_to_flat_dict(nest):
"""Convert a nested structure into a flat dictionary.
Args:
nest: A nested structure.
Returns:
flat_dict: A dictionary with strings keys that can be converted back into
the original structure via `flat_dict_to_nest`.
"""
flat_sequence = tf.nest.flatten(nes... | f74308fc4f7c0b97d6524faea65915263a8ced9b | 2,043 |
def plot_with_front(gen, front, title, fname):
"""
plot with front: Print the generation gen and front,
highlighting front as the pareto front on the graph.
Parameters:
gen: The generation to plot.
front: The pareto front extracted from generation gen
title: Plot Title
fname: path t... | 6556a22c6484e4c96f79a14a770cca934f50e274 | 2,046 |
def find_closest_positive_divisor(a, b):
"""Return non-trivial integer divisor (bh) of (a) closest to (b) in abs(b-bh) such that a % bh == 0"""
assert a>0 and b>0
if a<=b:
return a
for k in range(0, a-b+1):
bh = b + k
if bh>1 and a % bh == 0:
return bh
bh = b ... | 1a68e1767680f82db232095806adfe1c27fb956e | 2,047 |
def simplify_stl_names(decl):
"""Take common STL/Standard Library names and simplify them to help make the
stack trace look more readable and less like the graphics in the matrix.
"""
p = simplify_template_call(decl)
if p == []:
return decl
return p[0] + '<' + ', '.join(p[1:-1]) + ... | 53ea9c18e47ce4a7d922db74efdc45646441ea49 | 2,048 |
from typing import Sequence
from typing import Union
from typing import Callable
from typing import Optional
from typing import Tuple
def sample_switching_models(
models: Sequence,
usage_seq: Sequence,
X: Union[None, Sequence, Callable] = None,
initial_conditions: Optional[Tuple[Sequence, Sequence]] =... | 472e20968fe835b01da57c4a0abab376c006094b | 2,049 |
def eval_per_class(c_dets, c_truths, overlap_thresh=0.5, eval_phrase=False):
""" Evaluation for each class.
Args:
c_dets: A dictionary of all detection results.
c_truths: A dictionary of all ground-truth annotations.
overlap_thresh: A float of the threshold used in IoU matching.
Re... | 7884255c6fb45d6cb01b88edd5017d134f0344b0 | 2,050 |
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe
unit commitment for projects. Unless otherwise stated, all power
capacity is specified in units of MW and all sets and parameters
are mandatory.
-- Commit decision, limits, and headroom --
CommitP... | 4ad0aae0df9a3953309138dfbc138f944efba74e | 2,051 |
def adjustwithin(df, pCol, withinCols, method='holm'):
"""Apply multiplicity adjustment to a "stacked"
pd.DataFrame, adjusting within groups defined by
combinations of unique values in withinCols
Parameters
----------
df : pd.DataFrame
Stacked DataFrame with one column of pvalues
... | 4040c53def07ce5353c111036887b5df4666684c | 2,052 |
def parse_url_query_params(url, fragment=True):
"""Parse url query params
:param fragment: bool: flag is used for parsing oauth url
:param url: str: url string
:return: dict
"""
parsed_url = urlparse(url)
if fragment:
url_query = parse_qsl(parsed_url.fragment)
else:
url_... | 252d2ccfb2fb15db041e97908c982dae9bf3c1ef | 2,053 |
import torch
import math
def sample_random_lightdirs(num_rays, num_samples, upper_only=False):
"""Randomly sample directions in the unit sphere.
Args:
num_rays: int or tensor shape dimension. Number of rays.
num_samples: int or tensor shape dimension. Number of samples per ray.
upper_... | 7f7657ff66d0cffea6892dffdf49ba6b52b9def9 | 2,054 |
def gaussgen(sigma):
"""
Function to generate Gaussian kernels, in 1D, 2D and 3D.
Source code in MATLAB obtained from Qiyuan Tian, Stanford University, September 2015
:param sigma: Sigma for use in generating Gaussian kernel (see defaults in generate_FSL_structure_tensor)
:return: Gaussian kernel wi... | 7673e3fb8ddbb7bbb646331a24380581a7af9617 | 2,055 |
import types
from typing import List
def metrics_specs_from_keras(
model_name: Text,
model_loader: types.ModelLoader,
) -> List[config.MetricsSpec]:
"""Returns metrics specs for metrics and losses associated with the model."""
model = model_loader.construct_fn()
if model is None:
return []
metric... | fd471d20782507e983abec5610115e83c59ed7e0 | 2,056 |
def __main__(recipe, params):
"""
Main code: should only call recipe and params (defined from main)
:param recipe:
:param params:
:return:
"""
# ----------------------------------------------------------------------
# Main Code
# -----------------------------------------------------... | 3e9fc1006457be759e1e0b05f36c00297f0c5f4c | 2,057 |
def AICrss(n, k, rss):
"""Calculate the Akaike Information Criterion value, using:
- n: number of observations
- k: number of parameters
- rss: residual sum of squares
"""
return n * log((2 * pi) / n) + n + 2 + n * log(rss) + 2 * k | 988345930a8544d2979b99d6400198d3a59fa85c | 2,058 |
from typing import Optional
def get_username_from_access_token(token: str, secret_key: str, algorithm: str) -> Optional[str]:
"""
Decodes a token and returns the "sub" (= username) of the decoded token
:param token: JWT access token
:param secret_key: The secret key that should be used for token decod... | 461ce205b43961af25c77af4d3902d1342bba32a | 2,061 |
def date_handler(obj):
"""make datetime object json serializable.
Notes
-----
Taken from here: https://tinyurl.com/yd84fqlw
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError | 741867e05e1b5f3e9d0e042b3b1576fb61ab0219 | 2,063 |
def has_type(typestmt, names):
"""Return type with name if `type` has name as one of its base types,
and name is in the `names` list. otherwise, return None."""
if typestmt.arg in names:
return typestmt
for t in typestmt.search('type'): # check all union's member types
r = has_type(t, n... | d534331df62f76efdcbb93be52eb57ee600a7783 | 2,064 |
def generic_ecsv(file_name, column_mapping=None, **kwargs):
"""
Read a spectrum from an ECSV file, using generic_spectrum_from_table_loader()
to try to figure out which column is which.
The ECSV columns must have units, as `generic_spectrum_from_table_loader`
depends on this to determine the meaning... | 0c9ac3a8d31a449e698907e02ad4715868844403 | 2,065 |
def parse_valuation_line(s, encoding=None):
"""
Parse a line in a valuation file.
Lines are expected to be of the form::
noosa => n
girl => {g1, g2}
chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)}
:param s: input line
:type s: str
:param encoding: the encoding of the input... | aebd7ca9e4e321069a04536f281230b5cd23cceb | 2,066 |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def scrape_dailykos(keywords=KEYWORDS):
"""
Scrapes news article titles from dailykos.com
"""
dk_request = requests.get('https://www.dailykos.com')
dk_homepage = dk_request.content
dk_soup = BeautifulSoup(dk_homepage, ... | a6b5cbffce87f75c7561bc8939247f80bb10ae11 | 2,067 |
def parse_rows(m: utils.Matrix[str]) -> pd.DataFrame:
"""Parse rows to DataFrame, expecting specific columns and types."""
if len(m) < 2:
logger.error('More than one line expected in {}'.format(str(m)))
return pd.DataFrame()
# parse data rows and add type casting
cols = len(m[0])
df... | 46749bccf7af71256e1f1d490e1a2f241ed0c4d9 | 2,068 |
import base64
import struct
def tiny_id(page_id):
"""Return *tiny link* ID for the given page ID."""
return base64.b64encode(struct.pack('<L', int(page_id)).rstrip(b'\0'), altchars=b'_-').rstrip(b'=').decode('ascii') | 1a37b814ff9845949c3999999b61f79b26dacfdc | 2,069 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.