content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def copy_planning_problem(planning_problem):
"""
Make a copy of a planning problem.
Parameters:
planning_problem (PlanningProblem): A planning problem.
Returns:
(PlanningProblem): A copy of the given planning problem.
"""
copy = PlanningProblem(
initial=planning_proble... | 45,400 |
def test_synopsimPointings(fname, opsimversion, tableNames, angleUnit):
"""
test that the lengths of pointings for a random set of 100 positions
in the approximate LSST region match when calculated directly or with
the pointing tree
"""
fname = os.path.join(oss.example_data, fname)
synopsim ... | 45,401 |
def read_model(layer, filename):
""" Load the weights of a network """
with np.load(filename) as f:
param_values = [f['arr_%d' % i] for i in range(len(f.files))]
lasagne.layers.set_all_param_values(layer, param_values) | 45,402 |
def remove_pc(x, npc=1):
"""
Remove the projection on the principal components
:param x: X[i,:] is a data point
:param npc: number of principal components to remove
:return: XX[i, :] is the data point after removing its projection
"""
pc = compute_pc(x, npc)
if npc == 1:
xx = x -... | 45,403 |
def write4DFits(filename,img,dx,dx2=None):
"""
Write processed 4D data into a FITS file.
Axial pixel size is given by dx.
Azimuthal pixel size is given by dx2 - default to none
"""
hdr = pyfits.Header()
hdr['DX'] = dx
hdu = pyfits.PrimaryHDU(data=img,header=hdr)
hdu.writeto(filename,... | 45,404 |
def delete_rax_keypair(args):
"""Function for deleting Rackspace Key pairs"""
print("--- Cleaning Key Pairs matching '%s'" % args.match_re)
for region in pyrax.identity.services.compute.regions:
cs = pyrax.connect_to_cloudservers(region=region)
for keypair in cs.keypairs.list():
... | 45,405 |
def alerts_info(alert_object):
""" Takes a Dark Sky alert object (a list of dicts, one for each alert), and
prints out the summary information with an option to display a much
longer description. More on alert objects:
https://developer.forecast.io/docs/v2#alerts """
# TODO: move print outside of th... | 45,406 |
def invocation_parameter(s) :
"""argparse parameter conversion function for invocation request
parameters, basically these parameters are JSON expressions
"""
try :
expr = json.loads(s)
return expr
except :
return str(s) | 45,407 |
def build_bhp(bhm, dt_bin_edges, num_fissions = None,
pair_is = 'all', type_is = 'all', print_flag = False):
"""
Build the bicorr_hist_plot by selecting events from bhm and applying normalization factor. The normalization factor is only applied if norm_factor is provided. If not, norm_factor remai... | 45,408 |
def env_builder(env_name, env_info, **kwargs):
"""
the interface func for creating environment
:param env_name:the name of environment
:param env_info: the config info of environment
:return:environment instance
"""
return Registers.env[env_name](env_info, **kwargs) | 45,409 |
def plot_obs_vs_sim_case(m_d, case="eaa_ver", post_iter=None,
plt_name="obs_v_sim.pdf", focus=False):
"""plot ensemble-based observed vs simulated GW level and spring discharge time
series for a given PEST "case".
Args:
m_d (str): "master" directory that holds the simulated... | 45,410 |
def setup_transition_list():
"""
Creates and returns a list of Transition() objects to represent state
transitions for simple granular mechanics model.
Parameters
----------
(none)
Returns
-------
xn_list : list of Transition objects
List of objects that encode information ... | 45,411 |
def generate_macro(macro_dir,
macro_name,
link_module='core_ops',
link_name='HelloWorld',
is_create_init=False,
import_line='\n'):
"""Generate Eskapade macro.
:param macro_dir: absolute path to a directory where the ... | 45,412 |
def filter_functions(input_set, filter_set):
"""
Keeps only elements in the filter set
:param input_set:
:param filter_set:
:return:
"""
ns = {}
filter_low = {x.lower() for x in filter_set}
for x in input_set:
xl = x.lower()
if xl in filter_low:
ns[x] = in... | 45,413 |
def make_jtfs_pair(N, pair='up', xi0=4, sigma0=1.35):
"""Creates a 2D JTFS wavelet. Used in `wavespin.visuals`."""
from .scattering1d.filter_bank import morlet_1d, gauss_1d
from scipy.fft import ifftshift, ifft
morl = morlet_1d(N, xi=xi0/N, sigma=sigma0/N).squeeze()
gaus = gauss_1d(N, sigma=sigma0/... | 45,414 |
def convert(your_text):
"""
Changes foot-notes into numbered foot-notes
Args:
your_text (str): a certain text
Returns:
str
"""
# print(f"Hello world, I plan to convert the following text: {your_text}")
### Terminology
# Given a four-line text that looks like the (so... | 45,415 |
def categorical(cum_weights):
"""
Sample from a discrete distribution
:param cum_weights: list of cumulative sums of probabilities (should satisfy cum_weights[-1] = 1)
:return: sampled integer from `range(0,len(cum_weights))`
"""
p = _rand.random()
i = 0
while p > cum_weights[i]:
... | 45,416 |
def clear():
"""
Clear screen function for Windows, Linux and MacOS
"""
if name == 'nt':
_ = system('cls')
else:
_ = system('clear') | 45,417 |
def floodfill(image, *args, **kwargs):
"""
Performs a floodfill on the given image
:Parameters:
image : `Image` or `numpy.array` or `basestring`
The image object we would like to operate on as a numpy array, url, filepath, or image object
keycolor : `tuple`
The c... | 45,418 |
def frange(start,stop,step):
"""range(start,stop,step) for floating point numbers"""
x = start
if step<0.0:
while x>stop:
yield x
x += step
else:
while x<stop:
yield x
x += step | 45,419 |
def set_seed(seed):
"""Set seed rng for reproducibility."""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed) | 45,420 |
def get_words_per_sentence(content):
"""
Get words per sentance average
:content: str
:returns: int
"""
words = get_words(content)
sentences = get_sentences(content)
return words / sentences | 45,421 |
def timeout_soft_cmd(cmd, timeout):
"""Same as timeout_cmd buf using SIGTERM on timeout."""
if not timeout:
return cmd
return 'timeout %us stdbuf -o0 -e0 %s' % (timeout, cmd) | 45,422 |
def get_all_links_and_port_names_of_equipment(
client: SymphonyClient, equipment: Equipment
) -> List[Tuple[Link, str]]:
"""Returns all links and port names in equipment.
Args:
equipment ( `pyinventory.common.data_class.Equipment` ): could be retrieved from
- `pyinventory.api.eq... | 45,423 |
def test_is_ignored_false():
"""
Test one result
:return:
"""
file = os.path.join(data_folder, 'test.mkv')
assert not is_ignored(file) | 45,424 |
def get_model_input(image):
"""Function to perform the preprocessing required so that it can be passed to the model for prediction
Args:
image (PIL image object): image that has to be transformed
Returns:
tensor (4D torch tensor): transformed image to torch 4D tenso... | 45,425 |
def extract_api_tree():
"""
Generates a tree of command group names and function
signatures in leaves from API function names in Master
"""
api_funcs = {}
for i in dir(session['master'])+dir(public_api(None)):
if (i.startswith('api_') or i.startswith('admin_api_') or
i.st... | 45,426 |
def get_start_end_year(filename):
"""Get the start and end year from a file name.
Examples of allowed dates : 1980, 198001, 19801231,
1980123123, 19801231T23, 19801231T2359, 19801231T235959,
19801231T235959Z
Dates must be surrounded by - or _ or string start or string end
(after removing filen... | 45,427 |
def dataset_names_csv():
"""Returns the expected dataset names included in the tool."""
return resource_loader("dataset_names.csv") | 45,428 |
def is_subtree(cls_name):
"""Determine whether 'cls_name' is a subtree."""
if cls_name == "SequentialCell":
return True
if cls_name in _ms_common_ns or cls_name in _ms_nn_ns or cls_name in _ms_ops_ns:
return False
return True | 45,429 |
def relevancy_to_adjust(relevancy):
"""
Convert the old test case relevancy into adjust rules
Expects a string or list of strings with relevancy rules.
Returns a list of dictionaries with adjust rules.
"""
rules = list()
rule = dict()
if isinstance(relevancy, list):
relevancy = ... | 45,430 |
def create_bcs(dim, H, Hmin, inlet_velocity, inlet_velocityOil,
V_0, solutes, subdomains_file, WaterOilInlet,
concentration_left,
interface_thickness,
enable_NS, enable_PF, enable_EC,
mesh, boundaries_Facet, contact_angle, **namespace):
"""... | 45,431 |
def get_parameter_values(parameter, Grid, selectedmodels, noofind):
"""
Get parameter values from grid
Parameters
----------
parameter : str
Grid, hdf5 object
selectedmodels :
models to return
noofind :
number of parameter values
Returns
-------
x_all : ... | 45,432 |
def to_offset(_0: Literal["400d"], /):
"""
usage.dask: 1
"""
... | 45,433 |
def dumpj(game):
"""Dump a game to json"""
return game.to_json() | 45,434 |
def __add_statement2issue(statement_uid: int, issue_uid: int) -> StatementToIssue:
"""
Adds a new statement to issue link to the database
:param statement_uid: id of the related statement
:param issue_uid: id of the related issue
:return: New statement to issue object
"""
db_statement2issue... | 45,435 |
def CreateInnerMaskBmapFromOuterMask( srcBmap ) :
"""
Derive the inner mask wxBitmap from the Outer mask wxBitmap.
The srcBmap must be "well behaved" in that a continuous border
must present so that a floodfill to the perimeter area will not reach
into the inner area. The border color must b... | 45,436 |
def main():
"""Do something fun"""
form = cgi.FieldStorage()
huc12 = form.getfirst("huc12", "000000000000")[:12]
scenario = int(form.getfirst("scenario", 0))
ssw("Content-type: image/png\n\n")
ssw(make_plot(huc12, scenario)) | 45,437 |
def generate_fake_example(w: int, h: int, identifier: int):
"""Generate a random COCO example."""
num_objects = 8
return {
'image': np.random.randint(0, 256, size=(w, h, 3), dtype=np.uint8),
'image/filename': f'{identifier:012}.jpg',
'image/id': identifier,
'objects': {
'area': n... | 45,438 |
def get_optim(name: str):
""" get an optimizer by name """
if name.lower() == 'adam':
optimizer = torch.optim.Adam
elif name.lower() == 'adamw':
optimizer = torch.optim.AdamW
elif name.lower() == 'sgd':
optimizer = torch.optim.SGD
elif name.lower() == 'sgdw':
from ..l... | 45,439 |
def _get_functions_names(module):
"""Get names of the functions in the current module"""
return [name for name in dir(module) if
isinstance(getattr(module, name, None), types.FunctionType)] | 45,440 |
def ex_rvalue(name):
"""A variable store expression."""
return ast.Name(name, ast.Load()) | 45,441 |
def test_get_centerline_nurbs(img_ctl, expected, params):
"""Test centerline fitting using nurbs"""
if 'exclude_nurbs':
return
img, img_sub = [img_ctl[0].copy(), img_ctl[1].copy()]
img_out, arr_out, arr_deriv_out, fit_results = get_centerline(
img_sub, ParamCenterline(algo_fitting='nurbs... | 45,442 |
def roll(input, shifts, dims=None):
"""Roll elements along the given dimension.
:attr:`dims` could be negative or ``None``:
```python
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
# A negative dimension is the last-k dimension
print(torch.roll(x, shifts=1, dims=1)) # [[3, 1, 2], [6, 4, 5]]
pr... | 45,443 |
def configure_environment(arch_name, build_path, src_path):
"""Runs install scripts for deps, and configures temporary environment variables required by Chromium's build"""
if platform.system() == 'Linux':
if arch_name:
print('Running sysroot install script...')
sysroot_cmd = src_path + '/build/lin... | 45,444 |
def apply(
img: np.ndarray,
n_cols: int,
m_rows: int,
is_module_detail: bool,
orientation: str = None,
) -> Tuple[transform.Transform, np.ndarray, np.ndarray, np.ndarray]:
"""Locate the module in given EL image
Args:
img (np.array): The image
n_cols (int): Number of columns ... | 45,445 |
def gsl_eigen_genhermv_free(*args, **kwargs):
"""gsl_eigen_genhermv_free(gsl_eigen_genhermv_workspace w)"""
return _gslwrap.gsl_eigen_genhermv_free(*args, **kwargs) | 45,446 |
def render_template(template, target_file):
"""Render the template to the file supplied.
:param template: Template to be rendered
:type template: jinja2.Template
:param target_file: File name for rendered template
:type target_file: str
"""
try:
with open(target_file, "w") as fh:
... | 45,447 |
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, total_loss, classification_loss, input_image,
correct_label, keep_prob, learning_rate):
"""
Train neural network and print out the loss during training.
:param sess: TF Session
:param epochs: Number of epochs
:param batch_... | 45,448 |
def test_lt_dB_4():
""" test lt operator with different dB unit """
g1 = dBQuantity(0, 'dBV')
g2 = dBQuantity(0, 'dBW')
with raises(UnitError):
assert g1 < g2 | 45,449 |
def test_string_tokenize():
""" test helper function """
ret = main.string_tokenize("{}")
expected = [('{', 0), ('}', 1)]
assert ret == expected | 45,450 |
def read_names_dmp(infile, outdir):
"""
Reading names.dmp file
"""
outfile = os.path.join(outdir, 'names.dmp')
regex = re.compile(r'\t\|\t')
regexp = re.compile(r'^[^_]+_|_')
names_dmp = {}
logging.info('Reading dumpfile: {}'.format(infile))
with open(infile) as inF, open(outfile, '... | 45,451 |
def model3():
"""
PyMC configuration with Model 1.
preevac_alpha vs theta[0] + theta[1]*type + theta[2]*eff_wid + theta[3]*tread
"""
# Priors
theta = mc.Uniform('theta',
lower=[-10.0, -10.0],
upper=[ 10.0, 10.0],
... | 45,452 |
def getVTGui():
"""Small wrapper to hide the fact that vtapp object contains gui.
:return: main window object
"""
return vtutils.getVTApp().gui | 45,453 |
def ksd_parametric_custom(ksd_value, alpha, B_parametric):
"""
Compute KSD test using a parametric bootstrap with kernel matrix
inputs: ksd_values: (N,) array consisting of KSD values
for N bandwidths for inputs X and score_X
alpha: real number in (0,1) (level of the test)
... | 45,454 |
def freehand(img, depth=10., el=np.pi / 2.2, az=np.pi / 4):
"""
手绘风格图像生成
:param img:
:param depth: 深度,取值在0-100
:param el: 光源的俯视角度,弧度值
:param az: 光源的方位角度,弧度值
:return:
"""
img = rgb2grey(img)
img = img * 255 if np.max(img) <= 1.1 else img
grad = np.gradient(img) # 取图像灰度的梯度值
... | 45,455 |
def batch_compute_ic(trajs, params, *, weights=None, method="fft"):
"""Compute a batch of integrated correlated matrices.
Parameters
----------
trajs : list of (n_frames[i], n_features) ndarray
List of featurized trajectories.
params : 1d array-like or list of 1d array-like
If a 1d ... | 45,456 |
def gaussfitter(spectrum,initpar=None,noplot=True,silent=False,
vmax=None,vmin=None,detsnrthresh=0,dethtthresh=2.0,
debug=False,noremovesmall=False):
"""
This program tries to do gaussian analysis
on HI spectra.
Parameters
----------
spect... | 45,457 |
def test_provider_requests_delete(change_dir):
"""Verify the hook call works successfully."""
output = tackle('.', context_file='delete.yaml', no_input=True)
assert output['simple'] == 204 | 45,458 |
def genTrainFeatures(dimension=128):
"""
Input:
dimension: desired dimension of the features
Output:
X: n feature vectors of dimensionality d (nxd)
Y: n labels (-1 = girl, +1 = boy) (n)
"""
# Load in the data
Xgirls = name2features("data/girls.train", B=dimension)
... | 45,459 |
def do_os():
"""
The operating system basics
"""
print "Operating system:"
CMD = "/usr/sbin/lsb_release"
REDHAT = "/etc/redhat-release"
proc = None
if os.path.exists(CMD):
proc = subprocess.Popen([CMD, "--description"],
stdout=subprocess.PIPE,
... | 45,460 |
def stateDiff(start, end):
"""Calculate time difference between two states."""
consumed = (end.getTimestamp() - start.getTimestamp()).total_seconds()
return consumed | 45,461 |
def register_back():
"""Switch to register screen"""
root.title("Register or Login")
index_frame.pack(side=tk.TOP, padx=20, pady=20)
register_frame.pack_forget() | 45,462 |
def staticDepthLimit(max_depth):
"""Implement a static limit on the depth of a GP tree, as defined by Koza
in [Koza1989]. It may be used to decorate both crossover and mutation
operators. When an invalid (too high) child is generated, it is simply
replaced by one of its parents.
This operator c... | 45,463 |
def rotate(coor, alpha, beta, gamma):
"""Rotate 'coor' by the angles alpha, beta, gamma.
"""
R1 = getD(alpha)
R2 = getC(beta)
R3 = getD(gamma)
M = R3 * R2 * R1
return np.dot(coor, M) | 45,464 |
def plot(array):
"""Plot a numpy array with an NDVI colormap."""
pyplot.imshow(array, cmap='RdYlGn')
pyplot.colorbar() | 45,465 |
def test_pa_validation_start_different_15():
"""Test if an invalid number start is different 15"""
invalid_number = '172030964'
assert pa.start(invalid_number) == False | 45,466 |
def display_sample_prediction(args, model, X, y):
"""
Select a sequence of command lines and print the current prediction of the model.
"""
index = randint(0, len(X)-1)
rowX = X[np.array([index])]
rowy = y[np.array([index])]
vocab = Vocabulary(args.vocabulary)
sequence = vocab.decode(ro... | 45,467 |
def get_content(url):
"""get content - cfscrape"""
request = requests.get(url)
content = request.text
if request.status_code == 503:
scraper = cfscrape.create_scraper()
content = scraper.get(url).content
return content | 45,468 |
def change_user_to_waiting(user_ip):
"""Change the status of the standby user to waiting"""
global users_connected
user_ip = json.loads(user_ip)
for _, data in users_connected.items():
if data["ip"] == user_ip:
data["state"] = "waiting" | 45,469 |
def titlecase(string):
"""Turn string of words into titlecased words.
:type string: str
:param string: A string of words.
"""
return re.sub(
r"[A-Za-z]+('[A-Za-z]+)?",
lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),
string,
) | 45,470 |
def youdao_definition(wrapped_word):
"""
get word meaning from youdao.com, thanks for their great work.
"""
word = wrapped_word[:-2].strip()
url = constants.YOUDAO_URL_PREFIX + word
content = utility.get_content_of_url(url)
soup = bs4.BeautifulSoup(markup=content, features='lxml')
word_m... | 45,471 |
def bahai_from_fixed(date):
"""Return Bahai date [major, cycle, year, month, day] corresponding
to fixed date, date."""
g_year = gregorian_year_from_fixed(date)
start = gregorian_year_from_fixed(BAHAI_EPOCH)
years = (g_year - start -
(1 if (date <= fixed_from_gregorian(
... | 45,472 |
def create_or_update_record(tableName, record):
"""
Function to create or update a record in DynamoDB
Params:
tableName::str
The table name to get the record
record::dict
The object to store
Returns:
bool
If the record was inserted or not
... | 45,473 |
def download_noaa_weather(station_list_csv_path, years=[2019], work_dir='./'):
"""
{ item_description }
"""
from ftplib import FTP
try:
df_stations = pd.read_csv(station_list_csv_path)
except:
print(f"Fail to read station list from {station_list_csv_path}")
return
... | 45,474 |
def get_loader(json_path, data_dir, mask_dir, inp_size, feat_stride, preprocess,
batch_size, params_transform, training=True, shuffle=True, num_workers=1, aug=False, classification = False):
""" Build a COCO dataloader
:param json_path: string, path to jso file
:param datadir: string, path to... | 45,475 |
def get_service_status(fledge_url):
"""
Return ping status from fledge.
Args:
fledge_url: The URL of Fledge.
Returns:
A json string that contains ping status.
"""
_connection = http.client.HTTPConnection(fledge_url)
_connection.request("GET", '/fledge/service')
r = _conne... | 45,476 |
def test_1_1_4_tmp_mount_nosuid(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 1.1.4
Tests if /etc/systemd/system/tmp.mount contains nosuid
"""
assert host.file(TMP_MOUNT_FILE).contains('nosuid') | 45,477 |
def png_to_jpeg(image_bytes: bytes, quality: int = 100) -> np.ndarray:
"""Converts PNG image (bytes or str) to JPEG (bytes)."""
runner = _get_runner()
decode_fn = lambda img: tf.image.decode_png(img, channels=3)
image = runner.run(decode_fn, image_bytes)
fn = lambda img: tf.image.encode_jpeg(img, format='rgb'... | 45,478 |
def get_object_metadata(sess, bucket_name, blob_name):
"""
get object metadata
"""
url = "https://www.googleapis.com/storage/v1/b/{}/o/{}".format(
bucket_name, urllib.quote(blob_name, safe="")
)
return sess.request(method="GET", url=url) | 45,479 |
def complete(service, **kwargs):
"""Provide completions."""
complete_type = kwargs.pop('type')
if complete_type == 'issues':
issues = service.issues(kwargs.pop('state', 'open'))
if 'zsh' in environ['SHELL']:
# In zsh display the issue title as the description
output =... | 45,480 |
def j2_pert(s):
"""Returns the J2 acceleration for a given state.
Args:
s(1x6 numpy array): the state vector [rx,ry,rz,vx,vy,vz]
Returns:
1x3 numpy array: the J2 acceleration [ax,ay,az]
"""
r = np.linalg.norm(s[0:3])
K = -3*mu_Earth*J2*(Re**2)/2/r**5
comp = np.... | 45,481 |
def bootstrap(v):
"""
Constructs Monte Carlo simulated data set using the
Bootstrap algorithm.
Usage:
>>> bootstrap(x)
where x is either an array or a list of arrays. If it is a
list, the code returns the corresponding list... | 45,482 |
def html_table_header():
"""Return the HTML row with header cells used in all tables."""
markup = ("<tr>" +
"<th>Column name</th>" +
"<th>DataType</th>" +
"<th><abbr title='Primary Key'>PK</abbr></th>" +
"<th><abbr title='Foreign Key'>FK</abbr></th>" +
... | 45,483 |
def load_images(input_files):
"""
Flattens each image in a folder into a 1D numpy array.
Next, each 1D numpy array is stacked into a 2D numpy array,
where each row of the image is the flattened version of the image
"""
imgfiles = glob.glob(input_files)
arr = []
for i, imgfile in enumerat... | 45,484 |
def dnstest(domain, token):
"""
Create, verify, and delete DNS TXT records using an autodetected provider.
"""
print("[+] Starting ACME Tests.")
change_id = (domain, token)
acme_handler = AcmeHandler()
acme_handler.autodetect_dns_providers(domain)
if not acme_handler.dns_providers_for_d... | 45,485 |
def hpat_pandas_series_iloc(self):
"""
Pandas Series operators :attr:`pandas.Series.at`, :attr:`pandas.Series.iat`, :attr:`pandas.Series.iloc`, :attr:`pandas.Series.loc` implementation.
.. only:: developer
Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_iloc2
Parameter... | 45,486 |
def checkLoggedIn(session):
"""
checks if any player
has logged in yet
"""
try:
return session["roll"] is not None
except KeyError:
session["roll"] = None
return False | 45,487 |
def parse_car_multi_attrib_log(log_f_path):
"""
解析log文件找出准确率最高的epoch对应的断点文件
按照train_acc * test_acc最大的准则判断
"""
if not os.path.isfile(log_f_path):
print('[Err]: invalid log file path.')
return
pattern = '.*Epoch[\s|\t]+([0-9]+).*train\s{1}acc\s{1}([0-9]+\.[0-9]+)%\s{1}\|test\s{1}a... | 45,488 |
def save_trade_history(df, market, update, old_df=None):
"""
Saves a dataframe of the trade history for a market.
"""
filename = TRADE_DATA_DIR + market + '.csv.gz'
if update:
# TODO: need to get rid of reading the old DF, and just make_history_df
# sure there are no overlapping poin... | 45,489 |
def push_docker_image_buildah(external_docker_name, push_connection: typing.Optional[Connection]) -> str:
"""
Push the docker image using buildah
:param external_docker_name: external docker image target name, without host
:param push_connection: connection for pushing Docker images to
"""
if n... | 45,490 |
def _match(patspec, tree):
"""Test if a tree matches the given pattern statement; return the matches
>>> _match(b'f(_)', parse(b'f()'))
>>> _match(b'f(_)', parse(b'f(1)'))
[('func', ('symbol', 'f'), ('symbol', '1')), ('symbol', '1')]
>>> _match(b'f(_)', parse(b'f(1, 2)'))
"""
pattern = _cac... | 45,491 |
def list_methods(client: Client) -> List[str]:
"""Lists the methods which are available on the server.
Args:
client: A client instance.
Returns:
List of method names.
"""
return client._client.ListMethods() | 45,492 |
def MakeLocal(start, end, location, name):
"""
Create a local variable
@param start: start of address range for the local variable
@param end: end of address range for the local variable
@param location: the variable location in the "[bp+xx]" form where xx is
a number. T... | 45,493 |
def accuracy(y, t):
"""
y: baredl.Tensor or np.ndarray (n, c)
n: number of samples
c: number of classes
Assuming it contains probabilities for each class
e.g. [[0.1,0.3,0.6], [0.1,0.8,0.1], ...]
t: baredl.Tensor or np.array (n,)
n: number of samples
Assuming ... | 45,494 |
def get_config() -> Type[Config]:
"""Get the global spines configuration
Returns
-------
Config
The global configuration settings for the current spines
project.
"""
if _GLOBAL_CONFIG is None:
load_config()
return _GLOBAL_CONFIG.copy() | 45,495 |
def prompt_yes_or_no(
question: str,
yes_text: str = 'Yes',
no_text: str = 'No',
has_to_match_case: bool = False,
enter_empty_confirms: bool = True,
default_is_yes: bool = False,
deselected_prefix: str = ' ',
selected_prefix: str = '\033[31m>\033[... | 45,496 |
def cli(ctx, **kwargs) -> None:
"""Command Line Interface for Data Visualization."""
if ctx.invoked_subcommand is None:
_plot(**kwargs) | 45,497 |
def delete_bucket_object(name=None, **kwargs):
"""Deletes an object store bucket objects
Args:
name (str): The name of the object, can include * to match multiple
objects
**kwargs: Additional options
Keyword Args:
bucket_name (str): The name of the bucket.
... | 45,498 |
def off():
"""Clear the buffer and immediately update UnicornHat
Turns off all pixels."""
clear()
show() | 45,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.