content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy
def _from_records(vals, keys, typs=None, idxs=None):
""" create a table from a series of records
"""
if numpy.size(vals):
assert numpy.ndim(vals) in (1, 2)
vals = (numpy.array(vals) if numpy.ndim(vals) == 2 else
numpy.reshape(vals, (-1, 1)))
else:
v... | fe5eac16046cfece015a33d4127c3b7a84394386 | 41,600 |
def _build_rank_str(board, rank):
""" Builds string for a given rank (row).
Parameters
----------
board : chess.table.Board
Board to display
rank : int
Rank to build string for.
Returns
-------
str
row representation for a given rank.
"""
rank_str = '%s ... | 1b79a1e940f42e374ff3cd512bd44e7fe8853249 | 41,601 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This plot displays the directional frequency of
day to day changes in high or low temperature summarized by month."""
desc['... | 5298f1a19fa1ffe1d13315734dc4b635f87ea758 | 41,602 |
def train_discriminator(
discriminator_loss,
global_step,
params,
generator_scope,
encoder_scope,
discriminator_scope):
"""Returns discriminator's objects needed for training.
Args:
discriminator_loss: tensor, discriminator's loss with shape [].
g... | 9a7f14500d38e7d6d47c0ffc80581dbb851078d3 | 41,603 |
from typing import Dict
from typing import Hashable
from typing import List
def tabulate(*ds: D) -> Dict[Hashable, List[float]]:
"""
Tabulate data from a sequence of numdicts.
Produces a dictionary inheriting its keys from ds, and mapping each key to
a list such that the ith value of the list is equ... | ecb47f9fbe97417f2462711cfc5900ff98270141 | 41,604 |
def amplitude(data):
"""
Calculates the amplitude of a data list.
"""
n = len(data)
if (n == 0) :
amplitude = None
else :
min_value = min(data)
max_value = max(data)
amplitude = (max_value + min_value) / 2.0
return amplitude | 4dc053287f2de3748961943a8d9d064c9a3d1f87 | 41,605 |
import subprocess
import re
def mountpoint_dataset(mountpoint: str):
"""
Check if dataset at mountpoint is a 'zfs' mount.
return dataset, or None if not found
"""
try:
mount_list = _mount_list()
except subprocess.CalledProcessError:
raise RuntimeError(f"Failed to get mount data... | 805d95681fa651e0d7e8f0e58430222a83b83959 | 41,606 |
import functools
import sys
import traceback
import pdb
def debug_on(*exceptions):
"""Adapted from https://stackoverflow.com/questions/18960242/is-it-possible-to-automatically-break-into-the-debugger-when-a-exception-is-thro/18962528
"""
if not exceptions:
exceptions = (AssertionError,)
def ... | 753283205df93117745a6b19e6f377b5cdabdcfa | 41,607 |
import math
def get_force_block_pack(
hyps: np.ndarray,
name: str,
s1: int,
e1: int,
s2: int,
e2: int,
same: bool,
kernel,
cutoffs,
hyps_mask,
):
"""Compute covariance matrix element between set1 and set2
:param hyps: list of hyper-parameters
:param name: name of th... | 2a7e5464adf1015a2a059aa1502a3d4329dc4266 | 41,608 |
def ranks_from_scores(scores):
"""Return the ordering of the scores"""
return sorted(range(len(scores)), key=lambda i: scores[i], reverse=True) | f49fe306f456d990be5ad8308eae07f186a89da6 | 41,609 |
import requests
def validate_url(
url: str,
username: str | None,
password: str,
verify_ssl: bool,
authentication: str = HTTP_BASIC_AUTHENTICATION,
) -> str:
"""Test if the given setting works as expected."""
auth: HTTPDigestAuth | HTTPBasicAuth | None = None
if username and password:
... | 188aba336721736aec37578fb7e2c45071a4623d | 41,610 |
import struct
def unpack_word(str, big_endian=False):
""" Unpacks a 32-bit word from binary data.
"""
endian = ">" if big_endian else "<"
return struct.unpack("%sL" % endian, str)[0] | 8da8d168b1828062bd44ca3142c8b389bfd634c7 | 41,611 |
def test_two_to_one_connected():
"""Two converging lines.
--func1(.)--+
|
+-func2(.,.)--
|
--func1(.)--+
"""
def func1(x):
return x * 2
def func2(x, y):
return x + y
in_actor1 = FuncActor(func1, outports=('a', ))
in_act... | 78db24f9cff111fa96cc0593f0c7a15822a11fcf | 41,612 |
import ast
def parse_source(source, path=None):
"""Parse python source into an AST."""
path = "<unknown>" if path is None else path
return ast.parse(source, filename=path) | 7d1188e96b3a72220eca084cf18fc5f7b0b35ef3 | 41,613 |
def preprocess_img(img):
"""
Downsample Gridworld image by a factor of 2.
:param img: grid image (25, 25, 3)
:return: Grayscale downsample version (105, 80)
"""
return (img[::2, ::2, :]).astype(np.uint8) | e070120b9ea7e1199e3c341ccd0102c91be6265d | 41,614 |
def _plot_by_category(
summary: pd.DataFrame,
currency: str=None,
height: int=None,
) -> dict:
"""
Helper function for :func:`plot`.
"""
if summary["by_category"].empty:
return pg.Figure()
f = summary["by_category"].copy()
if currency is None:
currency = ""
ho... | ac96b49f803625bccb78b22c60c33d752f80006e | 41,615 |
def validate_date_window(days):
"""Validate the date range for the Security Fairy query"""
window = abs(days)
if window > 30 or window < 1:
print window
raise ValueError('Valid number of days is between 1 and 30 inclusive.')
return window | 898ae824b42aff9e5e097cd9fba7c6c84f0cc14c | 41,616 |
import logging
import dateutil
def get_script_logs(script):
"""Get a script logs"""
logging.info('[ROUTER]: Getting script logs of script %s ' % (script))
try:
start = request.args.get('start', None)
if start:
start = dateutil.parser.parse(start)
last_id = request.args.... | b84996b22c063145652a884d4ecd26ea5b090a47 | 41,617 |
def _enumerate_shifted_anchor(anchor_base, feat_stride, height, width):
"""
根据上面函数在原图的第(0,0)个特征图感受野中心位置生成的anchor_base, 在原图的特征图感受野中心生成anchors
:param anchor_base: anchors的坐标
:param feat_stride: 特征图缩小倍数(步长)
:param height: 特征图高度
:param width: 特征图宽度
:return: 原图上所有的anchors坐标,[h * w * #anchor,4]
... | 8a03dd0b8c9c76f6e355bd2b50a2c5ff5ec08fcc | 41,618 |
def interaction(data, factors, pairwise, max_factors, min_occurrence, destination_frame=None):
"""
Categorical Interaction Feature Creation in H2O.
Creates a frame in H2O with n-th order interaction features between categorical columns, as specified by
the user.
Parameters
----------
data : H2OFrame
... | 702e90e685edcb71c93edfb3047034b720b1651f | 41,619 |
import struct
def GetFloat(ea):
"""
Get value of a floating point number (4 bytes)
This function assumes number stored using IEEE format
and in the same endianness as integers.
@param ea: linear address
@return: float
"""
tmp = struct.pack("I", Dword(ea))
return struct.unpack... | 1fb6eeae92be575cf3bf98e817de885b3abd3991 | 41,620 |
def find_cod(query=None):
"""
Find city or state information.
Parameters
----------
query : str or int
if str search by name, int find by cod
Returns
-------
DataFrame
Examples
--------
>>> find_cod("Rio de Janeiro")
cod_ibge ente capital ... | e94ad364502c8842591317cb6082ef18e29b1988 | 41,621 |
import argparse
def post_process_arguments(args: argparse.Namespace) -> argparse.Namespace:
"""
post process sertop arguments
:param args: args parsed
:return: new name space
"""
for dirpath in args.coq_args_I:
args.sertop_args.extend(("-I", dirpath))
for pair in args.coq_args_R:
... | f31ef03bb1df0a13d3f3715e24588ed5373c66eb | 41,622 |
async def async_setup(opp, config):
"""Set up the onboarding component."""
store = OnboadingStorage(opp, STORAGE_VERSION, STORAGE_KEY, private=True)
data = await store.async_load()
if data is None:
data = {"done": []}
if STEP_USER not in data["done"]:
# Users can already have creat... | 1c64ee35f11ed8536db3b6b2847f7451bb0bff8f | 41,623 |
def is_hit(x, y):
"""Return wheter given coords hit a circular target of r=1."""
return x*x + y*y <= 1 | 4f71afa458ad0a891010e1f5a2be3049b0818c71 | 41,624 |
def get_user_by_id(
id: UUID,
current_user=Depends(get_current_user)
):
"""
Get user by ID
"""
user = find_user_by_id(id)
return user | 76cf59f9afcb2b13d75d54a7418103cc882d6f4e | 41,625 |
def set_fpn_weights(training_model, inference_model, verbose=False):
"""
Set feature pyramid network (FPN) weights from training to inference graph
Args:
training_model: MaskRCNN training graph, tf.keras.Model
inference_model: MaskRCNN inference graph, tf.keras.Model
verbose: ... | 29aadfcd0dcb50edb41938433ff644b1b62f209e | 41,626 |
def empty_graph(n=0, create_using=None, default=nx.Graph):
"""Returns the empty graph with n nodes and zero edges.
Parameters
----------
n : int or iterable container of nodes (default = 0)
If n is an integer, nodes are from `range(n)`.
If n is a container of nodes, those nodes appear i... | 81449b126d6cd025fab790194da9ba6a5b41f927 | 41,627 |
import time
def connect(**kwargs) :
"""Connects to host, port with authorization.
Returns client, expname, detname, db_exp, db_det, fs_exp, fs_det, col_exp, col_det
"""
host = kwargs.get('host', cc.HOST)
port = kwargs.get('port', cc.PORT)
user = kwargs.get('user', cc.USERNAME)
... | 10b28d2b185d41ae5b8ddd55f7d527c6d9ed983b | 41,628 |
def initialize():
"""
to initialize the parameters
:return: stat: type dict, trans_pro: transition probability, trans_rew: transition reward
"""
num_state = 2 #the number of states
num_action = 2 #the number of actions
q_value = np.zeros((num_state, num_action)) #size:2x2
trans_pro ... | b8edb8fb84c27be88d887011b92efd8f59ccaa0c | 41,629 |
def _get_persistent_binding(app, device_addr):
"""
:return: bool
"""
x = app.__dict__.get('persistent_binding', False)
if x and device_addr is None:
msg = ('In case of `persistent_binding` set to `True`, '
'the `device_addr` should be set and fixed.')
raise... | 3f6f4f71297fd8a6a9615d2a76529e5376e4786e | 41,630 |
from typing import List
def build_columns(columns: List[dict], is_temp=False) -> List[str]:
"""
Build up partial DDL for all non-skipped columns.
For our final table, we skip the IDENTITY (which would mess with our row at key==0) but do add
references to other tables.
For temp tables, we use IDEN... | f6efa441a2c883a64787fc07432be4230735ea07 | 41,631 |
def calcSignatureOverlaps(mode_ensemble, diag=True):
"""Calculate average mode-mode overlaps for a ModeEnsemble."""
if not isinstance(mode_ensemble, ModeEnsemble):
raise TypeError('mode_ensemble should be an instance of ModeEnsemble')
if not mode_ensemble.isMatched():
LOGGER.warn('mode... | c3830a2dbe3cc1dc4a2439f6705502d0ff83ae53 | 41,632 |
from typing import Optional
def config(config_path: Optional[str] = None) -> ServerConfig:
"""Retrieve server configuration, loading it from disk once and caching it."""
global _CONFIG # pylint: disable=global-statement
if _CONFIG is None:
_CONFIG = _load_config(config_path)
return _CONFIG | f56c14b7cc23e00e229c9cde0f8bc88127af8527 | 41,633 |
import math
def pop_age_data(pop, code, age, percent_pop):
"""Select and return the proportion value of population
for a given municipality, gender and age"""
n_pop = pop[pop['code'] == str(code)][age].iloc[0] * percent_pop
rounded = int(round(n_pop))
# for small `percent_pop`, sometimes we get 0... | f3a6a0c972eeea5a351d0f734a41a498035e5ecc | 41,634 |
def get_messier_object_by_mid(mid):
"""
Reply with the Messier object based on mid
:param mid:
:return:
"""
# perform a case-insensitive search
messier_object = messier_collection.find_one({'mid': {'$regex': mid, '$options': '-i'}})
if not messier_object:
abort(404)
messi... | d795fef48395c6f3c80b391a06b9d29f6569ef06 | 41,635 |
import functools
def idawrite_async(f):
"""
Decorator for marking a function as completely async.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
ff = functools.partial(f, *args, **kwargs)
return idaapi.execute_sync(ff, idaapi.MFF_NOWAIT | idaapi.MFF_WRITE)
return wrapper | 455382699bbaf00f6a3d936f00f7ac8012ee360f | 41,636 |
def port_is_used(port, host="127.0.0.1"):
"""
Returns if port is used. Port is considered used if the current process
can't bind to it or the port doesn't refuse connections.
"""
unused = _can_bind(port, host) and _refuses_connection(port, host)
return not unused | b21568219c242855f6bc69b0d5447d8549c31e64 | 41,637 |
from typing import OrderedDict
def video_info_url_age_restricted(video_id: str, embed_html: str) -> str:
"""Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str embed_html:
The html contents of the embed page (for age restricted videos).
:rtype: st... | 6d5d9601670a178e47c941d06612a2082c6346b1 | 41,638 |
def memcached(servers, key=None, from_cache=None, to_cache=None, time=0,
min_compress_len=0, debug=False):
"""memcached memoization function decorator.
The wrapped function is expected to return a value that is stored to a
memcached server, first translated by `to_cache` if provided. In the e... | c784d657eebad945b2ef7445931272418aa133c7 | 41,639 |
def slice_length(key: slice, length: int) -> int:
"""Calculate the length of the slice.
Args:
key: The slice to calculate the length of.
length: The maximum length of the slice.
Returns:
The length of the slice.
"""
return len(range(*_slice_default_bounds(key, length))) | 31e67a436a41602fe51e5c026a1aed9bb9a02153 | 41,640 |
def navamsa_from_long(longitude):
"""Calculates the navamsa-sign in which given longitude falls
0 = Aries, 1 = Taurus, ..., 11 = Pisces
"""
one_pada = (360 / (12 * 9)) # There are also 108 navamsas
one_sign = 12 * one_pada # = 40 degrees exactly
signs_elapsed = longitude / one_sign
fraction_left = sig... | d151f66c0e69541ccdcc3cabc4d0de82e7aa84bd | 41,641 |
import math
def LogNormalRiskyDstnDraw(RiskyAvg=1.0, RiskyStd=0.0):
"""
A class for generating functions that draw random values from a log-normal
distribution as parameterized by the input `RiskyAvg` and `RiskyStd`
values. The returned function takes no argument and returns a value.
"""
Risky... | 0931db4e50b3b6d0d21b5f9cdfa2d01617081509 | 41,642 |
def register(add_parser, _):
"""Adds this sub-command's parser and returns the action function"""
parser = add_parser('cat', help='output files by job or instance uuid')
parser.add_argument('target-entity', nargs=1,
help='Accepts either a job or an instance UUID or URL. The latest in... | 48d3cb55d1d8b7994e861a141acf557354c453bb | 41,643 |
import io
def is_serialised(serialised):
"""
Detects whether some bytes represent an enumerated type.
:param serialised: The bytes of which the represented type is unknown.
:return: ``True`` if the bytes represent an enumerated type, or ``False``
if it doesn't.
"""
try:
unicode_string = io.TextIOWrapper(io.B... | 039a25b13bded8f8c568c6d66071704b464109fc | 41,644 |
def compare_connexion(conn1, conn2):
"""See if two connexions are the same.
Because the :class:`connexion` could store the two components in different
orders, or have different instances of the same component object, direct
comparison may fail. This function explicitly compares both possible
combina... | 25c3737cfcdb0ab6516237ea5423e2237cc94529 | 41,645 |
def get_station(station_number: str, db: Session = Depends(get_db)):
"""
Get information about a stream monitoring station. Data sourced from the National Water Data Archive.
https://www.canada.ca/en/environment-climate-change/services/water-overview/quantity/monitoring/survey/data-products-services/nation... | f879ccb046d9b931d715b8f26e1f561549004a7a | 41,646 |
from typing import Union
import pytz
def get_reminder_timezone(
bot: Union[Sopel, SopelWrapper],
reminder: Reminder
) -> pytz.BaseTzInfo:
"""Select the appropriate timezone for the ``reminder``.
:param bot: bot instance
:param reminder: reminder to get the timezone for
:return: the appropriat... | 135def07afb778a15af7224b5931620173f35851 | 41,647 |
from typing import Union
from typing import Any
def is_successful_result(value: Union[MiddlewareResult, Any]) -> bool:
"""Returns ``True``, if given value is a successful middleware result."""
if value == MiddlewareResult.IGNORE:
return False
return True | 965cb54df43db62d0fe0b3a0f2440fc046bc941f | 41,648 |
from typing import List
from typing import Any
from typing import Callable
import click
def generate_dynamic_multicommand(
commands: List[Any],
callback_function: Callable,
create_short_names: bool = False
) -> Any:
"""Use provided dict to create a dynamic click.MultiCommand."""
has_sh... | 043efbec6c044a823af0f80170b3017eeaec267d | 41,649 |
import os
def get_verifier_repo_dir(verifier_id):
"""
Returns installed verifier repo directory for Tempest
"""
if not verifier_id:
verifier_id = get_verifier_id()
return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
'verification',
'... | 73e722dfc79ce93eb6ee6155d59ab9907729d5e6 | 41,650 |
def rmssd(nni: np.ndarray) -> float:
""" Root mean square of differences.
Params:
nni (np.ndarray): R-peak intervals
Returns:
float
"""
return np.sqrt(np.mean(np.square(np.diff(nni)))) | 4b2045133a909f2758871139857b531acabe73cb | 41,651 |
import os
import re
import errno
def get_kernel_pos_from_iomem(machine=None):
"""Get the position of some kernel segments using /proc/iomem
Since Linux 4.6, access to physical addresses in /proc/iomem is restricted
to privileged users, cf. commit 51d7b120418e ("/proc/iomem: only expose
physical resou... | 9f2ad3961097f920d6345e4fd1cfa4485a7ae14b | 41,652 |
def without_end_slash(url):
"""Makes sure there is no end slash at the end of a url."""
return url.rstrip("/") | 19d6b49f7d2a788ea4bb81179e596eb6f019843e | 41,653 |
import os
def get_ipython_dir():
"""Find the ipython local directory. Usually is <home>/.ipython"""
if hasattr(itango, "get_ipython_dir"):
return itango.get_ipython_dir()
if hasattr(IPython.iplib, 'get_ipython_dir'):
# Starting from ipython 0.9 they hadded this method
return IPyth... | e0453427810033494e02290abcc1a654f236df9e | 41,654 |
def find_cutlevels(image, min_percent=None, max_percent=None, percent=None):
"""
Find pixel values of the minimum and maximum image cut levels from
percentiles of the image values.
Parameters
----------
image : array_like
The 2D array of the image.
min_percent : float, optional
... | 08d111074c7b871d5ca2ec81c7d1b81d4147d619 | 41,655 |
def get_products(product_id):
"""
Retrieve a single Product
This endpoint will return a Product based on its id
"""
app.logger.info("Request for product with id: %s", product_id)
product = Product.find(product_id)
if not product:
raise NotFound("Product with id '{}' was not found.".f... | 0c9a576ecffee7572af27428ffaccab979111907 | 41,656 |
from sys import path
import re
def _parse_file():
"""Parse the config from a file.
Note:
Assumes any value that ``"$LOOKS_LIKE_THIS"`` in a service
definition refers to an environment variable, and attempts to get
it accordingly.
"""
file_name = path.join(
path.abspath(path... | 2b06efbb6ea8b81f619b80e664c84202fb2e1070 | 41,657 |
import sys
import json
def get_answers() -> dict:
"""Return a dictionary containing every answer."""
with open(sys.argv[1], "r") as f:
answers = json.load(f)
return answers | 73e0b8ece6658b27678bed3953859149cc868d04 | 41,658 |
import getpass
import click
import sys
def enter_password(prompt: str, default: str = '') -> str:
"""Hidden password input"""
try:
password = getpass(prompt)
except (KeyboardInterrupt, EOFError):
click.echo(None)
sys.exit(1)
if not password and default:
password = defa... | 9de96273432353af7d1b1966fb852bbd69d6ba99 | 41,659 |
def CloneNodeList(nodeList):
"""Return a clone of the given nodeList."""
# This is tricky because we want to maintain client/server links
# make a list of cloned nodes, map maps original nodes to new nodes
cloneList = []
map = {}
for node in nodeList:
newNode = node.Clone()
newNode.RemoveAllServers()
clone... | cfaeab6edc6d40dd3373ecedc1641b3f542deda4 | 41,660 |
import os
import errno
def last_bytes(path, num):
"""Return num bytes from the end of the file and unread byte count.
Returns a tuple containing some content from the file and the
number of bytes that appear in the file before the point at which
reading started. The content will be at most ``num`` by... | c6207ae675ab51f806ef64d10aa9e7989592b99a | 41,661 |
def project_stabilized_state(stabilizer_list, num_qubits=None,
classical_state=None):
"""
Project out the state stabilized by the stabilizer matrix
|psi> = (1/2^{n}) * Product_{i=0}{n-1}[ 1 + G_{i}] |vac>
:param List stabilizer_list: set of PauliTerms that are the stabiliz... | 4834f5aa75800b67511dfa445369c8cb2d3db671 | 41,662 |
import os
def newMenuItem(restaurant_id):
"""
Create a menu item with a specific restaurant's id.
:param restaurant_id: Restaurant's id to which new menu item belongs.
:return:
on GET: Render new menu form template.
on POST: Redirect to the menu page if the create request has been succeeded.
... | 00b39c6169d1fa804614df34ccb3d3128e50f6b4 | 41,663 |
def get_license_banner(comment: str = "") -> str:
"""Returns a commented out license banner.
comment is the style of comment supported by the source file type.
"""
return apply_comment(LICENSE_BANNER, comment) | a7a77e1e6a1d490c582591229729a0dff64d495c | 41,664 |
def parseXML(xml_filename: str) -> dict:
""" This function generates an annotation dictionary representation of
the contents of the specified XML filename.
Args:
xml_filename (str): Relative path to the XML file
Returns:
annotation (dict): Fepresentation of the entire XML file
"""
... | c75c6333c59564047aa3691437735448021fde74 | 41,665 |
from typing import Optional
from typing import List
async def direct_messages(sessionid: str = Form(...),
thread_id: int = Form(...),
amount: Optional[int] = Form(20),
clients: ClientStorage = Depends(get_clients)) -> List[DirectMessage]:
""... | 61da44cc96d1e242363688cd0fb3c9e5089c576e | 41,666 |
def randfor_cv(Xs, ys, folds=8, iterations=1, n_estimators=50,
max_features='log2', random_state=44, n_jobs=8):
"""Compute random forest regression accuracy statistics, shuffling at the sequence level."""
r2s = []
pcors = []
for i in range(iterations):
rs_iter = random_state + i
... | f0444cc682acf09ee3942863debfb6220c67a0d8 | 41,667 |
def var(u: Vec) -> float:
"""Computes the variance of the vector components
Args:
u (Vec): vector of values
Raises:
ValueError: if u is not provided or u is of non-numeric integral type
Returns:
float: the variance of the vectors components
"""
if not u:
raise ... | bea2bd1c7eb2407b64054e110b24b4a1c4b8a505 | 41,668 |
def calculate_final_assembly_tipracks(final_assembly_dict):
"""Calculates the number of final assembly tipracks required ensuring
no more than MAX_FINAL_ASSEMBLY_TIPRACKS are used.
"""
final_assembly_lens = []
for values in final_assembly_dict.values():
final_assembly_lens.append(len(values... | ee10b837d20949df460479308dfc83516926e52a | 41,669 |
import logging
def enforce_timeout_range(timeout_delta):
"""Enforce the range of allowed timeout values based on constants TIMEOUT_MIN
Warnings are raised if the timeout is outside of the range.
timeout_delta(timedelta): Timeout setting as instance of timedelta.
"""
if timeout_delta < TIMEOUT_MIN... | 6d877361b57b0a1e7ff6cee8344b08e7c9098b1f | 41,670 |
def cross_validation_split(dataset, folds=10):
"""Return dataset split into 10 folds"""
dataset_split = list()
dataset_copy = list(dataset)
fold_size = int(len(dataset) / folds)
for i in range(folds):
fold = list()
while len(fold) < fold_size:
index = randrange(len(datase... | f750c321ff37d4b372d01e173155d1be7469ddf3 | 41,671 |
def assert_configs_work(backend, client_config, server_config, hostname=None):
"""
Given a pair of configs (one for the client, and one for the server),
creates contexts and buffers, performs a handshake, and then sends a bit of
test data to confirm the connection is up.
Returns the client and serv... | f93b34faf7697967e3e48fff09a1140adee85146 | 41,672 |
def read_result_file(fname):
""" read file with world record distances/paces """
running_paces = []
with open(fname, 'r') as result_file:
for line in result_file:
ent = line.split()
if 'distance' in ent[0]:
continue
dist_meters = float(ent[0]) * 10... | 81daa1b83e7e2aed6d0df08e1d82f4b929391bcc | 41,673 |
def is_droid_in_network_generation(log, ad, nw_gen, voice_or_data):
"""Checks if a droid in expected network generation ("2g", "3g" or "4g").
Args:
log: log object.
ad: android device.
nw_gen: expected generation "4g", "3g", "2g".
voice_or_data: check voice network generation or... | 3e22de2bee512800d7a1b05955f181a6bc4f2b91 | 41,674 |
def _getMatricesFromDft2Outfile(outPath):
""" Parses all hamiltonian and overlap matrices from a dft2 file
Args:
outPath: Full path to the output file
Returns
allMatrices: types.SimpleNamespace with two fields, hamil and overlap. Both are lists of square numpy arrays (dtype=complex).
The ind... | de8a8a240b795f217e401222eb2df91bdbd6c72c | 41,675 |
import hashlib
def verifySignatureFromBytes(data, publicKey, signature):
"""
Verify signature.
Arguments:
data (bytes) -- data in bytes
publicKey (str) -- a public key as hex string
signature (str) -- a signature as hex string
Return bool
"""
if len(publicKey) == 66:
publicKey = uncompressEcdsaPublicKey(... | c80fb3f641b81e0b3ae7135c0bc2a437b2f298dd | 41,676 |
import re
def load_setting_api_access_token(logger, config_settings):
"""
Attempt to parse API token from config settings
:param logger: the logger
:param config_settings: config settings loaded from config file
:return: API token if valid, else None
"""
try:
... | a41d873ee9ee9323fa57c9c8e3fe58db4a3ee841 | 41,677 |
def limit_posts(posts, limit=POST_LIMIT):
"""Restrict posts to the <limit> most recent."""
return posts.order_by(desc(Post.published_datetime)).limit(limit).from_self() | b0f172ffbb71d2516ccadd1c3cc3611d1703cf17 | 41,678 |
def command(login_required=True):
"""a decorator for handling authentication and exceptions"""
def decorate(f):
def wrapper(self, args):
if login_required and self.api_client is None:
self.stdout.write("Please 'login' to execute this command\n")
return
... | eaab4b3fa49012726072f54a5cd68a4369b64e25 | 41,679 |
def do(ModeName, CaMap, IndentationSetup, IncidenceDb, ReloadState, dial_db):
"""________________________________________________________________________
Counting whitespace at the beginning of a line.
.-----<----+----------<--------------+--<----.
| | count ... | 870be816e5837b67f568d1f008ae580387bba09f | 41,680 |
from stat import S_ISDIR
def list_remote_files(con, directory):
"""
List the files and folders in a remote directory using an active SFTPClient from Paramiko
:param con: SFTPClient, an active connection to an SFTP server
:param directory: string, the directory to search
:return: (generator, generator), the files... | f65e4a5d48f793ff3703ea5e4fc88a0e9b7ea39d | 41,681 |
def potential_aneurysm(data, box_size=64, accuracy=0.005, neighbours=False, pix_close=10):
"""
Goes through the given image and returns a list of possible aneurysms
Parameters
----------
data : numpy.ndarray
Data array of the MRA image of interest
box_size : int
Size of one s... | 79b2f1123e33f012ddafceb90a0be660881736b8 | 41,682 |
def debug_build(enabled: bool):
"""Decorator logs Layer.build() input shape. `@debug_build(DEBUG)`"""
@wrapt.decorator(enabled=enabled)
def wrapper(wrapped, instance, args, kwargs):
print('{} build() (in {}) input_shape {}'.format(
instance.__class__.__name__, instance.__class__.__module__,
*args)... | 083535755b89e0560a1fb20271cf0055e402c32c | 41,683 |
def execute_script(script, *args):
"""Execute JavaScript in the currently selected frame or window.
Within the script, use `document` to refer to the current document.
For example::
execute_script('document.title = "New Title"')
:argument script: The script to execute.
:argument args: A ... | 3c2c60cdccf6b5613e37373f2f340939eb6d4731 | 41,684 |
def det_curve(y_true, scores, distances=False):
"""DET curve
Parameters
----------
y_true : (n_samples, ) array-like
Boolean reference.
scores : (n_samples, ) array-like
Predicted score.
distances : boolean, optional
When True, indicate that `scores` are actually `distan... | 8b2b08799ff3062783af5fc2e94bbc90238ae769 | 41,685 |
def _get_nary_broadcast_shape(*shapes):
"""
Broadcast any number of shapes to a result shape.
Parameters
----------
shapes : tuple[tuple[int]]
The shapes to broadcast.
Returns
-------
tuple[int]
The output shape.
Raises
------
ValueError
If the inpu... | 0669ba10cbdb824b5ca9a827d6935ddb9c9a787e | 41,686 |
def html_to_dot_sequential_name(
root: lxml.html.HtmlElement, graph_name: str, with_text: bool = False
) -> graphviz.Digraph:
"""
The names of the nodes are defined by `{tag}-{seq - 1}`, where:
tag: the html tag of the node
seq: the sequential order of that tag
ex: if it is the 2... | decd9a4b311c126b418a1be7a982475603001009 | 41,687 |
import six
def get_exception_for_sqlstate(code):
"""Translate the sqlstate to a relevant exception.
See for a list of possible errors:
http://www.postgresql.org/docs/current/static/errcodes-appendix.html
"""
if isinstance(code, six.binary_type):
code = bytes_to_ascii(code)
if code[0]... | 634e9485c19065db7f46bd76e431f303f52916a6 | 41,688 |
def action_from_policy(policy, deterministic=False):
"""
Samples an action from a given policy using numpy.
"""
if not deterministic:
return np.random.choice(range(len(policy)), p=policy)
else:
argmaxes = np.argwhere(policy == np.max(policy)).reshape(-1)
return choice(argmaxe... | 6f39eab81ef75f4a47bac792c6f3450de88423e1 | 41,689 |
def error_rate(predictions, imgs):
"""Return the error rate based on dense predictions and sparse labels."""
return 0.5 * ((predictions - imgs)**2).mean() | 22fb7ccee4facff54e41e784cdb7c317e0e3f8dc | 41,690 |
def setup_configs(args):
"""
args:
::dataset_name
::resolution
"""
ic(args)
config = Munch(
dataset_name=args.dataset_name, y_col="family", threshold=0, resolution="original"
)
target_config = Munch(
dataset_name=args.dataset_name, resolution=args.resolutio... | 502e2a60f1cac25b45804b98cf035ef544c87ae2 | 41,691 |
def fmap(func, obj):
"""fmap(func, obj) creates a copy of obj with func applied to its contents.
Override by defining obj.__fmap__(func). For numpy arrays, uses np.vectorize.
"""
obj_fmap = _coconut.getattr(obj, "__fmap__", None)
if obj_fmap is not None:
try:
result = obj_fmap(f... | 5022570ab4aa98fc6d65f8b93936902996f82fdb | 41,692 |
def last_month(date):
"""get the name of month"""
date = str(date)
date = date[:4] + '-' + date[4:]
date0 = arrow.get(date)
lastmon = date0.shift(months=-1)
lastmon = lastmon.format('YYYYMM')
return lastmon | ffa43a888cc3447c424358315c7a412fbb644704 | 41,693 |
def camera_to_sky(pos_x, pos_y, focal, pointing_alt, pointing_az):
"""
Parameters
----------
pos_x: X coordinate in camera (distance)
pos_y: Y coordinate in camera (distance)
focal: telescope focal (distance)
pointing_alt: pointing altitude in angle unit
pointing_az: pointing altitude i... | c2c15b6a1b0411e463cb8a7dabb3a3bfe0ac14c9 | 41,694 |
import dataclasses
def static_field(*args, **kwargs):
"""Substitute for dataclasses.field, which also marks a field as static."""
kwargs["metadata"] = kwargs.get("metadata", {})
kwargs["metadata"][FIELD_METADATA_STATIC_MARKER] = True
return dataclasses.field(*args, **kwargs) | 400dbfc987fa9378d71fa92da086cddf8abae112 | 41,695 |
def _standardize_overhangs_pair(overhangs):
"""Standardize a pair of overhangs (o1, o2).
Returns either ``(o1, o2)`` or its reverse complement ``(rev_o2, rev_o1)``,
whichever is smaller in alphabetical order.
"""
o1, o2 = overhangs
ro1, ro2 = [reverse_complement(o) for o in (o1, o2)]
return... | 433ac7517764d9c2614f2d87aefdb8949c835de8 | 41,696 |
import json
def unjsonb(bytes):
"""bytes -> list"""
return [json.loads(s.decode("utf-8")) for s in bytes.splitlines()] | e831851ea0149d46d73610fc1979168aba9ef1cd | 41,697 |
from datetime import datetime
def get_nixtime_from_msec(msec):
""" Convert unix epoch time in microseconds to a date string """
seconds, msec= divmod(msec, 1000000)
days, seconds = divmod(seconds, 86400)
if days > 20000 or days < 9000:
days = 0
seconds = 0
msec = 0
return d... | 6ec4f13a4296e2180eef4c0f99688ec997461739 | 41,698 |
import os
import glob
def explode_fasta(fasta, log):
"""split input fasta into individuals"""
in_file = False
outdir = "fastas"
if not os.path.exists(outdir):
os.mkdir(outdir)
with open(fasta, 'r') as infile:
for line in infile:
if line.startswith(">"):
... | d0d054972e8bbeb5d091e9f6744e346720b48d7c | 41,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.