content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def init_synsets(scene_graph, synset_file):
"""
Convert synsets in a scene graph from strings to Synset objects.
"""
syn_data = json.load(open(synset_file, 'r'))
syn_class = {s['synset_name']: Synset(
s['synset_name'], s['synset_definition']) for s in syn_data}
for obj in ... | 6e7f630bb1acc8bdc1670a1540027516cbb5d4a5 | 51,707 |
from datetime import datetime
def bundle_config(tmp_path):
"""Provide a config class with an extra set method for the test to change it."""
class TestConfig(config_module.Config, frozen=False):
"""The Config, but with a method to set test values."""
def set(self, prime=None, **kwargs):
... | 26cac266e2860db56cf72d96d5a677238ef18d35 | 51,708 |
def apex_settings(key=None, default=None):
""" Gets an apex setting if the key is set.
If no key it set, returns all the apex settings.
Some settings have issue with a Nonetype value error,
you can set the default to fix this issue.
"""
settings = get_current_registry().settings
... | 2d2d9dec52c9b17cb7fb3981873bd2bd7cbc5555 | 51,709 |
def linear_curve(t, a, b):
"""
fit data to linear model
"""
return a*t + b | da224450cffde96780268ad8d4abe4c754d55b46 | 51,710 |
def _get_channel_setting() -> dict:
"""Default config format for each channel
:return dict channel_setting : Default config format for each channel
"""
channel_setting = {
"block_versions": {
"0.1a": 0
},
"hash_versions": {
"genesis": 1,
"0x2"... | 94f19f0647b08db188aefc5e4899fc6d329f0e42 | 51,711 |
def serialize(iterable, encoding=None):
"""Serializes an iterable of key value pairs into a stream of
string chunks. If an encoding is provided, it will be encoded into that.
This is primarily used by the editor to write back data to a source file.
"""
def _produce(item, escape=False):
if ... | b30f60c7173c666eb4d1d796093ee205bccb4521 | 51,713 |
def test_pre_rescaling_integration(is_invertible, model):
"""Test the pre-scaling feature"""
def forward(x):
return np.log(x), -np.log(x)
def inv(x):
return np.exp(x), x.copy()
reparam = RescaleToBounds(
parameters='x',
prior_bounds={'x': [1.0, np.e]},
pre_resc... | 0a55f7ec19bd882edaa94b90a8d0c4ea843ad02d | 51,714 |
def DLSI_updateD(D, E, F, A, lambda1, iterations=100):
"""
def DLSI_updateD(D, E, F, A, lambda1, verbose = False, iterations = 100):
problem: `D = argmin_D -2trace(ED') + trace(FD'*D) + lambda *||A*D||F^2,`
subject to: `||d_i||_2^2 <= 1`
where F is a positive semidefinite matrix
========= aproac... | 9acbb70da112a266da041abeb6d827df43da35a1 | 51,715 |
from typing import Union
from typing import Iterable
from typing import Optional
from typing import Any
from typing import Callable
def dispatch_requests(
requests: Union[Request, Iterable[Request]],
methods: Methods,
*,
extra: Optional[Any] = None,
serialize: Callable = default_serialize,
) -> Re... | 69fce0d55a0213a7a31fe597fd11979b25e7f0ea | 51,716 |
def quicksort(data, leftmark, rightmark):
"""Quicksort implementation.
QUICKSORT(A, p, r)
if p<r
q = PARTITION(A, p, r)
QUICKSORT(A, p, q-1)
QUICKSORT(A, q+1, r)
Args:
data (list): array to be sorted
leftmark (int): starting index
rightmark (int): ending... | 74d211efecfb8128c3b321c2b236243b62a3aa44 | 51,717 |
def to_geopotential_height(z: pint.Quantity) -> pint.Quantity:
"""Convert altitude to geopotential height.
Parameters
----------
z: quantity
Altitude.
Returns
-------
quantity
Geopotential height.
"""
return R0 * z / (R0 + z) | 08493526ff930d834c6750da5881db7c13e2359c | 51,718 |
def parse_kind(key):
"""Extract kind from colorbrewer.json
.. note:: This can be None if key is not seq, div or qual
"""
if key == "seq":
return Kind.SEQUENTIAL
elif key == "div":
return Kind.DIVERGING
elif key == "qual":
return Kind.QUALITATIVE | 35a71ba3c89abe200e46e48654b5b74855f0ddf4 | 51,719 |
def is_bad(text):
"""
Returns true iff the given text looks like it contains mojibake.
This can be faster than `badness`, because it returns when the first match
is found to a regex instead of counting matches. Note that as strings get
longer, they have a higher chance of returning True for `is_bad... | f422df400118d5ff053003715e42cffced4a9684 | 51,720 |
import ast
import operator
import copy
import math
def math_eval(expression, variables=None, functions=None):
"""Evaluate a mathematical expression with variables.
All the functions in the standard module math are available together with
- step(x) : Heaviside step function (1.0 for x=0)
- step_hm(x) ... | a373754c3d9d536af2396d2b8a4aba77c16512ad | 51,721 |
def DBPossibleAddressWrites(reg, cst, constraint, assertion, n=1):
"""
Return the list of [addr_reg, addr_cst] such than mem(addr_reg, addr_cst) <- reg+cst
"""
return db.possibleAddressWrites(reg, cst, constraint, assertion, n) | 86ac19b0a617b90f45eaebb5ce45c78bf9c46cf1 | 51,722 |
def _decline(di, t, qoi, b):
"""Arp's equation for general decline in a well
- qoi: initial rate of production
- di: initial decline rate
- b: curvature (b=0 exponential)
"""
return qoi / ((1 + b * di * t) ** (1 / b)) | 86368cef4d7d24bff738d5fe4acde2a1a9fb8922 | 51,723 |
def su_calculation(f1, f2):
"""
This function calculates the symmetrical uncertainty, where su(f1,f2) = 2*IG(f1,f2)/(H(f1)+H(f2))
Input
-----
f1: {numpy array}, shape (n_samples,)
f2: {numpy array}, shape (n_samples,)
Output
------
su: {float}
su is the symmetrical uncertai... | a7a1a11b3701d1d4511f1dc17465c9ddd51d2b5e | 51,724 |
def _close_xml_tags(xml):
"""
Automagically takes an input xml string and returns that string
with all of the xml tags properly closed. It can even handle when
the open tag is in the middle of the string and not the end.
"""
output = []
stack = []
xml_chars = deque(list(xml))
c = Non... | c0eb655a08e53e97d8e8cacc970e391f67e18e3d | 51,725 |
from jpickle import NetObj
def NetPDF(addr):
"""
Retrieves a PDF from a remote address.
:param addr: URI. PDF must be stored in JSON format
:returns: A PDF object
:Example:
>>> u = NetPDF('http://foo.com/myproject/parameters/density')
"""
p = NetObj(addr)
if not isinstance(p, PD... | 2ef28c6f08aef3d73b3603ecc74f422d4450da02 | 51,726 |
import hashlib
def gen_robohash(s, size=200):
"""Return URL for robohash pic for sha1 hash of string ``s``"""
h = hashlib.sha1(s).hexdigest()
return ('http://robohash.org/{0}.png?size={1}x{1}&bgset=bg2&set=set1'
.format(h, size)) | f4ac71b54801a3b86e3ec4e0cf60f25a9cae5990 | 51,727 |
import collections
def infer_type_names(model: SystemModel, ul: UserLevel) -> TypeNameMap:
"""Generates a list of unique type names for all typedefs depending on the user levels.
Args:
model (SystemModel): A DeCoP system model.
ul (UserLevel): The highest user level for which code will be gen... | b0203a2e65ec0b7dac810e35af829b394561f1da | 51,731 |
import io
def detect_text(img):
"""Detects text in the file."""
with io.open(img, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image) # returns TextAnnotation
df = pd.DataFrame(columns=['descripti... | a70dc2739e904fba7ff0526dc0622cf06ac7594e | 51,732 |
def preproccess_image(image):
"""
this function applies some basic image processings to the original images
:param image: original image
:return: processed image
"""
# covert BGR image to RGB space
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# print(image.shape)
# covert RGB ima... | 6dc886fa4a79527040cc7de0a6d532755acd61a2 | 51,733 |
def setup_fig(title, x_label, y_label):
"""
set-up the figure for the the plots
pre-conditions:
title: <string> the title of the plot
x_label: <string> x axis label
y_label: <string> y axis label
post-conditions:
returns the figure and the axes
"""
fig, axes... | 8202ec86559623330fa977de38fbd1d2ccb4bbb5 | 51,734 |
def logq(x, q=1):
"""
Calculates the `q`-logarithm of x.
Parameters
----------
x : float, array
Real number or array containing real numbers.
q : float
Tsallis's `q` parameter (default: 1).
Returns
-------
: float or array
Value or array of values containing... | 9ddaaeb27be316a556cab92d8b2d4408149b8a71 | 51,737 |
def wrap_deepmind(env_id, episode_life=True, clip_rewards=True,
frame_stack=4, scale=False, warp_frame=True):
"""Configure environment for DeepMind-style Atari. The observation is
channel-first: (c, h, w) instead of (h, w, c).
:param str env_id: the atari environment id.
:param bool e... | 1758a46bad172d70bd08e7e95c80e6fdf05e6a43 | 51,738 |
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are numpy array, output 4D, target 3D
mini = 1
maxi = nclass
nbins = nclass
predict = np.argmax(output.astype(np.float32), 1) + 1
target = target.astype(np.float32) + 1
predict = predict.astype(np.float32) * (targ... | 355d060a5135663742826bb73745b2c2551ec5eb | 51,739 |
from typing import Callable
from typing import Any
async def _async_get_ws_formatted_events(
hass: HomeAssistant,
msg_id: int,
start_time: dt,
end_time: dt,
formatter: Callable[[int, Any], dict[str, Any]],
event_processor: EventProcessor,
) -> tuple[str, dt | None]:
"""Async wrapper around... | eb6850210d773fba91a2abc26c25a35398080525 | 51,740 |
def laplace_ptr(boundary, trace, nb, matrix=False):
"""
μ, c, θ = laplace_ptr(boundary, trace, nb, matrix=False)
The PTR method for the Laplace problem.
Parameters
----------
boundary : Boundary
Boundary object
trace : function
the function θ ↦ f(θ) the source term of the B... | 08e7ebd443036f0c981094dd0389eb6a85c90e46 | 51,741 |
def _popen(cmd, data_in, data_out=PIPE):
"""
Helper function subprocess.popen replaces os.system
- gives better input/output process control
usage: pass <data_in> to process <cmd> and return results
based on rgbeimage.py (Thomas Bleicher 2010)
"""
cmd = str(cmd) # gets rid of unicode odditie... | 5b3fc74f87a7e58ad85ba25ac282738b05430a27 | 51,742 |
def reduce_min(attrs, inputs, proto_obj):
"""Reduce the array along a given axis by mean value"""
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'min', new_attrs, inputs | 61d06d1a1c3fe8b86e0ba974802f2b49dc37c323 | 51,743 |
def fake_get_value(name, default=None):
"""
Method for getting configuration override values for a fake site.
"""
return FAKE_SITE.get(name, default) | 7124758583e55a65cfc261667b49b5431f9bca1e | 51,744 |
def _load_md(rec,keys):
"""
Helper for load ensemble. Extracts metadata defined by keys list and
posts to a Metadata container that is returned.
"""
# do this stupid for now without error handlers
md=Metadata()
for k in keys:
x=rec[k]
md.put(k,x)
return md | 3791e31f26129e14ea28b31d84e12ae88876caf7 | 51,747 |
import re
def start():
"""\\A: Match the start of the text."""
regex = re.compile(r'\Aa', flags=re.MULTILINE)
match_start = regex.search("album")
match_starting_newline = regex.search("\nart")
return match_start and not match_starting_newline and match_start.string | 9aa89978b122cd5dc3d3c00d3217e731636c2f71 | 51,748 |
def variance(y):
"""
Return the sample variance of y.
>>> y = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(y)
1.3720238095238095
"""
av = mean(y)
ss = sum((x-av)**2 for x in y)
return ss/(len(y)-1) | 6ca4e59ddd6725b31cf5dbd20adb85f1e0ed27f8 | 51,749 |
from typing import Callable
def get_text_preprocessor(func: str) -> Callable[[str], str]:
"""
Given a string descriptor of the function, return the requested preprocessing function.
Args:
func: Function name.
Returns:
Text preprocessing function.
"""
if func == TextPreprocess... | 9eb36d6b3017ec3394d47fd26908b6791dccf4e8 | 51,750 |
import numpy
def BM_spectrum(E, I, B, ph_energy, hor_acc_mrad=1.0):
"""
Calculates the emitted spectrum of a Bending Magnet (vertically integrated) whithin a horizontal acceptance\n
Units: [ph/s/0.1%bw]\n
:E: Storage Ring energy [GeV]
:I: Storage Ring current [A]
:B: Magnetic Field value [T] ... | fd87dae1dc35bcb4a2ab87cb8c881875caa6ebd0 | 51,751 |
def finite_zeroth_d(grid):
"""
Gives the zeroth derivative operator on the function
f(grid), so simply returns the identity matrix... XD
"""
return identity(len(grid)) | 95284bf0f16acc11b8d45396a2892865836d1813 | 51,752 |
def set_gdx_path(path):
"""Set file path of active GDX file."""
global ACTIVE_GDX
ACTIVE_GDX = Gdx(path)
logger.info(f"ACTIVE_GDX set to {ACTIVE_GDX.abs_path}")
return f"Active gdx set to {ACTIVE_GDX.abs_path}" | 7b196128cb77a10ffaab0d82da72ede7f6a86298 | 51,753 |
def bfs(problem, stype):
"""
Breadth-first search
:param problem: problem
:param stype: type of search: graph or tree (graph_search or tree_search)
:return: (path, stats): solution as a path and stats
The stats are a tuple of (time, expc, maxstates): elapsed time, number of expansions, max state... | f7f6c28e025e05d5acced7c1cf5702715903768d | 51,756 |
def stock_valuation_n_period(discount_rate ,LT_growth_rate, dividends):
"""
Summary: Given an array of dividends, estimate the stock price using an n-period model.
PARA discount_rate: The discount rate used to calculate the NPV & PV calcs.
PARA type: float
PARA LT_growth_rate: The long-ter... | 7e0670fea9b963aa92cc093e7e1d7751fe8af17d | 51,757 |
def two_versions(app, identity_simple, input_data, service):
"""Create 2 versions."""
# NOTE: We use app fixture to create/teardown the index only once for
# this module.
record = _create_and_publish(service, input_data, identity_simple)
recid = record.id
draft = service.new_version(recid,... | e9f72d6e74afbfca983ea427beabe4b9b5beeacd | 51,759 |
def prepare_simulation(a,b,c, n):
"""
prepare simulation
:return:
:rtype:
"""
f_f = ForceField(linear=True, amplitude=20)
f_f.origin = b
print(f_f)
# cell = CubicCell(a, b, c)
cell = ForceCubicCell(a,b,c, f_f)
print(cell)
print(cell.get_center())
print("the force o... | 0c4df93096752868ad5d30f2f338307c0988530b | 51,760 |
from itertools import chain
def flatten_list(lst):
"""
:param lst: original list
:return: flattened list
"""
return list(chain(*lst)) | 5f0f796a543f0364cdb238ede40b6f021e698ba6 | 51,761 |
def checkwait(space, w_sock, writing):
"""If the socket has a timeout, do a select()/poll() on the socket.
The argument writing indicates the direction.
Returns one of the possibilities in the timeout_state enum (above)."""
w_timeout = space.call_method(w_sock, "gettimeout")
if space.is_w(w_timeout... | 67123e1a5bb8803d3892387e067119bb69d4b1df | 51,762 |
def sample_user(
username='tesuser',
email='test@test.com',
password='Testpassword_123'
):
"""Create a sample user"""
return get_user_model().objects.create_user(username, email, password,) | 049453cd3bb9821b4bcd8a1081bf6c8d8f3a66d3 | 51,763 |
def min_date_nan(dates):
"""Find the earliest date from a series that may contain NaNs.
Find the earliest date from a pandas series of datetime.dates that may
contain NaNs. NaN dates are considered earlier than all others.
"""
if dates.isna().any():
return np.NaN
else:
return... | 5684fa178d723dc61e5faddb74ff2e359e98a29f | 51,764 |
from datetime import datetime
def to_utctimestamp(a_datetime):
"""
Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time.
- dt has tzinfo: use tzinfo.
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UT... | 96502d9d0c2eef4bd2ba52fe7a73c647502bf81b | 51,765 |
def function_with_cpp_args_kwargs(a, b, c=None, d=3, e=(None, "test")):
"""this is a doctring
"""
__cpp__ = """
return Py_BuildValue("(O,O,O,O,O)", a, b, c, d, e);
"""
return None | caf7622a4031bfee704f4ed3d0bcaa2a0591b52d | 51,766 |
from typing import Any
import attr
def validated() -> Any:
"""Decorate an entity to handle validation.
This will let ``attrs`` manage the class, using slots for fields, and forcing attributes to
be passed as named arguments (this allows to not have to defined all required fields first, then
optional ... | 6903d654e74b6bd6fc2d062755823043125c922a | 51,767 |
import uuid
import requests
import json
def create_vendor(config):
"""
POST request to create a Vendor in QBO
Refer here for other Vendor fields: https://developer.intuit.com/docs/api/accounting/vendor
"""
url = config['qbo_base_url'] + '/v3/company/' + config['realm_id'] + '/vendor?minorv... | c41a2bb5d589a5fa31eed3dda8506d49bcf42c57 | 51,768 |
def mean_match_accuracy(predicted, target):
"""Computes mean of number of matches between some target and some
predicted values.
Both 'predicted' and 'target' can be either scalars or sequences,
but have to be of the same length.
"""
return np.mean(prediction_target_matches(predicted, target)) | 432a263b10eadecec9b1342f7d1b150504d4ae82 | 51,769 |
from absa_api import export_data
import json
def download_data_and_compare_same(hostname=["http://192.168.50.139:8081/api/","http://192.168.50.139:8080/api/"], dirpath="/opt/lavector/absa/", jsonfile=["192.168.50.139_500_8081_0129.json","192.168.50.139_500_8080_0129.json"], isabsa=True):
"""
对比相同的hostname的数据
... | c8089ea765a36c95384980c34db9390da2c2a1d8 | 51,770 |
def getDecoderClass(typ):
""" Return Decoder class for the PK type. """
for cls in (CentralDirEntry, LocalFileHeader, EndOfCentralDir, DataDescriptor, Zip64EndOfDir, Zip64EndOfDirLocator, ArchiveExtraDataEntry, ArchiveSignature, ):
if cls.MagicNumber == typ:
return cls | 5071ed571f78af7b57edf451e4f3dab9fd570682 | 51,771 |
def connex(vertices: np.ndarray) -> list:
"""Connection array to build vertex edges for vispy LineVisual.
Notes
-----
See
http://api.vispy.org/en/latest/visuals.html#vispy.visuals.LineVisual
"""
return [True] * (vertices.shape[0] - 1) + [False] | b743f317a142da55ffd09409e16542d0263601db | 51,772 |
def __parse_options(config_file, section, options):
""" Parse the section options
:type config_file: ConfigParser object
:param config_file: The config file object to use
:type section: str
:param section: Which section to read in the configuration file
:type options: list of dicts
:param o... | c555855b56e35b53e14d664b99104e094d02a6a1 | 51,773 |
def visualize_cut_plane(
cut_plane, ax=None, minSpeed=None, maxSpeed=None, cmap="coolwarm", levels=None, title = None
):
"""
Generate pseudocolor mesh plot of the cut_plane.
Args:
cut_plane (:py:class:`~.tools.cut_plane.CutPlane`): 2D
plane through wind plant.
ax (:py:class:... | 1333b98664e1ed80c2dc18b3d3ce5d8438fa30fd | 51,774 |
from typing import Dict
from typing import Any
import copy
import functools
from datetime import datetime
def train(train_job_params: Dict[str, Any],
output_dir: str,
return_dict: Dict[str, float] = None,
progress_dict: Dict[str, float] = None,
env_tag: str = None):
"""Train.... | 07528c0d3e7e9236c7ef4c7465a882f4d656e278 | 51,775 |
import math
def get_multistage_merge_pipeline(
alias,
vcf_files,
processing_dir,
chunk_size,
bcftools_binary,
process_name,
process_command,
stage=0,
prev_stage_processes=None,
pipeline=None
):
"""
Generate Nextflow pipeline for m... | 7bda413b88f2eaad2e3cb2ecc9f15645b102a782 | 51,776 |
def tide_after_href(path):
"""Wrap href paths with 'app:/' and 'index.html' so all links point to
static files to make them work in the TideSDK app when we run python
application.py -f.
This way paths like '/view-location/123/' turn into
'app://view-location/123/index.html'
"""
if app.confi... | 9f9b068ed0cee6fdf10b11a270d7b55ac3f9f580 | 51,777 |
def guess_game_name_from_clone_arg(clone_arg: str) -> str:
"""Guess the name of the game from the --clone argument.
:arg clone_arg: The str given by the user for the clone argument.
Usually a git link as `https://github.com/ScienceGamez/world-3.git`..
"""
if "/" in clone_arg:
# If u... | 6a1203f966beb566195ae51960d727376b099cc1 | 51,778 |
def midpoint_point_point_xy_numba(u, v):
""" Compute the midpoint of two points lying in the XY-plane.
Parameters
----------
u : array
XY(Z) coordinates of the first point in the XY plane.
v : array
XY(Z) coordinates of the second point in the XY plane.
Returns
-------
... | f78a21117f105322101569f1384d695fc49939a8 | 51,779 |
def extract_training_glucose(data):
"""
Extract the input variables (x), the time (t), and the objective (y) from the data samples.
WARNING : need to be modified to include additional data, or override the function within the models
:param data:
:return:
"""
... | 144afb9cab81d67e9c2f966f0a80501697a820f4 | 51,780 |
def get_currencies(codes):
""" Returns a list of (code, translation) tuples for codes """
currencies = [(code, get_display(code)) for code in codes]
return currencies | 3249c374a21160f2d15b8b72dcb63768270419e5 | 51,781 |
import importlib
import pkgutil
def load_from_module(extension_point, module_name, extension_function_name='__extend__', propagate_exceptions=False):
"""Load an ExtensionPoint from a Python module.
This imports a module and scans it for immediate sub-modules, i.e. those modules nested directly under the firs... | 7c505caef775eed86d23a013676e3965e94a7eec | 51,782 |
import logging
def is_hsts_preloaded(domain):
"""
Whether a domain is contained in Chrome's HSTS preload list.
If preload_list is None, the caches have not been initialized, so do that.
"""
if preload_list is None:
logging.error('`preload_list` has not yet been initialized!')
rais... | 1ec508cc4b5096a7980ba0de0e8e6e210e958c08 | 51,783 |
def FOEEWMO(t, **kwargs):
"""from IFS Documentation Cycle 31,
Teten's formula for water only
after Tiedtke 1993 (cloud and large-scale precipitation scheme)
Uses the Tetens's formula
Based on Buck 1981 & Alduchov and Eskridge 1996
Args:
t: air temperature K
Returns:
es : sa... | 5c8471fcee1fd7b22ce34691dbd938352fd5a16f | 51,784 |
def partition(arr: list, start: int, end: int) -> int:
"""
Choosing last element as pivot
"""
i, j = start - 1, start
while j < end:
if arr[j] < arr[end]:
i += 1
arr[i], arr[j] = arr[j], arr[i]
j += 1
i += 1
arr[i], arr[end] = arr[end], arr[i]
re... | 766c8596aa434ede7ee269e75530859b06e1b59f | 51,786 |
def generate_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 027da4c8022f8d3600f24da759d2776e48f748fb | 51,787 |
def check_gae():
"""Checks if Google App Engine is present on system"""
return bool(find_gae_path()), 'Google App Engine SDK' | 3033ec22d779b008d9715daf0434f8b33f7f5546 | 51,788 |
def default() -> dict:
"""The default hyperparameters.
It will have a version key and a list of candidate models.
Each model has its own search space inside.
"""
ret = {
'version': 1,
'models': {
'BertForTextPredictionBasic': {
'search_space': {
... | 4ec6a4b13b756c378bf5c48752a2395f7ae4f47b | 51,789 |
import glob
def get_port_options(system):
"""Lists serial ports
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports
"""
sys_platform = system.get_sys_platform()
# For Windows Platform
if sys_platform == 'windows':
... | f9cf1feebfc086fee7e20a33d2b793a451167bde | 51,791 |
def fit_phase(w, si=1, fmin=0, fmax=None, axis=-1):
"""
Performs a linear regression on the unwrapped phase of a wavelet to obtain a time-delay
:param w: wavelet (usually a cross-correlation)
:param si: sampling interval
:param fmin: sampling interval
:param fnax: sampling interval
:param ax... | 74f41b6b0404c42a8a97570613f5295b35fec55b | 51,792 |
def count_threshold(x, threshold=10e-6):
""" count the number of above-threshold elements in an array """
return np.sum(x > threshold) | 36952fb8dee56f19a3a48779b2bc472f81c10fe2 | 51,793 |
import scipy.sparse as sp
from time import time
def fit_lmk3d( lmk_3d, # input landmark 3d
model, # model
lmk_face_idx, lmk_b_coords, # landmark embedding
weights, # weights for the objectives
s... | 3f03208ff2c73585faf2a4ae8b83d4b93d25a111 | 51,794 |
import socket
import json
def is_alive():
"""
Checks if engine is running.
Returns:
bool: True if the engine is running and accepting commands, False otherwise
"""
## ---------------------------------------------------------------
cmd = dict()
cmd["type_"] = "is_alive"
... | be9ceaa348a985b375f1bb75908bd26451f63f5e | 51,795 |
def read_xml_no_ns(filename):
"""
read in the file or data, populating a lxml._elementTree object
stripping out namespaces
:param filename: filename representing a xml file or a string of xml data
:return: lxml._elementTree object or None
"""
parsed_xml = read_xml(filename)
if parsed_xm... | b44606e6c736d041496d78d52d6f048d4613bdfa | 51,796 |
def keep_type(value):
"""
Keep hook returned value type
:param value: Value to be returned
:return: Any
"""
return value | f5048e2863aca6eced8c3be76a3623fd5f3a808e | 51,797 |
def r2_score(y_true: np.array, y_score: np.array) -> float:
"""
Calculate the coefficient of determination (R^2) for a ground-truth prediction vector pair.
Args:
y_true (array-like): An N x 1 array of ground truth values.
y_score (array-like): An N x 1 array of predicted values.
Return... | 6d29873e0fabd1f8a1d6b99f1c6c5aced822cc08 | 51,798 |
def varType(row):
"""Variants should be decomposed, and normalized
using vt before applying this function"""
c1 = len(row['REF']) == len(row['ALT'])
c2 = ',' in row['REF']
c3 = ',' in row['ALT']
if c2 or c3:
return 'other'
if c1:
return 'snp'
else:
return 'indel' | 5870eb1c1fb13beb7e8e9756fa99de19df1f93ee | 51,799 |
from functools import reduce
def shekel(x):
"""
Shekel: The modified fifth De Jong function, Equation (21) of [2]
minimum is f(x)=0.0 at x(-32,-32)
"""
A = [-32., -16., 0., 16., 32.]
a1 = A * 5
a2 = reduce(lambda x1,x2: x1+x2, [[c] * 5 for c in A])
x1,x2 = x
r = 0.0
for i in... | c2dd86b40072cc40dc4bba1a7f5d300d174c4ad8 | 51,800 |
def desitarget_nside():
"""Default HEALPix Nside for all target selection algorithms."""
nside = 64
return nside | 326338bcc9310725f92b74a29416812cebbd7db1 | 51,801 |
def get_best_hands_brute_force(board, hands):
""" get the index of the best holdem hand given a board
:param board: ([str]) list of 5 cards
:param hands: ([set(str)]) list of sets of 4 cards
:return: ([[int]]) indices of `hands` that makes the strongest holdem hand,
--> this is a list because i... | 35b01878ea967b0271741de427c7282aa82d4442 | 51,802 |
def logsig_fn(phi,X):
"""
sigmoid function
static nonlinearity from Rabinowitz et al 2011
"""
a=phi[0] # baseline
b=phi[1] # asymptote
c=phi[2] # inflection point
d=phi[3] # slope
Y=a+b/(1+np.exp(-(X-c)/d))
return(Y) | d13a4295e5e9f210ba8ff41167a23bc1785d4bff | 51,803 |
def get_table_9():
"""表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
Args:
Returns:
list: 表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
"""
table_9 = (0.0, 5.0, 20.0)
return table_9 | ed095f6ffd6fb146caed2628d089784ef91d6217 | 51,804 |
def find_nodes(graph, query, data=False):
""" Iterator over all nodes matching the data query.
"""
return ((v, graph.nodes[v]) if data else v
for v in graph if query(graph.nodes[v])) | e8f2e25f843133446c32ca7f012ac2aa1b80d2b9 | 51,805 |
def _SigninUIState(oobe):
"""Returns the signin ui state of the oobe. HIDDEN: 0, GAIA_SIGNIN: 1,
ACCOUNT_PICKER: 2, WRONG_HWID_WARNING: 3, MANAGED_USER_CREATION_FLOW: 4.
These values are in chrome/browser/resources/chromeos/login/display_manager.js
"""
return oobe.EvaluateJavaScript('''
loginHeader = docu... | 355b7ebbaf0010165109c27162ca70f5168abe05 | 51,806 |
def make_image(url, title=None, description=None):
"""Creates an image node
Args:
url (string): url to assign to image node
title (string, optional): assign a title to node on creation. Defaults to None.
description (string, optional): set image description on creation. Defaults to ... | 627b6fd368b83341b23378d4f6b5213be3cf3571 | 51,808 |
def get_plat_name():
"""获取所有平台ID与平台名的映射"""
plat_info = {}
res = bk.cc.get_plat_id()
for plat in res:
plat_id = int(plat['plat_id'])
plat_info[plat_id] = plat['plat_name']
return plat_info | f58517dca21a8653b14c2c46bf143600aa62290d | 51,809 |
def cluster_staypoints(staypoints,
method='dbscan',
epsilon=100,
num_samples=1,
distance_matrix_metric=None,
agg_level='user'):
"""Clusters staypoints to get locations.
Parameters
---------... | eda2bad60439cd5a3d585fa50d314a0f2669bd2f | 51,810 |
def word_count(df, new_col_name, col_with_lyrics):
"""
Count the number of words in a dataframe lyrics column, given a column name, process it, and save as new_col_name
Parameters
----------
df : dataframe
new_col_name : name of new column
col_with_lyric: column with lyrics
... | 6900e892a0f9fbc94c8c4ade24e12b7910b3c80c | 51,811 |
def ccd_to_list(file_path: str) -> list:
"""Converts a .ccd file into a dict"""
file = open(file_path, 'r')
lines = file.readlines()
file.close()
data = []
for index, line in enumerate(lines):
try:
if line.startswith(' '):
data.append(float(line.split(' ')[... | 12955459def48c12f0b7e6b0b889fd47df690b9d | 51,813 |
def add(a,b):
""" This function adds two numbers """
return a+b | 5dd8bcd4bbd9f610fe632c904bfc45a4ba9e249e | 51,814 |
def get_SSH_forcing(boundary, date):
"""A function that returns the ssh forcing for the month of the date and
boundary indicated.
:arg str boundary: A string naming the boundary. e.g 'north' or 'west'
:arg str date: A string indicating the date of interest. e.g. '01-Dec-2006'.
The... | 09c418e65e419ba71b6fb7bfd0284d6659eddbe0 | 51,815 |
import math
def draw_trial_im(t, epoch, label, n_avg=1, ch_names=None, cls_name=('non-target', 'target'), title='', **kwargs):
"""
Plot epochs trial by trial in an image.
:param t: tuple (start, end, samplerate)
:param epoch: (epochs, channels, time)
:param label:
:param n_avg:
:param ch_n... | b378d7c5e7aa28980ba7e6225d4da7fecdc96089 | 51,816 |
def _convert_imxyzs_to_npidxs(imxyzs, rows=13824, cols=7680, pixel_size=0.012):
"""
image space linear transform
pixel_size = sensor_width/image_cols = 92.16/7680 = sensor_height/image_rows = 165.8885/13824 # unit: mm/px
"""
col_zoomin, row_zoomin = 1/pixel_size, -1/pixel_size
xs, ys = imxyzs.T... | 491eb95a351f6200733057ca84c2131f1d805399 | 51,817 |
import hmac
import hashlib
def generate_dendrite_mac(shared_secret: str, username: str, password: str, admin: bool) -> str:
"""
Generate a MAC for using in registering users with Dendrite.
"""
# From: https://github.com/matrix-org/dendrite/blob/master/clientapi/routing/register.go
mac = hmac.new(
... | bed29168d88db0d9b2bd0bf95f493a9d4b5e7a3f | 51,819 |
import json
def create_snake_environment4eat(level_filename):
""" Create a new Snake environment from the config file. """
with open(level_filename) as cfg:
env_config = json.load(cfg)
return EnvironmentAttackRandomPoison(config=env_config, verbose=1) | 41856cc2d1811726f02c5a92bb43a6f1c1dfedb3 | 51,820 |
def Search(request):
"""Course search view handler."""
search_context = views_impl.Search(request)
template_name = 'search_results.html'
context = template.RequestContext(request, search_context)
return shortcuts.render_to_response(template_name, context_instance=context) | 5295e0e8fdacc29dba9de9b335aec58e872148a7 | 51,821 |
def _function_entry_stack_ops(op, to_pop):
"""Computes a set of stack operations for the entry to a FunctionCallOp.
The function calling convention is
- Push the arguments to the formal parameters
- Pop any now-dead arguments so they're not on the stack during the call
- Jump to the beginning of the function... | 6240a1ebaf0b00591a4f24648ab58bba3010ca56 | 51,822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.