content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
import torch
def get_token_ids_from_text_field_tensors(
text_field_tensors: Dict[str, Dict[str, torch.Tensor]],
) -> torch.Tensor:
"""
Our `TextFieldTensors` are complex output structures, because they try to handle a lot of
potential variation. Sometimes, you just want to grab... | 4898da3be21bac6011fe3d559d772da31c31f730 | 3,624,700 |
def ping():
"""Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully."""
global clf
if clf is None:
clf = ScoringService.get_model()
status = 200
return flask.Response(response='\n', status=status, mimetyp... | 350454d3771963bde5bfea94d3cb73d17629331d | 3,624,701 |
import math
def s_linear(y, a):
"""Transformation function."""
assert y >= 0.0
assert y <= 1.0
assert a > 0.0
assert a < 1.0
return correct_to_01(abs(y - a) / abs(math.floor(a - y) + a)) | 42dc5246d09d2d5924772acd1f481e63fd9d64f5 | 3,624,702 |
def posts_from_rest_files(fnames):
"""
Read posts from ReST files
"""
ret = []
for parts, docinfo in _parse_rest_files(fnames):
page = posts.Post(title=parts['title'],
contents=parts['body'],
slug=docinfo['slug'],
... | 30a3f04683536b4de31fd586ca52eb2f53f82f4b | 3,624,703 |
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up configured Weatherbit."""
# We allow setup only through config flow type of config
return True | 9c5b9abb131d9828904f51aee39243ff4136b8e2 | 3,624,704 |
def _validate_licence(data: dict) -> dict:
"""Validates that a Licence exists and that the Goods exist on that Licence"""
serializer = HMRCIntegrationUsageUpdateLicenceSerializer(data=data)
if not serializer.is_valid():
data["errors"] = serializer.errors
return data
try:
licen... | b4ab5daf915ec605ef135b07ed8da93c627b679d | 3,624,705 |
def extend_bed(bed, bp, direction='both'):
"""Extend each interval in bed file with specified basepairs.
If bp is a list, each interval will be extended bp[0] toward upstream, and
bp[1] toward downstream.
Note: Be careful! This method does not deal with strandedness of the interval.
:param (pybedt... | 94ae8f33353edceaf45511b5525ca3e2e72d3588 | 3,624,706 |
def chem_potential_water_t_exact(SA, t, p):
"""
Calculates the chemical potential of water in seawater.
Parameters
----------
SA : array-like
Absolute Salinity, g/kg
t : array-like
In-situ temperature (ITS-90), degrees C
p : array-like
Sea pressure (absolute pressure... | 153b6a9a235250fc21139a96da107dc3bfb0c7eb | 3,624,707 |
import random
def generate_neg_edges(G, num_neg_edges):
"""
Given a graph, sample negative edges from the complement graph.
:param G: graph
:param num_neg_edges: number of edges to sample
:returns neg_edges: the sampled edges
"""
G_comp = nx.complement(G)
neg_edges = random.sample(G_co... | fcbb577d8101cf54f227e82b279cbd8c8c24e85b | 3,624,708 |
def bolster_missing_time_periods(filter_time_periods, queryset, date_range_type, columns):
""" Given the following, generate a list of dict results split by fiscal years/quarters/months
Args:
filter_time_periods: list of time_period objects usually provided by filters
- {'start_... | c54361ab493c8590dac8c7a621831d2c9e9f1c25 | 3,624,709 |
import concurrent.futures
import datetime
def screenStocks_Multiproccesed(ticker_list, strategy, last_days):
"""
Screens stock list with strategy. Returns list of [tickers, last buy dates, stock performance stats] if last buy date of stock is within last_days
This particular function is multiproccesed wit... | 09f059885ff7aae27ea1a489de278894f5a6434b | 3,624,710 |
def get_cached_locale(locale):
"""
Gets the given locale from cache if present.
Parameters
----------
locale : `str`
The local to get from cache.
Returns
-------
locale : `str`
"""
return LOCALES.setdefault(locale, locale) | beb47af067b498b713352be0fd1e05e04145ad79 | 3,624,711 |
def _IsTpuTraining(p):
"""Whether we should create embedding tables and run lookup on tpu."""
return not p.is_inference and py_utils.use_tpu() | fdfe5e646125c0458da825be184c92609cb86ee2 | 3,624,712 |
def get_first_index_where(array, criterion, value):
"""get the first index where array fulfills a criterion w.r.t. value,
where criterion may be "geq" (greater equal), "gt" (greater than),
"leq" (less equal) or "lt" (less than). If criterion is met nowhere,
function returns len(array)
Args:
... | ed4bc09e107bddac20480610988768fea8e45a95 | 3,624,713 |
from typing import Tuple
def score_per_player(df: pd.DataFrame,
selected_player: str) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Plot score per player
Parameters:
-----------
selected_game_df : pandas.core.frame.DataFrame
Data for the selected game
selected_player : s... | a95b4c5c77e866212e2b5e1d33b648977fcec07b | 3,624,714 |
def GetXcodeDeveloperDirectory():
"""Returns the active developer directory as reported by 'xcode-select -p'.
Returns None if none is set."""
if not MacOS():
return None
return GetCommandOutput("xcode-select -p") | 4fea53abe054beaaa9599df5f745126e208e98c0 | 3,624,715 |
def norm(a, b):
""" Return a unit normal to a and b. """
k = np.cross(a, b)
return k / np.linalg.norm(k) | 4fb52fea0e61a9611ebfca26bff22c8cbd71fd52 | 3,624,716 |
def logical_factor_rules() -> FrozenDict:
"""Logical factor rules for Mixture of Experts."""
rules = flax_core.unfreeze(adafactor.standard_logical_factor_rules())
rules.update({
'expert': FactorDim.BATCH,
'expert_mlp': FactorDim.COLUMN,
'unmodeled': FactorDim.NONE
})
return flax_core.freeze(... | f79aee3825c53f09cd8b0a719c78522d908617bf | 3,624,717 |
from typing import Sequence
from typing import Optional
from typing import Union
def row_rounder(row: Sequence[str], line: Optional[int], has_total_col: bool = False) -> Sequence[Union[str, float]]:
"""
To convert the data in a CSV row to percentages and then smartly round the
percentages to no decimal wi... | 89d0f76469c6125c81871ba3bff045e529fcce35 | 3,624,718 |
def three_blocks_avgpooling(img_width, img_height, img_channels, output_dim):
"""
Define model architecture.
# Arguments
img_width: Target image widht.
img_height: Target image height.
img_channels: Target image channels.
output_dim: Dimension of model output.
# ... | ed5ca6122d03877fd02d0d6f63d98dab04169a09 | 3,624,719 |
import re
def parse_life_105(file):
"""Parse a Life 1.05 file, returning a tuple:
positions: list of (x,y) co-ordinates
comments: all comments in file, as a list of strings, one per line.
"""
lines = file.split("\n")
comments = []
positions = []
ox, oy = 0, 0
x, y = ox, oy... | 3faf204bb52f5c1dd5b350401afdaa2a021f80d4 | 3,624,720 |
from typing import Any
def tsa_constant_skater_factory(y: Y_TYPE, s: dict, k: int, a: A_TYPE = None,
t: T_TYPE = None, e: E_TYPE = None,
p:int=TSA_P_DEFAULT, d:int=TSA_D_DEFAULT, q:int=TSA_D_DEFAULT) -> ([float], Any, Any):
""" Extremely simple univariate,... | 0b35dbf09b0ae43a726c068e273f5b2f3d2bfc84 | 3,624,721 |
def save_vertex_attributes(mesh):
"""
Saves the boundary and cut attributes that are on the mesh on a dictionary.
"""
v_attributes_dict = {'boundary_1': [], 'boundary_2': [], 'cut': {}}
cut_indices = []
for vkey, data in mesh.vertices(data=True):
cut_index = data['cut']
if cut_i... | 91a46dd1060849e4581ee1fe037ce0ff7fadecd0 | 3,624,722 |
import traceback
def server_error_to_message(e, error_statement, error_detail, rows = None):
"""サーバーエラーレスポンス(メッセージ付き) server error response with message
Args:
e (Exception): 例外 exception
error_statement (str): エラー情報(処理内容)error info. process contents
error_detail (str): エラー情報詳細 error d... | ad34548aaf84c7f9c574fd017df78ebe01f340a7 | 3,624,723 |
def eliminate_nonvalid_coords(coords, mapshape):
""" Eliminate nonvalid indices
Args:
coords(set of tuples): input set of positions
h(int): height
w(int): width
Returns:
set of valid coordinates
"""
h, w = mapshape
valid = []
for j, i in coords:
if j < 0 or j >= h:... | a872f551c072f0e36e10d7aac02d68a370cdfdf1 | 3,624,724 |
from datetime import datetime
import os
def lastnedFlere(driftskontrakter = False, veglister=False, kostra=False, mappenavn=None, miljo=None ):
"""
Skjellet for det som skal bli en robust nedlasting av alle relevante rapporttyper for en (lang) liste av k.områder / andre områder. Under arbeid
TODO: Fors... | b63a0593d67977a22446ca5699bb340cfebcd732 | 3,624,725 |
from typing import Sequence
from typing import Optional
def construct_1d_ndarray_preserving_na(
values: Sequence, dtype: Optional[DtypeObj] = None, copy: bool = False
) -> np.ndarray:
"""
Construct a new ndarray, coercing `values` to `dtype`, preserving NA.
Parameters
----------
values : Sequ... | 8d4f6b77a89c848985d1b8a2fe21ba952da51fff | 3,624,726 |
def getPosUntilRoot(object):
"""
Go through the hierarchy of the object until reaching the top level,
increment the position to get the transformation due to parents.
@type object: hostObject
@param object: the object
@rtype: list
@return: the cumulative translation along the ... | 00ed1bbb3cce4c8f1309d2ee4b24025e767f7df9 | 3,624,727 |
import tqdm
def build_embedding_matrix(
embedding_model: gensim.models.keyedvectors.KeyedVectors,
embedding_dim,
vocab) -> np.ndarray:
"""
Builds the embedding matrix.
Parameters
----------
embedding_model : gensim.models.keyedvectors.KeyedVectors
Embedding model.
... | 31fbbd91dd7f835cf0b4123ddf42cce6c78063bd | 3,624,728 |
def calls_fixture(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") | 5a75d6de7e260b0845e38b6540a3fc3ee367f0ad | 3,624,729 |
def load_yaml(yaml_file, template_params=None, return_config_str=False):
"""
load_yaml_str will take in a string that has the correct yaml formatting
and generate classes or types according to the configuration in the yaml.
Example:
params = {'SOURCE_PATH': '/tmp/source', 'AGE': 30}
obj... | 9be438692be2ba54bcd345f29ed6c1f469df3586 | 3,624,730 |
def bprp_to_bv(bprp):
"""
Calculate a B-V color from a G_BP - G_RP color.
Poor fit at large and small bp-rp. (Especially bad for low-mass stars).
"""
p = [-0.0334115504231673, 0.3754200727545447, -1.4691791496336342,
2.209433533403669, -0.39641699367657274, 0.14752490961352926]
retur... | dbd75562649d7f1b093aa37efbb15fa95fd16541 | 3,624,731 |
def have_flirt():
""" Return True if we can call flirt without error
Relies on the fact that flirt produces text on stdout when called with no
arguments
"""
p = Popen('flirt', stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return stdout != '' | 34aef0b7bde4ca7dd087f4048084e0bb06beeb13 | 3,624,732 |
def effective_request_host(request):
"""Return the effective request-host, as defined by RFC 2965."""
return eff_request_host(request)[1] | 2443630193f5c1a02538347d71077f6ac69cc2e5 | 3,624,733 |
import ast
import requests
def get_nginx_generation_value(host) -> int:
"""
Send request to /api/api_version/nginx and parse the response.
:param host:
:return: 'generation' value
"""
resp = ast.literal_eval(requests.get(f"{host}/api/{NGINX_API_VERSION}/nginx").text)
return resp['generati... | c2ff155c711c7e668b86edf6523fecab5a0d508a | 3,624,734 |
from astroquery.gaia import Gaia
import numpy
import tempfile
import os
import csv
import shutil
def cds(cat,xcat='vizier:I/350/gaiaedr3',maxdist=2,colRA='RA',colDec='DEC',
selection='best',epoch=None,colpmRA='pmra',colpmDec='pmdec',
savefilename=None,gaia_all_columns=False):
"""
NAME:
... | 4cc7ac062a60c970c8d920cba4b97c547c701ce8 | 3,624,735 |
def get_job_by_id(job_id): # noqa: E501
"""Find my job by Id
For valid response try integer Ids with value >= 1 and <= 1000.\\ \\ Other values will generated exceptions # noqa: E501
:param job_id: Id of job to be fetched
:type job_id: str
:rtype: Job
"""
job = q.fetch_job... | 87fbc03012527c1eb60c946024fef5e00e7ef49f | 3,624,736 |
def delete_client(client_id):
"""
Delete a client
---
tags:
- clients
parameters:
- name: client_id
in: path
type: integer
example: 1
operationId: deleteClient
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
... | 3c2cd9c19bbbb9082a7b7247253f0414d3b09f88 | 3,624,737 |
def get_textregion_avg_line_distance(text_region: PageXMLTextRegion,
avg_type: str = "macro") -> np.float:
"""Returns the median distance between subsequent lines in a
textregion object. If the textregion contains smaller textregions, it only
considers line distances bet... | f0311add31985b7fb87a740cd3f02846f7e3183f | 3,624,738 |
import time
def dns_lookup(qname, **kwargs):
"""Function to perform DNS lookup queries.
Args:
qname (str) : The Domain name that you would like perform a DNS lookup for.
**ns (str/list): The nameserver to use when querying the provided domain.
... | ff4516aa5f85fb74b37174fcd8d4ac1d11b5f678 | 3,624,739 |
import warnings
import os
def L0Path(CD_J = None,
CD_J_AS = None,
lam_1 = None,
lams_2 = None,
active_set = None,
active_interaction_set = None,
beta = None,
zeta = None,
delta = None,
alpha = None,
B = No... | 59c666ebd2aa3402689863815fdc4dfeb757200e | 3,624,740 |
def kras_Rotate_Shift_old(krasFile, krasPos, angle):
"""For x1 KRAS rotate by a specific angle around z axes and shit to given x,y pos - Works for 4B only CYF based"""
kras = mda.Universe(krasFile)
farCOM = kras.select_atoms("resname CYF and name SC1").center_of_mass()
farCOM_z = 5.455 # Set all KRAS F... | a2287994d5f88c10f6350149dc70d7d39059955e | 3,624,741 |
from sys import modules
def get_hostname_prefix():
"""Returns the hostname prefix of a running Endpoints service.
The prefix is the portion of the hostname that comes before the API name.
For example, if a non-default version and a non-default service are in use,
the returned result would be '{VERSION}-dot-{... | 7e29528dc739d23d201612c684f231e75d3409b7 | 3,624,742 |
def get_aperture_fluxes(data, ap_radius):
"""
Make an aperture for every pixel, and do aperture photometry at all of them.
:param data: A 2D numpy array with the data to do photometry on
:ap_radius: The radius of the aperture to use.
"""
# Get all coordinates
nx, ny = data.shape
xx, yy... | 14fba44448771182431c1f3546122ce991c16b45 | 3,624,743 |
def _trash_ratio(text):
"""
Return ratio of non-common symbols.
"""
trash_count = 0
for char in text:
if char in list(u'.\'"+-!?()[]{}*+@#$%^&_=|/\\'):
trash_count += 1
return trash_count / float(len(text)) | 135bcabaa36a565b2e998932c70aaf4caf943af9 | 3,624,744 |
def compute_graph_nn_2(xyz, k_nn1, k_nn2):
"""compute simulteneoulsy 2 knn structures
only saves target for knn2
assumption : knn1 <= knn2"""
assert k_nn1 <= k_nn2, "knn1 must be smaller than knn2"
num_ver = xyz.shape[0]
#compute nearest neighbors
graph = dict([("is_nn", True)])
nn = Nea... | c4fd0e417243ca4726d21fb0f4837a2c139954e9 | 3,624,745 |
def index_of_spaces(text):
"""
Given text, return all space indices
@param text is the string to analyze
@returns a list of integers representing the indices
"""
res = []
for i in range(0, len(text)):
if text[i] == ' ':
res.append(i)
return res | 97b3618ffa54ee6d1b50c5bca3e196d3a6ae7f2a | 3,624,746 |
def strip_checkin(tweet):
""" Strip useless information from tweets as a checkin.
:tweet: @todo
:returns: @todo
"""
place = tweet['place']
return {
'created_at': tweet['created_at'].isoformat(),
'retweeted': tweet['retweeted'],
'retweet_count': tweet['retweet_count'],
... | eda8d0c61062ef4861ba085fda228e14f520cf04 | 3,624,747 |
def decrypt_story():
"""Load the file store.txt, and decript it"""
return CiphertextMessage(get_story_string()).decrypt_message() | 13ba9c6fba8fd358639606663f2928ead3bf8825 | 3,624,748 |
def aaa_get_kvm_launch_url(in_cookie, in_ipv4):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("AaaGetKVMLaunchUrl")
method.in_cookie = in_cookie
method.in_ipv4 = in_ipv4
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | 2bf389507028fc4b8ca5f0069295a5869f60ef67 | 3,624,749 |
def get_default_hparams():
""" Return default hyper-parameters """
params_dict = {
# Experiment Params:
'is_training': True, # train mode (relevant only for accelerated LSTM mode)
'data_set': 'cat', # datasets to train on
'epochs': 50, # how many times to go over the full trai... | 803cc08fc9de77b7c2608d10f6eca457ac175ab8 | 3,624,750 |
def _get_mf_picks(info, int_order, ext_order, ignore_ref=False, verbose=None):
"""Pick types for Maxwell filtering."""
# Check for T1/T2 mag types
mag_inds_T1T2 = _get_T1T2_mag_inds(info)
if len(mag_inds_T1T2) > 0:
warn('%d T1/T2 magnetometer channel types found. If using SSS, it is '
... | 83e3609ec7fd0916d8d76f1750ca918b45313b81 | 3,624,751 |
def bbcMicro_partPhonemeCount(pronunc):
"""Returns the number of 'part phonemes' (at least that's what I'm calling them) for the BBC Micro phonemes in pronunc. The *SPEAK command cannot take more than 117 part-phonemes at a time before saying "Line too long", and in some cases it takes less than that (I'm not sure... | bd1337214f8c0d39c79a7cd94e5720717335aad8 | 3,624,752 |
def build_MLP(X, y, layers=(50, 25, 15), dropout=0.1, activation='relu',
out_act='softmax'):
"""Utility function for building a Multi-layer perceptron.
Args:
- X: numpy array, input to the model.
- y: numpy array, target of the model.
- layers: tuple of ints, number of hid... | 8af98f627b67fdffccf8c340915bffa768a5c497 | 3,624,753 |
def idc(funcname):
"""获取所属机房逻辑"""
try:
custom_args = handle(custom_param_file,"custom_args")
return custom_args[funcname]
except Exception as e:
print "[error]:",e
return None | 3a5ee6c5a1cfd66c6f2c9a6988d2668355cc9e9a | 3,624,754 |
import yaml
def format_bundle(bundle):
"""
Converts a bundle object into a push-ready bundle by
changing list values of 'customResourceDefinitions',
'clusterServiceVersions', and 'packages' into stringified yaml literals.
This format is required by the Marketplace backend.
:param bundle: A b... | 472e7d4ad915ef1a57eef3e5ac4ae4085a67138f | 3,624,755 |
from typing import Optional
from typing import Tuple
def es_client(
host: Text,
port: int = 9200,
url_prefix: Optional[Text] = None,
username: Optional[Text] = None,
password: Optional[Text] = None,
timeout: int = 180) -> elasticsearch.client.Elasticsearch:
""" Elas... | 87d73e4cdbe629bc2e0cb325df6703e3b2d62de3 | 3,624,756 |
import os
def collect_type_path():
"""
收集不同任务的权重路径名
"""
all_weights_path = os.listdir(directory.MODEL_DIR)
weights_path_list = []
for weight_path in all_weights_path:
method = weight_path.split('_')[0] # 分开训练还是联合训练
task_name = weight_path.split('_')[1] # 训练的任务:区域/类型
... | c4049cc2c34aff09ab3de3508aa6056911f5dc3d | 3,624,757 |
def insert_at_midpoint(item, iterable):
"""
Inserts an item at the index of the midpoint of a list
Returns that list with the item inserted
"""
midpoint = int(len(iterable) / 2)
iterable.insert(midpoint, item)
return iterable | 9801e2f4cd1011914f15634898ed4d502edfee34 | 3,624,758 |
def upgrade(sql_connection, version=None):
"""
Upgrade the database's current migration level
:param sql_connection: sqlalchemy connection string
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(sql_connection) # Ensure db is under migration con... | 6bcfe5b79d8d7f955cfd47e2cbaa407b191eaa94 | 3,624,759 |
def unwrap_if_necessary(graph_node: PerceptionGraphNode) -> UnwrappedPerceptionGraphNode:
"""
Some nodes might be wrapped in tuples together with IDs to prevent them
from being compared equal and collapsed in perception graphs.
This method removes that wrapping.
"""
if isinstance(graph_node, tup... | 26aa90de70b06c498c71d8181d631e0c496718e8 | 3,624,760 |
def func(p, data):
"""
Calculate z = (x/maj)**2 + (y/min)**2
Note that z = 1 is an ellipse
"""
x0, y0, major, minor, pa = p
x, y = data
pa = radians(pa)
sinP = sin(-pa)
cosP = cos(-pa)
xt = x - x0
yt = y - y0
xr = xt * cosP - yt * sinP
yr = xt * sinP + yt * cosP
re... | dbef77e2fd5d61ef78bcce278023f6abfa86c609 | 3,624,761 |
import string
def urlEncode(s):
"""
Returns the encoded version of the given string, safe for using as a URL.
"""
return string.join(map(lambda c: _urlEncode[c], list(s)), '') | ac5467b6fdb8e9e1a4f4a300dba7b3372bad01ee | 3,624,762 |
def euclideanDistance(data_points, query_instance):
"""
Calculate euclidean distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return: distance value
"""
return np.sqrt(((data_points -... | fbab617733535dd1b3af47c3d2c972fa29009fbc | 3,624,763 |
from typing import Tuple
def _move_jackknife_sample_id_to_value(
slice_key: slicer.SliceKeyType, sample: metric_types.MetricsDict
) -> Tuple[slicer.SliceKeyType, metric_types.MetricsDict]:
"""Moves the jackknife sample ID from the key to value.
Args:
slice_key: The slice key which contains the sample_id.... | 0711418b4974639123c0a92ffb4122d8b5c6bcad | 3,624,764 |
def dfanet(classes=19, **kwargs):
"""
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
return xceptionAx3(classes, **kwargs) | 0004186558fe467bc1bf01b8e070d446231d870f | 3,624,765 |
def experiment_fn(run_config: RunConfig, params: HParams):
"""The experiment function, provided to learn_runner.
:param run_config:
:param params:
:return:
"""
run_config = run_config.replace(save_checkpoints_steps=params.min_eval_frequency)
estimator = tf.estimator.Estimator(
mod... | 7a0e411af98ca344ee321fc88435556d80fd783f | 3,624,766 |
from typing import Dict
from typing import List
def _check_antonymy(antonym_library: Dict[str, List[str]],
attr_value1: 'AttributeValue',
attr_value2: 'AttributeValue') -> Dict[str, str]:
"""
Check if there are any shared antonyms within the two values
Parameters
... | a4cfca502d99b35a60fd78f2b8a4a4e20453f187 | 3,624,767 |
def innerip(funcname):
"""获取内网IP逻辑"""
inner_ip = get_ip_address('eth0')
return inner_ip | daff3e1b994e3e24297517c615f27f5978d0ca75 | 3,624,768 |
def create_single_choice_question(text, choices, topic_id=None, scenario_id=None):
"""
Create a single choice question for either a topic *or* a scenario.
Parameters
----------
text : str
Body of the question.
choices : list
List of question choices.
It must be a list of... | 5645db0fd77b5f265d9906927f905dfb984f31d6 | 3,624,769 |
def render_cmdhelp_border(term: Terminal) -> str:
"""Render border around cmdhelp box"""
return render_border(
start_x=const.CMDHELP_X,
start_y=const.CMDHELP_Y,
height=const.CMDHELP_HEIGHT,
width=const.CMDHELP_WIDTH,
title=" Help ",
term=term,
) | 86b938476982f3c7853cabd382dd83d49381504c | 3,624,770 |
import pandas
def drop_child_cases(pcts, keep_child_entitlements=True):
"""
Drop all child cases from a PCTS extract (as indicated by them
having a parent case listed).
Parameters
==========
pcts: pandas.DataFrame
A PCTS extract of the shape returned by subset_pcts.
keep_child_e... | 2f4e0fb90a7d093342502e802d9818674960ce37 | 3,624,771 |
def reopen_gap(decanonicalized: BlockNumber, base_gaps: ChainGaps) -> ChainGaps:
"""
Add a new gap, for a header that was decanonicalized.
"""
current_gaps, tip_child = base_gaps
if tip_child <= decanonicalized:
return base_gaps
new_raw_gaps = current_gaps + ((decanonicalized, decanoni... | 2c8d7fd24a528d64ddb6f81a02a89b3284e6dde4 | 3,624,772 |
def is_std_wstring(type_):
"""
Returns True, if type represents C++ `std::wstring`, False otherwise.
"""
if utils.is_str(type_):
return type_ in wstring_equivalences
else:
type_ = remove_alias(type_)
type_ = remove_reference(type_)
type_ = remove_cv(type_)
r... | 7d223f6290db220250c709f5ea9de810d0fc175d | 3,624,773 |
def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
"""Returns a bipartite graph from two given degree sequences using
an alternating Havel-Hakimi style construction.
Nodes from the set A are connected to nodes in the set B by
connecting the highest degree nodes in set A to alternatively... | 72f332a05595163a119dd54d6d3e40cb7763e947 | 3,624,774 |
import io
def write_conformers(mol_input, mol_reference, conf_file):
"""
Generate conformer and calculate rmsd wrt reference
"""
top_rmsd = -1
conformer_generator = conformer.ConformerGenerator()
conformer_generator.settings.superimpose_conformers_onto_reference = True
conformers = conform... | 0513d92699220d3b9fed9a3b6828aa19b22ae51b | 3,624,775 |
def get_stdout():
"""Return the redirected stdout in the current context."""
return _get_context().get(REDIRECTING, {}).get('stdout') | f6a0b66d98f763e53702005b031454b6f1aede3f | 3,624,776 |
from typing import List
def _get_ner_tags_and_mask(current_instance: Instance,
input_field_to_attack: str,
ignore_tokens: List[str]):
"""
Used for the NER task. Sets the num_ignore tokens, saves the original predicted tag and a 0/1
mask in the position... | 3d496adea05576fe4fb06d1b4912e99d08a01d22 | 3,624,777 |
import pandas as pd
def get_employees(filepath):
""" takes a Toolbox csv filepath, retrieves it and exports as dataframe
"""
if not filepath:
print("Please provide a Toolbox filepath to 'employees.csv'")
return
try:
df =pd.read_csv(filepath, usecols=['employeeID','mail','h... | e327199867ad66021686185460b884eedacc60c1 | 3,624,778 |
def normalize_spec(value: t.Any) -> "TypeSpec":
"""normalize tensor spec"""
if not _isinstance_wrapper(value, TENSOR_CLASS_NAMES):
return value
if _isinstance_wrapper(value, "RaggedTensor"):
return tf.RaggedTensorSpec.from_value(value)
if _isinstance_wrapper(value, "SparseTensor"):
... | 831af3da7fc1e36966dd424ae42f40826ff50364 | 3,624,779 |
def get_cost(state):
"""Calculates cost/fitness for the solution/route."""
distance = 0
for i in range(len(state)):
from_city = state[i]
to_city = None
if i+1 < len(state):
to_city = state[i+1]
else:
to_city = state[0]
distance += data.get... | 89e8539c4cfd7ade46f3db634c16e8a8dd5932c8 | 3,624,780 |
import warnings
def fit_decision_tree(printscore=False):
"""
This function fits sklearn's decision tree classifier
on the college dataset and returns the model
The data values are first scaled using MinMaxScaler
and then split into train and test sets before using for fitting ML model
"""
... | 3a23230f4fcf4770f2897393fc933f7fe75add08 | 3,624,781 |
def parse_info(file_path, counter=1, verbose=True):
""" Grab html code from a file and parse for information - return dict of dicts. """
this_counter = counter
# Open file and parse with BS4
with open(file_path, "r") as f:
soup = bs(f.read().decode("utf-8"), "lxml")
# Get category
cate... | e88bb52512a165dbeb02c24bb5d0430181eed0d4 | 3,624,782 |
def describe(profile, description):
"""
Generate a query by describing it as a series of actions
and parameters to those actions. These map directly
to Query methods and arguments to those methods.
This is an alternative to the chaining interface.
Mostly useful if you'd like to put your queries... | b6ef8fef9f0443d78cd9236212d84962484d785a | 3,624,783 |
def get_filenames_request(products, download_directory):
"""Get local files url corresponding to a Copernicus request (must be already downloaded).
:param products: (dict) Copernicus Hub query
:param download_directory: (str) Url of folder for downloaded products
:return: (list) List of strings with lo... | 5591948ce2445399d06da6c84f3fe1f6b8b4b128 | 3,624,784 |
def nt_service_action(service: str, action: str) -> bool:
"""
Handle windows service
"""
elapsed_time = 0 # Number of seconds elapsed since we started Windows service
max_wait = 15 # Number of seconds we'll wait for Windows service to start
is_running = nt_service_status(service)
try:
... | 5587312b37f4fb319a0bfedc4cf63eddb54b754e | 3,624,785 |
def home():
"""Home endpoint that redirects to docs"""
return RedirectResponse("/docs") | 97e75427ea23670ca7a4ce5e4022cb26acde1c30 | 3,624,786 |
def check_bandpass_biquad(method):
"""Wrapper method to check the parameters of BandpassBiquad."""
@ wraps(method)
def new_method(self, *args, **kwargs):
[sample_rate, central_freq, Q, const_skirt_gain], _ = parse_user_args(
method, *args, **kwargs)
check_biquad_sample_rate(samp... | 22bb19470c33d4cf6972c63e1f65a5d788869643 | 3,624,787 |
def get_cached_ip():
"""
Retrieve Cached IP From File, cuts down on API requests if
IP Address hasn't changed.
Returns:
cached_ip: Cached IP or 0 to force refresh of public IP
"""
try:
cached_file = open(CACHE_FILE_PATH, 'r')
cached_ip = cached_file.read()
cache... | b172b0bfedc7d93e3771ea00e52d4664e0e27d6e | 3,624,788 |
def map_box_to_image(box, proj_mat):
"""
Projects 3D bounding box into the image plane.
Args:
box (Box3D)
proj_mat: projection matrix
"""
# box in camera coordinate
points_3d = box.in_camera_coordinate()
# project the 3d bounding box into the image plane
points_2d = proj... | 43c93c67f9314a3f786812c4aa3e02eb6bb6bb7c | 3,624,789 |
def loadCache(fname):
"""
Loads a pickle file from a filename and returns the resulting data.
@param fname: Filename to load
@return: data retrieved from file
"""
try:
data = util.file_pickle_load(fname)
except Exception:
raise RuntimeError("Could not read %s" % fname)
r... | 0ee4ecf0c59d80c12eaf940f05bd4d14928956ad | 3,624,790 |
def max_pool(inputs, size=-1):
"""max_pool downsamples a feature map."""
if not inputs[1]:
x_input = inputs[0][0]
else:
x_input = sum_op(inputs)
if size in [3, 5, 7]:
return tf.nn.max_pool(x_input, ksize=[1, size, size, 1], strides=[1, 1, 1, 1], padding='SAME')
else:
... | 302752663da0f706ac38d08918603ddcc706cd40 | 3,624,791 |
def _repo_choices(repos_map=None):
"""Make up repo choices.
"""
if repos_map is None:
repos_map = fleure.globals.REPOS_MAP
rss = [[(k, v) for v in vs] for k, vs in repos_map.items()]
return fleure.utils.uconcat(rss) | f4e607e81c2405a8a1630c8685fb8832506bb7b5 | 3,624,792 |
def grid_plot(filename, slice_index=0, axes=None, title="", vmin=None,
vmax=None, rel_smoothing_scale=None, filename2=None, factor=1.,
boxsize=None, colorbar=True, fix_colorbar=True, v_ratio=False,
factor_minus_allowed=False, cmap=None, norm=None, log_cbar=False,
... | 1d2d29b0f3c90feb0919a07546de4efec5e07ba9 | 3,624,793 |
def get_overrides(_conf=None):
"""
Read the configuration file and look for ceph-medic sections and flags to
set the defaults, these are later checked by the main method to see if any
need to be overridden *again* if specified on the CLI directly.
"""
# Get the subcommand name to avoid overwritt... | 7d6db52f97a425c6dcd39ceb7c4803579003f34b | 3,624,794 |
import yaml
import subprocess
import json
def get_dqlite_endpoints():
"""
Return the endpoints the current node has on dqlite and the endpoints of the rest of the nodes.
:return: two lists with the endpoints
"""
with open("{}/info.yaml".format(cluster_dir)) as f:
data = yaml.load(f, Loade... | 3ffb4877f28d18ed04db0891b08ec2d2a8f36c92 | 3,624,795 |
def left_hist_data(hotel_type="All", year=2016, month=1):
"""returns a data frame containing binned counts of hotel guests' country of origin
for the selected hotel type and time period
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
year: the year selected f... | a4aa27cadeda67771165a7ff4fd785c282dfb063 | 3,624,796 |
import calendar
from datetime import datetime
def get_first_day_next_month(day):
"""
Returns the next month given the current day
:param day:
:return:
"""
last_day = calendar.monthrange(day.year, day.month)[1]
one_day = datetime.timedelta(days=1)
return datetime.date(day.year, day.... | 8761477b28f59b2cbdf583114493a1af769f0d7a | 3,624,797 |
import yaml
def ensure_namespace(ctx):
"""创建命名空间"""
k8s_client = K8SClient(ctx)
def _add_token_to_ctx(k8s_client, ctx):
# 获取service_account_token
try:
ctx["service_account_token"] = get_service_account_token(k8s_client)
except Exception as error:
logger.err... | 943757653be64a8d648b810d80c90b0d17bac941 | 3,624,798 |
def dates(min_year=None, max_year=None):
"""Return a strategy for generating dates.
.. deprecated:: 3.9.0
use :py:func:`hypothesis.strategies.dates` instead.
All generated dates will be between min_year and max_year, inclusive.
"""
note_deprecation('Use hypothesis.strategies.dates, which s... | 09d0c13e93eb30091356ac89179ba63c12eccbb6 | 3,624,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.