content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_class_extensions(current_module, extension_key, extension_class_validator):
""" Load all registered extensions under the `extension_key` namespace in entry_points.
Attributes:
current_module: The module itself where extension classes should be added.
extension_key: The identifier as st... | 5,295,400 |
def check_output(output):
"""Check if output contains any error.
Several commands return output which we need to return back to the caller.
But, before we return anything back we want to perform a sanity check on
on the output in order to catch wrong input as it is impossible to
perform any sanitiz... | 5,295,401 |
def englishToFrench(EnglishText):
"""Translate english to french."""
translation = language_translator.translate(
text=EnglishText,
model_id='en-fr').get_result()
jsonStr = json.dumps(translation, indent=2, ensure_ascii=False)
data = json.loads(jsonStr)
for i in data['translations']:
... | 5,295,402 |
def nulls_first(column: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:
"""Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression.
:func:`.nulls_first` is intended to modify the expression produced
by :func:`.asc` or :func:`.desc`, and indicates how NULL values
should be handled whe... | 5,295,403 |
def send(message):
"""Submit a text event to the given or configured time-tunnel endpoint."""
click.echo('send - not implemented! args={0}'.format((message,))) | 5,295,404 |
def readHeader(fd):
"""read protocol header"""
data = fd.recv(6)
value = struct.unpack(">bib", data)
return value | 5,295,405 |
def load_default_item(monkeypatch) -> Item:
"""Save a default item object, and return the object"""
default_category = MockCategory.default_category()
save_mock_category(monkeypatch, default_category)
default_item = MockItem.default_item(parent_category=default_category)
save_mock_item(monkeypatch, ... | 5,295,406 |
def encode_vocab(data, word2ind):
"""Converts string tokens to indices based on given dictionary."""
dialogs = data['data']['dialogs']
print("[%s] Encoding caption tokens..." % data['split'])
for i, dialog in enumerate(tqdm(dialogs)):
dialogs[i]['caption_tokens'] = [word2ind.get(word, word2ind['... | 5,295,407 |
def test_delete_like(params, delete_likes_url, liked_post):
"""Проверка на удаление или добавление лайка посту в зависимости от исходного"""
post = liked_post["post_id"]
params["item_id"] = post
likes = requests.get(delete_likes_url, params=params).json()
assert not is_liked(post, params), "Пост не ... | 5,295,408 |
def get_RSI(df, column='Close', time_window=14):
"""Function to make the RSI values for a given stock dataframe"""
# Differential between the Column
diff = df[column].diff(1)
# Integrity of the difference values
up_chg = 0 * diff
down_chg = 0 * diff
# We consider the upchange as positive... | 5,295,409 |
def text_classification_mappings():
"""Text classification index mappings"""
return {
"_source": mappings.source(
excludes=[
# "words", # Cannot be exclude since comment text_length metric is computed using this source fields
"predicted",
"pre... | 5,295,410 |
def use_mapping(*args):
"""
use_mapping(ea) -> ea_t
Translate address according to current mappings.
@param ea: address to translate (C++: ea_t)
@return: translated address
"""
return _ida_bytes.use_mapping(*args) | 5,295,411 |
def get_prepared_data_summary(dataframe:pd.core.frame.DataFrame,
training_set_column_indicator:str='first_24_hour',
test_set_column_indicator:str='test_set',
target_column:str= 'next_hour_good_performance')->None:
"""
Prints info regarding train/test a... | 5,295,412 |
def get_oldest_timestamp(data, additional_groups_to_ignore, additional_tags_to_ignore, print_all_tags=False):
"""data as dictionary from json. Should contain only time stamps except SourceFile"""
# save only the oldest date
date_available = False
oldest_date = None
oldest_keys = []
# save src... | 5,295,413 |
def get_pascal_voc_colors():
"""Load the mapping that associates pascal classes with label colors
Returns:
np.ndarray with dimensions (21, 3)
"""
num_cls = 21
colors = [0] * (num_cls * 3)
colors[0:3] = (0, 0, 0) # 0: 'road'
colors[3:6] = (128, 0, 0) # 1 'sidewalk'
co... | 5,295,414 |
def orth_complement(A, B):
"""Returns the orthogonal complement of A in B
"""
rank_a = A.shape[1]
C = jnp.hstack([A, B])
Q, R = jnp.linalg.qr(C)
return Q[:, rank_a:] | 5,295,415 |
def deserialize_curve(fcurve, key_data_list):
"""Populates the given FCurve based on keyframe data listed in serialized
form. Expects key data to be ordered by time. Any existing keys will be
removed from the curve.
"""
# Ensure a blank slate
fcurve.EditClear()
# Loop 1: Add keys and se... | 5,295,416 |
def check_all_grammars(the_grammars, max_size):
"""
Does all the tests described above with all the grammars in the all_grammars script
Input:
- the_grammars is a dictionary will all grammars
- max_size is an integer representing the maximum size for the values on
"""
for grammar in the_grammars:
is_condensed... | 5,295,417 |
def test_read_sequencing(tmpdir):
"""Tests the correct number of reads were generated and the correct length of reads."""
read_sequencing.read_sequencing(
frag_file_name=Path.cwd() / 'tests/resources/test_terminal_fragments.txt',
num_reads=10,
read_len=80,
output_file_name=... | 5,295,418 |
def main():
"""
Bibmanager command-line interface.
Partially inspired by these:
- https://stackoverflow.com/questions/7869345/
- https://stackoverflow.com/questions/32017020/
"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatt... | 5,295,419 |
def test_normal_sample():
"""Sample from normal distribution."""
program_code = 'parameters {real y;} model {y ~ normal(0,1);}'
posterior = pystan.compile(program_code, data={})
assert posterior is not None
fit = posterior.sample()
assert fit.values.shape == (1, 1000, 1) # 1 chain, n samples, 1... | 5,295,420 |
def duplicate_notebook_error(name, library_list):
""" error display for doing operations on a notebook that exists in two places"""
from src.praxxis.sqlite import sqlite_library
print("%sThe notebook %s exists in two places. Specify which library to choose from." %(Fore.RED, name))
i = 0
for libr... | 5,295,421 |
def __api_operation_prep(log, arguments):
"""
API Operation Common Functionality
"""
# Parse the user data
example_user_config_json = "{\n 'user': <username>," \
"\n 'apikey': <apikey>\n}\n"
try:
user_data = json.load(arguments.user_config)
us... | 5,295,422 |
def get_grouped_data(input_data, feature, target_col, bins, cuts=0):
"""
Bins continuous features into equal sample size buckets and
returns the target mean in each bucket. Separates out nulls into
another bucket.
:param input_data: dataframe containg features and target column.
:param fe... | 5,295,423 |
def get_trajectory_from_environment(
environment: tf_py_environment.TFPyEnvironment,
observation: List[List[float]],
predicted_action: int) -> trajectories.Trajectory:
"""Gets trajectory data from `environment` based on observation and action.
Aligns `environment` observation to `observation` so that i... | 5,295,424 |
def test_fitted_attributes():
"""Test classifier attributes are set correctly after fitting."""
n_classes = 10
clf, (X, y) = make_classifier_and_data(n_classes=n_classes)
clf.fit(X, y)
assert_that(DiGraph(clf.class_hierarchy_), matches_graph(DiGraph(clf.class_hierarchy)))
assert_that(clf.graph... | 5,295,425 |
def resize_nd_skimage(img, size, order=1, **kwargs):
""" Resize the input numpy array image to the given size.
Args:
img (numpy array): Image to be resized.
size (tuple): Desired output size.
order (int, optional): Desired interpolation. Default is 1
kwargs: other parameters for... | 5,295,426 |
def MAXA(*args) -> Function:
"""
Returns the maximum numeric value in a dataset.
Learn more: https//support.google.com/docs/answer/3094016
"""
return Function("MAXA", args) | 5,295,427 |
def row_data(data):
"""handle tuple (row) data arrival"""
if is_ok(data):
return OK(data)
if is_eof(data):
if len(data) < 9:
return EOF(data)
return OK(data)
return Packet(data) | 5,295,428 |
async def test_gather_missing_workers_replicated(c, s, a, b, missing_first):
"""A worker owning a redundant copy of a key is missing.
The key is successfully gathered from other workers.
"""
assert b.address.startswith("tcp://127.0.0.1:")
x = await c.scatter("x", workers=[b.address])
bad_addr = ... | 5,295,429 |
def write_file(filename, constraints):
"""Write parameter constraints to a YAML file."""
with open(filename, 'w') as f:
yaml.dump(constraints.get_yaml_dict(), f) | 5,295,430 |
def timelined_cb(data, command, rc, stdout, stderr):
"""Very generic callback in case timelined acts weird."""
global buffers
buf = buffers[data]
name = wc.buffer_get_string(buf, "name")
stream = data + "STREAM"
del(hooks[stream])
wc.buffer_close(buf)
print_error("timelined for %s exited... | 5,295,431 |
def cli(kilosort_folder=None, do_parallel=True, do_pc_features=True, do_silhouette=True, do_drift=True, fs=3e4):
""" Calculate metrics for all units on one probe"""
# kilosort_folder = '~/res_ss_full/res_ss/tcloop_train_m022_1553627381_'
if kilosort_folder is None:
kilosort_folder = os.getcwd()
... | 5,295,432 |
def get_gpu():
"""Returns video device as listed by WMI.
Not cached as the GPU driver may change underneat.
"""
wbem = _get_wmi_wbem()
if not wbem:
return None, None
client = _get_win32com()
dimensions = set()
state = set()
# https://msdn.microsoft.com/library/aa394512.aspx
try:
for device... | 5,295,433 |
def tfnormalize(X):
"""
Skip connection layer normalization.
"""
sh = np.shape(X)
X_norm = tf.contrib.layers.layer_norm(X, trainable=False)
return X | 5,295,434 |
def init_table(con, tbl):
""" Create data table if it doesn't exist yet. """
tbl = _valid_table_name(tbl)
sql = f"CREATE TABLE IF NOT EXISTS [{tbl}] (_id TEXT PRIMARY KEY, _body TEXT)"
con.cursor().execute(sql)
_init_fts_table(con, tbl) | 5,295,435 |
def do_filter(parser, token):
"""
Filters the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escape... | 5,295,436 |
def find_ch_interest_dict(show_channel_dict : dict, usr_pref_dict : dict):
"""Pass in show_channel_dict {show:channels} and usr_pref_dict {show: rating}. Returns dictionary {channel : total rating}"""
ch_interest_dict = {}
for show in usr_pref_dict:
if show in show_channel_dict:
if show_... | 5,295,437 |
def newDB():
"""Configures and returns a connection to a freshly initialized DB."""
with app.app_context():
init_db()
create_db() | 5,295,438 |
def test_good_uniprot_2(rosetta):
"""Do we correctly synonymize if all we have is a UniProtKB identifier?"""
node = KNode('UniProtKB:P14416', type=node_types.GENE, name='')
rosetta.synonymizer.synonymize(node)
hgnc = node.get_synonyms_by_prefix('HGNC')
assert len(hgnc) == 1
assert hgnc.pop() == ... | 5,295,439 |
async def discover_source_aliases(serial_port=None):
"""
Discover the alias configured for each input
Cycle through the device sources and get the alias from the feedback message
Restore the original source (which we can only do once we know its alias)
Note that:
- the device will be powered o... | 5,295,440 |
def compute_average_embedding(input_embeddings, input_lengths):
"""Computes bag-of-words embedding.
Args:
input_embeddings: <tf.float32>[bs, max_seq_len, emb_dim]
input_lengths: <tf.int64>[bs, 1]
Returns:
bow_embedding: <tf.float32>[bs, emb_dim]
"""
max_seq_len = tf.shape(input_embeddings)[1]
... | 5,295,441 |
def test_set_get_item():
"""Testing setting and then getting an item."""
fig = Figure()
fig["a"] = 53
assert fig["a"] == 53 | 5,295,442 |
def plot_members_location_motion(gaia, pmra_pred=None, pmdec_pred=None, idx=None, radiant=None, add_errors=None, color=None,
path='members.png', title=''):
"""
:param gaia:
:param pmra_pred:
:param pmdec_pred:
:param idx:
:param radiant:
:param path:
:pa... | 5,295,443 |
def is_valid_int(s: str) -> bool:
"""
Return true if s can be converted into a valid integer, and false otherwise.
:param s: value to check if can be converted into a valid integer
:return: true if s can be converted into a valid integer, false otherwise
>>> is_valid_int("hello")
False
>>> ... | 5,295,444 |
def validate_report_input(X, y_true=None, y_pred=None, y_prob=None,
prtc_attr=None, priv_grp:int=1):
""" Raises error if data are of incorrect type or size for processing by
the fairness or performance reporters
Args:
X (array-like): Sample features
prtc_attr... | 5,295,445 |
def glEvalCoord1dv( v):
"""
v - seq( GLdouble, 1)
"""
if 1 != len( v):
raise TypeError( len( v), "1-array expected")
_gllib.glEvalCoord1dv( v) | 5,295,446 |
def myplot_mean(idx):
"""
This function displays a 16-bit averaged dark image at a certain exposure time (texp) with a logarithmic
colorbar which allows a 2D visualization of pixels intensity in ADU (or grey-scale value)
"""
a = np.abs(frame_mean_stack[:,:, idx])
plt.figure(num=None, dpi=300, ... | 5,295,447 |
def init_db():
"""
Context manager to init
and close the database
"""
if db.is_closed():
db.connect()
if not Work.table_exists():
Work.create_table()
yield
db.close() | 5,295,448 |
def gap_statistic(X, Wk, n_components, n_trials=100,
reference='uniform', n_jobs=1, random_state=None):
"""Calculate gap statistic for k-means clustering."""
rng = check_random_state(random_state)
random_seeds = []
for _ in range(n_trials):
has_seed_already = True
wh... | 5,295,449 |
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11... | 5,295,450 |
def tidy_cli(args):
"""Executes tidy similarly as from the command line.
:param args: command line arguments as a list of strings.
Example:
tidy_cli(['--format', 'txt', 'mytests.html'])
"""
TidyCommandLine().execute_cli(args) | 5,295,451 |
def _build_validator_subparser(
subparser_action: argparse._SubParsersAction,
base_subparser: argparse.ArgumentParser,
) -> argparse.ArgumentParser:
"""Returns the base subparser with arguments required for every validator.
Returns:
argparse.ArgumentParser: validator subparser with project, bra... | 5,295,452 |
def run_language_trimming(connection_params, lang_list):
"""Start the language trimming task.
Stage 4 in preprocessing pipeline.
"""
time1 = notifiers.time()
db_response = mongo_data_filters.language_trimming(
connection_params, lang_list)
time2 = notifiers.time()
result = db_resp... | 5,295,453 |
def InstanceNameRegexpValidator():
"""Returns a function that validates an instance name using predefined rules.
Returns:
function: str -> str, usable as an argparse type
"""
# : and . are not valid characters, but we allow them through this regex so
# that we can give a better error message using Valid... | 5,295,454 |
def segmentation_metrics_blend(
isolated_images, detected_segmentations, matches, noise_threshold, meas_band_num
):
"""Calculates segmentation metrics given information from a single blend.
The true segmentation is obtained from the isolated images by setting to True
the pixels above the noise_threshol... | 5,295,455 |
def convert_RGB_to_OD(I):
"""
Convert from RGB to optical density (OD_RGB) space.
RGB = 255 * exp(-1*OD_RGB).
:param I: Image RGB uint8.
:return: Optical denisty RGB image.
"""
mask = (I == 0)
I[mask] = 1
return np.maximum(-1 * np.log(I / 255), 1e-6) | 5,295,456 |
def delete_profession(profession_id):
"""delete_profession
Delete profession # noqa: E501
:rtype: Response
"""
# Remove evidences of this profession
evidences = DBEvidence.query.filter(DBEvidence.evidence_profession == profession_id).all()
for evidence in evidences:
delete_evidenc... | 5,295,457 |
def show_federation_config(data):
"""Show multi-clusters members this cluster knows."""
resp = data.client.show("fed/member", None, None)
# click.echo("Federation organization object: {}".format(json.dumps(resp)))
click.echo("")
if resp is None or (resp["fed_role"] == clusterRoleNone):
usePr... | 5,295,458 |
def process_remaining_mult_cases(chrom, positions, strand, edge_IDs, vertex_IDs,
transcript_dict, gene_starts, gene_ends, edge_dict,
locations, vertex_2_gene, run_info, cursor, tmp_gene):
""" This function is a catch-all for multiexonic transcripts t... | 5,295,459 |
def read_xlsx(filename: str, rows_count: int):
"""Читает документ xlsx и записывает данные в глобальную переменную названия телеграм каналов, локации и ссылки"""
tg = []
worksheet = xlrd.open_workbook(filename, on_demand=True).sheet_by_index(0)
for i in range(rows_count):
tg.append({'name': work... | 5,295,460 |
def HammerProj( lonlat, lon0=0.0 ):
"""Takes a point at the (longitude, latitude) point in lonlat (arg 1,
in radians) and returns the (x,y) coordinates of the Hammer
projection of that point. lon0 is the central longitude for the
projection process (in radians). The x coordinate is in the range
[-2*... | 5,295,461 |
def confusion_matrix_to_accuracy(conf_mat):
"""
Convert confusion matrix to accuracy
Parameters
conf_mat: np.ndarray | pd.DataFrame: confusion matrix, length of columns and that of rows must be same.
Returns
accuracy: float64: accuracy
"""
if type(conf_mat) is pd.DataFrame:
... | 5,295,462 |
def make_valid_param_card(path, restrictpath, outputpath=None):
""" modify the current param_card such that it agrees with the restriction"""
if not outputpath:
outputpath = path
cardrule = ParamCardRule()
cardrule.load_rule(restrictpath)
try :
cardrule.check_param_card... | 5,295,463 |
def multidevice_test_context(server_configuration: dict) -> Generator[MultiDeviceTestContext, None, None]:
"""Get generator for MultiDeviceTestContext."""
def _get_port() -> int:
import socket
from contextlib import closing
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)... | 5,295,464 |
def browserSelectedRefresh():
"""redetermine the title of the currently selected browser item."""
#14.01.04-18.59: allow directory XML data caching so folder data is only loaded once
debug("browserSelectedRefresh()")
global currentFolderList
selText=uist.listBrowser.currentItem().text()
for i in range(len(c... | 5,295,465 |
def deeplabv3_mobilenet_v2(
pretrained: bool = False,
progress: bool = True,
num_classes: int = 21,
aux_loss: Optional[bool] = None,
**kwargs: Any
) -> nn.Module:
"""Constructs a DeepLabV3 model with a MobileNetV2 backbone.
Args:
pretrained (bool): If True, returns a model pre-train... | 5,295,466 |
def create_isotropic_section(name, mat_names, region, part, model,T,Sect_name,OFFTS):
"""Creates an isotropic section
"""
from abaqusConstants import (MIDDLE_SURFACE, FROM_SECTION, SHELL, ON, OFF,
DEFAULT, UNIFORM, SIMPSON, GRADIENT, SYSTEM, ROTATION_NONE,
AXIS_1, AXIS_2, AXIS_3, S... | 5,295,467 |
def evaluate_compliance(configuration_item):
"""Check if given IAM user has a MFA device and return a string to be used for AWS config put_evaluations."""
if configuration_item['resourceType'] not in ['AWS::IAM::User']:
return 'NOT_APPLICABLE', 'Not applicable.'
if DEBUG_MODE is True:
print(... | 5,295,468 |
def process_sub_image(i, input_filepath, output_location, date_string, coords_string):
"""
Read file and run network centrality
"""
# open BWNDVI image
sub_image = Image.open(input_filepath)
image_array = pillow_to_numpy(sub_image)
# run network centrality
feature_vec, _ = subgraph_cen... | 5,295,469 |
def run_alembic_migrations(db, app_config, global_config):
"""Initializes a database and runs all Alembic migrations."""
Session = sessionmaker(bind=db.engine)
manager = AlembicMigrationManager(Session())
manager.init_or_migrate() | 5,295,470 |
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False,
minigui_mode=False):
"""Takes a path to model files and set up a GTP engine instance."""
# Here so we dont try load EdgeTPU python library unless we need to
if load_file.endswith('.tflite'):
from REDACTED.minigo.dual_net_e... | 5,295,471 |
def fetch_minion_pool() -> dict:
""" Fetch a new minion pool """
minions = [
minion
for minion in requests.get(settings.CARD_DB_ENDPOINT).json()
if minion.get("battlegroundsPremiumDbfId")
]
pool = defaultdict(list)
for minion in minions:
pool[minion.get("techLevel")].... | 5,295,472 |
def supprCouloir(grapheAmodif, noeud):
"""renvoie le graphe sans le couloir dans lequel se trouvait noeud"""
#un noeud-couloir est un noeud qui a seulement 2 voisins, qui ne contient pas de pièce.
#et aussi qui ne soit ni la position de départ du joueur, ni la position de départ de l'adversaire
#supprim... | 5,295,473 |
def make_notebook(data,
train_type='conv',
field_size=61,
ndim=2,
transform='pixelwise',
epochs=10,
optimizer='sgd',
skips=0,
n_frames=5,
normalization='std',... | 5,295,474 |
def API_StackDriver(config, auth, iterate=False):
"""StackDriver helper configuration for Google API.
Defines agreed upon version.
"""
api = {
'api': 'logging',
'version': 'v2',
'auth': auth,
'iterate': iterate
}
return API(config, api) | 5,295,475 |
def from_file(f):
""" Reads a namelist/configuration file and generates a
Namelist object. Anything enclosed in ${...} will be expanded
to a environment variable, while anything enclosed in
%(...) will be expanded to a previously defined variable within
the file. Anything enclosed in {} will be ... | 5,295,476 |
def con_K(x, y, beta, method='cdist', return_d=False):
"""con_K constructs the kernel K, where K(i, j) = k(x, y) = exp(-beta * ||x - y||^2).
Arguments
---------
x: :class:`~numpy.ndarray`
Original training data points.
y: :class:`~numpy.ndarray`
Control points used t... | 5,295,477 |
def gin_predictor_nasbench_nlp(search_space,
num_init=10,
k=10,
total_queries=150,
acq_opt_type='mutation',
allow_isomorphisms=False,
... | 5,295,478 |
def main(request: Request):
"""
Responds to an HTTP request.
Parameters:
----------
request (flask.Request):
HTTP request object.
"""
a.generate()
return jsonify({"sucess": True}) | 5,295,479 |
def manage(request):
""" All-encompassing view for management stuff """
assert isinstance(request, HttpRequest)
return render(
request,
'app/manage.html',
{
'title':'Dashboard',
}
) | 5,295,480 |
def runner(argv):
"""Tests DataStore using a test (i.e., TestCfg) store.
NOTE: this creates and leaves: data.d/test_cfg.yaml
"""
class TestCfg(DataStore):
"""
Specialized DataStore for test purposes.
"""
def __init__(self, storedir=None):
"""TBD"""
... | 5,295,481 |
def accuracy_score(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Accuracy classification score.
Args:
y_true (np.ndarray): correct target values.
y_pred (np.ndarray): estimated targets as returned by a classifier.
Returns:
float: proportion of correctly classified samples.
... | 5,295,482 |
def pick_balls(balls, n):
"""
"""
right = n - 1
for _ in range(right):
random_index = randint(0, right)
# swap them
print(balls[random_index])
balls[random_index], balls[right] = balls[right], balls[random_index]
right -= 1 | 5,295,483 |
def setup_logging_server():
""" Gets a testing server ready to go
and returns the port being used"""
port_to_try = 5000
# Try to get an open port 32 times
for _ in range(0, 32):
try:
server = LoggingHTTPServer(('', port_to_try), UpdatingWebsite)
return server
... | 5,295,484 |
def make_source_and_target_plates(target_df_list: List[pd.DataFrame],
max_volume_ul: float = MAX_WORKING_VOLUME_UL
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Generates optimized source and target plates.
Args:
target_df_list: A list of standar... | 5,295,485 |
def path_along_circles(
arc_angle: float, circles_centers: np.ndarray, axis: np.ndarray = OUT
) -> PATH_FUNC_TYPE:
"""This function transforms each point by moving it roughly along a circle, each with its own specified center.
The path may be seen as each point smoothly changing its orbit from its starting... | 5,295,486 |
def svn_wc_create_notify_url(*args):
"""svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t"""
return apply(_wc.svn_wc_create_notify_url, args) | 5,295,487 |
def prosecheck(c, root=ROOT):
"""
Run the following checkers for prose on all markdown source files:
- Proselint
- Alex
Proselint is used as a python library. Alex (an npm tool) is used by running
the command line tool on the markdown file.
Known exceptions are in `known.py`
"""
e... | 5,295,488 |
def update(branch='master', remote='origin', display_status=False, quiet=False): # pragma: no cover -- TODO commands
""" Performs full update (fetch+merge) of given Git branch.
Tries to resolve conflicts if possible.
Updates submodules as well.
"""
if not subprocess.check_output(['git', 'remote']).strip():
retur... | 5,295,489 |
def cleanup():
"""Handler to trigger when receiving the SIGTERM signal
Do cleanup inside this method, including:
1. Terminate all children processes
"""
do_print('Executor terminated; exiting all process in executor.')
# We would not wait or check whether process spawned dead or not
os.killpg(0, signal.SI... | 5,295,490 |
def make_model(n_size, n_output):
"""Create Keras model."""
model = Sequential()
model.add(LSTM(n_size))
model.add(Dense(n_output))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
ret... | 5,295,491 |
def humanize_seconds(total_seconds,
frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
"""Given time in int(seconds), return a string representing the time.
If negative_frmt is not given, a negative sign is prepended to frmt
and the result is wrap... | 5,295,492 |
def set_all_ref_clks(freq):
"""Set all RF data converter tile reference clocks to a given frequency.
freq: Target frequency, as selected from `get_freq_list()`.
"""
if not freq in _lmx2594Config:
raise RuntimeError(f"Frequency of {freq} MHz is not an option. "
"Please... | 5,295,493 |
def joint_residual(params, args):
"""
Residual for joint_fit
Input:
param_dict - suggested parameters of the functions Sigma and eta to be fit
args - arguments which remain fixed (e.g. r values)
Output:
residual - residual of the fit for the given parameters
"""
rA, Sigma... | 5,295,494 |
def test_name_badstr():
""" markup.encoder.text.TextEncoder().name() raises on bad string """
inst = _encoder.TextEncoder('utf-8')
with raises(RuntimeError):
inst.name(_test.badstr) | 5,295,495 |
def _batch_gather(params, indices, axis, batch_dims):
"""Helper that implements the body for ragged gather() when batch_dims>0.
Args:
params: The tensor from which to gather values.
indices: The indices of values to gather.
axis: The axis in `params` to gather `indices` from.
batch_dims: The number... | 5,295,496 |
def hola_y_adios():
""" Muestra la palabra 'hola' y, un segundo más tarde, muestra 'adiós's por pantalla"""
print("hola")
time.sleep(1) # Con esta línea obligamos a python a esperar 1 segundo.
print("adiós") | 5,295,497 |
def search(pattern: typing.Union[str, int],
**kwargs):
"""Compare value to pattern using search."""
value = kwargs.pop('value')
# type adaptation only if value is int
if isinstance(value, int):
value = type(pattern)(value)
if config.TYPE_CHECK_LEVEL > 0:
if not isinstanc... | 5,295,498 |
def tempdir():
"""
Create a temporary directory.
"""
directory = mkdtemp()
try:
yield directory
finally:
rmtree(directory) | 5,295,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.