content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import tempfile
import gzip
def load_training_data():
"""Loads the Fashion-MNIST dataset.
Returns:
Tuple of Numpy arrays: `(x_train, y_train)`.
License:
The copyright for Fashion-MNIST is held by Zalando SE.
Fashion-MNIST is licensed under the [MIT license](
https://githu... | be2a5d84c8ef0cd1aa62564a3fd3882af49344ca | 15,400 |
def set_difference(tree, context, attribs):
"""A meta-feature that will produce the set difference of two boolean features
(will have keys set to 1 only for those features that occur in the first set but not in the
second).
@rtype: dict
@return: dictionary with keys for key occurring with the first... | 7887f619e601624843c6507e7b93442020ecf1ea | 15,401 |
def create_STATES(us_states_location):
"""
Create shapely files of states.
Args:
us_states_location (str): Directory location of states shapefiles.
Returns:
States data as cartopy feature for plotting.
"""
proj = ccrs.LambertConformal(central_latitude = 25,
... | fe2b48f465ee7e63bb4dfa91e2c9917eeeab082f | 15,402 |
def get_name_by_url(url):
"""Returns the name of a stock from the instrument url. Should be located at ``https://api.robinhood.com/instruments/<id>``
where <id> is the id of the stock.
:param url: The url of the stock as a string.
:type url: str
:returns: Returns the simple name of the stock. If th... | c90e453bb1576d8c93a3388ab2cfe0d9f63d550c | 15,403 |
def recursively_replace(original, replacements, include_original_keys=False):
"""Clones an iterable and recursively replaces specific values."""
# If this function would be called recursively, the parameters 'replacements' and 'include_original_keys' would have to be
# passed each time. Therefore, a h... | aee393b09c74eb6cb1417d017d7004ac69bb3543 | 15,404 |
from typing import get_origin
from typing import get_args
def destructure(hint: t.Any) -> t.Tuple[t.Any, t.Tuple[t.Any, ...]]:
"""Return type hint origin and args."""
return get_origin(hint), get_args(hint) | 451d1fd5a3277f882b9645dcdc78b2accc4d56a2 | 15,405 |
def f_x_pbe(x, kappa=0.804, mu=0.2195149727645171):
"""Evaluates PBE exchange enhancement factor.
10.1103/PhysRevLett.77.3865 Eq. 14.
F_X(x) = 1 + kappa ( 1 - 1 / (1 + mu s^2)/kappa )
kappa, mu = 0.804, 0.2195149727645171 (PBE values)
s = c x, c = 1 / (2 (3pi^2)^(1/3) )
Args:
x: Float numpy array with... | 9933a379b659b38082aa91d4498a399a43b2e20c | 15,406 |
def index():
"""
if no browser and no platform: it's a CLI request.
"""
if g.client['browser'] is None or g.client['platform'] is None:
string = "hello from API {} -- in CLI Mode"
msg = {'message': string.format(versions[0]),
'status': 'OK',
'mode': 200}
... | d497ce0cf12bbe914ab3147080c05a4441e9d39b | 15,407 |
import sys
def prompt_yes_no(question, default=None):
"""Asks a yes/no question and returns either True or False."""
prompt = (default is True and 'Y/n') or (default is False and 'y/N') or 'y/n'
valid = {'yes': True, 'ye': True, 'y': True, 'no': False, 'n': False}
while True:
choice = input(question + pr... | 1cd9c6c19d8bca536b41baec901ba77baa1153c6 | 15,408 |
def attention_resnet20(**kwargs):
"""Constructs a ResNet-20 model.
"""
model = CifarAttentionResNet(CifarAttentionBasicBlock, 3, **kwargs)
return model | e44061a9ad42ceea26aa263a5169ffec62857f90 | 15,409 |
import re
def get_basename(name):
""" [pm/cmds] オブジェクト名からベースネームを取得する """
fullpath = get_fullpath(name)
return re(r"^.*\|", "", fullpath) | a18cd5ac563dd37c53bdf6b0c1ea6a55efa7a221 | 15,410 |
from typing import Optional
def get_live_token(resource_uri: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLiveTokenResult:
"""
The response to a live token query.
:param str resource_uri: The identifier of the resource.
"""
__args__ = dict(... | b82d799ff261994643c807f4d1b947ba591d6a14 | 15,411 |
def load_subspace_vectors(embd, subspace_words):
"""Loads all word vectors for the particular subspace in the list of words as a matrix
Arguments
embd : Dictonary of word-to-embedding for all words
subspace_words : List of words representing a particular subspace
Returns
subspace_e... | 5eb1db8be8801cf6b1fe294a6f2c93570e9a9fe1 | 15,412 |
from datetime import datetime
def _safe_filename(filename):
"""
Generates a safe filename that is unlikely to collide with existing
objects in Google Cloud Storage.
``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext``
"""
filename = secure_filename(filename)
date = datet... | 63e55ccbf29505868efe702cd7c25cdfb0e6ad2f | 15,413 |
from typing import List
from typing import Tuple
def get_raw(contents: List[str]) -> Tuple[sections.Raw, List[str]]:
"""Parse the \\*RAW section"""
raw_dict, rest = get_section(contents, "raw")
remarks = raw_dict[REMARKS] if REMARKS in raw_dict else ""
raw_info = sections.Raw(
remarks=remarks,... | 005af62533c129d39b7af1524b00a48a9113adde | 15,414 |
import itertools
def transfers_from_stops(
stops,
stop_times,
transfer_type=2,
trips=False,
links_from_stop_times_kwargs={'max_shortcut': False, 'stop_id': 'stop_id'},
euclidean_kwargs={'latitude': 'stop_lat', 'longitude': 'stop_lon'},
seek_traffic_redundant_paths=True,
seek_transfer_r... | 9e9456440b3dc6cbdd367f9ea99f85559e3343cd | 15,415 |
from pypy.module.cpyext.tupleobject import PyTuple_GetItem
from pypy.module.cpyext.listobject import PyList_GetItem
def PySequence_ITEM(space, w_obj, i):
"""Return the ith element of o or NULL on failure. Macro form of
PySequence_GetItem() but without checking that
PySequence_Check(o)() is true and withou... | 8a3bb364d6d2e96681bb89b170b8517e09eb719c | 15,416 |
import codecs
import binascii
def decode_hex(data):
"""Decodes a hex encoded string into raw bytes."""
try:
return codecs.decode(data, 'hex_codec')
except binascii.Error:
raise TypeError() | 115e89d6f80a6fc535f44d92f610a6312edf6daf | 15,417 |
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... | 2cd53c51f6a80034630a53a43678d22f1073e7f4 | 15,418 |
def computeDateGranularity(ldf):
"""
Given a ldf, inspects temporal column and finds out the granularity of dates.
Example
----------
['2018-01-01', '2019-01-02', '2018-01-03'] -> "day"
['2018-01-01', '2019-02-01', '2018-03-01'] -> "month"
['2018-01-01', '2019-01-01', '2020-01-01'] -> "year"
Parameters
-----... | e998a144b22c6e65599f1f6b5cc2ec893310e3cc | 15,419 |
from typing import Optional
from typing import Tuple
import sqlite3
def next_pending_location(user_id: int, current_coords: Optional[Tuple[int, int]] = None) -> Optional[Tuple[int, int]]:
"""
Retrieves the next pending stone's coordinates. If current_coords is not specified (or is not pending),
retrieves ... | fb26531819c19532d7dbf8152963245f07af8e7c | 15,420 |
import re
import keyword
def get_valid_identifier(prop, replacement_character='', allow_unicode=False):
"""Given a string property, generate a valid Python identifier
Parameters
----------
replacement_character: string, default ''
The character to replace invalid characters with.
allow_un... | a3eeb389b73540aba2041e877c2ff151e272ffdd | 15,421 |
from re import T
def temporal_padding(x, paddings=(1, 0), pad_value=0):
"""Pad the middle dimension of a 3D tensor
with `padding[0]` values left and `padding[1]` values right.
Modified from keras.backend.temporal_padding
https://github.com/fchollet/keras/blob/3bf913d/keras/backend/theano_b... | 8ccc828ac68cd98da4e7ec5f8253ae5385317d48 | 15,422 |
import sys
import os
def get_args_and_hdf5_file(cfg):
"""
Assembles the command line arguments for training and the filename for the hdf5-file
with the results
:return: args, filename
"""
common_parameters = [
"--train:mode", "world",
"--train:samples", "256**3",
"--tr... | c6cc382384274e6c127a7494f1cbf170dbe62158 | 15,423 |
def get_orientation(y, num_classes=8, encoding='one_hot'):
"""
Args:
y: [B, T, H, W]
"""
# [H, 1]
idx_y = np.arange(y.shape[2]).reshape([-1, 1])
# [1, W]
idx_x = np.arange(y.shape[3]).reshape([1, -1])
# [H, W, 2]
idx_map = np.zeros([y.shape[2], y.shape[3], 2])
idx_map[:, ... | 501c57cf447865ec03229a3ba15125da3837eb8e | 15,424 |
def plot_tempo_curve(f_tempo, t_beat, ax=None, figsize=(8, 2), color='k', logscale=False,
xlabel='Time (beats)', ylabel='Temp (BPM)', xlim=None, ylim=None,
label='', measure_pos=[]):
"""Plot a tempo curve
Notebook: C3/C3S3_MusicAppTempoCurve.ipynb
Args:
f_... | fd8f084d5912b7b64929e7bc8a61bd4dfc8ae107 | 15,425 |
def not_pathology(data):
"""Return false if the node is a pathology.
:param dict data: A PyBEL data dictionary
:rtype: bool
"""
return data[FUNCTION] != PATHOLOGY | b420826265164445e8df470a4049d68839182d4b | 15,426 |
def remove_index_fastqs(fastqs,fastq_attrs=IlluminaFastqAttrs):
"""
Remove index (I1/I2) Fastqs from list
Arguments:
fastqs (list): list of paths to Fastq files
fastq_attrs (BaseFastqAttrs): class to use for
extracting attributes from Fastq names
(defaults to IlluminaFastqAttrs)... | fc62bd4ab28427ba51d8cd56d17576c89e2ed7ad | 15,427 |
from typing import Union
from typing import List
def max(name: "Union[str, List[Expr]]") -> "Expr":
"""
Get maximum value
"""
if isinstance(name, list):
def max_(acc: Series, val: Series) -> Series:
mask = acc < val
return acc.zip_with(mask, val)
return fold(l... | 3ca308e951801e4376483188249da2333aafc789 | 15,428 |
def initialize(Lx, Ly,
solutes, restart_folder,
field_to_subspace,
concentration_init, rad,
enable_NS, enable_EC,
dx,
surface_charge,
permittivity,
**namespace):
""" Create the initial state. """
... | 802affd7e56598cb4a22e37480313401254e263f | 15,429 |
def _get_sentry_sdk():
"""Creates raven.Client instance configured to work with cron jobs."""
# NOTE: this function uses settings and therefore it shouldn't be called
# at module level.
try:
sentry_sdk = __import__("sentry_sdk")
DjangoIntegration = __import__(
"sentry_s... | 8682004e68606bf8f67487ad541455179c50493c | 15,430 |
def get_memos():
"""
Returns all memos in the database, in a form that
can be inserted directly in the 'session' object.
"""
records = [ ]
for record in collection.find( { "type": "dated_memo" } ):
record['date'] = arrow.get(record['date']).isoformat()
del record['_id']
r... | d9f0f66db05d368d086b77669418652565ea8587 | 15,431 |
import os
def filepath(folder, *args, ext='pkl'):
"""Returns the full path of the file with the calculated results
for the given dataset, descriptor, descriptor of the given dataset
Parameters
----------
folder : string
Full path of the folder where results are saved.
args : list or t... | b558559a7b92db6943b6dd04670d9dc4097b5675 | 15,432 |
def psplit(df, idx, label):
"""
Split the participants with a positive label in df into two sets, similarly for participants with a negative label. Return two numpy arrays of participant ids, each array are the chosen id's to be removed from two dataframes to ensure no overlap of participants between the two se... | fa8652d8812c8f4fd94c7d2601b964b7aaced963 | 15,433 |
def se_block(inputs, out_node, scope=None):
# TODO: check feature shape and dimension
"""SENet"""
with tf.variable_scope(scope, "se_block", reuse=tf.AUTO_REUSE):
channel = inputs.get_shape().as_list()[3]
net = tf.reduce_mean(inputs, [1,2], keep_dims=False)
net = fc_layer(net, [channel, out_node]... | 7fecd9c0796324c4e74eea0cf07a23ef50306aaf | 15,434 |
import os
import pickle
def deri_cie_ionfrac(Zlist, condifile='adia.exp_phy.info', \
condi_index=False, appfile=False, outfilename=False, rootpath=False):
"""
Derive the CIE ionic fraction based on the physical conditions in
an ASCII file. The only input parameter is the index (array) of
the elements.
P... | 65d29a7290b2d086e211d26dc3dd8166d5b0caaf | 15,435 |
from numscons import get_scons_build_dir
import os
def get_numpy_include_dirs(sconscript_path):
"""Return include dirs for numpy.
The paths are relatively to the setup.py script path."""
scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path))
n = scdir.count(os.sep)
dirs = _incdir()
... | 5ae44cadbf3451f88e5118e4493c7895ab6941e1 | 15,436 |
import numpy
def invU(U):
"""
Calculate inverse of U Cell.
"""
nr, nc = U.getCellsShape()
mshape = U.getMatrixShape()
assert (nr == nc), "U Cell must be square!"
nmat = nr
u_tmp = admmMath.copyCell(U)
u_inv = admmMath.Cells(nmat, nmat)
for i in range(nmat):
for j ... | 58765834bde6c93e419d3e2f6d8de25d1740c587 | 15,437 |
def liq_g(drvt,drvp,temp,pres):
"""Calculate liquid water Gibbs energy using F03.
Calculate the specific Gibbs free energy of liquid water or its
derivatives with respect to temperature and pressure using the
Feistel (2003) polynomial formulation.
:arg int drvt: Number of temperature deriv... | dfa3eef9d0b9228495b2d4d33a503c0e8c174c2a | 15,438 |
import os
def read(fname):
"""
Utility function to read the README file.
Used for the long_description. It's nice, because now 1) we have a top
level README file and 2) it's easier to type in the README file than to put
a raw string in below ...
"""
with open(os.path.join(os.path.dirname(... | 3320773f53a555e4a8c9ca84c76de282ff91d955 | 15,439 |
import asyncio
def get_tcp_client(tcp_server_address: str, tcp_server_port: int, session_handler: SessionHandler):
"""Returns the TCP client used in the 15118 communication.
:param tcp_server_address: The TCP server address.
:param tcp_server_port: The TCP server port.
:param session_handler: The ses... | 8ebf68acc054831d03e707b1b868bed62e9fe24a | 15,440 |
def extract_dates(obj):
"""extract ISO8601 dates from unpacked JSON"""
if isinstance(obj, dict):
new_obj = {} # don't clobber
for k,v in iteritems(obj):
new_obj[k] = extract_dates(v)
obj = new_obj
elif isinstance(obj, (list, tuple)):
obj = [ extract_dates(o) for o... | 1dd7dbda376755cd962c23d2149f41e8559cff12 | 15,441 |
def construct_covariates(states, model_spec):
"""Construct a matrix of all the covariates
that depend only on the state space.
Parameters
---------
states : np.ndarray
Array with shape (num_states, 8) containing period, years of schooling,
the lagged choice, the years of experience ... | 883395fc3561ea2fb774eb0ea6dfd866a3d2eed6 | 15,442 |
from datetime import datetime
def target_ok(target_file, *source_list):
"""Was the target file created after all the source files?
If so, this is OK.
If there's no target, or the target is out-of-date,
it's not OK.
"""
try:
mtime_target = datetime.datetime.fromtimestamp(
ta... | f47e89f10d9855913bcfaa07ac97965caabeeaa7 | 15,443 |
def check_oblique_montante(grille, x, y):
"""Alignements diagonaux montants (/) : allant du coin bas gauche au coin haut droit"""
symbole = grille.grid[y][x]
# Alignement diagonal montant de la forme XXX., le noeud (x,y) étant le plus bas et à gauche
if grille.is_far_from_top(y) and grille.is_far_from_r... | f1ca8d7b55117e3e03c5150a07fd483a1da0a4d5 | 15,444 |
def _rotate_the_grid(lon, lat, rot_1, rot_2, rot_3):
"""Rotate the horizontal grid at lon, lat, via rotation matrices rot_1/2/3
Parameters
----------
lon, lat : xarray DataArray
giving longitude, latitude in degrees of LLC horizontal grid
rot_1, rot_2, rot_3 : np.ndarray
rotation ma... | b6c81dcc8191c2843534f369269e5c9cd466d581 | 15,445 |
def dict_mapper(data):
"""Mapper from `TypeValueMap` to :class`dict`"""
out = {}
for k, v in data.items():
if v.type in (iceint.TypedValueType.TypeDoubleComplex,
iceint.TypedValueType.TypeFloatComplex):
out[k] = complex(v.value.real, v.value.imag)
elif v.typ... | b10ba4ed38d81cca3fc760d281a32d46d03d4223 | 15,446 |
import os
import sys
import re
def parse_prophage_tbl(phispydir):
"""
Parse the prophage table and return a dict of objects
:param phispydir: The phispy directory to find the results
:return: dict
"""
if not os.path.exists(os.path.join(phispydir, "prophage.tbl")):
sys.stderr.write("FA... | 5a913ec2818a37458fd84267748c199990035a8e | 15,447 |
import time
import asyncio
async def get_odds(database, params):
"""Get odds based on parameters."""
LOGGER.info("generating odds")
start_time = time.time()
players = [dict(
civilization_id=data['civilization_id'],
user_id=data['user_id'],
winner=data['winner'],
team_i... | 0f71b893df370244e82cd952f4bc1a15cae30728 | 15,448 |
def split_by_normal(cpy):
"""split curved faces into one face per triangle (aka split by
normal, planarize). in place"""
for name, faces in cpy.iteritems():
new_faces = []
for points, triangles in faces:
x = points[triangles, :]
normals = np.cross(x[:, 1]-x[:, 0], x[:... | 9a4c563465cc2deb5c2946f3e182fc9b71327081 | 15,449 |
def generate_index_distribution_from_blocks(numTrain, numTest, numValidation, params):
""" Generates a vector of indices to partition the data for training.
NO CHECKING IS DONE: it is assumed that the data could be partitioned
in the specified block quantities and that the block quantities describe ... | 7bb30a6f69a45d231cbb4a140d7527a270f22e27 | 15,450 |
def sct2e(sc, sclkdp):
"""sct2e(SpiceInt sc, SpiceDouble sclkdp)"""
return _cspyce0.sct2e(sc, sclkdp) | a32defabb20993b87c182121e209e62c190a46c8 | 15,451 |
import re
import json
def test_main(monkeypatch, test_dict: FullTestDict):
"""
- GIVEN a list of words
- WHEN the accent dict is generated
- THEN check all the jisho info is correct and complete
"""
word_list = convert_list_of_str_to_kaki(test_dict['input'])
sections = test_dict['jisho']['... | f32d75bc5219cf48eccffcd777dc0881e0299ae7 | 15,452 |
import os
def normalizeFilename(filename):
"""Take a given filename and return the normalized version of it.
Where ~/ is expanded to the full OS specific home directory and all
relative path elements are resolved.
"""
result = os.path.expanduser(filename)
result = os.path.abspath(result)
r... | a83e1ece98d23708eb6ae8a2acbe4f8495f9e2b8 | 15,453 |
def get_tn(tp, fp, fn, _all):
"""
Args:
tp (Set[T]):
fp (Set[T]):
fn (Set[T]):
_all (Iterable[T]):
Returns:
Set[T]
"""
return set(_all) - tp - fp - fn | a9afa3a2f07c8b63a6d6911b9a54cf9f9df08600 | 15,454 |
def download_cow_head():
"""Download cow head dataset."""
return _download_and_read('cowHead.vtp') | 70dc6617d3b9d6a8f9fa4df90caf749d00a6d778 | 15,455 |
def select_tests(blocks, match_string_list, do_test):
"""Remove or keep tests from list in WarpX-tests.ini according to do_test variable"""
if do_test not in [True, False]:
raise ValueError("do_test must be True or False")
if (do_test == False):
for match_string in match_string_list:
... | f77a0b9e91ec34b85479a442008241c7da386beb | 15,456 |
def get_last_ds_for_site(session, idescr: ImportDescription, col: ImportColumn, siteid: int):
"""
Returns the newest dataset for a site with instrument, valuetype and level fitting to the ImportDescription's column
To be used by lab imports where a site is encoded into the sample name.
"""
q = sess... | 41040efe43c0189a3cc8b7288e47eccd752674a7 | 15,457 |
def get_cart_from_request(request, cart_queryset=Cart.objects.all()):
"""Get cart from database or return unsaved Cart
:type cart_queryset: saleor.cart.models.CartQueryset
:type request: django.http.HttpRequest
:rtype: Cart
"""
if request.user.is_authenticated():
cart = get_user_cart(req... | 5d9d7e3708db5db38f07aea9299ee0aacdecea22 | 15,458 |
def _is_ge(series, value):
""" Returns the index of rows from series where series >= value.
Parameters
----------
series : pandas.Series
The data to be queried
value : list-like
The values to be tested
Returns
-------
index : pandas.index
The index of series fo... | 98b8825753953b1b9bf7348d04d260b7514a7749 | 15,459 |
def preprocess_image(image, image_size, is_training=False, test_crop=True):
"""Preprocesses the given image.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: Size of output image.
is_training: `bool` for whether the preprocessing is for training.
test_crop: whether or not ... | 913f614798daaf7b752195c92e48890868666b57 | 15,460 |
async def wait_for_reaction(self, message):
""" Assert that ``message`` is reacted to with any reaction.
:param discord.Message message: The message to test with
:returns: The reaction object.
:rtype: discord.Reaction
:raises NoReactionError:
"""
def check_reaction(reaction, user):
... | 67890343d6b59923e8fd3e655252eddcde88323c | 15,461 |
def _multivariate_normal_log_likelihood(X, means=None, covariance=None):
"""Calculate log-likelihood assuming normally distributed data."""
X = check_array(X)
n_samples, n_features = X.shape
if means is None:
means = np.zeros_like(X)
else:
means = check_array(means)
asser... | d5144074f0a88c51a0c46f1b36eb8bdd95f9140e | 15,462 |
import tokenize
def lemmatize(text):
"""
tokenize and lemmatize english messages
Parameters
----------
text: str
text messages to be lemmatized
Returns
-------
list
list with lemmatized forms of words
"""
def get_wordnet_pos(treebank_tag):
if treebank_... | 0a744953ac014f2c0551cecb9c235fc405bf5aaa | 15,463 |
def prune_non_overlapping_boxes(boxes1, boxes2, min_overlap):
"""Prunes the boxes in boxes1 that overlap less than thresh with boxes2.
For each box in boxes1, we want its IOA to be more than min_overlap with
at least one of the boxes in boxes2. If it does not, we remove it.
Arguments:
boxes1: a... | 5e1a04022707364f1d1a8b14afbd356e781137b9 | 15,464 |
def get_namespace_from_node(node):
"""Get the namespace from the given node
Args:
node (str): name of the node
Returns:
namespace (str)
"""
parts = node.rsplit("|", 1)[-1].rsplit(":", 1)
return parts[0] if len(parts) > 1 else u":" | a2305719c0e72614f75309f1412ce71c9264b5df | 15,465 |
def PricingStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | d87eae22f74b5251261bb39aea93e46887f03725 | 15,466 |
import json
import os
def get_structures(defect_name: str,
output_path: str,
bdm_increment: float=0.1,
bdm_distortions: list = None,
bdm_type="BDM",
):
"""Imports all the structures found with BDM and stores them in a... | 921996e12dc327e2a3f813bec278127c4963970e | 15,467 |
def create_whimsy_value_at_clients(number_of_clients: int = 3):
"""Returns a Python value and federated type at clients."""
value = [float(x) for x in range(10, number_of_clients + 10)]
type_signature = computation_types.at_clients(tf.float32)
return value, type_signature | 87d1d110392bd83585fd19ba2e8a10a0c8507d30 | 15,468 |
def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
return "[#%d](%s)" % (task... | b6b7975cb45cdae0a146a67c0fab51ef0724aee2 | 15,469 |
def get_tick_indices(tickmode, numticks, coords):
"""
Ticks on the axis are a subset of the axis coordinates
This function returns the indices of y coordinates on which a tick should be displayed
:param tickmode: should be 'auto' (automatically generated) or 'all'
:param numticks: minimum number of ... | 72cf3fed39db3cabf672bff4b042c8685356f9ff | 15,470 |
def fpIsNormal(a, ctx=None):
"""Create a Z3 floating-point isNormal expression.
"""
return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) | ee6e2cccf1ad0534929aa0632d271d37f58a232e | 15,471 |
import os
import argparse
def existingFile(filename):
""" 'type' for argparse - check that filename exists """
if not os.path.exists(filename):
raise argparse.ArgumentTypeError("{0} does not exist".format(filename))
return filename | 01d51420bba9edc18e7aecf53950a6ab843c384c | 15,472 |
import math
def siqs_find_next_poly(n, factor_base, i, g, B):
"""Compute the (i+1)-th polynomials for the Self-Initialising
Quadratic Sieve, given that g is the i-th polynomial.
"""
v = lowest_set_bit(i) + 1
z = -1 if math.ceil(i / (2 ** v)) % 2 == 1 else 1
b = (g.b + 2 * z * B[v - 1]) % g.a
... | d5529db62a194582aacd8769a56688cf6b42bbe1 | 15,473 |
def get_column(value):
"""Convert column number on command line to Python index."""
if value.startswith("c"):
# Ignore c prefix, e.g. "c1" for "1"
value = value[1:]
try:
col = int(value)
except:
stop_err("Expected an integer column number, not %r" % value)
if col < 1:... | 858f4128955c0af579d99dcd64be157b41c6dae3 | 15,474 |
def sdi(ts_split, mean=False, keys=None):
"""
Compute the Structural Decoupling Index (SDI).
i.e. the ratio between the norms of the "high" and the norm of the "low"
"graph-filtered" timeseries.
If the given dictionary does not contain the keywords "high" and "low",
the SDI is computed as the ... | 9ed09f72bc6902b5c007286e12f1ed72d904d4b8 | 15,475 |
def Class_Property (getter) :
"""Return a descriptor for a property that is accessible via the class
and via the instance.
::
>>> from _TFL._Meta.Property import *
>>> from _TFL._Meta.Once_Property import Once_Property
>>> class Foo (object) :
... @Class_Property
... | 845d62444f41b547b9922d10666f8a911c7e8de3 | 15,476 |
def naive_act_norm_initialize(x, axis):
"""Compute the act_norm initial `scale` and `bias` for `x`."""
x = np.asarray(x)
axis = list(sorted(set([a + len(x.shape) if a < 0 else a for a in axis])))
min_axis = np.min(axis)
reduce_axis = tuple(a for a in range(len(x.shape)) if a not in axis)
var_sha... | 78034c16e38c27b146a8ee1be1be86d9fc4ffe6a | 15,477 |
def cmpTensors(t1, t2, atol=1e-5, rtol=1e-5, useLayout=None):
"""Compare Tensor list data"""
assert (len(t1) == len(t2))
for i in range(len(t2)):
if (useLayout is None):
assert(t1[i].layout == t2[i].layout)
dt1 = t1[i].dataAs(useLayout)
dt2 = t2[i].dataAs(useLayout)
... | ce085c9998fddc86420ea4f5307e83e15d49372a | 15,478 |
def auth(body): # noqa: E501
"""Authenticate endpoint
Return a bearer token to authenticate and authorize subsequent calls for resources # noqa: E501
:param body: Request body to perform authentication
:type body: dict | bytes
:rtype: Auth
"""
db = get_db()
cust = db['Customer'].find... | 2992d119cf7fa3a5d797825c704cd837f647dbd7 | 15,479 |
def make_feature(func, *argfuncs):
"""Return a customized feature function that adapts to different input representations.
Args:
func: feature function (callable)
argfuncs: argument adaptor functions (callable, take `ctx` as input)
"""
assert callable(func)
for argfunc in argfuncs:
... | 26064ee0873d63edc877afdcb03a39e40453a831 | 15,480 |
import ctypes
def from_numpy(np_array: np.ndarray):
"""Convert a numpy array to another type of dlpack compatible array.
Parameters
----------
np_array : np.ndarray
The source numpy array that will be converted.
Returns
-------
pycapsule : PyCapsule
A pycapsule containing... | 2663b831274f1fc1dd2e597212fa475f6d03e578 | 15,481 |
def lmsSubstringsAreEqual(string, typemap, offsetA, offsetB):
"""
Return True if LMS substrings at offsetA and offsetB are equal.
"""
# No other substring is equal to the empty suffix.
if offsetA == len(string) or offsetB == len(string):
return False
i = 0
while True:
aIsLMS... | 5177b8cf5b2b80a519ef0d9fbb5f972c584a6b5b | 15,482 |
from .tools import nantrapz
def synthesize_photometry(lbda, flux, filter_lbda, filter_trans,
normed=True):
""" Get Photometry from the given spectral information through the given filter.
This function converts the flux into photons since the transmission provides the
fraction o... | 6eb8b9806388b9b373e37a2c813e3a4ba9696bc2 | 15,483 |
def get_A_dash_floor_bath(house_insulation_type, floor_bath_insulation):
"""浴室の床の面積 (m2)
Args:
house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸'
floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない'
Returns:
float: 浴室の床の面積 (m2)
"""
return get_table_3(15, house_insula... | fbcd2c6dd6b5e2099351b445bf4b3e71aed4d508 | 15,484 |
def cancel_task_async(hostname, task_id):
"""Cancels a swarming task."""
return _call_api_async(
None, hostname, 'task/%s/cancel' % task_id, method='POST') | fb1b57dac80518e2cf3b375d8ecd393b34855b45 | 15,485 |
def generate_two_files_both_stress_strain():
"""Generates two files that have both stress and strain in each file"""
fname = {'stress': 'resources/double_stress.json',
'strain': 'resources/double_strain.json'}
expected = [ # makes an array of two pif systems
pif.System(
pro... | 6cfe410071085bc975f630e34e43c8b2b626f846 | 15,486 |
import sys
def run_cli(entry_point, *arguments, **options):
"""
Test a command line entry point.
:param entry_point: The function that implements the command line interface
(a callable).
:param arguments: Any positional arguments (strings) become the command
... | 4ff525bd5b8b8edb520151475f6da58a9bed7172 | 15,487 |
def recipe_edit(username, pk):
"""Page showing the possibility to edit the recipe."""
recipe_manager = RecipeManager(api_token=g.user_token)
response = recipe_manager.get_recipe_response(pk)
recipe = response.json()
# shows 404 if there is no recipe, response status code is 404 or user is not the au... | 73735cd5c279c8e62aebdacfb29c5d3d83c856fa | 15,488 |
import re
def load_data_file(filename):
"""loads a single file into a DataFrame"""
regexp = '^.*/results/([^/]+)/([^/]+)/([^/]+).csv$'
optimizer, blackbox, seed = re.match(regexp, filename).groups()
f = ROOT + '/results/{}/{}/{}.csv'.format(optimizer, blackbox, seed)
result = np.genfromtxt(f, deli... | a2c53adfc356809f7ec554d20203a5ad276ebc1e | 15,489 |
def get_hub_manager():
"""Generate Hub plugin structure"""
global _HUB_MANAGER
if not _HUB_MANAGER:
_HUB_MANAGER = _HubManager(_plugins)
return _HUB_MANAGER | 384039f45f59cec3db737536a08719770ecfb3ff | 15,490 |
def extract_stimtype(
data: pd.DataFrame, stimtype: str, columns: list
) -> pd.DataFrame:
"""
Get trials with matching label under stimType
"""
if stimtype not in accept_stimtype:
raise ValueError(f"invalid {stimtype}, only accept {accept_stimtype}")
get = columns.copy()
get += ["par... | 186cc066133d1d8d6c443b17a2d17cc70d366d98 | 15,491 |
def compute_rank_clf_loss(hparams, scores, labels, group_size, weight):
"""
Compute ranking/classification loss
Note that the tfr loss is slightly different than our implementation: the tfr loss is sum over all loss and
devided by number of queries; our implementation is sum over all loss and devided by... | 12b45518d5bd11182dbf220ccfe90da2fe0d6c38 | 15,492 |
import string
def get_org_image_url(url, insert_own_log=False):
""" liefert gegebenenfalls die URL zum Logo der betreffenden Institution """
#n_pos = url[7:].find('/') # [7:] um http:// zu ueberspringen
#org_url = url[:n_pos+7+1] # einschliesslich '/'
item_containers = get_image_items(ELIXIER_LOGOS_PATH)
... | b80d29a3393820e6cfc58e36ae34361d4587bd73 | 15,493 |
import asyncio
import logging
async def download_page(url, file_dir, file_name, is_binary=False):
"""
Fetch URL and save response to file
Args:
url (str): Page URL
file_dir (pathlib.Path): File directory
file_name (str): File name
is_binary (bool): True if should download ... | 452285e7d47d7d7c227e356efc0e7dc1ad2ce7ee | 15,494 |
def normal_coffee():
"""
when the user decides to pick a normal or large cup of coffee
:return: template that explains how to make normal coffee
"""
return statement(render_template('explanation_large_cup', product='kaffee')) | ba9ed37cb85327d6541ad86071f047ce87297c95 | 15,495 |
def _transitive_closure_dense_numpy(A, kind='metric', verbose=False):
"""
Calculates Transitive Closure using numpy dense matrix traversing.
"""
C = A.copy()
n, m = A.shape
# Check if diagonal is all zero
if sum(np.diagonal(A)) > 0:
raise ValueError("Diagonal has to be zero for matr... | cf02a380dbf28a6442cc999b3faea329d5041b17 | 15,496 |
def convert_date(raw_dates: pd.Series) -> pd.Series:
"""Automatically converts series containing raw dates
to specific format.
Parameters
----------
raw_dates:
Series to be converted.
Returns
-------
Optimized pandas series.
"""
raw_dates = pd.to_datetime(raw_dates,... | 23a2310ec8fd30dd2b831805817fb3407c10c104 | 15,497 |
async def get_scorekeeper_by_id(scorekeeper_id: conint(ge=0, lt=2**31)):
"""Retrieve a Scorekeeper object, based on Scorekeeper ID,
containing: Scorekeeper ID, name, slug string, and gender."""
try:
scorekeeper = Scorekeeper(database_connection=_database_connection)
scorekeeper_info = scorek... | 044b3bacfdf47918c2ad15635958d69c17ccf5c8 | 15,498 |
import inspect
import os
def modulePath():
"""
This will get us the program's directory, even if we are frozen
using py2exe
"""
try:
_ = sys.executable if weAreFrozen() else __file__
except NameError:
_ = inspect.getsourcefile(modulePath)
return os.path.dirname(os.path.di... | 46c404ccb60044f7c1687692f5ba4903230a5769 | 15,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.