content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_data_args(parser: HyperOptArgumentParser) -> HyperOptArgumentParser:
"""
Functions that parses dataset specific arguments/hyperparameters.
:param hparams: HyperOptArgumentParser obj.
Returns:
- updated parser
"""
parser.add_argument(
"--data_type",
default="csv",... | 1b9b9310489554928a338d6d08cedc3bd54d1a0c | 59,800 |
def beam2d_KeMe(EI,L,Mass,T=0, theta=None, MMFormulation='consistent' ):
"""
Stiffness and mass matrices for Hermitian beam element with 2DOF per node.
- Bending in one transverse direction
Euler-Bernoulli beam model.
The beam coordinate system is such that the cross section is assumed ... | 8e2bf5bec351fbb7d0c27a02c6488cb8fa35d2f7 | 59,801 |
def manage_static_blocks(request):
"""Dispatches to the first static block or to the add static block form.
"""
try:
sb = StaticBlock.objects.all()[0]
url = reverse("lfs_manage_static_block", kwargs={"id": sb.id})
except IndexError:
url = reverse("lfs_manage_no_static_blocks")
... | 40d0260ea94fd37f8a890100bbe5f1c00d0379a1 | 59,802 |
import warnings
def modcpppxd(mod, exceptions=True, ts=None):
"""Generates a cpp_*.pxd Cython header file for exposing a C/C++ module to
other Cython wrappers based off of a dictionary description of the module.
Parameters
----------
mod : dict
Module description dictonary.
exceptions... | 0ed08446465956220e6922bf9f611dc51172ed1a | 59,803 |
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
"""Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
... | fbca0e5a62f2f5b1371d4d21a7665493fbea948a | 59,804 |
import unicodedata
import re
def slugify(name):
"""
Slugify a column header for use as a name.
Adapted from Django.
"""
slug = name
slug = unicodedata.normalize('NFKD', unicode(slug)).encode('ascii', 'ignore')
slug = unicode(re.sub('[^\w\s-]', '', slug).strip().lower())
slug = re.sub(... | 8865a1b6dda6bc3e9a3b1711058d6bb26cc324e4 | 59,805 |
import random
def get_challenge():
"""Prime game Q&A generation.
generate random Number and check if a Number is Prime
Returns:
question{str} : Number;
answer{str} : Prime status
"""
num = random.randint(MIN_NUM, MAX_NUM)
answer = 'yes' if is_prime(num) else 'no'
question... | a72d73ef9cf005f75f12e76475657b548b026f36 | 59,806 |
def dashboard_get_for_rendering(id):
"""Get a dashboard with its definition, and current settings necessary
for rendering.
"""
dashboard = database.DashboardRecord.query.get_or_404(id)
dash = _set_dashboard_hrefs(dashboard.to_json(True))
return {
'dashboard' : dash,
'preferences' : ... | 60d1351e45c0e83d45c2a4732aa33f871eef6a0a | 59,807 |
def page_dirs_to_page_name(page_dirs):
"""
[カテゴリ1,カテゴリ2,ページ]というディレクトリの配列状態になっているページパスを
「カテゴリ1/カテゴリ2/ページ」というファイル名に変換する。
:param page_dirs:
:return:
"""
page_name = ""
for page_dir in page_dirs:
if page_dir:
page_name = page_name + page_dir + "/"
page_name = page_na... | 0254fb2cab146fd8054de23d27b485094513447f | 59,808 |
def include_paths_for_include(source, include, headers):
"""Estimate include paths for single include in source file and mapped header file."""
database = defaultdict(list)
up_reference_count = 0
ambiguous_paths = list()
# Find if include in source_file could be mapped to some internal header
# ... | 857f0a49f2c59ef6d9afae91de433d3eeca7f6eb | 59,809 |
from math import erfc
def _phi_real(zs,rs,R,alpha, Rc):
"""Finds the real space portion of the ewald summation.
Args:
zs (list of int): The amount of charge on each nucleus.
rs (list of list of float): Each entry contains the position of an atom.
R (list of list of float): The lattice... | 3c02f161daa6c049e60ae60bcb48df0cab59f093 | 59,810 |
def _IsServicingPrivilegedRequest():
"""Checks whether the request is considered privileged."""
try:
request = webapp2.get_request()
except AssertionError:
# This happens in unit tests, when code gets called outside of a request.
return False
path = getattr(request, 'path', '')
if path.startswith(... | 69fce1fc56ed6b7958eda05055fa367f9b00cdf3 | 59,811 |
def get_team_slug_name(project_name, role):
"""
Get the team name and team slug based on GitHub's naming scheme. By
convention, teams are named in a well-defined .
team name schema
CT: <project name> <role, pluralized>
team slug schema
ct-<project_name_slug>-<role_slug>
@param project... | 8c830659eca6e35d0483ed3dad3b797eb91bbc25 | 59,812 |
def norm_weight(nin, nout=None, scale=0.01, ortho=True):
"""
Get a (orthogonal) Gaussian weight matrix W, scaled
if desired (and not orthogonal).
:param nin:
:param nout:
:param scale:
:param ortho:
:return W:
"""
logger.warn('Norm weight with range: +/-{}'.format(scale))
if ... | d993eb9660fc512274685ebd93b7126e3a0d9afb | 59,813 |
def validate_signature(uri, nonce, signature, auth_token=''):
"""
Validates requests made by Plivo to your servers.
:param uri: Your server URL
:param nonce: X-Plivo-Signature-V2-Nonce
:param signature: X-Plivo-Signature-V2 header
:param auth_token: Plivo Auth token
:return: True if the req... | 3ea7589f957391674ed05632e3188cd8338282e4 | 59,814 |
def DecryptAlgo(EncryptData,PayloadSize,StartKey,Keys):
"""
IN: Encrypted Data, PayloadSize,StartKey and Dictionary of keys
OUT: Bytearray of decrypted data
Description:
This function is the PlugX crypto routine used in compressed PlugX samples
"""
key0=StartKey&0xFFFFFFFF
key1=StartKey... | 05f802399b4485743609522f40b0e8f962f3332e | 59,815 |
from typing import Tuple
def compute_voronoi_density(
traj_data: pd.DataFrame,
measurement_area: pygeos.Geometry,
geometry: Geometry,
cuf_off: float = None,
num_edges: int = 40,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Compute the voronoi density of the trajectory per frame inside the given ... | 89ef38f8037ab0df6f3a6d069bf030794a5fce5f | 59,816 |
def psalfromasal(s_gkg,lon0,lat0,p_dbar):
"""Convert absolute salinity to practical salinity.
Convert salinity in practical salinity units (PSU) to absolute
salinity.
:arg float s_gkg: Absolute salinity in g/kg.
:arg float lon0: Reference longitude in degrees East.
:arg float lat0: Ref... | 6e00ebef75ca2746066e1b9f580983dbab18cba5 | 59,817 |
def prepare_maxmind_database(license_key, database_edition, storage_dir):
"""Downloads, extracts and caches a maxmind geoip database for offline use."""
checksum = download_maxmind_database_checksum(license_key, database_edition)
archive_path = download_maxmind_database_archive(license_key, database_edition... | 7324058c6b13038110a8d1d9ae62b66788018448 | 59,818 |
from datetime import datetime
import os
def promoteNamespaceRequests(request, license_id=None):
""" View for promote namespace license requests
returns promote_namespace_requests.html template
"""
if request.method == "POST" and request.is_ajax():
promoted = request.POST.get('promoted', False)... | 4c051991a0788cb9ef91ce121829f95d5c5e53a4 | 59,819 |
def read_csv(
file_path: str,
delim: str,
header_rows: int,
footer_rows: int,
encod: str,
) -> pd.DataFrame:
"""
Read a specified CSV file into a Dataframe.
:param file_path: Path to CSV file
:type file_path: str
:param delim: CSV separator
:type delim: str
:param header... | c84374ca3d1a0a3e9c37c498dde4f8e6bc122689 | 59,820 |
def reproject_raster_dataset(src_ds, **kwargs):
"""Reproject/Resample given dataset according to keyword arguments
Parameters
----------
src_ds : :py:class:`gdal:osgeo.gdal.Dataset`
raster image with georeferencing (GeoTransform at least)
Keyword Arguments
-----------------
spacing... | 291403b2433ba1c0bf73830cc449a2dddf75bb82 | 59,821 |
def np_onehot(data, num_class=None):
"""Numpy based one-hot encoding in the last dimmension"""
if num_class is not None:
num_class = np.max(data) + 1
onehot_data = np.eye(num_class)[data]
return onehot_data | 942dc6fe319feb24ea2938f12c3777a7dda03161 | 59,822 |
def camera_connected():
"""Return the list of connected camera compatible with gPhoto2.
"""
if hasattr(gp, 'gp_camera_autodetect'):
# gPhoto2 version 2.5+
cameras = gp.check_result(gp.gp_camera_autodetect())
else:
port_info_list = gp.PortInfoList()
port_info_list.load()
... | 89bba43ca7de8a8a74af7c0ed65adba3f952c3f6 | 59,823 |
import copy
def get_action_movement(movement, annotation, data_config):
"""
Get movement of actions before and after the screen time.
There essentially will be two actions for each player in the annotation.
Parameters
----------
movement: pandas.DataFrame
sportvu movement data
dat... | 10508f10a05d9a43b7125293d14c2eac8b277963 | 59,824 |
def make_grpc_stub(url: str, port: int) -> ChupacabraServerStub:
"""Make a stub for the GRPC server."""
location = '{}:{}'.format(url, port)
channel = grpc.insecure_channel(location)
stub = ChupacabraServerStub(channel)
return stub | c4bb0b39cd9b1843980261262e4b917da12d7a4d | 59,825 |
def build_gaussian_layer(mean, standard_deviation, step=1, len=8, sharpness=0.2):
"""
copy from blog.csdn.net
"""
# scaled_size = int(len / sharpness)
scaled_size = len
center_point = (scaled_size, scaled_size)
x = np.arange(-scaled_size + 1, scaled_size, step) * (sharpness**2)
y = np.ar... | 59358f0ef4907e2d8e5d92159c5cd8cb73985e0d | 59,826 |
def getLogs(d, rho, v, usingT=True):
"""
Function to make plotting convenient
"""
dpth, rholog = getPlotLog(d, rho)
_, vlog = getPlotLog(d, v)
zlog = getImpedance(rholog, vlog)
rseries, _ = getReflectivity(d, rho, v, usingT)
return dpth, rholog, vlog, zlog, rseries | ce36fa820105d014d79c93e98202833ad7407811 | 59,827 |
def parse_raw(output):
"""Just return `output` as a single string assigned to dict key '_'
for reference in assertion expressions.
Returns {'_': output}
"""
return dict(_=output) | 7fe463b997687bedad6d77d4bca4718037f18069 | 59,828 |
def to_list(gen_out):
"""Generation output handler that converts to the rev 1.0 format."""
if isinstance(gen_out, list) and len(gen_out) == 1:
out = [c['cf_mean'] for c in gen_out[0].values()]
if isinstance(gen_out, dict):
out = [c['cf_mean'] for c in gen_out.values()]
return out | 51dc2e93e3bc741d51a19bacd4b2200fb0e6b3f7 | 59,829 |
import scipy.linalg
import numpy
def sift_keypoints (fn):
"""
Return the SIFT keypoints of an image.
Two arrays are returned, the first giving the locations (and
corresponding scales and orientations) of the feature points found,
while the second contains the associated descriptors.
Argument... | 5881512f2b58a18fce5bb48bad51306c903ba97d | 59,830 |
from functools import reduce
def chinese_remainder(n: int, a: int) -> int:
"""Chinese remainder theorem in Python
shamelessly stolen from
https://rosettacode.org/wiki/Chinese_remainder_theorem#Python_3.6
"""
sum = 0
prod = reduce(lambda a, b: a * b, n)
for n_i, a_i in zip(n, a):
p... | daf0806c6b1801bef24e69634ad06422f06166fa | 59,831 |
def sample_word_language_model_family_cfg(seed):
"""Sample a word language model config."""
rng = np.random.RandomState(seed)
cfg = {}
cfg["embed_dim"] = utils.sample_log_int(rng, 8, 128)
cfg["w_init"] = utils.sample_initializer(rng)
cfg["vocab_size"] = utils.sample_log_int(rng, 1000, 30000)
cfg["core"] =... | 4f5d48e91717048f598aa9cdaef3043c506b802d | 59,832 |
def ask_yes_no(prompt, default=None):
"""Asks a question and returns a boolean (y/n) answer.
If default is given (one of 'y','n'), it is used if the user input is
empty. Otherwise the question is repeated until an answer is given.
An EOF is treated as the default answer. If there is no default, an
... | 54c238df04e593b4cbea239ee970345f1305738d | 59,833 |
from typing import Callable
def make_vector_gradient(bcs: Boundaries) -> Callable:
"""make a discretized vector gradient operator for a cylindrical grid
{DESCR_CYLINDRICAL_GRID}
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
Returns:
... | c19259d3d6f9cfa76bb4d3e227fd5e365cd986af | 59,834 |
def _kl_dirichlet_dirichlet(d1, d2, name=None):
"""Batchwise KL divergence KL(d1 || d2) with d1 and d2 Dirichlet.
Args:
d1: instance of a Dirichlet distribution object.
d2: instance of a Dirichlet distribution object.
name: Python `str` name to use for created operations.
Default value: `None` (i... | 66719bf0d1517dfe44ddba696cfe4fb6e60a4beb | 59,835 |
def _resolve_fork_relationships(workflow):
"""
Requires proper workflow structure.
Fork must come before a join.
"""
def helper(workflow, node, last_fork):
if isinstance(node, Fork):
join = None
children = node.get_children()
for child in children:
join = helper(workflow, child.g... | 24d34fb786e66f67db06d691c3fb372d281d427c | 59,836 |
def max_neighbors(G,f,column,n=1):
"""
Adds a column to the dataframe f with the maximum value of its neigbors feature.
G: a networkx graph.
f: a pandas dataframe.
column: the column to which the mean is applied.
n: neighbourhood order.
"""
if not(set(f.name) == set(G.nodes()) and len(f.... | 4a483d9a90cce6e9bfa6c0d20797395239387972 | 59,837 |
def _c_helper_fieldaccess_expr(prefix, field=None):
"""
turn prefix, which is a list of tuples (name, separator, Type obj) into a string
representing a valid field-access-expression in C (based on the context)
if field is not None, append access to the field as well.
"separator" is one of the C-ope... | dcc3a9b3063040426f450eb8fee27278ddbee206 | 59,838 |
def rivers_by_station_number(stations, N):
"""Given a list of station objects, and a value N, this function
returns a list of tuples with the N rivers with the largest number
of stations. If there is more than one river with the same number
of stations as the Nth river, they will be included as well"""
... | 3dcd1207f28f27a8cdb4a6e502b4b6dbfe143cf4 | 59,839 |
def getOrbitalElements(_parVec:list) -> OrbitElem:
"""
Returns all Orbital Elements and the Period, packed into a data class
Parameters
----------
_parVec : list
Parameter Vector for current orbit
Returns
-------
OrbitalElem Object
"""
Pars = ParVecToParams(_parVec)
... | 0f09718d9595e089d821af3678370e58427dfc8a | 59,840 |
import os
def tests_data(scope="session"):
"""A dict with paths and URLs to tests data files."""
datafiles = {}
tests_dataurl = "https://github.com/BLSQ/geohealthaccess/raw/master/tests/data/"
tests_datadir = os.path.dirname(
resource_filename(__name__, "data/madagascar.geojson")
)
for... | a78ec4e8b5efbf9453cec7e697a343ec2f938fba | 59,841 |
import signal
import getopt
import sys
def main(argv):
"""
Run as a portable command-line program.
This program handles data through standard I/O streams as UTF-8 text.
Input has any leading byte-order marks stripped out from the beginning
of the input stream. Broken pipes and SIGINT are handled ... | 76eded1408d0dfa308f3d9161fc3b689f1ed9463 | 59,842 |
def request_passes_test(test_func, redirect_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the request passes the given test,
redirecting to the redirect url if necessary. The test should be a
callable that takes the request and retur... | 057348b67d929e17d01801b6916dd86dd6ebb648 | 59,843 |
def curve_fit(f, x, y, p0):
"""Fits an arbitraty function to data (x,y).
This part comes from:
http://projects.scipy.org/scipy/browser/trunk/scipy/optimize/minpack.py
:param f:
:type f:
:param x:
:type x:
:param y:
:type y:
:param p0:
:type p0:
:returns:
:rtype:
... | 58a769a77c9052a29a1d1151bc89e0d638daa2f5 | 59,844 |
def pole_from_endpoints(coord1, coord2):
"""Compute the pole from a great circle that connects the two specified
coordinates.
This assumes a right-handed rule from coord1 to coord2: the pole is the
north pole under that assumption.
Parameters
----------
coord1 : `~astropy.coordinates.SkyCo... | 975def501cbdaf0065ca62c3370d7f06ddac29b1 | 59,845 |
from random import random
from phenum.msg import verbosity
from tqdm import tqdm
from random import randrange
def add_arrows(col,agroup,dim, translations, accept=None,nested=False,num_wanted=None, small=False, supers = False):
"""Finds the unique arrangements of arrows for a given configuration.
Args:
... | d8ee5e65f68e9c3f4709c17edeb6f2b387b1a3fa | 59,846 |
from typing import Dict
import torch
from typing import Optional
import warnings
def make_mesh_texture_atlas(
material_properties: Dict,
texture_images: Dict,
face_material_names,
faces_verts_uvs: torch.Tensor,
texture_size: int,
texture_wrap: Optional[str],
) -> torch.Tensor:
"""
Give... | b9507fc9d5b0371b6334dd164c935069d8aa02a2 | 59,847 |
def calc_reference_quantiles(prcp: pd.DataFrame) -> pd.DataFrame:
"""Composition of calc_reference_station and reference_quantiles."""
# This makes sure that we do not use the reference dataset directly, just the quantiles
ref = calc_reference_station(prcp)
q = reference_quantiles(ref)
return q | c14e0a1e4f07d7a6f2c0e66c078594cdd5537bd0 | 59,848 |
def CalculateChannelSlope(pts_array, slope_window_size=5):
"""
Clubb 2019 - JGR:ES
Modified from: https://github.com/UP-RS-ESP/river-clusters/blob/master/clustering.py
"""
grad = np.empty(len(pts_array))
slicer = (slope_window_size - 1)/2
for index, x in enumerate(pts_array):
start... | f6c31ad36446d35d1dca07343dfcac4dbfb123d5 | 59,849 |
def get_regulon(hp, parent=None, layers=None):
"""Build a subgraph to replace a node."""
num_layers = safe_sample(hp.min_layers, hp.max_layers)
M = nx.MultiDiGraph()
ids = []
for layer_number in range(num_layers):
n_nodes = safe_sample(hp.min_nodes, hp.max_nodes)
log(f"add layer {lay... | 8837dfc60637426fcc028719a5f76b5b1d689b30 | 59,850 |
def inference_on_image(model, image, network_dim, obj_thresh, letterbox=False, show_img=False):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Similar to inference except takes in an image as input (simpler to use)
- Performs all needed pre and post processing
- Returned detection... | 6924a4e747d292127ab86bcf083204424ac9306d | 59,851 |
import os
def get_conf(parser):
""" parse the arguments and set the model configuration parameters """
conf = parser.parse_args()
# make paths absolute
wd = os.path.dirname(__file__)
conf.model_dir = os.path.join(wd, conf.model_dir)
conf.data_dir = os.path.join(wd, conf.data_dir)
if hasat... | 5930a3b24f8a429a3a3b19c14a9976f1cbf57051 | 59,852 |
import re
def http_header_link_regex(relation_type):
"""Create a regex matching the http header links of the given type."""
return re.compile(r'.*;+\s*rel="{}"\s*(;.*)?'.format(
re.escape(relation_type))) | 4085e9258c0f6d5d1de33f82318aa9006fbe40bc | 59,853 |
from datetime import datetime
def _get_new_end_time(latest_time):
""" Helper function to move the end time to the next 9am.
Args:
latest_time: the time in ms
Returns:
the new time in ms
"""
time_9am = datetime.time(9,0,0)
end_datetime = datetime.datetime.fromti... | 13c2b7357a9d5f79002628a61b8b6cdad7b5e3af | 59,854 |
def trial_reshape_spectral(positions, spectrum, trial_inds):
"""
reshapes the spectral data if the data is trial type
Args:
positions (np.ndarray): point positions
spectrum (np.ndarray): spectrogram array
trial_inds (np.ndarray): array of the trial indices
Returns:
resh... | 3471a1f7d7d8d944b48ac5c3fd823c275646e9c8 | 59,855 |
from typing import Iterable
def none_of(elements: Iterable[Element]) -> CNF:
"""Forces exclusion of matching rows on a truth table"""
return Q(elements) == 0 | 2d0789f3c00da27ee56c4db4b2b82dcef01861ca | 59,856 |
def rolling_count(arg, window, **kwargs):
"""
Rolling count of number of non-NaN observations inside provided window.
Parameters
----------
arg : DataFrame or numpy ndarray-like
window : int
Size of the moving window. This is the number of observations used for
calculating the ... | 386dbfdc2b41519b58f6dad344c480abbf317994 | 59,857 |
def softmax_backward(Y, softmax_out):
"""
Y: labels of training data. shape: (vocab_size, m)
softmax_out: output out of softmax. shape: (vocab_size, m)
"""
dL_dZ = softmax_out - Y
assert(dL_dZ.shape == softmax_out.shape)
return dL_dZ | c814b04d864953318b16140d8c348fb3d7275c89 | 59,858 |
def inp():
"""
For taking integer inputs.
"""
return(int(input())) | 2d776b703c9825a33ae80f7e966f00a4aa9c2289 | 59,859 |
import colorcet
def _get_from_colorcet(name):
""" import colormap from colorcet definition """
try:
except ModuleNotFoundError:
return None
color_strings = colorcet.palette[name]
color_list = []
for hex_str in color_strings:
if hex_str[0] != '#': continue
if len(hex_str... | ecb31a880a0e433b4e48cb39b9dabc703deb0bfb | 59,860 |
def D(n):
"""" Convert n to decimal """
if n is None:
return None
return Decimal(str(n)) | d1d2a3cac9facc67c50f69eac20d1849dec26beb | 59,861 |
def reorient(in_file, newpath=None):
"""Reorient Nifti files to LPS."""
out_file = fname_presuffix(in_file, suffix='_lps', newpath=newpath)
to_lps(nb.load(in_file)).to_filename(out_file)
return out_file | cb186c1317c36da26a35bff55ffc806364951437 | 59,862 |
def term_op():
"""Parser for symbolic operators
>>> pstream(term_op(),'PRIM_TERM_OP_CONTROLSEQ { TERM } {TERM }')
Etok(cs_brace,prim_term_op_controlseq,'PRIM_TERM_OP_CONTROLSEQ { TERM } { TERM }')
"""
return first(get_lookup_parse('prim_term_op') ,
cs_brace(get_lookup_parse('prim_te... | f79a6ca7c8f34751771a0e96ae0e8e02572cf86e | 59,863 |
def PARAM_writer(input_dictionary):
"""Return the PARAM section
Parameters
----------
input_dictionary : dictionary
Dictionary with the defined parameter information
Returns
-------
str
string : string containing PARAM section
"""
string="PARAM----1----*----2----*----3----*----4----*----5----*----6---... | 71c3b63298a397723f3c59a381e382dd856cec5e | 59,864 |
def squares_within_unit_list(s, unit_type):
"""Returns a list of the squares within the same unit as s.
unit_type can be 'row', 'column', or 'unit3x3' """
assert unit_type in unit_types
if unit_type == 'row':
return (units[s][0])
elif unit_type == 'column':
return (units[s][1])
... | 78876de8aaa16f850049e531be229ffa9934bde0 | 59,865 |
def optimalLocationRectangularDistance(D_filtered: pd.DataFrame, latCol: str, lonCol: str, weightCol: str):
"""
this function returns the optimal location based on rectangular distances
Args:
D_filtered (pd.DataFrame): Input dataframe.
latCol (str): Column name containing latitude.
... | 27244d1880f99259f4614d2d0dca95392ff6e871 | 59,866 |
def assemble(inputs, outputs, dataset, seed=None):
"""Assemble the HyperBlocks based on the dataset and input output nodes.
# Arguments
inputs: A list of InputNode. The input nodes of the AutoModel.
outputs: A list of HyperHead. The heads of the AutoModel.
dataset: tf.data.Dataset. The ... | b57490b17cb69a593fa25357c6b29c7dbb5d3264 | 59,867 |
def read_txt(path):
"""Read a mass spectrum from a text file.
Args:
path (str): Path to the spectrum.
Returns:
tuple: Lists with m/z and intensities.
"""
mz = []
i = []
with open(path) as f:
for line in f:
line = line.split()
mz.appen... | e0efe8549596ec2bf312967ecf265d8eb8b3372c | 59,868 |
import requests
def latest_branch_commit(user: str, repo: str, branch: str) -> str:
"""
Grabs the latest commit for a specific branch.
Args:
user: (`str`)
The account name.
repo: (`str`)
The repo name.
branch: (`str`)
The branch name.
Retur... | a4e0f3a7f61a404d64bd38cc9fd662e6a9242919 | 59,869 |
import json
def model_to_dictionary(obj):
"""
Given a model instance `obj`, return a dictionary that represents it.
E.g. something like
{
'pk': 15,
'model':
'audit.auditorstaffmember',
'auditor_firm': 15,
'user': 934
}
For _simple_ use from templates, th... | a12c9906de39486846ee8e51571d75578334aa6f | 59,870 |
def get_back_labels(node,root):
"""given a node, return a list of back tip labels"""
all_labels = get_front_labels(root)
front_labels = get_front_labels(node)
return set(all_labels) - set(front_labels) | afca33f9954125d076cdca74bb5005a9c93413e2 | 59,871 |
def random():
"""Return a random parameter set for the model."""
fractal_dim = np.random.uniform(0, 6)
surface_portion = np.random.uniform(0, 1)
fractal_dim_surf = fractal_dim*surface_portion
fractal_dim_mass = fractal_dim - fractal_dim_surf
rg_cluster = 10**np.random.uniform(1, 5)
rg_primar... | 47c85b745af4cecd2104bb667c52baaeb0b463fb | 59,872 |
import requests
import html
import re
def snopes(text):
"""snopes <topic> -- Searches snopes for an urban legend about <topic>."""
try:
params = {'sp_q': text, 'sp_c': "1"}
request = requests.get(search_url, params=params)
request.raise_for_status()
except (requests.exceptions.HTT... | eebec93f70ce00ee2a13d58b37b775810046ba2d | 59,873 |
def log(bot, message):
"""
记录聊天记录.
"""
logging = Log(qq=message.qq, type=type(message).__name__)
if isinstance(message, RcvdGroupMessage):
logging.group = message.group
elif isinstance(message, RcvdDiscussMessage):
logging.discuss = message.discuss
logging.save()
retur... | 8e67b8c16fd5d969c68e6839900186a3d28eb2c2 | 59,874 |
def apology(message, code=400):
"""
Render message as an apology to user
"""
return render_template('apology.html', code=code, message=message), code | 90962de02c3e43f7561cd380f05aaade2bf3eb72 | 59,875 |
def SetDocEndTime(doc:NexDoc, endtime):
"""Sets the length (in seconds) of experimental session for the document."""
return NexRun("SetDocEndTime", locals()) | 5daa4905c059fff5ffee91abb5db428ef9f360fa | 59,876 |
def now():
"""Returns the current timestamp in ms
Returns:
int -- current ms
"""
return rospy.Time.now().to_nsec() | 00c57a01055d3516f34be2ca5d94a4ff4129f76c | 59,877 |
def find_parent(
child: str,
parent_of: dict,
recursive=False):
"""
Find the parent or great-great-...-great-parent of a child
Required Parameters
-------------------
child: str
If this is already the greatest-parent, will return itself
otherwise, raise KeyE... | 429f91160f6abc8710ced71b07e5e2e5c0a97cfc | 59,878 |
import os
def process_config(raw_path, cache_dir, cache_file, **kwargs):
"""
Read a build configuration and create it, storing the result in a build
cache.
Arguments
raw_path -- path to a build configuration
cache_dir -- the directory where cache should be written
cache_file -- The filena... | c7a797ca168ad8c6512d641379ec97650b25b04e | 59,879 |
def process_immediate(immediate):
"""
Returns a integer object from a string object.
"""
if not isinstance(immediate, str):
raise TypeError('Immediate must be a String object.')
if immediate.startswith("0x"):
return int(immediate, 16)
else:
return int(immediate) | b6665563663731337df2b7a31defaca0ae3de24f | 59,880 |
from typing import Any
import lzma
import json
def get_gist_json_file(db_url: str, file_name: str) -> Any:
"""
Grab the contents from a gist file
:param db_url: Database URL
:param file_name: File to open from Gist
:return: File content
"""
LOGGER.info("Cloning gist database")
git_sh =... | 600db080b792da554780b93250eee1e71a713226 | 59,881 |
def get_all_records_by_country(instance):
"""
Collect all confirmed, recovered and deaths for all the countries
:param instance: class instance
:return: dict
"""
result = dict()
for _action in instance._actions_files.keys():
reader = instance.get_reader(_action)
# Dict reade... | 79d0ddac0f2dbfbbc56ad06117c1bcf7bde17bd9 | 59,882 |
def zeros(shape, typecode='l', savespace=0, dtype=None):
"""zeros(shape, dtype=int) returns an array of the given
dimensions which is initialized to all zeros
"""
dtype = convtypecode(typecode,dtype)
return mu.zeros(shape, dtype) | 53c8b96caa0ff70dee4c59037cfc2b9fd33b65ee | 59,883 |
def egenskapfilter(v4, regl, dakat):
"""
Filterer V4-dataframe på egenskapverdi hvis reglene tilsier det
ARGUMENTS:
v4 - dataframe
regl - Regler
dakat = datakatalogdefinisjon for denne objekttypen, tilpasset vår logikk
KEYWORDS:
None
RETURNS:
Et subs... | 6b41dcf56846e8f708b363c33904a5433a25d5f8 | 59,884 |
import sys
def loadValidationFile( known_file ): ##############################################
""" this version stores:
refA->refB->ATxpt = 'c':call, 't':set(Btxpts), 'g':set(Bgenes)
"""
refD = {}
source_ids = set( [] )
uniques = set([ 'absent_gene', 'absent_genome', 'absent_transcript', 'gene_fusion'... | fd263854927135da60704c44b0351065f54cf17d | 59,885 |
def successors_query(var_name, node_id, node_label,
edge_label, successor_label=None,
undirected=False):
"""Generate query for getting the ids of all the successors of a node.
Parameters
----------
var_name
Name of the variable corresponding to the node... | 7ad64a3d535e575af3db4e5f6719ce0d0b702a97 | 59,886 |
def sub_menu(request, page_id):
"""Render the children of the requested page with the sub_menu
template."""
page = Page.objects.get(id=page_id)
pages = page.children.all()
page_languages = settings.PAGE_LANGUAGES
return render(request, "admin/pages/page/sub_menu.html", {
'can_publish': r... | 0f180268ed126e0e1c7db7ac6ee17897db7db8b0 | 59,887 |
def handle_fs_errors(function):
"""Method decorator to report FS errors in the appropriate way.
This decorator catches all FS errors and translates them into an
equivalent OSError, then returns the negated error number. It also
makes the function return zero instead of None as an indication of
successful executi... | 833724326db34a01b45ea7222cbae0057aa496fd | 59,888 |
def _TimeToString(datetime):
"""Converts a datetime object into a string
adapted from M-LOOP: mloop.utilities
Args:
datetime (datetime): datetime object (e.g. datetime.datetime.now())
Returns:
str: date time as 'yyyy-mm-dd_hh-mm'
"""
return datetime.strftime("%Y-%m-%d_%H-%M") | 3f778b8b15f19bdfe5238799cb248316772380b4 | 59,889 |
import os
def create_profiler(config_name, iteration, input_ckpt=None):
"""
@config: configuration for train_nx_graph
"""
# load configuration file
all_config = load_yaml(config_name)
config = all_config['segment_training']
config_tr = config['parameters']
batch_size = n_graphs = co... | b940bf974498ceeff8d76bed67a92717c3824f03 | 59,890 |
import copy
def update_octree_belief(octree_belief, real_action, real_observation,
alpha=1000., beta=0., gamma=DEFAULT_VAL):
"""
real_observation (Observation)
"""
if not isinstance(real_observation, OOObservation):
raise TypeError("Belief update should happen using "\
... | b0a5f7b48f3ccc8fc9413bb64363cd76d94d122a | 59,891 |
import tokenize
def is_media(user):
"""
Is twitter user a member of the media
"""
if user['screen_name'] in KNOWN_MEDIA:
return True
name_tokens = []
description_tokens = []
for token in tokenize(user['name']):
for t in token.split('-'):
name_tokens.append(t.low... | ad125107c0018e9d9319505a6b1e71ddff46ab4f | 59,892 |
def matching_files(directory, suffix=None, prepend=False):
"""Get a list of files that start with a specific prefix, optionally removing
any files that end in `_001`.
Args:
directory (str): The directory containing files.
suffix (str): A suffix (file extension) to match filenames against.
... | c9105ee73c6a25598c2afe4a216016b4a5b197ed | 59,893 |
def event_names(lang="en"):
"""This resource returns an unordered list of the localized event names
for the specified language.
:param lang: The language to query the names for.
:return: A dictionary where the key is the event id and the value is the
name of the event in the specified lang... | 8fb2e3fd82d438bfb652eb3c0f46d2bd2d34a03f | 59,894 |
import os
def thermo_paths(spc_dct_i, run_prefix, idx):
""" Set up the path for saving the pf input and output.
Placed in a MESSPF, NASA dirs high in run filesys.
"""
# Get the formula and inchi key
spc_info = inf.get_spc_info(spc_dct_i)
spc_formula = automol.inchi.formula_string(spc_info... | 3a65f8911b52335c2f6a449bce6d6743912e4222 | 59,895 |
def generate_tiny_dataset(n_samples, language="english", seed=None, **kwarg):
"""Generate a dataset of 8x8 resolution in gray scale
with scale of 1 and minimal variations.
"""
fg = SolidColor((1, 1, 1))
bg = SolidColor((0, 0, 0))
attr_sampler = basic_attribute_sampler(
alphabet=LANGUAGE_... | 92818f77ccfc2b48457b6bf520a5c356f7229b09 | 59,896 |
def array(string):
"""Converts string to a list, split on whitespace
:param:
string(str): The string to split
:return
string.split()(list): The string split into a list on the white space."""
return string.split() | c48c35d321848f3e997931c5ab9f9357842b9228 | 59,897 |
def count_nans_by_period(
df: pd.DataFrame,
config: cconconf.Config,
period: str,
top_n: int = 10,
) -> pd.DataFrame:
"""
Count NaNs by period.
:param df: data
:param period: time period, e.g. "D" - to group by day
:param top_n: display top N counts
:return: table with NaN count... | 6860604095a438aa29dcfc31bcf20b5eec384eff | 59,898 |
import os
def read_data(doc_path, source_vocab, target_vocab, max_seq_length=200):
"""Read parallel data and convert to token ids."""
print("doc_path", doc_path)
for dir in os.listdir(doc_path):
source_path = doc_path + "/" + dir + "/fr.txt"
target_path = doc_path + "/" + dir + "/en.txt"
... | b3f48baad9a0e591f1cfce4f0008904933e4bbd2 | 59,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.