content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def cmd_openfile(pid,abs_filename,line_no=1,column_no=1): """ファイルをコンパイルする abs_filename - ファイル名の絶対パス (Ex.) c:/project/my_app/src/main.cpp """ dte = get_dte_obj(pid) if not dte: _vs_msg("Not found process") return False abs_filename = _to_unicode(a...
0ca1e0c26fe12677c3c4b3ff73eafdf6ea11485e
3,627,700
def optimize(s, probability, loBound, hiBound): """ Optimiere auf die max. mögliche Entnahme bei einer vorgegebenen Fehlerquote Returns: widthdrawal: max. mögliche prozentuale Entnahme """ n_ret_months = s.simulation['n_ret_years'] * 12 accuracy = 0.01 # Genauigkeit der Optimierung ...
0c572b885f5803d832b1ff1bde0e4013895b4665
3,627,701
from typing import Tuple import torch def torch_data_loader( features: np.ndarray, labels: np.ndarray, batch_size: int, shuffle: bool = None, num_workers: int = 0 ) -> Tuple[torch.utils.data.DataLoader]: """ Creates the data loader for the train and test dataset. Parameters ------...
4891a486f980714d8500c246e022c1412f27e563
3,627,702
def delete_row_col(np_arr, row, col): """Removes the specified row and col from a Numpy array. A new np array is returned, so this does not affect the input array.""" return np.delete(np.delete(np_arr, row, 0), col, 1)
bcdb55aa78d676861ed820a550a85ad0c24bbe76
3,627,703
def make_3d(adata, time_var='Metadata_Time', tree_var='Metadata_Trace_Tree', use_rep=None, n_pcs=50): """Return three dimensional representation of data. Args: time_var (str): Variable in .obs with timesteps tree_var (str): Variable in .obs with t...
01abf024914bcb12a2f02f542cc4c406e461fe79
3,627,704
import re def _natural_key(x): """ Splits a string into characters and digits. This helps in sorting file names in a 'natural' way. """ return [int(c) if c.isdigit() else c.lower() for c in re.split("(\d+)", x)]
1fab7dffb9765b20f77ab759e43a23325b4441f4
3,627,705
def get_location_1(box_2d, dimension, rotation_x, rotation_y, rotation_z, proj_matrix): """ 方法1 2Dbbox中心与3Dbbox中心重合 只存在一个中心点间的对应关系。难以约束。 若是将Z的值替换成真实值,效果还行。Z方向的值与XY相比差距太大。 """ R = get_R(rotation_x, rotation_y) # format 2d corners xmin = box_2d[0] ymin = box_2d[1] xmax = box_2d[2]...
54b575ec603de0c65d57b6e07ef62d56b3f12ee2
3,627,706
import os def find_file(directory: str, search_file: str) -> str: """Finds relative path of file in given directory and its subdirectories. Args: directory (str): Directory to search in. search_file (str): File to search in directory. Returns: str: Path to file. """ pat...
4f272ab643d8b271d01cd38041e1e003e3171224
3,627,707
def get_smoothing_kernel(x, y, smoothing_length): """ x = x - xj, y = y - yj""" r_xy_2 = x + y q_xy_2 = r_xy_2 / smoothing_length return get_dimensionless_2D_kernel(q_xy_2)
183087724d2c3a921e64a65a00f2ec5c783ceb40
3,627,708
def evolve_population(population: list, generation: int) -> list: """ This evolves an existing population by doubling them (binary fission), then introducing random mutation to each member of the population. :param generation: Helps determine the starting point of the numbering system so the bacteria ha...
e631864de0c25857ffcb4dff0504dac63ee49aab
3,627,709
def create_siamese_trainer( model, optimizer, loss_fn, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform=output_transform_trainer, ): """Factory function for creating an ignite trainer Engine for a siamese architecture. Args: model: siamese networ...
5a81b6d58f824dff857ce662505c3896c4af9a66
3,627,710
import json def handle_methods( request, GET=None, POST=None, PUT=None, PATCH=None, DELETE=None, args=[], kwargs={}, ): """ REST Method Handler. Return the view handleMethods(request) Add all allowed methods with their responses. These can either be a Django HttpRespon...
ee87a12959c32a42ca39b231c6e3956050b427b3
3,627,711
def compute_bounding_box(points, convex_hull=None, given_angles=None, max_error=None): """ Computes the minimum area oriented bounding box of a set of points. Parameters ---------- points : (Mx2) array The coordinates of the points. convex_hull : scipy.spatial.C...
0c77963ed739431f1e0a02125a3703a76a26866f
3,627,712
import argparse from typing import Tuple from typing import List import re import sys def parse_outputs_from_args(args: argparse.Namespace) -> Tuple[List[str], List[int]]: """Get a list of outputs specified in the args.""" name_and_port = [output.split(':') for output in re.split(', |,', args.output_layers)] ...
25fe89ed77b44344bad945bf91a2024f3753cd49
3,627,713
def n_pitches_used(tensor): """Return the number of unique pitches used per bar.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") return tf.reduce_mean(tf.reduce_sum(tf.count_nonzero(tensor, 3), 2), [0, 1])
0ad75015c4333e2a981d3cd344d6a279a98d9392
3,627,714
from datetime import datetime def survey(): """Survey home page.""" N_SIMULATION_PERIODS = get_n_periods() db = get_db() user_data = db.execute( "SELECT * FROM user WHERE id = ?", (session["user_id"],) ).fetchone() user_stage = user_data['current_stage'] simulation_period =...
8a839041bbb4cc8b5e2c0ecb2e5a09395552bf8a
3,627,715
import struct def ReadXTrace(trace_filename): """ Returns the trace for this XTrace dataset. @param trace_filename: location of file to read into XTrace object """ # maximum size for strings max_bytes = 32 max_function_bytes = 64 # open the file with open(trace_filename, 'rb') as ...
9ce8271e9f45463721582939ea54a63a25e2e9ac
3,627,716
import pandas as pd import numpy as np import mydatapreprocessing as mdp def to_vue_plotly(data: np.ndarray | pd.DataFrame, names: list = None) -> dict: """Takes data (dataframe or numpy array) and transforms it to form, that vue-plotly understand. Links to vue-plotly: https://www.npmjs.com/package/vue-...
e29814b89550ae0247342607bea90ec263dbf72a
3,627,717
def get_model_name(file_path, sheet_name): """ Return the model name, which is assumed to be in the first row, second column of the sheet_name. Args: file_path: path to file containing the model sheet_name: sheet_name: name of the excel sheet where the model name is, should be 'general' ...
30cb673e87a6b71d76049434615a9b4396130125
3,627,718
def duplicate_ticket_view(request, uuid): """ Create duplicate of a given ticket (found by uuid) i The result is a new ticket, which has the same connection and validity_period Does not allow duplicating shared tickets. Does not allow to duplicate if you are not the author of ticket. """ t...
07cfd486d9812227686301f87d9317d65a51d82a
3,627,719
from typing import Tuple import math def _projected_velocities_from_cog(beta: float, cog_speed: float) -> Tuple[float, float]: """ Computes the projected velocities at the rear axle using the Bicycle kinematic model using COG data :param beta: [rad] the angle from rear axle to COG at instantaneous center ...
defbfa58d1e67b67ff4a118ebff03e62f4c1042c
3,627,720
from typing import List import math def prime_factors(a:int) -> List[int]: """ Returns the prime factors of a number. Parameters: a (int): the number to return the prime factors of Returns: (list[int]): an unsorted list of the prime factors of a """ # prime numbers only...
75b27331c8dbb9fd6ed03c97af841bc76ed6cd8f
3,627,721
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
8e339e6b5c3fca6f62fd38804465488297b93ad3
3,627,722
import json def get_sea_surface_height_trend_image(): """generate bathymetry image for a certain timespan (begin_date, end_date) and a dataset {jetski | vaklodingen | kustlidar}""" r = request.get_json() image = ee.Image('users/fbaart/ssh-trend-map') image = image.visualize(**{'bands': ['time'], 'mi...
89e23fdb458b8fbb3230f19ab8664e102ed215fb
3,627,723
def xy_to_rho(pt1, pt2): """convert two points of line into rho, theta form""" # find inverse of slope of line m, b = xy_to_mb(pt1, pt2) minv = -1 / m if m else None if m == 0 else 0 # find intersection point of line with line defined by rho, theta intersection = line_intersection(m, b, minv, 0...
b9ec3e3af6e734580a9ffd05a022e29e8e36d1eb
3,627,724
from numpy import meshgrid, arange, ones, zeros, sin, cos, sqrt, clip from scipy.special import jv as bessel from numpy.random import poisson as poisson def generate_image(image_parameters): """Generate image with particles. Input: image_parameters: list with the values of the image parameters in a d...
1ebb0b5fa200b5590769d5e09fdeef9d57bfcdcb
3,627,725
import numpy def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """Multidimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars Standard deviation for Gaussian kernel. The standard deviations ...
f9fdac5e8c3c38936db8f44731dd975ed8d78c12
3,627,726
def run_test(target_call, num_steps, strategy, batch_size=None, log_steps=100, num_steps_per_batch=1, iterator=None): """Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. nu...
f9e996198a0dee309f7a2e08505d0cc0e5778023
3,627,727
import tqdm import logging def remove_punctuation_from_text(data): """ Enriches a dataframe or Anytree structure containing "text" field with "clean text" field See utils.clean_text for more information Returns: [pd.DataFrame or dictionary] -- conversations with new clean text field """ if isinst...
1c76585b07c8865913aa3e0660b3bc59b9edf6a3
3,627,728
def querystring_parse(parameter_data): """Parse dictionary to querystring""" data = parameter_data return urlencode(data).replace("%2F","/")
41035637b5af123b6102c27df24f95bbfd030de2
3,627,729
def _deployment_rollback(deployment_id): """ :param deployment_id: the application id :type deployment_di: str :returns: process return code :rtype: int """ client = marathon.create_client() deployment = client.rollback_deployment(deployment_id) emitter.publish(deployment) retu...
37faad940a7f5a20b5e8d17c62920a9c9f781cd8
3,627,730
def find_regular_bin_edges_from_centers(centers): """ Finds bin (grid cell) edges from center positions. Assumes a regular grid. Inputs: centers = bin/grid center position vector of current grid, shape [nb] Returns: edges = edge positions of bins (grid), shape [nb+1] """ edges =...
c5a957209222b9b1d63ce1b6efa72b4abb3591b9
3,627,731
def postordereval(parseTree): """Compute the result inline with postorder""" ops = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv} if parseTree: evalLeft = postordereval(parseTree.getLeftChild()) evalRight = postordereval(parseTree.getRightChild()) if evalLeft and evalRight...
0192ddfb601192ac5ca37527e28da9655fde10ea
3,627,732
def non_max_suppression(boxes, scores, threshold, max_num): """Performs non-maximum suppression and returns indices of kept boxes. boxes: [N, (z1, y1, x1, z2, y2, x2)]. Notice that (z2, y2, x2) lays outside the box. scores: 1-D array of box scores. threshold: Float. IoU threshold to use for filtering. ...
5e0d166667f3f82f622ac4607b4235a4db06aab3
3,627,733
def mask2rle(img): """ - https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode img: numpy array, 1 -> mask, 0 -> background Returns run length as string formated """ pixels= img.T.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[...
e2f06ac4767e3af1a88cee0ac1ae7686487dece6
3,627,734
import os def fp(path): """Prepends SEIR_HOME to path and returns full path.""" return os.path.join(SEIR_HOME, path)
e085a9fdc54b891ffcfedb5ab614edd1148426c9
3,627,735
def rgb_to_hsv(color: np.ndarray) -> np.ndarray: """ Convert a color from the RGB colorspace to the HSV colorspace >>> rgb_to_hsv(np.array([10, 20, 30], np.uint8)) array([105, 170, 30]) Args: color: Color as numpy array. Can either have shape (X, Y, 3) if it is a whole image, (...
b44e443a215c080f9fa7a107686a400aa8ac3ea7
3,627,736
def plot_params(model): """Print parameters """ x0 = 0.05 y0 = 0.95 dy = 0.03 fig = plt.figure(1, figsize=(10, 10)) plt.subplots_adjust(left=0.1, top=0.95, bottom=0.05, right=0.95) ax_lab = fig.add_subplot(111) ax_lab.xaxis.set_visible(False) ax_lab.yaxis.set_visible(False) ...
58ae599ff0073c6c51ef2c4058f54646186b5d87
3,627,737
import torch def class_avg_chainthaw(model, nb_classes, loss_op, train, val, test, batch_size, epoch_size, nb_epochs, checkpoint_weight_path, f1_init_weight_path, patience=5, initial_lr=0.001, next_lr=0.0001, verbose=True): """ Finetunes give...
2aeb2f442fb648ac7bb9536b989e3a0ea2f77087
3,627,738
def quality_scrub(df, target_cols = ['quality_1', 'quality_2', 'quality_3']): """ Definition: Filters a dataframe where each target_col does not contain 'no_cough' Args: df: Required. A dataframe containing the target columns target_cols: default = ['quality_1', 'quality_2', 'quality_3']. Returns: Re...
1187278e008f1e4ec4688d3cf9a3d7a0c1a82dc0
3,627,739
def create_arrival_timer(model, name, descr = None): """Return a new timer that allows measuring the processing time of transacts.""" y = ArrivalTimerPort(model, name = name, descr = descr) code = 'newArrivalTimer' y.write(code) return y
276a439fb0152f66cf6cc420cb7599b83d1718f6
3,627,740
from typing import Dict from re import T import torch def get_default_transforms() -> Dict[T.Compose, T.Compose]: """augmentationを取得 Returns: Dict[T.Compose, T.Compose]: 学習用,検証用のaugmentation """ transform = { "train": T.Compose( [ T.RandomHorizontalFlip(), ...
5cbea521348a2bed215a2692eb9be7dea2af1b7e
3,627,741
import subprocess import os def simple_shell(args, stdout=False): """ Simple Subprocess Shell Helper Function """ if stdout: rc = subprocess.call(args, shell=False) else: rc = subprocess.call(args, shell=False, stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT) return rc
b922e35565a5da58cec153415b9112e560de6c73
3,627,742
def print_decorator(fct): """dento dekorator pouzivam, na to aby som dokazal testovat aj vypisy na standardny vystup""" original_fct = fct output = [] def wrapper(*args): output.append((args)) return original_fct(*args) return wrapper
4fa74cf9bf3653f89114cbdd6503ef13630a17e7
3,627,743
import logging def parse_testresults(xml, test_id, domain): """ Parse the given XML file and build mappings """ global_lookup = {} global_testresults = {} for event, element in etree.iterparse(xml, events=("start", "end")): try: global_id, global_title, global_fixtext = \ ...
f36923e8a17f0c9646fcde570a008b030eda464f
3,627,744
def remodel_matrix(matrix, new_fire_cells, moisture_matrix): """ matrix: Array of the fire spread area new_fire_cells: list of tuples, each tuple representing the x,y coordinates of a new cell that has been affected by the fire spread. """ for cell in new_fire_cells: x = int(cell[0]...
c24c8fae19e0a8bb884103191906e76af625430f
3,627,745
import re def getOffers(session, city): """ Parameters ---------- session : ikabot.web.session.Session city : dict Returns ------- offers : list[dict] """ html = getMarketHtml(session, city) hits = re.findall(r'short_text80">(.*?) *<br/>\((.*?)\)\s *</td>\s *<td>(\d+)</td>\s *<td>(.*?)/td>\s *<td><img src=...
bed8332cd501da9871ec2a9a576783bdc87340de
3,627,746
def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor): """ 给训练添加一个新的softmax和全连接层, 我们需要重新训练顶层来识别我们的新类,所以这个函数为graph添加了正确的操作 :param class_count: 多类的事物总数 :param final_tensor_name: 生成结果的新的最终节点的名称字符串。 :param bottleneck_tensor: 主CNN图的输出。 :return: The tensors for the training...
96d80fe0aded67684a4ed8534a9634995c4cad4e
3,627,747
def generate_northern_ireland_data(directory, file_date, records): """ generate northern ireland file. """ northern_ireland_data_description = lambda: { # noqa: E731 "UIC": _("random.custom_code", mask="############", digit="#"), "Sample": _("random.custom_code", mask="#&&&", digit="#",...
b74bb5d25b401a3695276f49bbddfb08ed025d26
3,627,748
def create_message(address, subject, message_text, html=True, attachments=None): """Create a message for an email, using the low-level API. Arguments: address (str): Email address(es) of the receiver. subject (str): The subject of the email message. message_text (str): The text of the e...
9e1638e2940ef133dfb185e2bf54002cfb25f9e4
3,627,749
import logging def whole_appendix(xml, cfr_part, letter): """Attempt to parse an appendix. Used when the entire appendix has been replaced/added or when we can use the section headers to determine our place. If the format isn't what we expect, display a warning.""" xml = deepcopy(xml) hds = xml.xp...
b1e757ae292d299096abde80c74354093c1d6684
3,627,750
import collections def read_image_files(image_files,image_shape=None, crop=None, label_indices=None): """ :param image_files: :param image_shape: :param crop: :param use_nearest_for_last_file: If True, will use nearest neighbor interpolation for the last file. This is used because the last ...
0e01d5a47786154cde030b7cd252154a183c7358
3,627,751
import traceback def wrap_unexpected_exceptions(f, execute_if_error=None): """A decorator that catches all exceptions from the function f and alerts the user about them. Self can be any object with a "logger" attribute and a "ipython_display" attribute. All exceptions are logged as "unexpected" exceptions...
d2f37ff0c8a1dac6cbab1fe8e8c6598de0ab059a
3,627,752
def store_topology(topology_file_string: str, fileformat="pdbx"): """Store a file (containing topology, such as pdbx) in a topology XML block.""" root = etree.fromstring(f'<TopologyFile format="{fileformat}"/>') root.text = topology_file_string return root
ed9b2b27cda4a31fcd04a920ce4d344b268bf012
3,627,753
def zeros_like(tab): """ Wrapper to numpy.zeros_like, force order to hysop.constants.ORDER """ return np.zeros_like(tab, dtype=tab.dtype, order=ORDER)
ab089b5003ce07ef8bc9a6ac4b027a974833a04b
3,627,754
def get_bert_embeddings(input_ids, bert_config, input_mask=None, token_type_ids=None, is_training=False, use_one_hot_embeddings=False, scope=None): """Returns embeddings for ...
8dc60142ded4951e9ae69f02f8eb928c3f6c0b2a
3,627,755
import time def blind_deconvolution_multiple_subjects( X, t_r, hrf_rois, hrf_model='scaled_hrf', shared_spatial_maps=False, deactivate_v_learning=False, deactivate_z_learning=False, deactivate_u_learning=False, n_atoms=10, n_times_atom=60, prox_z='tv', lbda_strategy='ratio', lbda=0.1, ...
a4fa4eabe035c792fdd1a3b75600a443e9f73058
3,627,756
def _TestRemovePhotos(tester, user_cookie, request_dict): """Called by the ServiceTester in order to test remove_photos service API call.""" validator = tester.validator user_id, device_id = tester.GetIdsFromCookie(user_cookie) request_dict = deepcopy(request_dict) user = validator.GetModelObject(User, user_i...
d71619608435bc763d8902856ce39585f62dd320
3,627,757
import csv def get_author_book_publisher_data(filepath): """ This function gets the data from the csv file """ with open(filepath) as csvfile: csv_reader = csv.DictReader(csvfile) data = [row for row in csv_reader] return data
5d095b20e2e32aacbe4d85efd80461abfa175127
3,627,758
from typing import Optional async def update_workflow_revision( # pylint: disable=W0622 id: UUID, updated_workflow_dto: WorkflowRevisionFrontendDto, ) -> WorkflowRevisionFrontendDto: """Update or store a transformation revision of type workflow in the data base. If no DB entry with the provided i...
888fa1edd72232c0300cf02b194330e4d9dbfaea
3,627,759
def tf_repeat(tensor, repeats): """ Args: input: A Tensor. 1-D or higher. repeats: A list. Number of repeat for each dimension, length must be the same as the number of dimensions in input Returns: A Tensor. Has the same type as input. Has the shape of tensor.shape * repeats """ expande...
5a9022d427caed7ad645c7ede8142851c1d0af88
3,627,760
def apply_slim_collections(cost): """ Add the cost with the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. Args: cost: a scalar tensor Return: a scalar tensor, the cost after applying the collections. """ regulization_losses = set(tf.get_collection(tf.GraphKeys.REGULAR...
7182995a31c3daa6b33bb8be28ec3a1b2a98e7d6
3,627,761
import re def isGoodResult(name, show, log=True, season=-1): """ Use an automatically-created regex to make sure the result actually is the show it claims to be """ all_show_names = allPossibleShowNames(show,season=season) showNames = map(sanitizeSceneName, all_show_names) + all_show_names f...
c29ff6dbb829553d546d9f80975b3eb6c355fa6d
3,627,762
import six import itertools def get_configuration(configuration_schema, command_line_options=None, environment_variables=None, config_content=None, django_settings=None): """Get configuration from all sources. Notes: ...
88a363d474ba3eebace2ebb2085572850345240b
3,627,763
from typing import Tuple def convert_descriptor_to_type(desc: str) -> Tuple[str, int]: """ Converts a java descriptor to the java type, in the inverse of convert_descriptor_to_type() Returns the type, and the number of array levels (e.g. [[Z would return ('boolean', 2), not 'boolean[][]' Optionally will r...
6f5aaa164636c0e99472c56b212b3a586939f62a
3,627,764
import pandas def _normalize_similarity(df: pandas.DataFrame) -> None: """Normalizes similarity by combining cls and transformation.""" df["params.similarity"] = (df["params.similarity.cls"] + "_" + df["params.similarity.transformation"]) # transformation only active if similarity in {l1, 2} unused_t...
048c1a7107cf61c20ebc7d2e10214c434898466e
3,627,765
def density_bounds(density, wi, vo=.49, ve=.5, dt=.1, exact=False): """THIS IS A BOUND, NOT THE ACTUAL VELOCITY. Min density bound for nnovation front as derived from MFT and compared with simulation results. Depends on ob...
548e06e8b4a148c5ca1ffd95ce1cfcfb51183773
3,627,766
def process_instructions(instructions): """Process instructions in order, starting from line 0""" line = 0 instructions_executed = set() accumulator = 0 while line not in instructions_executed: try: instruction = instructions[line] except IndexError: print(f'E...
4c2278b03db2ddb0ca3292f591509d82b2e8f361
3,627,767
from typing import List def check_absence_of_skip_series( movement: int, past_movements: List[int], max_n_skips: int = 2, **kwargs ) -> bool: """ Check that there are no long series of skips. :param movement: melodic interval (in scale degrees) for line continuatio...
94ff2f3e03956d5bea1173182e389a3e6bb4b487
3,627,768
import glob import os def get_preview_images_by_rootname(rootname): """Return a list of preview images available in the filesystem for the given ``rootname``. Parameters ---------- rootname : str The rootname of interest (e.g. ``jw86600008001_02101_00007_guider2``). Returns -----...
cf615abde2f09251e0b9e2ab5e89347994f9c29f
3,627,769
def get_discharge_measurements(sites=None, start=None, end=None, **kwargs): """ Get discharge measurements from the waterdata service. Parameters (Additional parameters, if supplied, will be used as query parameters) ---------- sites: array of strings If the qwdata parameter site_no is supp...
855b875dda057108129da5f742a4257b73a20510
3,627,770
def get_full_frame_size(body_size): """ Returns size of full frame for provided frame body size :param body_size: frame body size :return: size of full frame """ return eth_common_constants.FRAME_HDR_TOTAL_LEN + \ get_padded_len_16(body_size) + \ eth_common_constants.FRAME...
23986f5d3ffda84fe8eebff8ab6159f96ab5f2f4
3,627,771
def is_iterable(obj): """ Returns *True* when an object *obj* is iterable and *False* otherwise. """ try: iter(obj) except Exception: return False return True
cb4b383780ac6f257c734aef2ccd8f00ecd9af77
3,627,772
def vels2waves(vels, restwav, hdr, usewcs=None, observatory="SPM"): """Heliocentric radial velocity (in km/s) to observed wavelength (in m, or whatever units restwav is in) """ # Heliocentric correction vels = np.array(vels) + helio_topo_from_header( hdr, usewcs=usewcs, observatory=observat...
7153d751793a7e8370fa206c591d73d5245ff955
3,627,773
def make_blueprint(db_connection_string=None, configuration={}): # noqa """Create blueprint. """ controllers = Controllers(configuration=configuration, connection_string=db_connection_string) # Create instance blueprint = Blueprint('pipelines', 'pipelines') @che...
df5871436fd8768224a342daffe2afffb262e402
3,627,774
from typing import Any from pathlib import Path def jsonable(obj: Any): """Convert obj to a JSON-ready container or object. Args: obj ([type]): """ if isinstance(obj, (str, float, int, complex)): return obj elif isinstance(obj, Path): return str(obj.resolve()) elif isi...
494bd41dc0b3ef4cc81e4daf5b1bc24b618ea7f8
3,627,775
def read_data_from(file_: str) -> dict: """Load image tiles from file.""" tiles = {} tile = [] for line in open(file_, "r").read().splitlines(): if "Tile" in line: idx = int(line[5:-1]) elif line == "": tiles[idx] = np.array(tile) tile = [] els...
4b4a072cf9c2a28fa64b18adff1354ac171ad18c
3,627,776
def create_graph(A, create_using=None, remove_self_loops=True): """ Function for flexibly creating a networkx graph from a numpy array. Params ------ A (np.ndarray): A numpy array. create_using (nx.Graph or None): Create the graph using a specific networkx graph. Can be used for forcing an ...
3baa2be7cbf3f0e2c18273aabe7ae7864853c59f
3,627,777
def delete(*tables): """ Returns :py:class:`~.Delete` instance and passed arguments are used for list of tables from which really data should be deleted. But probably you want to use :py:func:`~.delete_from` instead. """ return Delete(*tables)
9cd4099655d1e8f4393fcad07b453a9597aaf5d7
3,627,778
def create_string_for_failing_metrics(hpo_objects): """ Function is used to create a string for the failing metrics that can ultimately be inserted into the email output. Parameters ---------- hpo_objects (list): contains all of the HPO objects. the DataQualityMetric objects will now be ...
4128685d058e5fba4efbcbe30aa6e45bf5aeef2a
3,627,779
import argparse def _main(argv, standard_out, standard_error, standard_in): """Run internal main entry point.""" flargs = {} if "--config" in argv: flargs = find_config_file(argv) parser = argparse.ArgumentParser(description=__doc__, prog='docformatter') changes = parser.add_mutually_exc...
3a87528c2680eea464cd3b2f1f911f7010d7d018
3,627,780
from typing import Coroutine from typing import Any def current_effective_deadline() -> Coroutine[Any, Any, float]: """ Return the nearest deadline among all the cancel scopes effective for the current task. :return: a clock value from the event loop's internal clock (``float('inf')`` if there is no ...
b3230c8aeb240d0a02fabdfabbb2adadb57062a8
3,627,781
import time def from_openid_response(openid_response): """ return openid object from response """ issued = int(time.time()) sreg_resp = sreg.SRegResponse.fromSuccessResponse(openid_response) \ or [] ax_resp = ax.FetchResponse.fromSuccessResponse(openid_response) ax_args = {} if ax_...
d98ce4587f2ac380c77ec92f948f355c051f4184
3,627,782
from typing import Callable import click def dcos_login_pw_option(command: Callable[..., None]) -> Callable[..., None]: """ A decorator for choosing the password to set the ``DCOS_LOGIN_PW`` environment variable to. """ function = click.option( '--dcos-login-pw', type=str, ...
fe4b4d9dac90536046bcebf56fa2fe5144aaa665
3,627,783
from typing import Dict from typing import Tuple from typing import Any def get_default_triggers() -> Dict[Tuple[Tuple[str, Any]], Dict[str, Any]]: """Make _triggers read only""" return _default_triggers
a467de3534e58701f26d9d8d57f105743dcf283a
3,627,784
def yesno_choice(title, callback_yes=None, callback_no=None): """ Display a choice to the user. The corresponding callback will be called in case of affermative or negative answers. :param title: text to display (e.g.: 'Do you want to go to Copenaghen?' ) :param callback_yes: callback function to be...
93b76a3c7740b90dd01bd46ed429411991f3f34d
3,627,785
def is_tensor_object(x): """ Test whether or not `x` is a tensor object. :class:`tf.Tensor`, :class:`tf.Variable` and :class:`TensorWrapper` are considered to be tensor objects. Args: x: The object to be tested. Returns: bool: A boolean indicating whether `x` is a tensor objec...
8b2610d6d26bc3bb1ae72a11416507110a2d2bef
3,627,786
import json def slack(text: str, webhookAddress: str) -> str: """Send a slack message""" data = bytes(json.dumps({"text": text}), "utf-8") handler = urlopen(webhookAddress, data) return handler.read().decode('utf-8')
5570ba3c11f907e0b96f4878fc915c711b01ef3b
3,627,787
def wrap_col(string, str_length=11): """ String wrap """ if [x for x in string.split(' ') if len(x) > 25]: parts = [string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return ('\n'.join(parts) + '\n') else: return (string)
7b5cdf37cb84a2d2ebbc421ea917fc563026927e
3,627,788
import re def tokenize_text_with_special(text): """ Tokenizes a string. Does not filter any characters. :param text: The String to be tokenized. :return: Tokens """ token = [] running_word = "" for c in text: if re.match(alphanumeric, c): running_word += c e...
e6fbc0067dddf749f1d969646f2544352c36a380
3,627,789
def rms_slope_from_profile(topography, short_wavelength_cutoff=None, window=None, direction=None): """ Compute the root mean square amplitude of the height derivative of a topography or line scan stored on a uniform grid. If the topography is two dimensional (i.e. a topography...
fc6a1b1ce653c16b34bc42151dd62a05be6fc36f
3,627,790
def _get_exec_driver(): """ Get the method to be used in shell commands """ contextkey = "docker.exec_driver" if contextkey not in __context__: from_config = __salt__["config.option"](contextkey, None) # This if block can be removed once we make docker-exec a default # option...
33a9b06543af74c91bf0720caaad7c9ddd793ccd
3,627,791
def combine_results_jsons(drtdp_json, psrtdp_json, vi_json): """ takes overall results jsons and combines them to one json :param drtdp_json a json for drtdp overall results :param psrtdp_json a json for ps-rtdp overall results :param vi_json a json for value iteration overall results :return co...
a2bedf628e2af91af2c16111cd33600ade7e435e
3,627,792
def preprocess_data(data_path, embeds_path, lang='fr'): """ Loads pre-embedded dataset and labels, in a random (but consistent) order. :param data_path: (str) filepath to csv :param embeds_path: (str) filepath to json :return: X (list of list of list), y (len(train) x 2) np array """ X = loa...
6b516bacc7084b1df892fdbadecea78ff7e65121
3,627,793
def text_comp19_to_df(): """ Returns a pandas Dataframe object with the data of the TextComplexityDE19 dataset """ # Path to relevant csv file csv_path = join( dirname(dirname(dirname(abspath(__file__)))), "data", "TextComplexityDE19/ratings.csv", ) # read in c...
d12500ace3fe92bc0e39cb86d58a8077fcc28635
3,627,794
def from_relay(func: relay.Function) -> IRModule: """Convert a Relay function into a Relax program. Parameters ---------- func : relay.Function Relay function to be converted Returns ------- mod : tvm.IRModule The Relax IRModule for compilation """ # A map to store ...
fc1031fff3098e7c53321c2f7ca4ecfbdb456255
3,627,795
import os def get_list_of_all_data_file_names(datadirectory): """ Return list of all data files (.txt) in specified directory """ print('get_list_of_all_data_file_names', datadirectory) list_of_files = [] for file in os.listdir(datadirectory): if file.endswith('txt'): list_...
35dd02acdc492d1d38e9cedbe154f2754706e25b
3,627,796
def function_profiler(naming='qualname'): """ decorator that uses FunctionLogger as a context manager to log information about this call of the function. """ def layer(function): def wrapper(*args, **kwargs): with FunctionLogger(function, naming): return function(...
001977a23788a6e897b0882b894a5cdecc6b881f
3,627,797
from unittest.mock import Mock def mock_data_manager(components): """Return a mock data manager of a general model.""" dm = Mock() dm.components = components dm.fixed_components = [] return dm
e796dbe73e2ec7df650ceab450a3a5449a6af9ed
3,627,798
def load_data_fashion_mnist(batch_size, resize=None): #@save """下载Fashion-MNIST数据集,然后将其加载到内存中""" trans = [transforms.ToTensor()] if resize: trans.insert(0, transforms.Resize(resize)) trans = transforms.Compose(trans) mnist_train = paddle.vision.datasets.FashionMNIST(mode="train", transform=...
d946c33f7bff29a3278f5dcdc85195de772e85f7
3,627,799