content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def friable_sand(Ks, Gs, phi, phic, P_eff, n=-1, f=1.0):
"""
Friable sand rock physics model.
Reference: Avseth et al., Quantitative Seismic Interpretation, p.54
Inputs:
Ks = Bulk modulus of mineral matrix
Gs = Shear modulus of mineral matrix
phi = porosity
... | 5,333,900 |
def get_available_currencies():
"""
This function retrieves a listing with all the available currencies with indexed currency crosses in order to
get to know which are the available currencies. The currencies listed in this function, so on, can be used to
search currency crosses and used the retrieved d... | 5,333,901 |
def create_announcements():
"""
fill MongoDB Announcements collection
"""
pass | 5,333,902 |
def test_evaluate_with_labels_k2_r5_no_verbose(capsys):
"""Silently evaluate observation sequences with labels (k=2, r=5)"""
acc, cm = clfs[1].evaluate(X, y, labels=labels, verbose=False)
assert 'Classifying examples' not in capsys.readouterr().err
assert isinstance(acc, float)
assert isinstance(cm,... | 5,333,903 |
def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
This function is unsafe and should not be used. The file name
refers to a file that ... | 5,333,904 |
def getTaskIdentifier( task_id ) :
"""Get tuple of Type and Instance identifiers."""
_inst = Instance.objects.get( id = task_id )
return ( _inst.type.identifier , _inst.identifier ) | 5,333,905 |
def hessian_vector_product(loss, weights, v):
"""Compute the tensor of the product H.v, where H is the loss Hessian with
respect to the weights. v is a vector (a rank 1 Tensor) of the same size as
the loss gradient. The ordering of elements in v is the same obtained from
flatten_tensor_list() acting on t... | 5,333,906 |
def clean_cells(nb_node):
"""Delete any outputs and resets cell count."""
for cell in nb_node['cells']:
if 'code' == cell['cell_type']:
if 'outputs' in cell:
cell['outputs'] = []
if 'execution_count' in cell:
cell['execution_count'] = None
ret... | 5,333,907 |
def _spanned(scond: _SpanConductor) -> Callable[..., Any]:
"""Handle decorating a function with either a new span or a reused span."""
def inner_function(func: Callable[..., Any]) -> Callable[..., Any]:
def setup(args: Args, kwargs: Kwargs) -> Span:
if not isinstance(scond, (_NewSpanConduct... | 5,333,908 |
def filter_by_distance(junctions, min_distance, max_distance):
"""Yields the junction sites that have a distance less than equal max_distance"""
for j in junctions:
d = abs(j.descriptor[2] - j.descriptor[5])
if min_distance <= d and d <= max_distance:
yield j | 5,333,909 |
def getProjectProperties():
"""
:return:
@rtype: list of ProjectProperty
"""
return getMetDataLoader().projectProperties | 5,333,910 |
def svn_client_cleanup(*args):
"""svn_client_cleanup(char dir, svn_client_ctx_t ctx, apr_pool_t scratch_pool) -> svn_error_t"""
return _client.svn_client_cleanup(*args) | 5,333,911 |
def model_chromatic(psrs, psd='powerlaw', noisedict=None, components=30,
gamma_common=None, upper_limit=False, bayesephem=False,
wideband=False,
idx=4, chromatic_psd='powerlaw', c_psrs=['J1713+0747']):
"""
Reads in list of enterprise Pulsar instance an... | 5,333,912 |
def restore(backup_path: str, storage_name: str, target: str or None = None, token: str or None = None) -> str:
"""
Downloads the information from the backup
:returns path to the file
"""
if not token:
token = _restore_token(storage_name)
print(f'[{__name__}] Getting storage...')
st... | 5,333,913 |
def test_f32(heavydb):
"""If UDF name ends with an underscore, expect strange behaviour. For
instance, defining
@heavydb('f32(f32)', 'f32(f64)')
def f32_(x): return x+4.5
the query `select f32_(0.0E0))` fails but not when defining
@heavydb('f32(f64)', 'f32(f32)')
def f32_(x): retu... | 5,333,914 |
def get_message_bytes(
file_path: Union[str, Path],
count: int,
) -> bytes:
"""
从 GRIB2 文件中读取第 count 个要素场,裁剪区域 (东北区域),并返回新场的字节码
Parameters
----------
file_path
count
要素场序号,从 1 开始,ecCodes GRIB Key count
Returns
-------
bytes
重新编码后的 GRIB 2 消息字节码
""... | 5,333,915 |
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : p... | 5,333,916 |
def lint(ctx, error=False):
"""Lint Robot Framework test data and Python code."""
print("Lint python")
black_command = "black --config ./pyproject.toml assertionengine/ tasks.py atest/"
isort_command = "isort assertionengine/"
if error:
black_command = f"{black_command} --check"
isor... | 5,333,917 |
def define_macos_utilities():
""" Set some environment variables for Darwin systems differently
The variables are: READLINK, SED, DATE_UTIL and LN_UTIL
"""
if os.uname()[0] == 'Darwin':
if check_darwin('greadlink'):
set_env_var('READLINK','greadlink')
if check_darwin('gsed')... | 5,333,918 |
def discover_climate_observations(
time_resolution: Union[
None, str, TimeResolution, List[Union[str, TimeResolution]]
] = None,
parameter: Union[None, str, Parameter, List[Union[str, Parameter]]] = None,
period_type: Union[None, str, PeriodType, List[Union[str, PeriodType]]] = None,
) -> str:
... | 5,333,919 |
def set_template(template_name, file_name, p_name):
"""
Insert template into the E-mail.
"""
corp = template(template_name, file_name, p_name)
msg = MIMEMultipart()
msg['from'] = p_name
msg['subject'] = f'{file_name}'
msg.attach(MIMEText(corp, 'html'))
return msg | 5,333,920 |
def glVertex2dv(v):
"""
v - seq( GLdouble, 2)
"""
if 2 != len(v):
raise TypeError(len(v), "2-array expected")
_gllib.glVertex2dv(v) | 5,333,921 |
def lazy_gettext(string):
"""A lazy version of `gettext`."""
if isinstance(string, _TranslationProxy):
return string
return _TranslationProxy(gettext, string) | 5,333,922 |
def read_table(filepath_or_buffer: _io.BytesIO):
"""
usage.dask: 4
"""
... | 5,333,923 |
def toggleautowithdrawalstatus(status, fid, alternate_token=False):
"""
Sets auto-withdrawal status of the account associated
with the current OAuth token under the specified
funding ID.
:param status: Boolean for toggle.
:param fid: String with funding ID for target account
:return: String ... | 5,333,924 |
def load_avenger_models():
"""
Load each instance of data from the repository into its associated model at this point in the schema lifecycle
"""
avengers = []
for item in fetch_avenger_data():
# Explicitly assign each attribute of the model, so various attributes can be ignored
ave... | 5,333,925 |
def pytest_configure(config):
"""Scan for test files. Done here because other hooks tend to run once
*per test*, and there's no reason to do this work more than once.
"""
global test_file_tuples
global test_file_ids
include_ruby = config.getoption('include_ruby')
test_file_filter = config.... | 5,333,926 |
def aggregate_points(point_layer,
bin_type=None,
bin_size=None,
bin_size_unit=None,
polygon_layer=None,
time_step_interval=None,
time_step_interval_unit=None,
time_step_repe... | 5,333,927 |
def scattered_embedding_lookup(params,
values,
dimension,
name=None,
hash_key=None):
"""Looks up embeddings using parameter hashing for each value in `values`.
The i-th embedding component of... | 5,333,928 |
def supported_camera_list():
""" Grabs the list of gphoto2 cameras and parses into a list
"""
check_gphoto2() # No reason to keep going if GPhoto2 isn't installed
# TODO: Error checking/Handling
# Capture and cleanup camera list output
cameras = subprocess.run("gphoto2 --list-cameras", shell=... | 5,333,929 |
def register_multiple_fake_users(user_number: int, plans_number: int):
"""
Регистрация нескольких случайных пользователей
:param user_number: Число пользователей
:param plans_number: Число планов на пользователя
"""
from faker import Faker
fake = Faker()
from app.models.fake.profile ... | 5,333,930 |
def get_features_and_labels(instances: Iterable[NewsHeadlineInstance],
feature_generator: Callable[[NewsHeadlineInstance],
dict[str]]) -> tuple[list[dict[str]], list[int]]:
""" Return a tuple of the features and labels for each i... | 5,333,931 |
def countBarcodeStats(bcseqs,chopseqs='none',bcs = ["0","1"],use_specific_beginner=None):
"""this function uses edlib to count the number of matches to given bcseqs.
chopseqs can be left, right, both, or none. This tells the program to
chop off one barcode from either the left, right, both, or non... | 5,333,932 |
def update_world():
"""Update function for our world """
global millis_elapsed
millis_elapsed += clock.get_time()
#millis_elapsed is total time elapsed since world bagan
cursor.update() | 5,333,933 |
def on_post_message(data, token):
"""Clients send this event to when the user posts a message.
All messages here are broadcasted to all room members
"""
try:
data['roomid'] = session['roomid']
except:
data['roomid'] = 0
rv = requests.post('/api/messages', json=data,
... | 5,333,934 |
def test_DiskCache():
"""Unit tests for DiskCache class"""
testdir = tempfile.mkdtemp()
try:
# Testing that subfolders get created, hence the long pathname
tmp_fname = os.path.join(
testdir, 'subfolder1/subfolder2/DiskCache.sqlite'
)
dc = DiskCache(db_fpath=tmp_fn... | 5,333,935 |
def is_underflow(bin_nd, hist):
"""Retuns whether global bin number bin_nd is an underflow bin. Works
for any number of dimensions
"""
flat1d_bin = get_flat1d_bin(bin_nd, hist, False)
return flat1d_bin == 0 | 5,333,936 |
def evaluate_speed(model, dataloader):
"""This function evaluates only the speed of the given model"""
with torch.no_grad():
t0 = time.time()
for inputs, _ in dataloader:
model(inputs)
t1 = time.time()
time_elapsed = t1 - t0
print('Evaluation complete in {:.0f}m {:.0f}s'.... | 5,333,937 |
def deprecated_func_docstring(foo=None):
"""DEPRECATED. Deprecated function."""
return foo | 5,333,938 |
def inv_recv_attr(status):
"""
Set field attributes for inv_recv table
"""
s3db = current.s3db
settings = current.deployment_settings
table = s3db.inv_recv
table.sender_id.readable = table.sender_id.writable = False
table.grn_status.readable = table.grn_status.writable = False
... | 5,333,939 |
async def test_departures_error_server(httpx_mock):
"""Test server error handling."""
httpx_mock.add_response(data="error", status_code=500)
rmv = RMVtransport()
station_id = "3006904"
await rmv.get_departures(station_id) | 5,333,940 |
def get_all_nodes(starting_node : 'NodeDHT') -> 'list[NodeDHT]':
"""Return all nodes in the DHT"""
nodes = [starting_node]
node = starting_node
while node != starting_node:
node = node.succ
nodes.append(node)
return nodes | 5,333,941 |
def reversed_lines(fin):
"""Generate the lines of file in reverse order."""
part = ''
for block in reversed_blocks(fin):
if PY3PLUS:
block = block.decode("utf-8")
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ... | 5,333,942 |
def get_uvj(field, v4id):
"""Get the U-V and V-J for a given galaxy
Parameters:
field (str): field of the galaxy
v4id (int): v4id from 3DHST
Returns:
uvj_tuple (tuple): tuple of the form (U-V, V-J) for the input object from mosdef
"""
# Read the file
uvj_df = ascii.read(imd.loc_uv... | 5,333,943 |
def import_data_from_folder2(folder_path):
"""
导入期货1分钟历史数据
:param folder_path:
:return:
"""
logger.info("导入历史数据 开始 %s", folder_path)
datetime_start = datetime.now()
# 获取文件列表
file_path_list = []
for dir_path, sub_dir_path_list, file_name_list in os.walk(folder_path):
fo... | 5,333,944 |
def by_regex(regex_tuples, default=True):
"""Only call function if
regex_tuples is a list of (regex, filter?) where if the regex matches the
requested URI, then the flow is applied or not based on if filter? is True
or False.
For example:
from aspen.flows.filter import by_regex
@... | 5,333,945 |
def deserialize(name):
"""Get the activation from name.
:param name: name of the method.
among the implemented Keras activation function.
:return:
"""
name = name.lower()
if name == SOFTMAX:
return backward_softmax
if name == ELU:
return backward_elu
if name == SEL... | 5,333,946 |
def expected_improvement_search(features, genotype):
""" implementation of CATE-DNGO-LS on the DARTS search space """
CURR_BEST_VALID = 0.
CURR_BEST_TEST = 0.
CURR_BEST_GENOTYPE = None
PREV_BEST = 0
MAX_BUDGET = args.max_budgets
window_size = 1024
round = 0
counter = 0
visited = ... | 5,333,947 |
def delete_item_image(itemid, imageid):
"""
Delete an image from item.
Args:
itemid (int) - item's id
imageid (int) - image's id
Status Codes:
204 No Content – when image deleted successfully
"""
path = '/items/{}/images/{}'.format(itemid, imageid)
return delete(pa... | 5,333,948 |
def plot_results_unordered(predicted_data, true_data, plt_file):
"""Plot actual vs predicted results"""
fig = plt.figure(facecolor='white', figsize=(20,5))
# fig = plt.figure(facecolor='white', figsize=(20,15)) # uncomment for DWS plot
axis = fig.add_subplot(111)
axis.plot(true_data, label='Tru... | 5,333,949 |
def bytes_(s, encoding='utf-8', errors='strict'): # pragma: no cover
"""Utility to ensure binary-like usability.
If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``s``"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
return... | 5,333,950 |
def create_job_id(success_file_path):
"""Create job id prefix with a consistent naming convention based on the
success file path to give context of what caused this job to be submitted.
the rules for success file name -> job id are:
1. slashes to dashes
2. all non-alphanumeric dash or underscore wil... | 5,333,951 |
def test_stochatreat_within_strata_no_probs(n_treats, stratum_cols, df):
"""
Tests that within strata treatment assignment counts are only as far from
the required counts as misfit assignment randomization allows with equal
treatment assignment probabilities but a differing number of treatments
"""
... | 5,333,952 |
def normal_transform(matrix):
"""Compute the 3x3 matrix which transforms normals given an affine vector transform."""
return inv(numpy.transpose(matrix[:3,:3])) | 5,333,953 |
async def async_unload_entry(hass, config_entry):
"""Unload OMV config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
if unload_ok:
controller = hass.data[DOMAIN][config_entry.entry_id]
await controller.async_reset()
hass... | 5,333,954 |
def test_scenario_delete_meta_warning(mp):
"""
Scenario.delete_meta works but raises a deprecation warning.
This test can be removed once Scenario.delete_meta is removed.
"""
scen = ixmp.Scenario(mp, **DANTZIG)
meta = {"sample_int": 3, "sample_string": "string_value"}
remove_key = "sample_s... | 5,333,955 |
def create_prediction_data(validation_file: typing.IO) -> dict:
"""Create a dictionary object suitable for prediction."""
validation_data = csv.DictReader(validation_file)
races = {}
# Read each horse from each race
for row in validation_data:
race_id = row["EntryID"]
finish_pos = f... | 5,333,956 |
def username(request):
""" Returns ESA FTP username """
return request.config.getoption("--username") | 5,333,957 |
def complete_data(df):
"""Add some temporal columns to the dataset
- day of the week
- hour of the day
- minute
Parameters
----------
df : pandas.DataFrame
Input data ; must contain a `ts` column
Returns
-------
pandas.DataFrame
Data with additional columns `da... | 5,333,958 |
def is_valid_mac_address_normalized(mac):
"""Validates that the given MAC address has
what we call a normalized format.
We've accepted the HEX only format (lowercase, no separators) to be generic.
"""
return re.compile('^([a-f0-9]){12}$').match(mac) is not None | 5,333,959 |
def cleanup():
"""Resource cleanup."""
mega.close()
print('Resource cleanup completed.')
exit(0) | 5,333,960 |
def get_Y(data):
"""
Function: convert pandas data table to sklearn Y variable
Arguments
---------
data: panadas data table
Result
------
Y[:,:]: float
sklearn Y variable
"""
return np.array((data["H"],data["sigma"])).T | 5,333,961 |
def get_bbox(mask, show=False):
"""
Get the bbox for a binary mask
Args:
mask: a binary mask
Returns:
bbox: (col_min, col_max, row_min, row_max)
"""
area_obj = np.where(mask != 0)
bbox = np.min(area_obj[0]), np.max(area_obj[0]), np.min(area_obj[1]), np.max(area_obj[1])
i... | 5,333,962 |
def check_mobile_mode() -> bool:
"""
Return if you are working in mobile mode, searching local settings or check QtCore.QSysInfo().productType().
@return True or False.
"""
from pineboolib.core import settings
return (
True
if QtCore.QSysInfo().productType() in ("android", "ios... | 5,333,963 |
def check_for_overflow_candidate(node):
"""
Checks if the node contains an expression which can potentially produce an overflow
meaning an expression which is not wrapped by any cast, which involves the operator
+, ++, *, **. Note, the expression can have several sub-expression. It is the case
of the expression (a... | 5,333,964 |
def parse_monitor_message(msg):
"""decode zmq_monitor event messages.
Parameters
----------
msg : list(bytes)
zmq multipart message that has arrived on a monitor PAIR socket.
First frame is::
16 bit event id
32 bit event value
no padding
Se... | 5,333,965 |
def load_config(fpath):
"""
Load configuration from fpath and return as AttrDict.
:param fpath: configuration file path, either TOML or JSON file
:return: configuration object
"""
if fpath.endswith(".toml"):
data = toml.load(fpath)
elif fpath.endswith(".json"):
with open(fpa... | 5,333,966 |
def find_packages(name, pkg_dir):
"""Locate pre-built packages in the _packages directory"""
for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder):
package_path, cache_path = c.make_package_path(pkg_dir, name)
if package_path.exists():
yield c.type_code, pack... | 5,333,967 |
def softmax_layer(inputs, n_hidden, random_base, drop_rate, l2_reg, n_class, scope_name='1'):
"""
Method adapted from Trusca et al. (2020). Encodes the sentence representation into a three dimensional vector
(sentiment classification) using a softmax function.
:param inputs:
:param n_hidden:
... | 5,333,968 |
def node2freqt(docgraph, node_id, child_str='', include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph node into a FREQT string."""
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
token_str = escape_func(node_attrs[docgraph.ns+':token'])
if... | 5,333,969 |
def build_arg_parser():
"""Build the ArgumentParser."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-f", "--fritzbox", default="fritz.box")
parser.add_argument("-u", "--username", default="dslf-config")
parser.add_argument("-... | 5,333,970 |
def get_marathon_url():
"""Get Marathon URL from the environment.
This is optional, default: http://leader.mesos:8080.
"""
marathon_url = os.environ.get("MARATHON_URL", None)
if marathon_url is None:
logger.warning("Unable to parse MARATHON_URL environment variable, using default: http://le... | 5,333,971 |
def _load_dataset(name, split, return_X_y, extract_path=None):
"""Load time series classification datasets (helper function)."""
# Allow user to have non standard extract path
if extract_path is not None:
local_module = os.path.dirname(extract_path)
local_dirname = extract_path
else:
... | 5,333,972 |
def run_cc_net_nmf(run_parameters):
""" wrapper: call sequence to perform network based stratification with consensus clustering
and write results.
Args:
run_parameters: parameter set dictionary.
"""
tmp_dir = 'tmp_cc_net_nmf'
run_parameters = update_... | 5,333,973 |
def search(news_name):
"""method to fetch search results"""
news_name_list = news_name.split(" ")
search_name_format = "+".join(news_name_list)
searched_results = search_news(search_name_format)
sourcess=get_source_news()
title = f'search results for {news_name}'
return render_template('sea... | 5,333,974 |
def encrypt_document(document):
"""
Useful method to encrypt a document using a random cipher
"""
cipher = generate_random_cipher()
return decrypt_document(document, cipher) | 5,333,975 |
def do_width_file(width, filename):
"""
This function takes a file pairs of unicode values (hex), each of
which is a range of unicode values, that all have the given width.
"""
for line in open(filename).readlines():
if line.startswith("#"):
continue
vals = line.split()
... | 5,333,976 |
def test_open_run(
data=(
(0, 0.75, True, False, False),
(1, 0.25, True, False, False),
(2, 0.75, False, True, False),
(3, 0.25, False, True, False),
(4, 0.75, False, False, True),
(5, 0.25, False, False, True),
),
in_columns=(
"subject_id",
"g... | 5,333,977 |
def bootstrap_alert(visitor, items):
"""
Format:
[[alert(class=error)]]:
message
"""
txt = []
for x in items:
cls = x['kwargs'].get('class', '')
if cls:
cls = 'alert-%s' % cls
txt.append('<div class="alert %s">' % cls)
if 'clos... | 5,333,978 |
def masked_mean(x, *, mask, axis,
paxis_name, keepdims):
"""Calculates the mean of a tensor, excluding masked-out entries.
Args:
x: Tensor to take the mean of.
mask: Boolean array of same shape as 'x'. True elements are included in the
mean, false elements are excluded.
axis: Axis... | 5,333,979 |
def clients_ping():
"""
Ping bountytools clients to test connectivity
:return:
""" | 5,333,980 |
def dbsession(engine, tables):
"""Returns an sqlalchemy session, and after the test tears down everything properly."""
connection = engine.connect()
# begin the nested transaction
transaction = connection.begin()
# use the connection with the already started transaction
session = Session(bind=co... | 5,333,981 |
def run_project_patcher_internal(context, identifier, dry_run, should_log, deployment_name=None):
"""Internal call point for post project update"""
# Patch project stack if it exists
if identifier is None:
# Select default patch
identifier = DEFAULT_PATCH_IDENTIFIER
if identifier == DEF... | 5,333,982 |
def log_error(error, file_path="logs/", message=None):
"""log Exception to error log with optional message.
Args:
exception (var, str): output from except statement
file_path (str): path to error log
message (str, optional): custom message. Defaults to None.
"""
msg = f"{date_ti... | 5,333,983 |
def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight):
"""This function helps position an image within a box.
It first normalizes for two cases:
- if the width is None, it assumes imWidth
- ditto for height
- if width or height is negative, it adjusts x or y and makes them pos... | 5,333,984 |
def __do_core(SM, ToDB):
"""RETURNS: Acceptance trace database:
map: state_index --> MergedTraces
___________________________________________________________________________
This function walks down almost each possible path trough a given state
machine. During the process of walking ... | 5,333,985 |
def circle_area(radius: int) -> float:
""" estimate the area of a circle using the monte carlo method.
Note that the decimal precision is log(n). So if you want a precision of
three decimal points, n should be $$ 10 ^ 3 $$.
:param r (int): the radius of the circle
:return (int): the estimated area o... | 5,333,986 |
def Quantized_MLP(pre_model, args):
"""
quantize the MLP model
:param pre_model:
:param args:
:return:
"""
#full-precision first and last layer
weights = [p for n, p in pre_model.named_parameters() if 'fp_layer' in n and 'weight' in n]
biases = [pre_model.fp_layer2.bias]
#layer... | 5,333,987 |
def _super_tofrom_choi(q_oper):
"""
We exploit that the basis transformation between Choi and supermatrix
representations squares to the identity, so that if we munge Qobj.type,
we can use the same function.
Since this function doesn't respect :attr:`Qobj.type`, we mark it as
private; only thos... | 5,333,988 |
def main(args):
"""
This is the main function of the repo runner
It will be executed with the arguments suplied if the end user called this.
"""
dependency.installCommon()
dependency.installFullRepo()
if not checks.inCorrectDirectory("repo"):
logger.log("Could not detect build files ... | 5,333,989 |
def get_attention_weights(data):
"""Get the attention weights of the given function."""
# USE INTERACTIONS
token_interaction = data['tokeninteraction']
df_token_interaction = pd.DataFrame(token_interaction)
# check clicked tokens to draw squares around them
clicked_tokens = np.array(data['final... | 5,333,990 |
def save_ecg_example(gen_data: np.array, image_name, image_title='12-lead ECG'):
"""
Save 12-lead ecg signal in fancy .png
:param gen_data:
:param image_name:
:param image_title:
:return:
"""
fig = plt.figure(figsize=(12, 14))
for _lead_n in range(gen_data.shape[1]):
curr_lea... | 5,333,991 |
def zip_files(name_of_zip: str, files_to_zip: str) -> None:
"""Zip files.
Examples
--------
.. code-block:: robotframework
ZipFiles my_zip_file rabbit.txt
ZipFiles my_zip_file_2 dog.txt
ZipFiles my_zip_file_3 rabbit.txt, dog.txt
ZipF... | 5,333,992 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry) | 5,333,993 |
def logging_init(log_path, log_filename, html=False):
"""
Initializes the LOG object for global logging, which is a rotating log-handler:
creates max of LOG_BACK_COUNT log files; older ones are deleted, with each log
file of size LOG_MAX_BYTES. Can be configured to log HTML or text, defaults to text.
"""
gl... | 5,333,994 |
def get_all_score_dicts(ref_punc_folder_name, res_punc_folder_name):
"""
Return a list of score dictionaries for a set of two folders. This function assumes the naming
of the files in the folders are correct according to the diagram and hence if sorted
match files. Both folders should be in the dire... | 5,333,995 |
def run_random_climate(gdir, nyears=1000, y0=None, halfsize=15,
bias=None, seed=None, temperature_bias=None,
climate_filename='climate_monthly',
climate_input_filesuffix='', output_filesuffix='',
init_area_m2=None, unique_sample... | 5,333,996 |
def export_action(modeladmin, request, queryset):
"""Admin action to launch the export process."""
for import_model in queryset:
import_model.export_data(async_process=True)
modeladmin.message_user(request, _("Launched export tasks...")) | 5,333,997 |
def sync_get_ami_arch_from_instance_type(instance_type: str, region_name: Optional[str]=None) -> str:
"""For a given EC2 instance type, returns the AMI architecture associated with the instance type
Args:
instance_type (str): An EC2 instance type; e.g., "t2.micro"
region_name (Optional[str], optional):... | 5,333,998 |
def atan2(y, x):
"""Returns angle of a 2D coordinate in the XY plane"""
return math.atan2(y, x) | 5,333,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.