content
stringlengths
22
815k
id
int64
0
4.91M
def main_locust(): """ Performance test with locust: parse command line options and run commands. """ try: from ate import locusts except ImportError: print("Locust is not installed, exit.") exit(1) sys.argv[0] = 'locust' if len(sys.argv) == 1: sys.argv.extend(["...
32,500
def secret_delete( config, validate, repository, profile_name, secret_name ): """[sd] Delete secrets from multiple repositories providing a string delimited by commas ","\n Example: ghs secret-delete -p willy -r 'githubsecrets, serverless-template'""" # noqa: 501 profile = Profile(config, profile_name)...
32,501
def test_vuln_list_route(cl_operator): """vuln list route test""" response = cl_operator.get(url_for('storage.vuln_list_route')) assert response.status_code == HTTPStatus.OK
32,502
def load_html_file(file_dir): """ Uses BeautifulSoup to load an html """ with open(file_dir, 'rb') as fp: data = fp.read() if os.name == 'nt' or sys.version_info[0] == 3: data = data.decode(encoding='utf-8', errors='strict') data = re.sub(r'(\>)([ ]+)', lambda match: match.group(1) + ('!...
32,503
def read_single_keypress(): """Waits for a single keypress on stdin. This is a silly function to call if you need to do it a lot because it has to store stdin's current setup, setup stdin for reading single keystrokes then read the single keystroke then revert stdin back after reading the keystroke...
32,504
def reject(node_id, plugin): """Mark a given node_id as reject for future connections. """ print("Rejecting connections from {}".format(node_id)) plugin.reject_ids.append(node_id)
32,505
def set_table(table, fold_test, inner_number_folds, index_table, y_name): """ Set the table containing the data information Set the table by adding to each entry (patient) its start and end indexes in the concatenated data object. In fact each patients i is composed by `n_i` tiles so that for example patie...
32,506
def parse_args(): """ 引数パース """ argparser = ArgumentParser() argparser.add_argument( "-b", "--bucket-name", help="S3 bucket name", ) argparser.add_argument( "-d", "--days", type=int, help="Number of days", ) return argparser.par...
32,507
def main(): """ Re-construct the ALPHABET with the secret number offered by user. And encrypt the garbled message for the user to get the meaningful message. """ # user's secret number secret = int(input('Secret number: ')) # construct new alphabet system with the secret number new_alpha...
32,508
def predict(file): """ Returns values predicted """ x = load_img(file, target_size=(WIDTH, HEIGHT)) x = img_to_array(x) x = np.expand_dims(x, axis=0) array = NET.predict(x) result = array[0] answer = np.argmax(result) return CLASSES[answer], result
32,509
def sample_categorical(pmf): """Sample from a categorical distribution. Args: pmf: Probablity mass function. Output of a softmax over categories. Array of shape [batch_size, number of categories]. Rows sum to 1. Returns: idxs: Array of size [batch_size, 1]. Integer of category sa...
32,510
def make_Dex_3D(dL, shape, bloch_x=0.0): """ Forward derivative in x """ Nx, Ny , Nz= shape phasor_x = np.exp(1j * bloch_x) Dex = sp.diags([-1, 1, phasor_x], [0, Nz*Ny, -Nx*Ny*Nz+Nz*Ny], shape=(Nx*Ny*Nz, Nx*Ny*Nz)) Dex = 1 / dL * sp.kron(sp.eye(1),Dex) return Dex
32,511
def test_2d_array_support(): """ Test with 2d array """ result = variance_thresholding( [[1, 6, 0, 5], [1, 2, 4, 5], [1, 7, 8, 5]] ) assert np.array_equal(result, [1, 2])
32,512
def feature_decoder(proto_bytes): """Deserializes the ``ProtoFeature`` bytes into Python. Args: proto_bytes (bytes): The ProtoBuf encoded bytes of the ProtoBuf class. Returns: :class:`~geopyspark.vector_pipe.Feature` """ pb_feature = ProtoFeature.FromString(proto_bytes) retur...
32,513
async def calculate_board_fitness_report( board: list, zone_height: int, zone_length: int ) -> tuple: """Calculate Board Fitness Report This function uses the general solver functions api to calculate and return all the different collisions on a given board array representation. Args: boa...
32,514
def del_record(conn, hosted_zone_id, name, type, values, ttl=600, identifier=None, weight=None, comment=""): """Delete a record from a zone: name, type, ttl, identifier, and weight must match.""" _add_del(conn, hosted_zone_id, "DELETE", name, type, identifier, weight, values, ttl, co...
32,515
def quote_fqident(s): """Quote fully qualified SQL identifier. The '.' is taken as namespace separator and all parts are quoted separately Example: >>> quote_fqident('tbl') 'public.tbl' >>> quote_fqident('Baz.Foo.Bar') '"Baz"."Foo.Bar"' """ tmp = s.split('.', 1) if len(tmp)...
32,516
def export_model(save_path, output_file, gc_metadata=None): """ Export the variables from a TF v1 or v2 model to a given output folder and optionally validate them against a given json metadata file. """ meta_file = save_path + ".meta" pb_file = os.path.join(save_path, "saved_model.pb") pbtxt_file = os.path...
32,517
def row_generator(x, H, W, C): """Returns a single entry in the generated dataset. Return a bunch of random values as an example.""" return {'frame_id': x, 'frame_data': np.random.randint(0, 10, dtype=np.uint8, size=(H, W, C))}
32,518
def find(ctx, acronyms, tags): """Searches for acronyms.""" lookups = LookupAggregate(LookupFactory.from_config(ctx.obj)) lookups.request(acronyms) if tags: lookups.filter_tags(tags) lookups.show_results()
32,519
def update_mac_to_name_entries(): """Updates the mac_to_name table with new entries from the log """ _logger.debug("Updating mac_to_name table") connection = get_saib_connection().cursor() try: with connection.cursor() as cursor: sql = ''' INSERT INTO mac_to_name ...
32,520
def accuracy(output, target, topk=(1,)): """Computes the precor@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: ...
32,521
def define_model(input_shape, output_shape, FLAGS): """ Define the model along with the TensorBoard summaries """ data_format = "channels_last" concat_axis = -1 n_cl_out = 1 # Number of output classes dropout = 0.2 # Percentage of dropout for network layers num_datapoints = input_sh...
32,522
def test_has_version(module): """Test has_version function.""" assert imported.has_version(module)
32,523
def group_files(config_files, group_regex, group_alias="\\1"): """group input files by regular expression""" rx = re.compile(group_regex) for key, files in list(config_files.items()): if isinstance(files, list): groups = collections.defaultdict(list) unmatched = [] ...
32,524
def integration_test( name, srcs, deps = [], defs = [], native_srcs = [], main_class = None, enable_gwt = False, gwt_deps = [], closure_defines = dict(), disable_uncompiled_test = False, disable_compiled_test = False, suppre...
32,525
def get_current_icmp_seq(): """See help(scapy.arch.windows.native) for more information. Returns the current ICMP seq number.""" return GetIcmpStatistics()['stats']['icmpOutStats']['dwEchos']
32,526
def text_mocked_request(data: str, **kwargs) -> web.Request: """For testng purposes.""" return mocked_request(data.encode(), content_type="text/plain", **kwargs)
32,527
def doCVSUpdate(topDir, root, outDir): """ do a CVS update of the repository named root. topDir is the full path to the directory containing root. outDir is the full path to the directory where we will store the CVS output """ os.chdir(topDir) print "cvs update %s" % (root) os.system("cv...
32,528
def get_imu_data(): """Returns a 2d array containing the following * ``senses[0] = accel[x, y, z]`` for accelerometer data * ``senses[1] = gyro[x, y, z]`` for gyroscope data * ``senses[2] = mag[x, y, z]`` for magnetometer data .. note:: Not all data may be aggregated depending on the IMU device co...
32,529
def is_numeric_dtype(arr_or_dtype: List[Literal["d", "a", "b", "c"]]): """ usage.seaborn: 1 """ ...
32,530
def test_documents_post_error1(flask_client, user8, dev_app): """User should be given error if no title providing when adding a new item.""" access_token = api.create_token(user8, dev_app.client_id) response = flask_client.post( "/api/documents", headers={"authorization": "Bearer " + access_token}, ...
32,531
def loads(self, serializer, data): """ Unserializes (loads) converting and loading the given data into the current object. :type serializer: Serializer :param serializer: The serializer object to be used to unserialize the given data. :rtype: String :return: The serialized data...
32,532
def parse_proc_diskstats(proc_diskstats_contents): # type: (six.text_type) -> List[Sample] """ Parse /proc/net/dev contents into a list of samples. """ return_me = [] # type: List[Sample] for line in proc_diskstats_contents.splitlines(): match = PROC_DISKSTATS_RE.match(line) if ...
32,533
def test_pivot_with_sphere_fit(): """Tests pivot calibration with sphere fitting""" config = {"method" : "sphere_fitting"} file_names = glob('tests/data/PivotCalibration/*') arrays = [np.loadtxt(f) for f in file_names] matrices = np.concatenate(arrays) number_of_matrices = int(matrices.size/16) ...
32,534
def test_kwargs_unique(rotation): """ return_index and return_inverse edge cases""" rotation.unique(return_index=True, return_inverse=True) rotation.unique(return_index=True, return_inverse=False) rotation.unique(return_index=False, return_inverse=True)
32,535
def normalize(x): """Normalize a vector or a set of vectors. Arguments: * x: a 1D array (vector) or a 2D array, where each row is a vector. Returns: * y: normalized copies of the original vector(s). """ if x.ndim == 1: return x / np.sqrt(np.sum(x ** 2)) eli...
32,536
def compute_perrakis_estimate(marginal_sample, lnlikefunc, lnpriorfunc, lnlikeargs=(), lnpriorargs=(), densityestimation='histogram', **kwargs): """ Computes the Perrakis estimate of the bayesian evidence. The estimation is based on n marginal pos...
32,537
def update_configuration_set_event_destination(ConfigurationSetName=None, EventDestinationName=None, EventDestination=None): """ Update the configuration of an event destination for a configuration set. In Amazon Pinpoint, events include message sends, deliveries, opens, clicks, bounces, and complaints. Eve...
32,538
def main(): """ ALGORITHM : find out the index of the ciphered string, and convert into the deciphered index! """ rule = int(input('Secret number: ')) code = str(input('What\'s the ciphered string?')) ans = decipher(rule, code) print('The deciphered string is: ' + ans)
32,539
def extract_features(extractor, loader, device, feature_transform=None): """Iterable that extracts features from images and optionally transforms them""" for batch_idx, data in enumerate(loader): with torch.no_grad(): data = data.to(device).float() features = extractor(data)...
32,540
def postNewProfile(profile : Profile): """Gets all profile details of user with given profile_email Parameters: str: profile_email Returns: Json with Profile details """ profile_email = profile.email profile_query = collection.find({"email":profile_email}) profile...
32,541
def store_incidents_for_mapping(incidents, integration_context): """ Stores ready incidents in integration context to allow the mapping to pull the incidents from the instance. We store at most 20 incidents. Args: incidents (list): The incidents integration_context (dict): The integration c...
32,542
def main(is_semi_supervised, trial_num): """EM for Gaussian Mixture Models (unsupervised and semi-supervised)""" print('Running {} EM algorithm...'.format('semi-supervised' if is_semi_supervised else 'unsupervised')) # Load dataset train_path = os.path.join('.', 'train.csv') x_all, z_all = load_gmm...
32,543
def buy(): """Buy shares of stock.""" # if user reached route via POST (as by submitting a form via POST) if request.method == "POST": # ensure SYMBOL and Share is submitted if request.form.get("symbol") == "" or request.form.get("share") == "": return apology("Please Enter SYM...
32,544
def get_templates() -> List[dict]: """ Gets a list of Templates that the active client can access """ client = get_active_notification_client() if not client: raise NotificationClientNotFound() r = _get_templates(client=client) return r
32,545
def svn_mergeinfo_intersect2(*args): """ svn_mergeinfo_intersect2(svn_mergeinfo_t mergeinfo1, svn_mergeinfo_t mergeinfo2, svn_boolean_t consider_inheritance, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _core.svn_mergeinfo_intersect2(*args)
32,546
def credit(args): """ credit 自动访友获取信用点 """ CreditSolver().run()
32,547
def _update_images(): """Update all docker images in this list, running a few in parallel.""" any_new = False def comment(name, new): nonlocal any_new if new: log.info(f"Downloaded new Docker image for {name} - {docker.image_size(name)}") else: log.debug(f"...
32,548
def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)): """ Performs back propagation over a convolutional layer of a neural network dZ is a numpy.ndarray of shape (m, h_new, w_new, c_new) containing the partial derivatives with respect to the unactivated output of the convolutional lay...
32,549
def clone(repo, user, site, parent=None): """ Clone a repo from the requested site and user. :param repo: The name of the repo. :param user: The name of the user. :param site: The site to download from. :param parent: The parent folder where the repo will be cloned. By default, this...
32,550
def print_board(board): """ This will print the whole sudoku board :param board: The actual board :return: print the board """ # len(board) = 9 # this prints the horizontal line after every three rows for i in range(len(board)): if i % 3 == 0 and i != 0: p...
32,551
def get_final_text(pred_text, orig_text, do_lower_case): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the sp...
32,552
def test_pushing(reference, summary, numbers): """ Проверка добавления элементов """ m = MovingAverage(window=4) for ref, summ, number in zip(reference, summary, numbers): m.push(number) assert approx(m.avg) == ref assert approx(m.sum) == summ
32,553
def _test_montage_trans(raw, montage, pos_test, space='fsaverage', coord_frame='auto', unit='auto'): """Test if a montage is transformed correctly.""" _set_montage_no_trans(raw, montage) trans = template_to_head( raw.info, space, coord_frame=coord_frame, unit=unit)[1] mon...
32,554
def createContext(data, id=None, keyTransform=None, removeNull=False): """Receives a dict with flattened key values, and converts them into nested dicts :type data: ``dict`` or ``list`` :param data: The data to be added to the context (required) :type id: ``str`` :keyword id: The I...
32,555
def default_xonshrc(env) -> "tuple[str, ...]": """ ``['$XONSH_SYS_CONFIG_DIR/xonshrc', '$XONSH_CONFIG_DIR/xonsh/rc.xsh', '~/.xonshrc']`` """ dxrc = ( os.path.join(xonsh_sys_config_dir(env), "xonshrc"), os.path.join(xonsh_config_dir(env), "rc.xsh"), os.path.expanduser("~/.xonshrc...
32,556
def move_existing_application(): """Check if the sidewalk-webpage directory exists already. If so, change the name of the directory""" print "Checking if the directory `sidewalk-webpage` already exists" command = "ls %s" % sidewalk_git_directory p = subprocess.Popen(command.split(), stdout=subprocess.PI...
32,557
def haversine(phi1, lambda1, phi2, lambda2): """ calculate angular great circle distance with haversine formula see parameters in spherical_law_of_cosines """ d_phi = phi2 - phi1 d_lambda = lambda2 - lambda1 a = math.pow(math.sin(d_phi / 2), 2) + \ math.cos(phi1) * math.cos(phi2) * m...
32,558
def get_backup_start_timestamp(bag_name): """ Input: Fisrt bag name Output: datatime object """ info_dict = yaml.load(Bag(bag_name, 'r')._get_yaml_info()) start_timestamp = info_dict.get("start", None) start_datetime = None if start_timestamp is None: print("No start time info in...
32,559
def ResidualSlopesSequence2ResidualPhase(Gradients,S2M,M2V,name='residual_phase_cube.fits',\ path='.',binning=40): """ Same functions as ResidualSlopes2ResidualPhase but applies it to a sequence of slopes (gradients) instead of a single vector. Input: - Gradients: a seque...
32,560
def get_mask_areas(masks: np.ndarray) -> np.ndarray: """Get mask areas from the compressed mask map.""" # 0 for background ann_ids = np.sort(np.unique(masks))[1:] areas = np.zeros((len(ann_ids))) for i, ann_id in enumerate(ann_ids): areas[i] = np.count_nonzero(ann_id == masks) return are...
32,561
def s3_analysis(conc=None): """ Long running job where more information is collected. Use S3 get_object_list_v2 to get a list of the objects """ bucket_stats = s3_bucket_stats() update_s3_gauges(bucket_stats) commit_s3_gauges()
32,562
def run(agent, root_dir, restore_ckpt): """Main entrypoint for running and generating visualizations. Args: agent: str, agent type to use. root_dir: str, root directory where files will be stored. restore_ckpt: str, path to the checkpoint to reload. """ tf.compat.v1.reset_default_graph() config =...
32,563
def cursor_from_image(image): """ Take a valid cursor image and create a mouse cursor. """ colors = {(0,0,0,255) : "X", (255,255,255,255) : "."} rect = image.get_rect() icon_string = [] for j in range(rect.height): this_row = [] for i in range(rect.width): ...
32,564
def h_matrix(jac, p, lamb, method='kotre', W=None): """ JAC method of dynamic EIT solver: H = (J.T*J + lamb*R)^(-1) * J.T Parameters ---------- jac: NDArray Jacobian p, lamb: float regularization parameters method: str, optional regularization method Ret...
32,565
def _get_flavors_metadata_ui_converters_from_configuration(): """Get flavor metadata ui converters from flavor mapping config dir.""" flavors_metadata_ui_converters = {} configs = util.load_configs(setting.FLAVOR_MAPPING_DIR) for config in configs: adapter_name = config['ADAPTER'] flavor...
32,566
def outermost_scope_from_subgraph(graph, subgraph, scope_dict=None): """ Returns the outermost scope of a subgraph. If the subgraph is not connected, there might be several scopes that are locally outermost. In this case, it throws an Exception. """ if scope_dict is None: scope_dict...
32,567
def calc_entropy_ew(molecule, temp): """ Expoential well entropy :param molecule: :param temp: :param a: :param k: :return: """ mass = molecule.mass / Constants.amu_to_kg * Constants.amu_to_au a = molecule.ew_a_inv_ang * Constants.inverse_ang_inverse_au k = molecule.ew_k_kca...
32,568
def registerCreatorDataCallbackURL(): """ params: creatorID dataCallbackURL """ try: global rmlEngine rawRequest = request.POST.dict for rawKey in rawRequest.keys(): keyVal = rawKey jsonPayload = json.loads(keyVal) ...
32,569
def csm(A, B): """ Calculate Cosine similarity measure of distance between two vectors `A` and `B`. Parameters ----------- A : ndarray First vector containing values B : ndarray Second vector containing values Returns -------- float d...
32,570
def RationalsModP(p): """Assume p is a prime.""" class RationalModP(_Modular): """A rational modulo p The rational is stored with numerator and denominator relatively prime. This is done to prevent growth in numerator or denominator which causes overflow and makes math harder. """ de...
32,571
def pytest_sessionfinish(session, exitstatus): """Remove data generated for the tests.""" print("\nRemoving datasets generated for the test session.") for file in FILES_TO_GENERATE: file_path = os.path.join(DATA_PATH, file) if os.path.exists(file_path): os.remove(file_path)
32,572
def rand_email(): """Random email. Usage Example:: >>> rand_email() Z4Lljcbdw7m@npa.net """ name = random.choice(string.ascii_letters) + \ rand_str(string.ascii_letters + string.digits, random.randint(4, 14)) domain = rand_str(string.ascii_lowercase, random.randint(2, ...
32,573
def __parse_quic_timing_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame: """ Parse the quic timing results in the given scenario. :param in_dir: The directory containing all measurement results :param scenario_name: The name of the scenario to parse :param pep: Whet...
32,574
async def value_to_deep_structure(value, hash_pattern): """build deep structure from value""" try: objects = {} deep_structure0 = _value_to_objects( value, hash_pattern, objects ) except (TypeError, ValueError): raise DeepStructureError(hash_pattern, value) from N...
32,575
def get_users_run(jobs, d_from, target, d_to='', use_unit='cpu', serialize_running=''): """Takes a DataFrame full of job information and returns usage for each "user" uniquely based on specified unit. This function operates as a stepping stone for plotting usage figures and return...
32,576
def get_classes_constants(paths): """ Extract the vtk class names and constants from the path. :param paths: The path(s) to the Python file(s). :return: The file name, the VTK classes and any VTK constants. """ res = collections.defaultdict(set) for path in paths: content = path.re...
32,577
def predict_unfolding_at_temperature(temp, data, PDB_files): """ Function to predict lables for all trajectoires at a given temperature Note: The assumption is that at a given temperature, all snapshots are at the same times Filter should be 'First commit' or 'Last commit' or 'Filter osc' as descri...
32,578
def test_agricrop(): """ https://smart-data-models.github.io/dataModel.Agrifood/AgriCrop/examples/example-normalized.jsonld """ e = Entity( "AgriCrop", "AgriCrop:df72dc57-1eb9-42a3-88a9-8647ecc954b4", ctx=[ "https://smartdatamodels.org/context.jsonld", "ht...
32,579
def _frac_scorer(matched_hs_ions_df, all_hyp_ions_df, N_spectra): """Fraction ion observed scorer. Provides a score based off of the fraction of hypothetical ions that were observed for a given hypothetical structure. Parameters ---------- matched_hs_ions_df : pd.DataFrame Dataframe of...
32,580
def animation_import_button(self, context: Context): """Targets animation importer class on menu button press. Args: self (): A reference to this bpy dynamic draw function. context (Context): The context containing data for the current 3d view. """ self.layout.operator(CalAnimationImpor...
32,581
def role_in(roles_allowed): """ A permission checker that checks that a role possessed by the user matches one of the role_in list """ def _check_with_authuser(authuser): return any(r in authuser.roles for r in roles_allowed) return _check_with_authuser
32,582
def elements_for_model(model: Model) -> List[str]: """Creates a list of elements to expect to register. Args: model: The model to create a list for. """ def increment(index: List[int], dims: List[int]) -> None: # assumes index and dims are the same length > 0 # modifies index ar...
32,583
def form_IntegerNoneDefault(request): """ An integer field defaulting to None """ schema = schemaish.Structure() schema.add('myIntegerField', schemaish.Integer()) form = formish.Form(schema, 'form') form.defaults = {'myIntegerField':None} return form
32,584
def tree_checkout(repo, tree, path): """Recursively instantiates a tree during checkout into a empty directory""" for item in tree.items: obj = object_read(repo, item.sha) rootPath = os.path.realpath(os.path.join(repo.vcsdir, '../')) relativePath = item.path.decode().replace(rootPat...
32,585
def tokenize(text, stopwords): """Tokenizes and removes stopwords from the document""" without_punctuations = text.translate(str.maketrans('', '', string.punctuation)) tokens = word_tokenize(without_punctuations) filtered = [w.lower() for w in tokens if not w in stopwords] return filtered
32,586
def add_subscription_handler(args: argparse.Namespace) -> None: """ Handler for "groups subscription add" subcommand. """ new_subscription_id = 0 params = {"type": "subscription_type"} try: # resolve index try: resources: BugoutResources = bc.list_resources...
32,587
def to_dict(prim: Primitive) -> ObjectData: """Convert a primitive to a dictionary for serialization.""" val: BasePrimitive = prim.value data: ObjectData = { "name": val.name, "size": val.size, "signed": val.signed, "integer": prim in INTEGER_PRIMITIVES, } if val.min...
32,588
def setup_testing_all_data(): """ Function to initialize truffe data for testing """ admin_user = setup_testing_users_units() setup_testing_main(admin_user) setup_testing_vehicles(admin_user) setup_testing_logistics() setup_testing_communication() setup_testing_notifications(admin_us...
32,589
def sarif_result_to_cso_warning(state, version, result): """Report a CodeSonar warning The specific warning report will depend on the contents of the sarif result as follows: The locations list is expected to be a singleton. This will form the endbox of the CodeSonar warning. If the list of r...
32,590
def sync_remote_catalogs(*args, **kwargs): """Synchroniser les catalogues distants.""" for RemoteCatalog in RemoteCatalogs: for remote in RemoteCatalog.objects.filter(**kwargs): logger.info("Start synchronize remote instance %s %d (%s)" % ( remote.__class__.__qualname__, rem...
32,591
def plotFitSize(logbook, fitness="min", size="avg"): """ Values for fitness and size: "min" plots the minimum "max" plots the maximum "avg" plots the average "std" plots the standard deviation """ gen = logbook.select("gen") fit_mins = logbook.chapters["fitness"].select(fit...
32,592
def get_raw_img(url): """ Download input image from url. """ pic = False response = requests.get(url, stream=True) with open('./imgs/img.png', 'wb') as file: for chunk in response.iter_content(): file.write(chunk) pic = True response.close() return pic
32,593
def set_layer(context, request): """Set the calendar layer on the request, so the resources are rendered.""" zope.interface.alsoProvides( request, icemac.ab.calendar.browser.interfaces.ICalendarLayer)
32,594
def get_and_validate_study_id(chunked_download=False): """ Checks for a valid study object id or primary key. If neither is given, a 400 (bad request) error is raised. Study object id malformed (not 24 characters) causes 400 error. Study object id otherwise invalid causes 400 error. Study ...
32,595
def flirt_registration(input_file, output_file, matrix_file, ref_file, verbose=False): """Registration to MNI template using FSL-FLIRT Ubuntu: Create link for flirt sudo ln -s /usr/bin/fsl5.0-flirt /usr/bin/flir...
32,596
async def multiple_database_queries(r, w, c): """ Test type 3: Multiple database queries """ num_queries = get_num_queries(r._scope) row_ids = [randint(1, 10000) for _ in range(num_queries)] worlds = [] connection = await pool.acquire() try: statement = await connection.prepare(...
32,597
def tokenize_char(pinyin: str) -> tuple[str, str, int] | None: """ Given a string containing the pinyin representation of a Chinese character, return a 3-tuple containing its initial (``str``), final (``str``), and tone (``int; [0-4]``), or ``None`` if it cannot be properly tokenized. """ import re ...
32,598
def test_task_relation_hash_func(pre_code, post_code, expect): """Test TaskRelation magic function :func:`__hash__`.""" task_param = TaskRelation(pre_task_code=pre_code, post_task_code=post_code) assert hash(task_param) == expect
32,599