content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import glob
def datedfile(filename,date):
""" select file based on observation date and latest version
Parameters
----------
filename: text file name pattern, including "yyyymmdd_vnn" place holder for date and version
date: yyyymmdd of observation
Returns: file name
"""
filelist = ... | 203cf848e351ef9b8b77bda62d5850b35485762a | 3,626,883 |
import random
import string
def random_user(n):
"""generate a random user id of size n"""
chars = []
for i in range(n):
chars.append(random.choice(string.ascii_lowercase))
return ''.join(chars) | 21d8ec2ef8b275ffca481e4553ec396ff4010653 | 3,626,884 |
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place,
or a player tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches... | 7b8d50b1b4dbc592e2792f248df6f848c9c3aac6 | 3,626,885 |
import logging
def load_statistics(
input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList:
"""Loads data statistics proto from file.
Args:
input_path: Data statistics file path. The file should be a one-record
TFRecord file or a plain file containing the statistics proto in Proto
T... | a86b6cfd25b6e77db78419afad41aa6b7e456b7e | 3,626,886 |
from typing import Counter
def get_counter(request):
"""
Get the Counter object associated with a request.
Raise AjaxError if session is invalid or counter is not found.
"""
if "counter" not in request.session:
raise AjaxError(RET_UNAUTHORIZED, _(u"Not logged in."))
counter_id = requ... | 6d676880fccb47b05c1936e26c8be819136ad399 | 3,626,887 |
def _get_parse_input(parse_args, args_in, dict_in):
"""Return default for parse_input.
This is to decide if context_parser should run or not.
To make it easy on an API consumer, default behavior is ALWAYS to run
parser UNLESS dict_in initializes context and there is no args_in.
If dict_in specifi... | 64dcfd32a3d9f66749a27d4b26bd5fb3a66edf28 | 3,626,888 |
def is_average_pooling(layer):
"""Checks if layer is an average-pooling layer."""
AVERAGEPOOLING_LAYERS = (
keras_layers.AveragePooling1D,
keras_layers.AveragePooling2D,
keras_layers.AveragePooling3D,
keras_layers.GlobalAveragePooling1D,
keras_layers.GlobalAveragePooling2... | 7a0d91d291b13006341a86bf3864b612bad247c2 | 3,626,891 |
def MergeDictsRecursively(original_dict, merging_dict):
"""
Merges two dictionaries by iterating over both of their keys and returning the merge
of each dict contained within both dictionaries.
The outer dict is also merged.
ATTENTION: The :param(merging_dict) is modified in the process!
:para... | 43174a7f5163a36eb850bc2c4d0f557790920189 | 3,626,893 |
def eq_assoc(u, v, eq=core.eq, n=None):
""" Goal for associative equality
>>> from logpy import run, var, fact
>>> from logpy.assoccomm import eq_assoc as eq
>>> fact(commutative, 'add') # declare that 'add' is commutative
>>> fact(associative, 'add') # declare that 'add' is associative
... | b7ba81dbd73091dc6a2e01ec5136c80cf3c49c88 | 3,626,894 |
import six
def printer(func=None, **options):
""" Decorator used to print whatever text is returned in the caller
function.
When a list or a tuple are returned, then the contents are iterated
and printed.
Options:
dedent - whether or not to dedent the text (default: ... | 632cfb59fbc213b3c8f69f05d6f8ff686207a6e3 | 3,626,895 |
from StringIO import StringIO
from io import StringIO
def strio():
"""
This was difficult to get right in doctests when porting to Python 3.
"""
try:
except ImportError:
return StringIO() | 9900b0a15da617278e3a5a1de8ef45a417e4e813 | 3,626,898 |
def getJamLengthMeters(detID):
"""getJamLengthMeters(string) -> double
Returns the jam length in meters within the last simulation step.
"""
return _getUniversal(tc.JAM_LENGTH_METERS, detID) | 750d7579ffded917e18faa5ec2f991576606aaf8 | 3,626,899 |
async def grant_access(hub, ctx, name, resource_group, access, duration, **kwargs):
"""
.. versionadded:: 4.0.0
Grants access to a disk.
:param name: The name of the disk to grant access to.
:param resource_group: The resource group name assigned to the disk.
:param access: Possible values i... | 929cc6c28fa6ab48b26e4d4d9edf8076b32eb892 | 3,626,900 |
from datetime import datetime
def get_device_uptime(status: dict, last_uptime: str) -> str:
"""Return device uptime string, tolerate up to 5 seconds deviation."""
delta_uptime = utcnow() - timedelta(seconds=status["uptime"])
if (
not last_uptime
or abs((delta_uptime - datetime.fromisoform... | 887fa4eb3d710fffa080523d1025cfa6bc37425a | 3,626,901 |
def int_deg(angle):
"""Return an angle object with only integer degrees."""
dms = str(angle).split(':')
return ephem.degrees(dms[0]) | 9de23da1b3a7eb132b826cf1d885b5489c0018a1 | 3,626,902 |
def rgb(data):
""" normalize rgb
data [H, W, C], data type is float32 (0 to 1) or uint8 (0 to 255)
"""
if data.dtype == np.float32:
return (data - 0.5) / 0.5
else:
return (data.astype(np.float32) - 127.0) / 127.0 | b706181722e7ca259a5add728a1c3d9705b79459 | 3,626,903 |
def create_base_feed() -> FeedGenerator:
"""Create feed generator and configure feed-level data."""
fg = FeedGenerator()
fg.id(PG_URL)
fg.title("Paul Graham Essays (Audio)")
# fg.author({"name": "App Champ", "email": "app.engine.champ@gmail.com"})
fg.link(
href="https://podcast.app/p... | 83ffca22b3e089fa07dc87bad7046e7e7bec620f | 3,626,904 |
def _split_hdf5_path(path):
"""Return the group and dataset of the path."""
# Make sure the path starts with a leading slash.
if not path.startswith('/'):
raise ValueError(("The HDF5 path '{0:s}' should start with a "
"leading slash '/'.").format(path))
if '//' in path:... | f0f8bba67254e3616a80c26b58fdcb91db00a49b | 3,626,905 |
def mission_derivs(s,t,**kwargs):
"""
Returns right-hand side of Kepler ODE; used by Runge-Kutta routines
Inputs
s State vector [[m r(1) r(2) v(1) v(2)]...]
t Time (not used)
Output
deriv Derivatives [[dr(1)/dt dr(2)/dt dv(1)/dt dv(2)/dt]...]
"""
sun_mass = kwa... | 58616baaacd046b03d1cbfb50731433d6d03ef35 | 3,626,906 |
def remove_non_whole_numbers(
df: pd.DataFrame, var_name: str
) -> pd.DataFrame:
"""Removes non-whole-number floats. Preserves other missing
values."""
unrounded = df.loc[df[var_name].notnull(), var_name]
rounded = unrounded.round()
diff = rounded != unrounded
diff_i = diff[diff == True]... | 1d5608586de4617ed19c28ffcd3f657e9699cff4 | 3,626,907 |
def get_entropy(word, data: pd.DataFrame, obs: list = []):
"""Get the optimal guess given previous observations.
Args:
data: a DataFrame containing all possible function outputs
obs: a list of observed guess, value pairs
Returns:
The word that maximizes the partition entropy over t... | 7e839e991090392a0ce7b34e3ca719928547a167 | 3,626,908 |
def add_config(name, config_parser):
"""
Add a config_parser object to metaconfig.
"""
if _metaconfig is None:
init()
return _metaconfig.add_config(name, config_parser) | be9e143b17cba3f6fa3679bc21c4d5f7a11909b2 | 3,626,909 |
def rebuildEventList(events, eventList = None):
"""
Add all events (top and nested) from event trees to a list.
"""
if eventList == None:
eventList = []
for event in events:
if event not in eventList:
eventList.append(event)
for arg in event.arguments:
... | 404ac02e6807214c82d30e465766a4e7af89016b | 3,626,910 |
def rpc_blocktime_participation(rpc):
"""
Determine if node is returning stale data
"""
ret = wss_query(rpc, ["database", "get_objects", [["2.1.0"]]])[0]
unix = from_iso_date(ret["time"])
participation = bin(int(ret["recent_slots_filled"])).count("1") / 1.28
return unix, participation | 4fb899e82fb0ef1ce9eef1e6c5ce68742f062d56 | 3,626,911 |
import sympy
import random
def make_quadratic_eq(x="x", rhs = None):
"""
Generates quadratic equation problem expression and
set of solutions
x : charector for the variable to be solved for. defaults to "x".
OR
a list of possible charectors. A random selection will... | 9ac35587166571b0513f6b3c7f4f79771d85b49f | 3,626,912 |
def generate_rules_engine(config):
"""Generate Terraform for the Rules Engine
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
dict: Rules Engine Terraform definition to be marshaled to JSON
"""
prefix = config['global']['account']['prefix']
result = in... | 9d654585604c63ccf4ec84ce1d53dd8f05ccd7db | 3,626,913 |
import colorsys
import math
def generated_edge_compute(e1, e2):
"""
Return the distance between colors of two edges for generated puzzle.
:param e1: Edge object
:param e2: Edge object
:return: distance Float
"""
#edge size
shapevalue, distvalue = dist_edge(e1, e2)
... | 206bfc3d75b6916b57159d5c9c9d8e36d0ac7162 | 3,626,914 |
def package():
""" [deploy] Creates a deployment package. """
branch, summary, version = _get_versioning_metadata()
# Builds the deployment package.
local('fpm -s dir -t deb -n endagaweb -a all -v %(version)s \
--description "%(branch)s: %(cs)s" \
-d byobu -d nginx -d python-pip... | 96600d07b8d9b3b0979e563fd4eb5c746cfbf1fb | 3,626,915 |
def _pack_64b_int_arg(arg):
"""Helper function to pack a 64-bit integer argument."""
return ((arg >> 56) & 0xff), ((arg >> 48) & 0xff), ((arg >> 40) & 0xff), ((arg >> 32) & 0xff), \
((arg >> 24) & 0xff), ((arg >> 16) & 0xff), ((arg >> 8) & 0xff), (arg & 0xff) | 274fadb627de9ac47bff34c8e55db545b8e6cf0a | 3,626,916 |
def subroutine_to_c_header(subroutine, export=True):
"""Returns the function declaration in C"""
output = ['\n/*>']
output.append('\n *>'.join(subroutine.comment_lines))
output.append(' */\n')
output.append('{0}cmfe_Error {1}('.format('IRON_C_EXPORT ' if export else '', subroutine_c_names(subroutin... | a50586714f7013560108534a1a052a90f957a50b | 3,626,918 |
def list_array_paths(path, array_dict):
"""
Given a dictionary containing each directory (experiment folder) as a
key and a list of array data files (analysis of array containing Log2Ratio
data) as its value (i.e., the output of 'find_arrays'), returns a list of
full paths to array files.
"""
... | 79d5f58a97005fb915de290ae8ccc480fbacd3c0 | 3,626,919 |
def log_simple(n, k):
"""
A function that simply finds how many k's does n have.
For example 28 = 2 * 2 * 7, so log_simple(28, 2) will return 2
and log_simple(28, 7) will return 1
"""
log_result = 0
while (n % k == 0):
log_result += 1
n /= k
return n, log_resu... | 22bda2911aa14a5866759cc0e5d8bf377b372bd7 | 3,626,920 |
def parse_fq(fq):
"""Parse a FASTQ file
Args:
fq(str): path to fastq file
Returns:
fqd(dict): dictionary with read names as keys, seq and quality as values
in a list
"""
def get_fq_reads(allreads):
read_dict = {}
for title, seq, qual in FastqGeneralIterator(al... | f5d19943cac7c0311781849b6ffd98903cf3889f | 3,626,921 |
def force_ref(w_obj):
"""Convert a reference-or-object into a reference"""
if not isinstance(w_obj, W_Reference):
return W_Reference(w_obj)
else:
return w_obj | b1f504f26c35eacaef3ee65501df885aade1d709 | 3,626,922 |
def http_file_upload_post(host, port, uri, params={}, files=[]):
"""Perform a plain HTTP file upload post (for task farming)"""
content_type, body = client._encode_multipart_formdata(params, files)
h = httplib.HTTP(host, port)
h.putrequest('POST', uri)
h.putheader('content-type', content_type)
h... | 6839336b1255a9704535f97023f581d109d342d2 | 3,626,923 |
def bleu_score(references, hypotheses):
"""Computes bleu score.
Args:
references: list of list (one hypothesis)
hypotheses: list of list (one hypothesis)
Returns:
BLEU-4 score: (float)
"""
references = [[ref] for ref in references] # for corpus_bleu func
BLEU_4 = nltk... | 51150201c560f2b27da04a93acc0740ebe3120dc | 3,626,924 |
def main():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
service = get_service()
spreadsheetId = ... | 716e782e6875786c5e0a693b335bb7bb6a950078 | 3,626,925 |
def conv_block(x, filters, kernel_size = (7,7), padding="same", strides=1):
"""
conv_block(x, filters, kernel_size = (7,7), padding="same", strides=1)
This function applies batch normalization to an input layer, then convolves with a 2D convol layer
The two actions combined is called a convolutional blo... | 64a6899a7ceacdbb6e211171d4e685d453403a67 | 3,626,926 |
import logging
def test_logging_decorator_res_only(caplog):
"""Verify that only the response gets logged"""
caplog.set_level(logging.INFO)
@log_traffic(log_request=False)
def mock_func():
return {'foo': 'bar'}
with app.test_request_context(environ_base=REQ):
mock_func()
asser... | 48f6caaab49845905eb40cb5b69aa4fd1c826330 | 3,626,927 |
from datetime import datetime
def download_media(request):
"""
Make a gzip copy of all media files.
"""
lazy_create_permission('make_backup')
if not request.user.has_perm('make_backup'):
return HttpResponseForbidden('you do not have permission to create backups')
zip_pth = join(gettempdir(), 'media_export')
... | 169e79ba798abf039b0873d0e91dfaa9b497a540 | 3,626,928 |
def square_to_square_dataframe(df, cov_func, **cov_func_kwargs):
""" Map square dataframe to square dataframe """
return pd.DataFrame( index=df.index, columns=df.columns, data=cov_func(df.values, **cov_func_kwargs)) | 1841844c19d9141fe77ff36df39cbcfd3d9929c0 | 3,626,929 |
def fitparams_for_update(fitparams):
"""
Extracts a dictionary of fitparameters from
modelmiezelb.io.ContrastData.fitparams for updating e.g. a sqe model
via modelmiezelb.sqe_model.SqE.update_params
Parameters
----------
fitparams : modelmiezelb.io.ContrastData.fitparam
Return
-... | b4f2ddf26dbdcb37105da4dcf23602fec19bf4e1 | 3,626,930 |
import math
def detectorResponseToCell(r):
"""
Given helicopter over a cell, calculate detector response to particular cell
"""
return (((MONITOR_PROPORTION_COEF) * (1 + (RADIATION_BUILDUP_FAC * r)) * (math.exp(-1 * RADIATION_ABSORPTION_COEF * r))) / (r) ** 2) | 007b22919f784e5ec94505a9a412629336bd7e0b | 3,626,931 |
def datetime_to_timestamp(dt=None):
"""Convert a datetime to a timestamp string.
Parameters
----------
dt : datetime (defaults to now)
Returns
-------
str
"""
if dt is None:
dt = arrow.now()
return dt.strftime("%Y%m%d_%H%M%S") | 669f5d7248e3a610d4241c86218b908c2e9302a5 | 3,626,932 |
def buildAction(obj, actionName, target):
"""Setup an object QAction triggering a callable
A `QAction` will be created with name `actionName`, added as a child of `obj`.
When the action's `triggered()` signal is emitted, the `target` will be called.
See :any:`QObject.setObjectName`.
:param obj: the object in wh... | c9b78f30d43257e980fb81db001d198880a53b12 | 3,626,933 |
import random
def get_hash_family(n_funcs, num_shingles):
""" Get N hash functions:
f(x = ((a*x + b) % p )
"""
h_funcs = []
a_done = []
b_done = []
p = get_prime_larger_than(num_shingles)
while h_funcs.__len__() < n_funcs:
a = random.randint(1, num_shingles)
b ... | 28a8d39caebed05108a379d292fdbffa248c4555 | 3,626,934 |
import json
def loads(s, *v, cls=None, parse_float=None, parse_int=None, parse_constant=None,**kw):
"""
json.loads互換の関数です。
"""
return json.loads(s, *v, cls=cls, object_hook=_load_hook,parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant,**kw) | 5005b240f9b3f8a5ac5842928297e41702de3bed | 3,626,938 |
def get_export_collections(only_selected=False):
"""Returns a list of Export Collections in the current scene.
:param only_selected: If `True`, only return selected Export Collections, defaults to `False`
:return: List of :class:`ExportCollection` objects
"""
collections = [coll for coll in bpy.dat... | 55bd3def9d4817676102c25823dd295172be9b28 | 3,626,939 |
def levenshtein_distance(s1, s2):
"""Compute Levenshtein distance btw two strings
Note
----
Taken from wikibooks.org-wiki-Algorithm_Implementation
"""
if len(s1) < len(s2):
return levenshtein_distance(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
pr... | 22f494dec8b2869d576c9714f482f822cfa5ff6d | 3,626,940 |
def sample_videos_to_images(
video_dataset,
image_dataset_path,
stride=None,
num_images=None,
frame_filter=lambda labels: True,
image_extension=".jpg",
description=None,
):
"""Creates a `LabeledImageDataset` by extracting frames and their
corresponding labels from a `LabeledVideoData... | 9c5fb29c043850f0f9ae4f6f81d628504e9a3787 | 3,626,941 |
def deg_monitoring(year, ts_status, path, row, old_coefs, train_ndfi,
first, tmean):
""" Main function for monitoring, should be looped over for each year """
# REGRESSION
# train array = ndfi collection as arrays
train_array = ee.ImageCollection(train_ndfi).select('NDFI').map(
... | b85e7e60bd5f9bbbbd632125e3bf6303651dc2a1 | 3,626,942 |
def distmat2dqueuing(B1, B2):
"""
Creates distance matrix for queuing
Parameters
----------
B1 - Buffer size of first queue
B2 - Buffer size of second queue
Returns
-------
distance matrix
"""
nStates = (B1 + 1) * (B2 + 1)
d = np.ones((nStates, nStates))
vec_tuple = ... | 3c634694b4d2832b792c06ae891993c377a9934e | 3,626,943 |
import inspect
def mismatch_rate_mapqge20(mqc):
"""
The fraction of bases that mismatch the reference in reads with MAPQ>=20.
Source: picard AlignmentSummaryMetrics (PF_HQ_ERROR_RATE)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_picard_AlignmentSummar... | 0272e5ec916cff155b0afda4e6a9c96f149f7142 | 3,626,944 |
def _validate(cmd, references):
""" Make sure all references in the command are in the reference mapping
Raises
------
TypeError, if a tag is missing from references
"""
replacements = {}
references_new = {}
for match in TAG_RE.finditer(cmd):
tag = match.group('tag')
if... | 419c2601da8f5c1800e46f6947d00d8c035f56a3 | 3,626,945 |
import orwell.messages.controller_pb2 as pb_controller
import orwell.messages.robot_pb2 as pb_robot
import orwell.messages.server_game_pb2 as pb_server_game
import orwell.messages.server_web_pb2 as pb_server_web
def generate():
"""Used to generate code with cog."""
TEMPLATE = """
class {name}(yaml.YAMLObject... | f8361d9cc20cd963770251b28920a0caac048e74 | 3,626,946 |
def readUInt(stream, size):
""" Read an unsigned integer from a file (or file-like stream).
@param stream: The source file-like object.
@param size: The number of bytes to read from the stream.
@return: The decoded value.
"""
if size == 0:
return 0
data = stream.read(s... | 0ac4c20922104930885407fd15fcab826063c3c9 | 3,626,947 |
from typing import Type
from pydantic import BaseModel # noqa: E0611
from typing import Tuple
from typing import Optional
def validate_model( # noqa: C901 (ignore complexity)
model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None
) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]:
... | 55d41b7b23b9d0d99748e17f42617c42771311a7 | 3,626,949 |
def spinChainProductSum(spins):
"""
Calculate the Ising nearest neighbor interactions of a spin chain, periodic boundary condition(PBC).
Parameters
----------
spins : list of ints or floats
The given spin under PBC.
Returns
float
The nearest neighbor interactions(products).... | 0f115c3284f5680b28d1648140c8618de873e16c | 3,626,950 |
from typing import Any
def fs_error_handler(f: Any) -> Any:
"""
A Decorator that handles error from FileSystem for HiveTableLastUpdatedExtractor use case
If it's client side error, it logs in INFO level, and other errors is logged as error level with stacktrace.
The decorator is intentionally not re-r... | 7dc23b28ff25670f8b0bc7e69a7630ca2dd05ca8 | 3,626,951 |
def has_ext_state(section: str, key: str) -> bool:
"""
Return whether extended state exists for given section and key.
Parameters
----------
section : str
Extended state section.
key : str
Extended state key.
Returns
-------
has_ext_state : bool
"""
has_ext_... | 2483763cbe05f404331d8dfe8a1112fc15b70029 | 3,626,952 |
def build_udp_header(src_port, dest_port, ip_header, data):
"""
Building an UDP header requires fields from
IP header in order to perform checksum calculation
"""
# build UDP header with sum = 0
udp_header = UDPHEADER(src_port,
dest_port,
UD... | db2086a5dd8ec44db2ef5bf8b9a3855cf7b99e16 | 3,626,953 |
def run_sim(nns, task_rate, track, num_inputs):
"""
Run the simulation for this set of nns
"""
vehs, is_alive, nn_inputs, nn_outputs, t_stationary = init_pop(len(nns), task_rate, track, num_inputs)
tSim = 0.0
max_steer = np.zeros(len(nns)) # log the maximum steering angle applied
while a... | 1f3c6413e1cb9ff823298f24257411c307b8e8fd | 3,626,954 |
def test_default_next_offset_to_read(tmpdir, mocker):
"""Override the default setup because we want to mock out the
the query result of _get_last_apply_record to return nothing
"""
(oracle_processor,
mock_target_db,
mockargv,
mock_audit_factory,
mock_audit_db) = cdc_utils.setup_depen... | 3386013976c944732ad403e27bdd1f1e57b39bac | 3,626,956 |
def delete(user_id=None):
"""
This will delete a user from the Database
:param user_id: int of the users id
:return: User dict of the user created
"""
user = User.query.filter_by(user_id=user_id).first()
return user | e2caa42b495946f95b8bfc510d3d3e10a827a785 | 3,626,957 |
import torch_optimizer as optim
from typing import Optional
def get_uutils_default_adafactor_from_torch_optimizer_and_scheduler_default(mdl: nn.Module,
lr: float = 1e-4,
... | 93a99a92f6eb98fc58b9cad36aacd8c1ff0c6095 | 3,626,958 |
from typing import Callable
def fnot(function: Callable) -> Callable:
"""Inverse of composing a function with bool.
For example:
```
fnot(identity)(True) == False
fnot(identity)(False) == True
greater_or_equal_to = less | fnot
greater_or_equal_to(2).lmap([1, 2, 3]) == [False, True, True]
... | 7da6439a58474ebc19311ac2b76fc30a465070c0 | 3,626,959 |
from pyqmc.matrices.gms import Fort70
def load_fort70_wfn(chkdata, fort70file, verbose=10):
"""Loads a (multideterminant) wave function from fort.70 file.
This is necessary to get the wave function in the orthogonal basis.
Another alternative would be to reconstitute the X basis-orthogonalization
matrix from ... | 090d19c77bdbdd810f4247616deb63490ff42f82 | 3,626,960 |
import random
def analisis_info(info:pd.DataFrame, Level:int, Coincidences:str)->tuple:
"""Usa la columna de elemntos a ingresar, lo corta a la cantidad de elementos necesarios y
lo multiplica por la cantidad de coincidencias necesarias para llenar los botones y
la mezcla para obtener posiciones aleator... | 9de023bd6dda66497ce7842a59a9b18f1b67c9b7 | 3,626,961 |
def plot_argus_phosphenes(X, argus, scale=1.0, axon_map=None, show_fovea=True,
ax=None):
"""Plots phosphenes centered over the corresponding electrodes
.. versionadded:: 0.7
Parameters
----------
X : pd.DataFrame
argus : :py:class:`~pulse2percept.implants.ArgusI` or :... | 12a99302bab8e19b0541a5d425987fe0426c1c0a | 3,626,962 |
import re
def _escape_for_regex(text):
"""Escape ``text`` to allow literal matching using egrep"""
regex = re.escape(text)
# Seems like double escaping is needed for \
regex = regex.replace("\\\\", "\\\\\\")
# Triple-escaping seems to be required for $ signs
regex = regex.replace(r"\$", r"\\\$... | c7d9866dfe4b9c96e500a43d3726db8e7ea73532 | 3,626,963 |
def color_to_256(color):
"""Convert color into ANSI 8-bit color format.
Red is converted to 196
This converter emits the 216 RGB colors and the 24 grayscale colors.
It does not use the 16 named colors.
"""
output = 0
if color.r == color.g == color.b:
# grayscale case
if color... | 3fc747404f393d1adc04de06f59903593979a2a1 | 3,626,964 |
from typing import Union
import json
def cmd_app_config(mixcli: MixCli, **kwargs: Union[str, bool]):
"""
Default funciton when app lookup command is called.
:param mixcli: MixCli instance
:param kwargs: keyword arguments from keyword arguments from cmd line
:return: True
"""
ns_name = kwa... | 49e969512ebb2bde7c087ef8178d5b3fa963cd52 | 3,626,965 |
def t_low(t, df):
"""Returns left-hand tail of Student's t distribution (-infinity to x).
df, the degrees of freedom, ranges from 1 to infinity.
Typically, df is (n-1) for a sample size of n.
Result ranges from 0 to 1.
See Cephes docs for details.
"""
if df < 1:
raise ValueError("... | c09edc04fa9aab7fd75ef75c73e556ac20bb7a04 | 3,626,966 |
def breadcrumb(*args):
""""Render a breadcrumb trail
Args:
args (list) : list of urls and url name followed by the final name
Example: url1, name1, url2, name2, name3
"""
def pairs(l):
a = iter(l)
return list(zip(a,a))
return {
'urls': pairs(ar... | dd4fbd6c130da497a1f38c876685dc3f17298efb | 3,626,967 |
def get_sampling_frequency_and_duration_from_frequency_array(frequency_array):
"""
Calculate sampling frequency and duration from a frequency array
Attributes:
-------
frequency_array: array_like
Frequency array to get sampling_frequency/duration from: array_like
Returns
-------
... | c27cbbbd63f772f63b0e43a1cb3b31e4080f9f28 | 3,626,968 |
def sequence_layers(layers):
"""Go through the list of layers and fill in the missing bits of information.
The basic rules are this:
* If the current layer has data set to None, take the data from previous layer.
* For each aesthetic mapping, if that mapping is set to None, take it from previous layer.
... | 2a906f997ec6bcf08057a7aef83528815b9adc2d | 3,626,970 |
def start_end(data, num_start=250, num_end=100, full_output=False):
"""
Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_en... | 9cfd37bb50651eff37e3d8acb65d82bf449f9474 | 3,626,971 |
def to_rpc_literal(value):
"""
void @0 :Void;
bool @1 :Bool;
int8 @2 :Int8;
int16 @3 :Int16;
int32 @4 :Int32;
int64 @5 :Int64;
uint8 @6 :UInt8;
uint16 @7 :UInt16;
uint32 @8 :UInt32;
uint64 @9 :UInt64;
float32 @10 :Float32;
float64 @11 :Float64;
text @12 :Text;
... | 38abe72d61cea12d68328b9d17cf548741d0be2a | 3,626,973 |
def fit_gaussian( df ):
"""
Fit a Gaussian to the data
:param df: A Pandas DataFrame inedxed by wavelength with spectral data
:returns: A Pandas DataFrame of the fit parameters
"""
gaussian = lambda x, A, mu, sigma: (
A* np.exp( -np.power( ( x - mu ), 2 )/( 2* np.power( sigma, 2 ) ) )... | b420108e8f8ec9f4a2f987f547fd0c0466895c2e | 3,626,974 |
import inspect
def get_activation(fn_name,only_layer=False):
"""
Args:
only_layer (bool):
fn_name ():
Returns:
Examples:
>>> a=get_activation('relu')
>>> print(get_activation('swish'))
"""
if fn_name is None:
return None
fn_modules = ['trident.... | 2deda9da0fadc0485b2d2c6a2c6439b4f4c6e8ea | 3,626,975 |
def _conv_filter(state_dict, patch_size=16):
""" convert patch embedding weight from manual patchify + linear proj to conv"""
out_dict = {}
for k, v in state_dict.items():
if 'patch_embed.proj.weight' in k:
if v.shape[-1] != patch_size:
patch_size = v.shape[-1]
... | 29f35fd5323208443f1380b56a7bcc87eb2a938f | 3,626,976 |
from typing import Any
from typing import Callable
def _pluck(key: Any) -> Callable[[Observable], Observable]:
"""Retrieves the value of a specified key using dict-like access (as in
element[key]) from all elements in the Observable sequence.
Args:
key: The key to pluck.
Returns a new Observ... | eaae0002e0f2764af3b1e4c32cc3967144af1bc3 | 3,626,978 |
from typing import Optional
def change_rv_size(
rv_var: TensorVariable,
new_size: PotentialShapeType,
expand: Optional[bool] = False,
) -> TensorVariable:
"""Change or expand the size of a `RandomVariable`.
Parameters
==========
rv_var
The `RandomVariable` output.
new_size
... | 1d47cb36cbe351b40b066cd6da3cc70dccc140ed | 3,626,979 |
def validate_number_in_board(number, project, old_value=None):
"""
Validates `Column's` `number_in_board` field.
Args:
number (int) - Number to validate.
project (`Project`) - Project instance.
Returns:
Tuple (bool, str) - Tuple which first value is success status and second
... | b7456b056737982523307f96e6a2691d2ce1000f | 3,626,980 |
def translate(value, leftMin, leftMax, rightMin, rightMax):
"""
Normalize the data in range rightMin and rightMax
:param value: Value to be normalize
:param leftMin: original min value
:param leftMax: original max value
:param rightMin: final min value
:param rightMax: final max value
:r... | 2cc02618edaec4112d30a4f61de9c95d5e8a0f8b | 3,626,981 |
def generated_refl():
"""Generate a reflection table."""
# these miller_idx/d_values don't make physical sense, but I didn't want to
# have to write the tests for lots of reflections.
reflections = flex.reflection_table()
reflections["intensity.prf.value"] = flex.double([1.0, 10.0, 10.0, 1.0, 2.0])
... | f83772af0dbb90c47d4b785839385e5a15350ab8 | 3,626,983 |
def euclidean_distance(position1, position2):
"""
:return: Euclidean distance between current pose and the goal pose
"""
x1, y1 = position1
x2, y2 = position2
return np.sqrt(pow((x2 - x1), 2) +
pow((y2 - y1), 2)) | 1f7cfdd4a2ad3eb3907599ed511bf6e1c1618375 | 3,626,984 |
def post_process_content(org_docs, api_method):
"""
Processes the content retrieved from mongo before presenting this to the users.
:param org_docs: documents retrieved from mongo
:param api_method: the fully qualified name of the target API method
:return:
"""
docs = list(org_docs)
for ... | 7fb1b7350cc3fdf8c18184cb7d4d634b5c3f4fb7 | 3,626,985 |
def get_sqrt_2():
"""Returns an approximation for the square root of 2"""
return 1.41421356 | 56c24f16bc27b9b40b771ed545cc553b817f8260 | 3,626,986 |
def _wavefunctions_to_density(num_electrons, wavefunctions, grids):
"""Converts wavefunctions to density."""
# Reduce the amount of computation by removing most of the unoccupid states.
wavefunctions = wavefunctions[:num_electrons]
# Normalize the wavefunctions.
wavefunctions = wavefunctions / jnp.sqrt(jnp.su... | 7c9480e29241df003a6942f6ec0d66a68d4e6692 | 3,626,987 |
from typing import Dict
from typing import Optional
def get_gsx_entry_value(entry: Dict[str, Dict[str, str]], field: str) -> Optional[str]:
"""Returns the `entry` value for the given `field`."""
if not entry or not field:
return None
field = f"gsx${field}"
if field not in entry:
retur... | 788c0a3e99691bfa81386c6fc2b5ea05332c06fd | 3,626,988 |
def SEResNet(input_shape=None,
num_outputs=1000,
initial_conv_filters=64,
depth=(3, 4, 6, 3),
filters=(64, 128, 256, 512),
width=1,
bottleneck=False,
weight_decay=1e-4,
include_top=True,
weights=None,
... | 3a8e9055a97399c5602b2c5538dd1bed2c053ea0 | 3,626,989 |
def binary(gray_img, threshold, max_value, object_type="light"):
"""Creates a binary image from a grayscale image based on the threshold value.
Inputs:
gray_img = Grayscale image data
threshold = Threshold value (0-255)
max_value = value to apply above threshold (usually 255 = white)
... | 641abea528443aaa76a7325a50cd0bf84bd46636 | 3,626,990 |
def tf_hgrid_coords(shape: RankStaticShape) -> tf.Tensor:
"""
Produce hyper-grid coordinates
:param shape:
:return:
"""
static_rank = len(shape)
shape = tf.convert_to_tensor(shape, dtype=tf.int64)
comps = [tf.tile(tf_repeat_1d(tf.range(shape[k]), t=tf.reduce_prod(shape[k+1:])), [tf.reduc... | af7531338a717971197e57cffb57443389ef727f | 3,626,991 |
def listify(revision_str):
"""Split a revision string into a list of alternating between strings and
numbers, padded on either end to always be "str, int, str, int..." and
always be of even length. This allows us to trivially implement the
comparison algorithm described at
http://debian.org/doc/deb... | d6f728f18649a5dd42de4930cb2ab133f23d725e | 3,626,992 |
from typing import Sequence
import re
def parse_fvalues(fvalues: Sequence) -> frozenset:
"""
Parse a sequence of fvalues as a frozenset.
This function is mostly used for parsing string provided by the user,
splitting them accordingly, but accepts any sequence type. If a string is
passed, it will ... | 7c6356b5320e6a7056f615bf5a324edbe7c66e47 | 3,626,993 |
def get_resume(text):
"""
:param text: text to resume
:return: first paragraphe in the text
"""
# regex = re.compile(r"^(.*?)\n")
# return regex.match(text).group(1)
return text[:500] | f247222de19cc131ecdb99400be2a8957cc5ea56 | 3,626,994 |
def convert_quat_to_rotmat(quat, quat_scalar_last=False):
"""Convert quaternion rotation to rotation matrix."""
if quat_scalar_last:
return R.from_quat(quat).as_matrix()
else:
return R.from_quat(
convert_quat_wxyz_to_xyzw(quat)
).as_matrix() | e5f60fa6f8770e692bd2c10ec5513557a9b06c18 | 3,626,995 |
def vgg_like_v2(input_shape, base_filters=32):
"""
a VGG structure model, used this one in final object-wise detection
input_shape: input size in (x,y,z)
"""
input_shape = input_shape + (1,) # one channel
inputs = Input(shape=input_shape) # 48x48x48
conv1 = _conv_block(input_tensor=input... | 0133483691e3c4b5b194e24e8e696aa17a8e7554 | 3,626,996 |
import torch
def fuse_conv(conv, norm):
"""
[https://nenadmarkus.com/p/fusing-batchnorm-and-conv/]
"""
fused_conv = torch.nn.Conv2d(conv.in_channels,
conv.out_channels,
conv.kernel_size,
conv.stride,
... | 69f72724ae6181c23652b601e841d1b37d2095db | 3,626,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.