content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _write_file(file_name, content, forced=False):
"""
Create a file in the specified directory.
If the file does not exist, it will be created.
If forced==False and the file exists, it will raise an error.
If forced==True and the file exists, the file will be overwritten.
"""
if os.path.is... | 64,700 |
def app(mocked_config, tmpdir_factory):
"""Method to create an app for testing."""
# need to import this late as it might have side effects
from app import app as app_
# need to save old configurations of the app
# to restore them later upon tear down
old_url_map = copy.copy(app_.url_map)
o... | 64,701 |
def lambda_handler(event, context):
"""
handles request to the lambda function from frontend. parses json request
and sends to update_table function.
"""
bucket = event['bucket']
path = event['path']
response = list_all_objects(bucket, path)
# ACTUALLY USE RESPONSE HERE TO RETURN AN ERRO... | 64,702 |
def window_add_dataframe_date(date, df):
"""
Add data from a a dataframe.
Dataframe has data only from a day
Remove seconds from T_Hora_C, where time are store
:param date: day
:param df:data
:return:
"""
def filter_time(row):
return row["T_Time"][:5]
df["T_Time"] = df.ap... | 64,703 |
def any_in(collection, values):
"""
Check if any of a collection of values is in `collection`.
Returns boolean.
"""
for value in values:
if value in collection:
return True
return False | 64,704 |
def test_image_methods(task, method):
"""Test Docker image retrieval for methods."""
_test_image(task, "--methods", method) | 64,705 |
def __virtual__():
"""
Only load if requests is installed
"""
if HAS_LIBS:
return __virtualname__
else:
return (
False,
'The "{0}" module could not be loaded: '
'"requests" is not installed.'.format(__virtualname__),
) | 64,706 |
def floatingip_migration(context, l3_driver):
"""
# table floatingips, ipallocations
floatingip = {
u'floatingip': {
u'floating_network_id': u'2bdcaa63-22c5-4e58-8e2e-8f35bef7f513',
'tenant_id': u'11513667f4ee4a14acb0985659456f24',
'fixed_ip_address': None,
... | 64,707 |
def cdsem_straight(w, dw, spacing=5.0, length=20.0):
"""
w
dw
"""
c = pp.Component()
c.move(c.size_info.cc, (0, 0))
return c | 64,708 |
def interpolate(
input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=False,
):
"""Resize input via interpolating neighborhoods.
Specify either ``size`` or ``scale_factor`` to compute output size:
```python
x = torch.ones((1, 2, 3, 4))
y = F.interpolate(x, size=6)... | 64,709 |
def log_poisson_binomial(log_q0, log_q1):
"""
Computes the events log probabilities w.r.t. a batch of Poisson Binomial R.V.
The computation is numerically stable.
Parameters
----------
log_q0 : torch.tensor (dtype=torch.float)
The log probability of each bits to be zero. The Poisson... | 64,710 |
def writing(dataset1, te_report, tr_report, sheet_name, row=0):
"""Writes to excel"""
if not path.exists(f"ensemble_scores/intramodel_knn.xlsx"):
wb = Workbook()
ws = wb.active
ws.title = sheet_name
wb.save(filename=f"ensemble_scores/intramodel_knn.xlsx")
book = load... | 64,711 |
def display_lint_report(run: LintReport) -> None:
"""
Iterates over all the strings collected in the LintReport, sorts and
filters according to thresholds, manages the warn_as_error logic, and
prints out the appropriate messages in the report.
:param run: LintReport
"""
proj: Project = run.... | 64,712 |
def LogDashedString(text, platform, logging_level=logging.INFO):
"""Log text message with dashes on both sides."""
msg = text
if platform:
msg += ': ' + platform
if len(msg) < 78:
dashes = '-' * ((78 - len(msg)) / 2)
msg = '%s %s %s' % (dashes, msg, dashes)
if logging_level == logging.ERROR:
... | 64,713 |
def de_bias_binary(frame, pos_examples, neg_examples, left_examples, right_examples):
"""
De-bias a distinction that is presumed - for the purposes of de-biasing -
to form two ends of a scale. The prototypical example is male vs. female,
where words that are not inherently defined by gender end up being... | 64,714 |
def has_rings():
"""
Determine if we can see the ring logo.
"""
pos = pyautogui.locateOnScreen('rings.png', confidence=0.5)
if not pos:
pos = pyautogui.locateOnScreen('rings2.png', confidence=0.5)
print(f"Found at: {pos}")
return pos is not None | 64,715 |
def get_zip_names(path, dir, infold=True):
"""Loads the filenames for the data matching 'path' in the location 'dir'
('dir' does not have to end with '.zip').
Returns a list of filenames and the zip archive."""
folder = os.path.split(dir)[1] if infold else ''
if not dir.endswith('.zip'):
di... | 64,716 |
def contador (i, f, p):
"""
-> Faz uma contagem e mostra na tela.
:param i: início da contagem
:param f: fim da contagem
:param p: passo da contagem
:return: sem retorno
"""
c= i
while c <=f:
print(f'{c}', end=' ')
c = c + p
print('FIM!') | 64,717 |
def custom_tokenizer(nlp): # pragma: no cover
"""
Creates a custom spaCy tokenizer.
:param nlp: a spaCy Language object
:return:
"""
prefix_re = spacy.util.compile_prefix_regex(nlp.Defaults.prefixes)
suffix_re = spacy.util.compile_suffix_regex(nlp.Defaults.suffixes)
infix_re = spacy.ut... | 64,718 |
def _verify_trusted_keys_dir(trusted_keys_dir):
"""Verify that a trusted keys directory has the proper contents"""
files = glob.glob(os.path.join(trusted_keys_dir, "*"))
has_pub_key = any(filepath.endswith(".pub.asc") for filepath in files)
if not has_pub_key:
raise ValueError("No public keys fo... | 64,719 |
def choose_barrier(x, reverse=False):
"""
Choose the scenario where the AV hits the barrier.
If there is no such scenario, abstain.
:param reverse: If false, choose to hit the barrier. Else choose not to.
"""
if x["Passenger_noint"] == 0 and x["Passenger_int"] == 0: return -1
if x["Passenge... | 64,720 |
def test_no_lfe_out():
"""When there is no LFE output, both LFE1 and LFE2 should be discarded."""
layout = bs2051.get_layout("0+2+0")
p = DirectSpeakersPanner(layout)
npt.assert_allclose(p.handle(tm_with_labels(["LFE1"], lfe_freq=True)), np.zeros(len(layout.channels)))
npt.assert_allclose(p.handle(... | 64,721 |
def plot_violin(df: pandas.DataFrame, key: str, color: Union[str, Tuple], group_by: str, ax: plt.Axes = None):
"""
Draw a violin plot, showing the distribution of the field 'key', grouped by 'group_by'
Parameters
----------
df : DataFrame
Output from benchmark.py
key : str
Show ... | 64,722 |
def _find_user_traceback_depth(tb):
"""Returns the depth of user-specific code in a traceback.
This is the depth from wich we find a frame where __name__ is '__p1__'.
Args:
tb: A traceback object.
"""
depth = 0
while tb:
# Find the topmost frame
frame = tb.tb_frame
... | 64,723 |
def load_config(cfg_path: str) -> DictConfig:
"""
Load configuration file. `base_config.yaml` is taken as a base for every config.
:param cfg_path: Path to the configuration file
:return: Loaded configuration
"""
base_cfg = OmegaConf.load('legoformer/config/base_config.yaml')
curr_cfg = ... | 64,724 |
def source_vectors(theta, phi):
"""
Produces vectors along the polarization axes and the direction of GW
propagation for sources at (theta, phi).
"""
# theta, phi is the direction to the source
# everything below needs the direction of GW propagation
theta_prop = np.pi - theta
phi_prop =... | 64,725 |
def get_gradient_thresh(img):
"""
Calculate a gradient threshold of an image
:param img: BGR image
:return: Binary gradient threshold image
"""
ksize = 5
img = undistort_image(img, mtx, dist)
#hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS).astype(np.float)
#s_channel = hls[:, :, 2]
g... | 64,726 |
def test_collated_task_dataset_getitem_bad_index(collated_task_dataset, index):
"""Test TaskDataset.__getitem__ explodes when given a bad index."""
with pytest.raises(IndexError, match=f'.*bounds: {index}.*'):
collated_task_dataset[index] | 64,727 |
def refresh(self, errorfile):
"""
Recompile all the entire blog.
Put the result into a log file.
"""
# BUG FROM MAKEFLY WITH HYMBY: The refresh method is called at the same time than the post creation.
#+ This way, the new post have the same date as the compilation.
#+ In Makefly, we don't c... | 64,728 |
def do_split(s, sep):
"""
Divides an input string into an array using the argument as a separator.
split is commonly used to convert comma-separated items from a string to an
array.
https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/standardfilters.rb#L88
... | 64,729 |
def TruncateToZero(path):
"""Truncates a file size to 0.
Args:
path: Path to the file.
"""
with open(path, 'w'):
pass | 64,730 |
def atualizar():
"""
Função para atualizar um produto
"""
conn = conectar()
cursor = conn.cursor()
codigo = int(input('Informe o código do produto: '))
nome = input('Informe o nome do produto: ')
preco = float(input('Informe o preço do produto: '))
estoque = int(input('Informe a qua... | 64,731 |
def optimal_init():
"""Initializes first case of optimal result"""
for i in range(num_parameters):
optimal[i] = 100 | 64,732 |
def process_covid_csv_data(covid_csv_data: csv) -> tuple[int, int, int]:
"""
(For Test) Processes covid data from a csv file.
Arguments:
covid_csv_data: A csv file of all the data.
Parameters:
last7days_cases: The number of cases in the last 7 days with a default value of 0.
dict_... | 64,733 |
def test_kde_2d_gaussian_with_weights_against_scipy():
"""
We compare only against a unimodal distribution as "bimodal or multi-modal
distributions tend to be oversmoothed" by `scipy.stats.gaussian_kde`, i.e. it is
not a reliable reference solution.
"""
np.random.seed(42)
n_sample = 3000
... | 64,734 |
def downscale_params(args):
"""Downscale operation
Arguments:
args {[type]} -- [description]
"""
scen, param_name, prism_dem, self = args
# Load the PRISM parameter
param, bbox, csx, csy = read_array(os.path.join(
self['climate_grids'], param_name + '.tif'), self['bbox'], self[... | 64,735 |
def _FormatLabelsArgsToKeyValuePairs(labels):
"""Flattens the labels specified in cli to a list of (k, v) pairs."""
labels = [] if labels is None else labels
labels_flattened = []
for labels_sublist in labels:
labels_flattened.extend([label.strip() for label in labels_sublist])
labels_flattened_unique = ... | 64,736 |
def get_syncitems():
"""Run the loop to get all 'syncitems' entries.
Returns a list of (syncitem, time) tuples."""
syncitems = lj.run('syncitems')
items = []
total = int(syncitems['sync_total'])
print '%d/%d syncitems' % (len(items), total)
lastsync = None
while len(items) < total:
... | 64,737 |
def router_id(conn, ref, required=True):
"""Fetch ID of Router identified by reference dict `ref`. Use
OpenStack SDK connection `conn` to fetch the info. If `required`,
ensure the fetch is successful.
Returns: the ID, or None if not found and not `required`
Raises: openstack's ResourceNotFound whe... | 64,738 |
def read_examples(examples, is_training, shuffle_examples,
skip_n_initial_records, hparams):
"""Returns a tf.data.Dataset from TFRecord files.
Args:
examples: A string path to a TFRecord file of examples, a python list of
serialized examples, or a Tensor placeholder for serialized examp... | 64,739 |
def model_data(
train_samples: int, targets: Optional[list[str]] = None
) -> tuple[list[str], Data]:
"""
Get the training and testing data to be used for the model.
Inputs
------
train_sample : int
How many samples per example
targets : Optional[list[str]]
If specified, this... | 64,740 |
def retention(retention):
"""
Parses a retention object give in JSON to Retention type
:param retention: retention in JSON
:return: PropertyInstance.Retention
"""
if retention is None:
return None
context = None
if retention.get('context') is not None:
context = Property... | 64,741 |
def get_ansible_vars(host):
"""Define get_ansible_vars"""
repository_role = "file=../../vars/main.yml name=repository_role"
tomcat_role = "file=../../../tomcat/vars/main.yml name=tomcat_role"
java_role = "file=../../../java/vars/main.yml name=java_role"
common_vars = "../../../common/vars/main.yml n... | 64,742 |
def ReduceToAlgebra(left,right):
"""
Converts a parsed Group Graph Pattern into an expression in the algebra by recursive
folding / reduction (via functional programming) of the GGP as a list of Basic
Triple Patterns or "Graph Pattern Blocks"
12.2.1 Converting Graph Patterns
.. sourcecode:: t... | 64,743 |
def get_upgrade_command(latest_version=None):
"""
Get GridCal update command
:return:
"""
if latest_version is None:
latest_version = find_latest_version()
cmd = [sys.executable, '-m', 'pip', 'install',
'GridCal=={}'.format(latest_version),
'--upgrade',
'... | 64,744 |
def DilatedSpatialPyramidPooling(dspp_input,
num_filters=256,
dilation_rates=[1,6,12,18]):
"""
Instantiates the Atrous/Dilated Spatial Pyramid Pooling (ASPP/DSPP)
architecture for the DoubleU-Net segmentation model.
Args:
dspp_in... | 64,745 |
def cleanup_whitespace(text_content):
"""clean up junk whitespace that comes with every table cell"""
return re.sub(REGEX_WHITESPACE, ' ', text_content.strip()) | 64,746 |
def filter(request, site, condition, val):
"""
分类显示
:param request:
:param site:
:param condition:
:param val:
:return:
"""
user_home = models.Blog.objects.filter(site=site).select_related('user').first()
if not user_home:
return redirect('/')
template_name = "home_su... | 64,747 |
def sst_ERSSTv5():
"""
get the sea surface temperature from the ERSST-v5 data set
"""
data = xr.open_dataset(join(rawdir, 'sst.mnmean.nc'))
data.sst.attrs['dataset'] = 'ERSSTv5'
return data.sst | 64,748 |
def _week_value(dt, as_string=False):
"""
Mixpanel weeks start on Monday. Given a datetime object or a date string of format YYYY-MM-DD,
returns a YYYY-MM-DD string for the Monday of that week.
"""
dt = datetime.datetime.strptime(dt, '%Y-%m-%d') if isinstance(dt, compat.string_type) else dt
dt =... | 64,749 |
def swap_AL(peptide:str)->str:
"""
Swaps a A with L. Note: Only if AA is not modified.
Args:
peptide (str): peptide.
Returns:
str: peptide with swapped ALs.
"""
i = 0
while i < len(range(len(peptide) - 1)):
if peptide[i] == "A":
peptide[i] = peptide[i + 1... | 64,750 |
def mpgm_loss(target, prediction, l_A=1., l_E=1., l_F=1., zero_diag: bool=False, softmax_E: bool=True):
"""
Modification of the loss function described in the GraphVAE paper.
The difference is, we treat A and E the same as both are sigmoided and F stays as it is softmaxed.
This way we can have multiple ... | 64,751 |
def loss(y, y_hat):
"""
Evaluates cross-entropy loss for the given next-node distributions
and predicted distributions # todo fix
"""
y_hat_log = np.log(y_hat)
y_hat_log[y_hat_log == -np.inf] = 0
return -np.sum(y_hat_log * y) / y.shape[1] | 64,752 |
def show_menu_item_by_id(item_id): # noqa: E501
"""Info for a specific menu item
# noqa: E501
:param item_id: The id of the menu item to retrieve
:type item_id: str
:rtype: MenuItem
"""
if (item := models.MenuItem.query_by_id(int(item_id))) :
return item.serialize()
else:
... | 64,753 |
def test_unexpected_error():
"""The credential should log stderr when Get-AzAccessToken returns an unexpected error"""
class MockHandler(logging.Handler):
def __init__(self):
super(MockHandler, self).__init__()
self.messages = []
def emit(self, record):
self... | 64,754 |
def test_get_page(stem: str, expected: str):
"""Test `get_page` for PdfDocument
Arguments:
stem {str} -- stem of sample path
expected {str} -- expected content
"""
with get_stream(get_path(stem)) as stream:
src = PdfFileReader(stream)
received = get_page(src, 0).strip()... | 64,755 |
def get_minmax(Data):
"""
Get daily minima and maxima on days when no 30-min observations are missing.
Days with missing observations return a value of c.missing_value
Values returned are sample size (Num), minimum (Min) and maximum (Max)
Usage qcts.get_minmax(Data)
Data: 1-... | 64,756 |
def padding_box(rect, padding):
"""
Get a new Rect where rect is enlarged by padding width.
:param Rect rect
:param int padding
:return enlarged Rect
:rtype Rect
"""
top_left, bottom_right = rect
return (add_positions(top_left, (-padding, -padding)),
add_positions(bott... | 64,757 |
def binarize(y, label):
"""Binarize array-like data according to label."""
return (np.array(y) == label).astype(int) | 64,758 |
def buy():
"""Buy shares of stock"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
if not request.form.get("symbol"):
return apology("must provide stock’s symbol", 400)
elif not request.form.get("shares"):
return apolo... | 64,759 |
def bokeh_bands(bandsdata,
*,
k_label='kpath',
eigenvalues='eigenvalues_up',
weight=None,
xlabel='',
ylabel=r'E-E_F [eV]',
title='',
special_kpoints=None,
size_min=3.0,
... | 64,760 |
def monitor_saturation(model):
"""Monitor the saturation rate."""
monitors = {}
for name, p in model.named_parameters():
p = F.sigmoid(p)
sat = 1 - (p - (p > 0.5).float()).abs()
monitors['sat/' + name] = sat
return monitors | 64,761 |
def main():
"""Main entry point for the `finddup` script."""
atexit.register(finddup.output.use_default) # Close output on exit
args = _parse_args()
if args.output:
finddup.output.redirect(args.output)
if args.verbose:
logging.basicConfig(level=logging.INFO)
# Generate filel... | 64,762 |
def ensure_job_exists_in_s3(job_id):
"""_ensure_job_exists_in_s3
:param job_id:
"""
try:
inputs = S3_CLIENT.list_objects(Bucket=tfvars.S3_JOBS_BUCKET,
Prefix=job_id+'/inputs')
if inputs.get('Contents'):
return True
return False... | 64,763 |
def dict2kvtable(obj, env):
"""Generate an HTML table from a dictionary"""
return "XXX table" | 64,764 |
def u_law_expend(arr):
"""
Expend compressed array.
:param arr: given array
:return: expended array
"""
u = 255
max_in_arr = np.amax(arr)
out = np.array(arr, dtype=float)
for i in range(0, len(arr)):
p = math.log(256) * abs(arr[i]) / max_in_arr
o = max_in_arr * (mat... | 64,765 |
async def get_attentions_and_preds(
model: str, sentence: str, layer: int, request_hash=None
) -> api.AttentionResponse:
"""For a sentence, at a layer, get the attentions and predictions
Args:
request['model']: Model name
request['sentence']: Sentence to get the attentions for
r... | 64,766 |
def read_and_record_shortcuts(path, filename):
"""Read content of the directory, check validity, record to YAML file"""
path = Path(path)
symlinks = sorted([x for x in path.iterdir() if x.is_symlink()])
default_version = None
version_file = path / ".version"
if version_file.exists():
ve... | 64,767 |
def initDatabase():
"""
Initialize the to-do list database
"""
scriptPath = os.path.dirname(os.path.realpath(__file__))
databasePath = scriptPath + "/../data/todo_list.sqlite"
database = TodoDatabase(databasePath)
return database | 64,768 |
def dynamic_lisa_composite(rose, gdf,
p=0.05, figsize=(13, 10)):
"""
Composite visualisation for dynamic LISA values over two points in time.
Includes dynamic lisa heatmap, dynamic lisa rose plot,
and LISA cluster plots for both, compared points in time.
Parameters
--... | 64,769 |
def brick_get_connector_properties(multipath=False, enforce_multipath=False):
"""Wrapper to automatically set root_helper in brick calls.
:param multipath: A boolean indicating whether the connector can
support multipath.
:param enforce_multipath: If True, it raises exception when mul... | 64,770 |
def write(fd, data):
"""
Write `data` to the PTY at `fd`.
"""
os.write(fd, data) | 64,771 |
def vandermond(X):
"""
Create a vandermond matrix(nxn) by x values
Parameters
----------
X : list
list of x values
Returns
-------
np.array
vandermond matrix
"""
n = len(X)
V = np.zeros((n, n))
for i in range(n):
V[i, :] = [X[i... | 64,772 |
def test_get_odu_oru_status(mock_send_message_json):
"""Test Sdnc's class method."""
OranSdnc.get_odu_oru_status("o-du", "radio21", BASIC_AUTH)
mock_send_message_json.assert_called_once_with('GET',
'Get status of Odu connectivity',
... | 64,773 |
def bbknn(
adata,
batch_key="batch",
use_rep="X_pca",
approx=True,
use_annoy=True,
metric="euclidean",
copy=False,
**kwargs
):
"""
Batch balanced KNN, altering the KNN procedure to identify each cell's top neighbours in
each batch separately instead of the entire cell pool wi... | 64,774 |
def point_on_line(p1, p2, point):
"""Checks if a point falls along a given line segment.
Args:
p1 (tuple): The (x, y) coordinates of the starting point of the line.
p2 (tuple): The (x, y) coordinates of the end point of the line.
point (tuple): The (x, y) coordinates to test against the... | 64,775 |
def fn_col_mapping_dict_for_rename(df):
"""Return a column mapping dictionary with column name and associated column index number.
This can be used to assign new column names"""
return {c[1]:c[1] for c in enumerate(df.columns)} | 64,776 |
def do_query(archives, config_file=None, logger=None, context=None):
"""
Gets concordance and collocation analysis for keywords giving a target word, and it groups the results by date.
The window variable can be used for specifying the number of words to the right and left to take.
config_file mu... | 64,777 |
def evict():
""" Execute the drain command. Will loop forever until it completes successfully. """
node_name = os.environ['NODE_NAME']
while True:
proc = subprocess.run(
['/app/kubectl', 'drain', '--delete-local-data', '--ignore-daemonsets', '--force', '--timeout=60s', node_name]
... | 64,778 |
def first_inside_quotes(s):
"""
Returns the first substring of s between two (double) quotes
A quote character is one that is inside a string, not one that
delimits it. We typically use single quotes (') to delimit a
string if want to use a double quote character (") ... | 64,779 |
def main():
"""
A simple game loop with nothing going on except for the checking of
whether the mouse buttons are pressed
If none of the mouse buttons are pressed, the loop while continually print out:
"All mouse buttons released!"
If any of the mouse buttons are pressed... | 64,780 |
def pc_upsampling(xyz_upsample,
xyz,
feat,
scope='upsampling'):
""" Fully connected layer with non-linear operation.
Args:
xyz_upsample: 3-D tensor B x N2 x 3
xyz: 3-D tensor B x N x 3
feat: 3-D tensor B x N x C
Returns:
feat_upsample: 3-... | 64,781 |
def get_background_training_patches2(
ibs,
target_species,
dest_path=None,
patch_size=48,
patch_size_min=0.80,
patch_size_max=1.25,
annot_size=300,
patience=20,
patches_per_annotation=30,
global_limit=None,
train_gid_set=None,
visualize=False,
visualize_path=None,
... | 64,782 |
def prob3(num=600851475143):
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
a = []
b = 1
i = 3
while True:
if b == num:
break
elif num % i == 0:
b *= i
a.append(i)... | 64,783 |
def save(eid):
"""
Saves the coworker to the database. This function calls on the
`app.utils.update_coworker_info` function.
:param eid: The `eid` of the song to be saved.
:type eid: int
:returns: Redirects to the `/coworkers/` page (master table).
"""
update_coworker_info(request=requ... | 64,784 |
def is_compatible_type(type: Type) -> bool:
"""Returns `True` if the type is opyrator-compatible."""
try:
if issubclass(type, BaseModel):
return True
except Exception:
pass
try:
# valid list type
if type.__origin__ is list and issubclass(type.__args__[0], Bas... | 64,785 |
def barchart_onevar(dataset, var_x, y_title, filter = False, controlplotshow=True, filelocation = True):
"""
description:
-------------------------------------
param:
dataset: dataframe
var_x: x-axis
y_title: the title of y-axis
filter: the filter of query
controlplotshow: ... | 64,786 |
def get_all_namespaces_for_service(
service: str, soa_dir: str = DEFAULT_SOA_DIR, full_name: bool = True
) -> Sequence[Tuple[str, ServiceNamespaceConfig]]:
"""Get all the smartstack namespaces listed for a given service name.
:param service: The service name
:param soa_dir: The SOA config directory to ... | 64,787 |
def normal(shape, mean, stddev, seed=0):
"""
Generates random numbers according to the Normal (or Gaussian) random number distribution.
It is defined as:
Args:
shape (tuple): The shape of random tensor to be generated.
mean (Tensor): The mean μ distribution parameter, which specifies th... | 64,788 |
def circle(**kwargs) -> Expando:
"""
Draw a circle.
See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle
Args:
kwargs: Attributes to use for the initial render. SVG attributes, snake-cased.
Returns:
Data for the graphical element.
"""
return _el('c', kwargs) | 64,789 |
def merge_windows_in_cc(cc_idx, opts):
""" Merge the consensus sequences from all windows into one sequence (contig).
Parameters
----------
cc_idx : int (index of the connected component)
opts : dict (keywords arguments for global parameters)
"""
# Parse arguments
TRIM_MARGIN = opts['T... | 64,790 |
def display_loss_curve(losses, save_location: str=None):
"""
Plots and displays the loss curve (usually for Neural Network models)
Parameters
----------
save_location : str
the location to save the figure on disk. If None, the plot is displayed on runtime and not saved.
losses : numpy.a... | 64,791 |
def is_turkish_id(x):
"""
checks if given id is valid TC ID
"""
if len(str(x)) != 11:
return False
str_id = str(x)
# first 10 digit sum mod 10 equals 11th digit control
lst_id = [int(n) for n in str_id if n.isdigit()]
if lst_id[0] == 0:
return False
# first 10 digit... | 64,792 |
def L_p ( x ):
"""
Calculates the sound pressure level from the sound pressure squared:
L_p = 10 lg x/4e-10
Parameters
----------
x: array of floats
The squared sound pressure values
Returns
-------
array of floats
The corresponding sound pressure levels... | 64,793 |
def _generate_item(click_context, item_type, specification_path):
"""Generate an item based on a specification and add it to the configuration file and agent."""
# check protocol buffer compiler is installed
ctx = cast(Context, click_context.obj)
res = shutil.which("protoc")
if res is None:
... | 64,794 |
def adaboost():
"""
Classifies dataset samples using Adaboost
"""
data = datasets.load_digits()
y = data.target
digit_one, digit_two = 1, 8
idx = np.append(
np.where(y == digit_one)[0],
np.where(y == digit_two)[0])
y = data.target[idx]
# Change labels [-1, 1]
... | 64,795 |
def prediction(args):
"""
%prog prediction saved_model test_csv, test_dir, output
Args:
saved_model: saved model with either a .pt or .pth file extension
test_csv: csv file (comma separated without header) containing all testing image filenames
test_dir: directory where testing image... | 64,796 |
def get_abs_path(path: str) -> str:
"""
Returns absolute path
Parameters
----------
path : str
.
"""
return os_path.abspath(path) if path else None | 64,797 |
def start_expr_following_without_order_by_error(self):
"""Check range expr following frame without order by returns an error.
"""
exitcode, message = window_frame_error()
self.context.node.query("SELECT empno, depname, salary, sum(salary) OVER (RANGE 1 FOLLOWING) AS sum FROM empsalary",
exitcod... | 64,798 |
def index():
"""
This function renders the Index page for application. It shows list of all
messages logged by all bots and also provides a form for filtered
messages. Upon filtering, it redirects to a page showing filtered messages.
:return: ../index
"""
# get all messages.
page = reque... | 64,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.