content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def home(): """Home page.""" form = LoginForm(request.form) # Handle logging in if request.method == 'POST': if form.validate_on_submit(): login_user(form.user) flash('You are logged in.', 'success') redirect_url = request.args.get('next') or url_for('user.mem...
4bed46f095b31a61746c382460b6f477a4aa215e
3,654,900
def countingsort(A): """ Sort the list A. A has to be a list of integers. Every element of the list A has to be non-negative. @param A: the list that should get sorted @return the sorted list """ if len(A) == 0: return [] C = [0] * (max(A)+1) B = [""] * le...
ebdaac4580f910873f77878978b57e193334a4ea
3,654,901
import math def calc_obstacle_map(ox, oy, resolution, vr): """ Build obstacle map according to the distance of a certain grid to obstacles. Treat the area near the obstacle within the turning radius of the vehicle as the obstacle blocking area and mark it as TRUE. """ min_x = round(min(ox)) min_y = ro...
87d44c5eb799bf3b2ea64ac0717b8d7f260a4a37
3,654,902
import itertools def dilate(poly,eps): """ The function dilates a polytope. For a given polytope a polytopic over apoproximation of the $eps$-dilated set is computed. An e-dilated Pe set of P is defined as: Pe = {x+n|x in P ^ n in Ball(e)} where Ball(e) is the epsilon neighborhood with no...
0ae4d8ea9cb6977939e4d3bed6454ed55e8855cf
3,654,903
def read_files_to_vardf(map_df, df_dict, gridclimname, dataset, metadata, file_start_date, file_end_date, file_delimiter, file_time_step, file_colnames, subset_start_date, subset_end_date, min_elev, max_elev, variable_list=None): """ # r...
31bc460eb0035d3bbd51f266c96a53f537495a53
3,654,904
import pickle def read_file(pickle_file_name): """Reads composite or non-composite class-activation maps from Pickle file. :param pickle_file_name: Path to input file (created by `write_standard_file` or `write_pmm_file`). :return: gradcam_dict: Has the following keys if not a composite... gr...
3f2f7fb1a5a904f494e64f840f6a8d6ae207c900
3,654,905
import string def tacodev(val=None): """a valid taco device""" if val in ('', None): return '' val = string(val) if not tacodev_re.match(val): raise ValueError('%r is not a valid Taco device name' % val) return val
4cffd52f9e7673ad45e697aadfbb3515ecd3d209
3,654,906
import torch import os def VioNet_densenet(config, home_path): """ Load DENSENET model config.device config.pretrained_model config.sample_size config.sample_duration """ device = config.device ft_begin_idx = config.ft_begin_idx sample_size = config.sample_size[...
bdaa386b68d41190b4bf711ece571df14bb8012d
3,654,907
def decode_layout_example(example, input_range=None): """Given an instance and raw labels, creates <inputs, label> pair. Decoding includes. 1. Converting images from uint8 [0, 255] to [0, 1.] float32. 2. Mean subtraction and standardization using hard-coded mean and std. 3. Convert boxes from yxyx [0-1] to x...
a54b26a8b4d82a6a9e5bc093f9f59b7a74450916
3,654,908
import plotly.figure_factory as ff def bact_plot(samples, bacteroidetes, healthiest_sample): """ Returns a graph of the distribution of the data in a graph ========== samples : pandas.DataFrame The sample data frame. Must contain column `Bacteroidetes` and `Firmicutes` that contai...
d21bb3bd534f92cc6eed3bb467fe355abcf1afd2
3,654,909
import os def dynamic_upload_to(instance, filename): """ 根据链接类型,决定存储的目录 """ file_dir = (LogoImgRelatedDirEnum.APP.value if instance.link_type == LinkTypeEnum.LIGHT_APP.value else LogoImgRelatedDirEnum.ICON.value) return os.path.join(file_dir, filename)
ce8ca6083a8014d7613b7ffa09a1c0c8f0cb0323
3,654,910
def xdraw_lines(lines, **kwargs): """Draw lines and optionally set individual name, color, arrow, layer, and width properties. """ guids = [] for l in iter(lines): sp = l['start'] ep = l['end'] name = l.get('name', '') color = l.get('color') arrow = l.g...
bebeb2d400ed8c779281b67f01007e953f15460f
3,654,911
def _emit_params_file_action(ctx, path, mnemonic, cmds): """Helper function that writes a potentially long command list to a file. Args: ctx (struct): The ctx object. path (string): the file path where the params file should be written. mnemonic (string): the action mnemomic. cmds (list<string>): th...
adafb75e24b2023ad2926e4248e8b2e1e6966b8e
3,654,912
import gettext def annotate_validation_results(results, parsed_data): """Annotate validation results with potential add-on restrictions like denied origins.""" if waffle.switch_is_active('record-install-origins'): denied_origins = sorted( DeniedInstallOrigin.find_denied_origins(parsed_...
659ec92f98c2678de2ee8f2552da77c5394047c5
3,654,913
import sys import subprocess import threading from io import StringIO import time def RunCommand(command, input=None, pollFn=None, outStream=None, errStream=None, killOnEarlyReturn=True, verbose=False, debug=False...
4ad8a94f6079c33bfbd64e4d975b8c50317e03e9
3,654,914
import textwrap def ignore_firstline_dedent(text: str) -> str: """Like textwrap.dedent(), but ignore first empty lines Args: text: The text the be dedented Returns: The dedented text """ out = [] started = False for line in text.splitlines(): if not started and no...
04bde49e72e07552f2f88e9112546d00b85a2879
3,654,915
def read_file(filename): """ Read a file and return its binary content. \n @param filename : filename as string. \n @return data as bytes """ with open(filename, mode='rb') as file: file_content = file.read() return file_content
2417aa5cfa0d43303f9f6103e8b1fee9e8d652e2
3,654,916
def getdictkeys(value): """ Returns the ordered keys of a dict """ if type(value) == dict: keys = list(value.keys()) keys.sort(key=toint) return keys return []
adf49dbfa46f5174aa1435756c6e099b08b7c6c9
3,654,917
def exp_lr_scheduler(optimizer, epoch, init_lr=5e-3, lr_decay_epoch=40): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.1**(epoch // lr_decay_epoch)) if epoch % lr_decay_epoch == 0: print('LR is set to {}'.format(lr)) for param_group in optimizer....
520a7960ee589e033920cf182d75ea896cc8b8b7
3,654,918
from datetime import datetime import os def _check_draw_graph(graph_file): """Check whether the specified graph file should be redrawn. Currently we use the following heuristic: (1) if graph is older than N minutes, redraw it; (2) if admin has active session(s), redraw on every cron run (we detect t...
8a1b48f3e38c4cd6e52a6515e11088cb1c35eb0f
3,654,919
def random_shadow(image): """ Function to add shadow in images randomly at random places, Random shadows meant to make the Convolution model learn Lanes and lane curvature patterns effectively in dissimilar places. """ if np.random.rand() < 0.5: # (x1, y1) and (x2, y2) forms a line ...
118fbffa04bbd3551eff3f4298ba14235b00b7c3
3,654,920
def build_channel_header(type, tx_id, channel_id, timestamp, epoch=0, extension=None, tls_cert_hash=None): """Build channel header. Args: type (common_pb2.HeaderType): type tx_id (str): transaction id channel_id (str): channel id ...
cfd7524de77a61fe75d3b3be58e2ebde4d743393
3,654,921
def get_character(data, index): """Return one byte from data as a signed char. Args: data (list): raw data from sensor index (int): index entry from which to read data Returns: int: extracted signed char value """ result = data[index] if result > 127: result -= ...
5a08102cb9dc8ae7e2adcab9b5653b77ee2c6ae3
3,654,922
def df_to_embed(df, img_folder): """ Extract image embeddings, sentence embeddings and concatenated embeddings from dataset and image folders :param df: dataset file to use :param img_folder: folder where the corresponding images are stored :return: tuple containing sentence embeddings, image embedding...
cda55f06a74c1b0475bc6a9e35e657b4f3ce0392
3,654,923
from sys import path import pickle def load_release_data(): """ Load the release data. This always prints a warning if the release data contains any release data. :return: """ filen = path.join(PATH_ROOT, PATH_RELEASE_DATA) try: with open(filen, "r") as in_file: data =...
9ccc7d95638f2af8702065d58efd52016da27dc7
3,654,924
import random def generate_player_attributes(): """ Return a list of 53 dicts with player attributes that map to Player model fields. """ # Get player position distribution position_dist = get_position_distribution() # Get player attribute distribution attr_dist = get_attribute_distri...
57c16d998348b9db1384dc98412bd69e62d0c73d
3,654,925
def colour_from_loadings(loadings, maxLoading=None, baseColor="#FF0000"): """Computes colors given loading values. Given an array of loading values (loadings), returns an array of colors that graphviz can understand that can be used to colour the nodes. The node with the greatest loading uses baseColor...
8bd65e5b4aa54558d3710a8518bbbe6400559046
3,654,926
def determineDocument(pdf): """ Scans the pdf document for certain text lines and determines the type of investment vehicle traded""" if 'turbop' in pdf or 'turboc' in pdf: return 'certificate' elif 'minil' in pdf: return 'certificate' elif 'call' in pdf or 'put' in pdf: return '...
e6c5adc10168321fd6a534dd8e9fbf2e8ccb1615
3,654,927
import argparse def setup_parser() -> argparse.ArgumentParser: """Set default values and handle arg parser""" parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="wlanpi-core provides backend services for the WLAN Pi. Read the manual with: man wl...
7144ee5d790fbf703e0809d43122e1e94cd68378
3,654,928
from typing import Any import pickle def deserialize_api_types(class_name: str, d: dict) -> Any: """ Deserializes an API type. Allowed classes are defined in: * :mod:`maestral.core` * :mod:`maestral.model` * :mod:`maestral.exceptions` :param class_name: Name of class to deserializ...
f9c3962a1c18bd6dfb385af37e90b5062d1e0eef
3,654,929
from click.testing import CliRunner def runner() -> CliRunner: """Fixture for invoking command-line interfaces.""" return testing.CliRunner()
39f241b8192a3c06750e850c8c953822e4db5634
3,654,930
import torch import os def cal_quant_model_accuracy(model, gpu_index, val_loader, args, config_file, record_file): """Save the quantized model and infer the accuracy of the quantized model.""" torch.save({'state_dict': model.state_dict()}, os.path.join(TMP, 'model_best.pth.tar')) print('==> AMCT step3: sa...
e3bbc5e26a6824cd7a9d494348441a611a9f6b9d
3,654,931
import math def give_color_to_direction_dynamic(dir): """ Assigns a color to the direction (dynamic-defined colors) Parameters -------------- dir Direction Returns -------------- col Color """ dir = 0.5 + 0.5 * dir norm = mpl.colors.Normalize(vmin=0, vmax=...
ece62af230cda4870df099eae50a26b72848b2de
3,654,932
def pfilter(plugins, plugin_type=Analyser, **kwargs): """ Filter plugins by different criteria """ if isinstance(plugins, models.Plugins): plugins = plugins.plugins elif isinstance(plugins, dict): plugins = plugins.values() logger.debug('#' * 100) logger.debug('plugin_type {}'.format...
8a291743e410ca98716c8f71a87346ca1e86115f
3,654,933
import subprocess def tmux_session_detection(session_name: str) -> bool: """ Function checks if session already exists. """ cmd = ['tmux', 'has-session', '-t', session_name] result = subprocess.call(cmd, stderr=subprocess.DEVNULL) if result == 0: return True else: retu...
275d85e087fa271c76fe44f2a67ea4c719e0c031
3,654,934
def prune_arms(active_arms, sample_arms, verbose=False): """Remove all arms from ``active_arms`` that have an allocation less than two standard deviations below the current best arm. :param active_arms: list of coordinate-tuples corresponding to arms/cohorts currently being sampled :type active_arms: list ...
bd82f77503a9f0fa6a49b9f24ce9846849544b00
3,654,935
def prepare_string(dist, digits=None, exact=False, tol=1e-9, show_mask=False, str_outcomes=False): """ Prepares a distribution for a string representation. Parameters ---------- dist : distribution The distribution to be stringified. digits : int or None The p...
09abba1e5027049b9a43cb83e8de6f95daf5b431
3,654,936
def verifier(func): """ Creates a `Verifier` by given specifier. Parameters ---------- func: callable, [callable], (str, callable), [(str, callable)] The specifier of `Verifier` which can take various forms and determines the attributes and behaviors of `Verifier`. When it is declar...
665bc9cf5039e568fb2325a1cf0a25f72311eab8
3,654,937
import os def obtain_celeba_images(n_people:int) -> pd.DataFrame: """ Unique labels: 10,177 It is expected for the structure to be as following: <CELEBA_PATH>/ ├─ identity_CelebA.txt ├─ img_align_celeba/ ├─<images> * 'identity_CelebA.txt' is the downloaded identity ...
dcaa72c6ef32939dd55ba62a05bcbfba35236402
3,654,938
def get_add_diff_file_list(git_folder): """List of new files. """ repo = Repo(str(git_folder)) repo.git.add("sdk") output = repo.git.diff("HEAD", "--name-only") return output.splitlines()
af6ff7ffb076fb382aaa946e11e473f2f45bad0e
3,654,939
from PIL import Image import os def _save_qr_code(qr_code: str, filepath: str = qr_path, filename: str = qr_name) -> str: """Use it for save QrCode from web.whatsapp.com (copied as string) to PNG file to your path and your filename. :param qr_code: QrCode string from web.whatsapp.com. :param filepath...
fa5118f00b3174235fe455c678e08ee5d460fe2d
3,654,940
def has_read_perm(user, group, is_member, is_private): """ Return True if the user has permission to *read* Articles, False otherwise. """ if (group is None) or (is_member is None) or is_member(user, group): return True if (is_private is not None) and is_private(group): return False ...
6c1bc51abd50a5af76e16e7723957c758822c988
3,654,941
import tempfile import os import shutil def _create_docker_build_ctx( launch_project: LaunchProject, dockerfile_contents: str, ) -> str: """Creates build context temp dir containing Dockerfile and project code, returning path to temp dir.""" directory = tempfile.mkdtemp() dst_path = os.path.join(d...
3c5fc48d025494c2f92b07a5700b827382945d29
3,654,942
def normalize_df(dataframe, columns): """ normalized all columns passed to zero mean and unit variance, returns a full data set :param dataframe: the dataframe to normalize :param columns: all columns in the df that should be normalized :return: the data, centered around 0 and divided by it's standa...
39b23a6f11794323f1d732396021d669410c7de1
3,654,943
import json def PeekTrybotImage(chromeos_root, buildbucket_id): """Get the artifact URL of a given tryjob. Args: buildbucket_id: buildbucket-id chromeos_root: root dir of chrome os checkout Returns: (status, url) where status can be 'pass', 'fail', 'running', and url looks like: ...
c74b7c5a120d3d489e6990bd03e74bb0d22fea27
3,654,944
def frozenset_code_repr(value: frozenset) -> CodeRepresentation: """ Gets the code representation for a frozenset. :param value: The frozenset. :return: It's code representation. """ return container_code_repr("frozenset({", "})", ...
b4a3b283c7d21d0ae888c588471f9dea650215fb
3,654,945
def SRMI(df, n): """ MI修正指标 Args: df (pandas.DataFrame): Dataframe格式的K线序列 n (int): 参数n Returns: pandas.DataFrame: 返回的DataFrame包含2列, 是"a", "mi", 分别代表A值和MI值 Example:: # 获取 CFFEX.IF1903 合约的MI修正指标 from tqsdk import TqApi, TqSim from tqsdk.ta import SR...
29726385da068446cd3dd3ee13f8d95b88c36245
3,654,946
def get_purchase_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(Purchase, *args, **kwargs)
505ace358b619a736bc7a71139e307110cd7c27d
3,654,947
def depart_delete(request): """ 删除部门 """ nid = request.GET.get('nid') models.Department.objects.filter(id=nid).delete() return redirect("/depart/list/")
753c01771ad59b789f324a0cb95e94dcf9e48e9d
3,654,948
def create_condor_scheduler(name, host, username=None, password=None, private_key_path=None, private_key_pass=None): """ Creates a new condor scheduler Args: name (str): The name of the scheduler host (str): The hostname or IP address of the scheduler username (str, optional): The u...
d47c8c69fea249139698564b52520d95fbb1a75f
3,654,949
from meerschaum.config._edit import general_edit_config from typing import Optional from typing import List def edit_stack( action : Optional[List[str]] = None, debug : bool = False, **kw ): """ Open docker-compose.yaml or .env for editing """ if action is None: act...
b9d969040daf30924f72fafca71980ed3ec153b6
3,654,950
def dot_to_underscore(instring): """Replace dots with underscores""" return instring.replace(".", "_")
cf9441702ffb128678a031eabb4fa48be881cae5
3,654,951
def get_birthday_weekday(current_weekday: int, current_day: int, birthday_day: int) -> int: """Return the day of the week it will be on birthday_day, given that the day of the week is current_weekday and the day of the year is current_day. current_weekday is the current day of ...
5b4ba9f2a0efcdb9f150b421c21bb689604fbb11
3,654,952
import matlab.engine import os def matlab_kcit(X: np.ndarray, Y: np.ndarray, Z: np.ndarray, seed: int = None, matlab_engine_instance=None, installed_at=None): """Python-wrapper for original implementation of KCIT by Zhang et al. (2011) References ---------- Zhang, K., Peters, J., Janzing, D., & Schöl...
0b941742ad4c8c31009064c29bfc003767aad098
3,654,953
def _check(err, msg=""): """Raise error for non-zero error codes.""" if err < 0: msg += ': ' if msg else '' if err == _lib.paUnanticipatedHostError: info = _lib.Pa_GetLastHostErrorInfo() hostapi = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType) msg += 'U...
2f0b2ccd055bbad814e48b451eb72c60e62f9273
3,654,954
def RunPackage(output_dir, target, package_path, package_name, package_deps, package_args, args): """Copies the Fuchsia package at |package_path| to the target, executes it with |package_args|, and symbolizes its output. output_dir: The path containing the build output files. target: The deploym...
f5251fdbef0a209aa4bfa97a99085cae91acf3e3
3,654,955
def make_flood_fill_unet(input_fov_shape, output_fov_shape, network_config): """Construct a U-net flood filling network. """ image_input = Input(shape=tuple(input_fov_shape) + (1,), dtype='float32', name='image_input') if network_config.rescale_image: ffn = Lambda(lambda x: (x - 0.5) * 2.0)(imag...
ff8c90b3eecc26384b33fd64afa0a2c4dd44b82d
3,654,956
def FRAC(total): """Returns a function that shows the average percentage of the values from the total given.""" def realFrac(values, unit): r = toString(sum(values) / len(values) / total * 100) r += '%' if max(values) > min(values): r += ' avg' return [r] retu...
41946163d5c185d1188f71d615a67d72e6eaee4f
3,654,957
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return (None, None) low = ints[0] high = ints[0] for i in ints: if i < low: low = i ...
14c7d4cc73947c8de38bb598e295d9a1b4b7e5f6
3,654,958
def gen_sweep_pts(start: float=None, stop: float=None, center: float=0, span: float=None, num: int=None, step: float=None, endpoint=True): """ Generates an array of sweep points based on different types of input arguments. Boundaries of the array can be specified usin...
fb67623acfea433331babf7b7e1217cfa4e9e7ae
3,654,959
def set_lang_owner(cursor, lang, owner): """Set language owner. Args: cursor (cursor): psycopg2 cursor object. lang (str): language name. owner (str): name of new owner. """ query = "ALTER LANGUAGE \"%s\" OWNER TO \"%s\"" % (lang, owner) executed_queries.append(query) cu...
07cf4a33ca766a8ccf468f59d33318bab88c4529
3,654,960
def rstrip_tuple(t: tuple): """Remove trailing zeroes in `t`.""" if not t or t[-1]: return t right = len(t) - 1 while right > 0 and t[right - 1] == 0: right -= 1 return t[:right]
a10e74ea4a305d588fbd1555f32dda1d4b95266e
3,654,961
def _calc_active_face_flux_divergence_at_node(grid, unit_flux_at_faces, out=None): """Calculate divergence of face-based fluxes at nodes (active faces only). Given a flux per unit width across each face in the grid, calculate the net outflux (or influx, if negative) divided by cell area, at each node that ...
82c485935a3190c07ab12f7c838d52f5fecb78d0
3,654,962
def get_EL(overlaps): """ a) 1 +++++++++|---|--- 2 --|---|++++++++++ b) 1 ---|---|+++++++++++++ 2 ++++++++++|---|--- """ EL1a = overlaps['query_start'] EL2a = overlaps['target_len'] - overlaps['target_end'] - 1 EL1b = overlaps['query_len'] - overlaps['query_...
c0416091ecbfe40110fcda75cf12aae411cc4eba
3,654,963
from typing import NoReturn def get_line(prompt: str = '') -> Effect[HasConsole, NoReturn, str]: """ Get an `Effect` that reads a `str` from stdin Example: >>> class Env: ... console = Console() >>> greeting = lambda name: f'Hello {name}!' >>> get_line('What is your na...
47c58bb6ab794fdf789f0812dc1dc6d977106b60
3,654,964
def reconstruct_wave(*args: ndarray, kwargs_istft, n_sample=-1) -> ndarray: """ construct time-domain wave from complex spectrogram Args: *args: the complex spectrogram. kwargs_istft: arguments of Inverse STFT. n_sample: expected audio length. Returns: audio (numpy) "...
8624602efe1ab90304da05c602fb46ac52ec86e0
3,654,965
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ # first = [] student_names = [] score = [] print (student_info) for name in student_info: ...
ac7580cce134627e08764031ef2812e1b70ba00f
3,654,966
import argparse def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--cl_kernel_dir", type=str, default="./mace/ops/opencl/cl/", help="The cl kernels directory.") parser.add_argument( "--output_path", ...
86b45bfeb0ebfbc4e3e4864b55736b6c5bb42954
3,654,967
def get_composite_component(current_example_row, cache, model_config): """ maps component_id to dict of {cpu_id: False, ...} :param current_example_row: :param cache: :param model_config: :return: nested mapping_dict = { #there can be multiple components component_id = { #componen...
201db2016ea59cbf4a20ce081813bfd60d58bf67
3,654,968
def presigned_url_both(filename, email): """ Return presigned urls both original image url and thumbnail image url :param filename: :param email: :return: """ prefix = "photos/{0}/".format(email_normalize(email)) prefix_thumb = "photos/{0}/thumbnails/".format(email_normalize(email)) ...
7f37cf388ef944d740f2db49c5125435b819e0e8
3,654,969
def check_if_event_exists(service, new_summary): """ Description: checks if the event summary exists using a naive approach """ event_exists = False page_token = None calendarId = gcalendarId while True: events = ( service.events().list(calendarId=calendarId, pageToken=pa...
c6cc8bd3e4548cda11f9eaad6fd2d3da7a5c7e20
3,654,970
def retry(func, *args, **kwargs): """ You can use the kwargs to override the 'retries' (default: 5) and 'use_account' (default: 1). """ global url, token, parsed, conn retries = kwargs.get('retries', 5) use_account = 1 if 'use_account' in kwargs: use_account = kwargs['use_account...
7749fcd63f8d795692097b0257adde4147ecb569
3,654,971
def eval_f(angles, data=None): """ function to minimize """ x1, x2, d, zt, z, alpha, beta, mask, b1, b2 = data thetaxm, thetaym, thetazm, thetaxp, thetayp, thetazp = angles rm = rotation(thetaxm, thetaym, thetazm) rp = rotation(thetaxp, thetayp, thetazp) x1r = rm.dot(x1.T).T x2r = rp...
622c18d21224ab40d597a165bff3e0493db4cdcc
3,654,972
def clamp(min_v, max_v, value): """ Clamps a value between a min and max value Args: min_v: Minimum value max_v: Maximum value value: Value to be clamped Returns: Returns the clamped value """ return min_v if value < min_v else max_v if value > max_v else value
1a9aaf3790b233f535fb864215444b0426c17ad8
3,654,973
def collatz(n): """Sequence generation.""" l = [] while n > 1: l.append(n) if n % 2 == 0: n = n / 2 else: n = (3 * n) + 1 l.append(n) return l
69d993147604889fe6b03770efbfa6fb7f034258
3,654,974
import os import transformers def _load_tokenizer(path, **kwargs): """TODO: add docstring.""" if not os.path.isdir(path): raise ValueError( "transformers.AutoTokenizer.from_pretrained" " should be called with a path to a model directory." ) return transformers.Auto...
07b061448017960bca4e146a628c860e25ff4a19
3,654,975
def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6), stride=16): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ...
083bfad62fac67e0f7fb02251bc3db7904629bd5
3,654,976
import re def number_format(number_string, fill=2): """ add padding zeros to make alinged numbers ex. >>> number_format('2') '02' >>> number_format('1-2') '01-02' """ output = [] digits_spliter = r'(?P<digit>\d+)|(?P<nondigit>.)' for token in [m.groups() for m in re.find...
ee44167b4597fbe7c9f01fa5b26e02d7608c3677
3,654,977
def box_postp2use(pred_boxes, nms_iou_thr=0.7, conf_thr=0.5): """Postprocess prediction boxes to use * Non-Maximum Suppression * Filter boxes with Confidence Score Args: pred_boxes (np.ndarray dtype=np.float32): pred boxes postprocessed by yolo_output2boxes. shape: [cfg.cell_size * cfg.c...
07be8b953b82dbbcc27daab0afa71713db96efc1
3,654,978
from functools import reduce def many_hsvs_to_rgb(hsvs): """Combine list of hsvs otf [[(h, s, v), ...], ...] and return RGB list.""" num_strips = len(hsvs[0]) num_leds = len(hsvs[0][0]) res = [[[0, 0, 0] for ll in range(num_leds)] for ss in range(num_strips)] for strip in range(num_strips): ...
0842ecb4a42560fb6dae32a91ae12588152db621
3,654,979
def _convert_paths_to_flask(transmute_paths): """flask has it's own route syntax, so we convert it.""" paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
f8ea95e66c68481f0eb5a6d83cf61d098806f6be
3,654,980
def check_isup(k, return_client=None): """ Checks ping and returns status Used with concurrent decorator for parallel checks :param k: name to ping :param return_client: to change return format as '{k: {'comments': comments}}' :return(str): ping ok / - """ if is_up(k): comments ...
8ebb346eb74cb54aa978b4fff7cd310b344ece50
3,654,981
def percent_uppercase(text): """Calculates percentage of alphabetical characters that are uppercase, out of total alphabetical characters. Based on findings from spam.csv that spam texts have higher uppercase alphabetical characters (see: avg_uppercase_letters())""" alpha_count = 0 uppercase_count =...
61ccf42d06ffbae846e98d1d68a48de21f52c299
3,654,982
def get_move() -> tuple: """ Utility function to get the player's move. :return: tuple of the move """ return get_tuple('What move to make?')
ef35ab6fcb9cdfd60ecc91ff044b39600659c80f
3,654,983
def set_value(parent, type, name, value) : """ Sets a value in the format Mitsuba Renderer expects """ curr_elem = etree.SubElement(parent, type) curr_elem.set("name", name) curr_elem.set("id" if type in ["ref", "shapegroup"] else "value", value) # The can be an id return curr_elem
6ace9a4a5858f3fb80bbe585580345369d7f6e63
3,654,984
def create_bst(nodes) -> BST: """Creates a BST from a specified nodes.""" root = BST(nodes[0]) for i in range(1, len(nodes)): root.insert(nodes[i]) return root
d93164dcc94f36ea9d5643467cf157d0f387c149
3,654,985
from typing import Generator import math def get_dec_arch(gen: Generator) -> nn.Sequential: """ Get decoder architecture associated with given generator. Args: gen (Generator): Generator associated with the decoder. Returns: nn.Sequential: Decoder architecture. """ # As defin...
dbadcb662e0c9a3089a4f152675d91b0d3e8898d
3,654,986
import xml def add_page_to_xml(alto_xml, alto_xml_page, page_number=0): """ Add new page to end of alto_xml or replace old page. """ # If book empty if (alto_xml == None): page_dom = xml.dom.minidom.parseString(alto_xml_page) page_dom.getElementsByTagName("Page")[0].setAttribut...
d9303db2e6ce9c672d0548f81ddece36b1e59be3
3,654,987
def calculate_performance(all_data): """ Calculates the performance metrics as found in "benchmarks" folder of scikit-optimize and prints them in console. Parameters ---------- * `all_data`: dict Traces data collected during run of algorithms. For more details, see 'evaluate_opt...
0b2d185c2cafdddc632ee5b94a6e37c7450f096b
3,654,988
def connected_components(num_nodes, Ap, Aj, components): """connected_components(int const num_nodes, int const [] Ap, int const [] Aj, int [] components) -> int""" return _amg_core.connected_components(num_nodes, Ap, Aj, components)
a3306dd4357b6db91bdbb3033b53effe8f5e376d
3,654,989
def get_drm_version(): """ Return DRM library version. Returns: str: DRM library version. """ path = _join(PROJECT_DIR, "CMakeLists.txt") with open(path, "rt") as cmakelists: for line in cmakelists: if line.startswith("set(ACCELIZEDRM_VERSION "): vers...
b94da9049be428fc38992c34c829e202e98cb69d
3,654,990
def pmx(p1, p2): """Perform Partially Mapped Crossover on p1 and p2.""" return pmx_1(p1, p2), pmx_1(p2, p1)
60ac365efe3fd66eea24859afd9cfa470c061de2
3,654,991
import os def get_met_rxn_names(raw_data_dir: str, model_name: str) -> tuple: """ Gets the names of metabolites and reactions in the model. Args: raw_data_dir: path to folder with the raw data. model_name: named of the model. Returns: A list with the metabolite names and anot...
8036037b83b92756d2d5e703387bcb6a25fb1436
3,654,992
def meshparameterspace(shape=(20, 20), psi_limits=(None, None), eta_limits=(None, None), psi_spacing="linear", eta_spacing="linear", user_spacing=(None, None)): """Builds curvilinear mesh inside parameter space. :param ...
87c928bb598bfd86f29c9ecf83534c6994a11441
3,654,993
def get_key_information(index, harness_result: HarnessResult, testbed_parser, esapi_instance: ESAPI): """ 1. key_exception_dic是以引擎名为key的字典,若能提取错误信息,value为引擎的关键报错信息,若所有引擎均没有报错信息,则value为引擎的完整输出 返回[double_output_id, engine_name, key_exception_dic, api_name, 过滤类型]。过滤类型分为两种:第一类型是指异常结果 存在错误信息,第二类型是指异常结果...
734838a08760e5203701bc2bb21ff38c6e579873
3,654,994
from io import StringIO def open_image(asset): """Opens the image represented by the given asset.""" try: asset_path = asset.get_path() except NotImplementedError: return Image.open(StringIO(asset.get_contents())) else: return Image.open(asset_path)
11e2ca552ab898801dba4dea9e8776b93532ac11
3,654,995
def gather_audio_video_eavesdropping(x) : """ @param x : a Analysis instance @rtype : a list strings for the concerned category, for exemple [ 'This application makes phone calls', "This application sends an SMS message 'Premium SMS' to the '12345' phone number" ] """ result = [] ...
01a4cc13865e8810a26d8d08ec3cf684d4a1c8a1
3,654,996
def vdw_radius_single(element): """ Get the Van-der-Waals radius of an atom from the given element. [1]_ Parameters ---------- element : str The chemical element of the atoms. Returns ------- The Van-der-Waals radius of the atom. If the radius is unknown for the element...
6c705ce2309b470c3b6d8445701e831df35853ec
3,654,997
import typing def evaluate_ins_to_proto(ins: typing.EvaluateIns) -> ServerMessage.EvaluateIns: """Serialize flower.EvaluateIns to ProtoBuf message.""" parameters_proto = parameters_to_proto(ins.parameters) config_msg = metrics_to_proto(ins.config) return ServerMessage.EvaluateIns(parameters=parameters...
e7cbbf7d78f2ac37b6248d61fe7e797b151bba31
3,654,998
def avatar_synth_df(dir, batch_size, num_threads): """ Get data for training and evaluating the AvatarSynthModel. :param dir: The data directory. :param batch_size: The minibatch size. :param num_threads: The number of threads to read and process data. :return: A dataflow for parameter to bitm...
1fcecb5769d7c38c84bcd02cff8159381e113861
3,654,999