content
stringlengths
22
815k
id
int64
0
4.91M
def ellipse_from_second_moments(image, labels, indexes, wants_compactness = False): """Calculate measurements of ellipses equivalent to the second moments of labels image - the intensity at each point labels - for each labeled object, derive an ellipse indexes - sequence of indexes to process ...
5,290,600
async def test_form_user_multiple_ups(hass): """Test we get the form.""" config_entry = MockConfigEntry( domain=DOMAIN, data={"host": "2.2.2.2", "port": 123, "resources": ["battery.charge"]}, options={CONF_RESOURCES: ["battery.charge"]}, ) config_entry.add_to_hass(hass) res...
5,290,601
def test_list_string_max_length_nistxml_sv_iv_list_string_max_length_1_5(mode, save_output, output_format): """ Type list/string is restricted by facet maxLength with value 5. """ assert_bindings( schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-maxLength-1.xsd", ...
5,290,602
def get_pager(config, logger): """Get the pager""" pager = config.get_config('pager') if not pager: logger.log('No pager configured!') return None return pager
5,290,603
def main(): """Console script entry point""" parser = ArgumentParser('cmdq') parser.add_argument('filename', help='Config filename.') parser.add_argument('--thread-count', type=int, default=4, help='Thread count.') args = parser.parse_args() config = load_configuration(args.filename) scrip...
5,290,604
def get_list(): """ Get the poet list """ url = HOME_PAGE + "zhongguoshiren" response = requests.get(url) response.encoding = "UTF-8" text = response.text soup = BeautifulSoup(text, "lxml") div_list = soup.find_all("div", class_="fontlist") poet_list = [] index...
5,290,605
def get_data_from_file(market, interval=var.default_interval, exchange='bittrex', filetype='csv'): """ Gets data from file. Args: - market: str with market. - interval: str with time between measures. Empty for default_int...
5,290,606
def plot_kmeans(n, km_psd, f_idx, X, y_pred, raw=False, std=True): """ plot k-means clusters """ spin_range = n.metadata['spindle_analysis']['spin_range'] n_clusters = km_psd.cluster_centers_.shape[0] centroids = km_psd.cluster_centers_ if n_clusters == 2: fig, axs = plt.subplots(1...
5,290,607
def process_dssp_df(df: pd.DataFrame) -> pd.DataFrame: """ Processes a DSSP DataFrame to make indexes align with node IDs :param df: pd.DataFrame containing the parsed output from DSSP. :type df: pd.DataFrame :return: pd.DataFrame with node IDs :rtype: pd.DataFrame """ # Convert 1 lett...
5,290,608
def done(msg=""): """Erase progress message and type msg argument. Args: msg (str): Message that will be showed. STDOUT: Prints message: {msg} """ print(f"\n{msg}")
5,290,609
def basic_animation(frames=100, interval=30): """Plot a basic sine wave with oscillating amplitude""" fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) x = np.linspace(0, 10, 1000) def init(): line.set_data([], []) return line, def ...
5,290,610
def weight_distr(df, mode): """ Create charts with overall and outlier weight distributions (included values only) """ wgt_grp = df[(df["param"] == "WEIGHTKG") & (df["include"] == True)] if mode == "high": wgt_grp = wgt_grp.loc[wgt_grp["measurement"] >= 135] plt.title("Weights At or ...
5,290,611
def Create(asset_type, name, amount, precision, owner, admin, issuer): """ :param asset_type: :param name: :param amount: :param precision: :param owner: :param admin: :param issuer: """ pass
5,290,612
def sum_node_list(node_list): """Custom sum func to avoid creating redundant nodes in Python sum func.""" node_list = [n for n in node_list if n is not None] if node_list == []: return None return reduce(add, node_list)
5,290,613
def generate_name(): """ Wrapper to fetch the latest source, parse it for adjectives and names, and then generating a random name in the Docker container style. Parameters ---------- Returns ------- str A name for a Docker container. """ source = _fetch_latest_source() ...
5,290,614
def create_case_text(volume_id, update_existing=False): """ Create or update cases for each volume """ cases = CaseMetadata.objects \ .in_scope() \ .order_by('id') \ .filter(volume_id=volume_id) \ .select_related('case_xml', 'case_text') if not update_existing: ...
5,290,615
def signal_post_migrate_callback(**kwargs): """ Actions to do after a migrate command has completed """ # print('post migration signal received') pass
5,290,616
def write_items_to_csv(repo_path: str, output_path: str, show_commit: bool, value_regex: Union[str, None] = None): """Determines the contents of '.properties-MERGED' files and writes to a csv file. Args: repo_path (str): The local path to the git repo. output_path (str): The output path for the...
5,290,617
def find_account(account): """ Function that finds an account name and returns the account """ return Credential.find_by_account(account)
5,290,618
def iteration(V, D, N_DV, N_D, alpha, beta, M, phi_TV, z_D, inv_z_T, active_topics, inactive_topics, N_TV, N_T, D_T): """ Performs a single iteration of Radford Neal's Algorithm 8. """ for t in active_topics: phi_TV[t, :] = dirichlet(N_TV[t, :] + beta / V) for d in xrange(D): old_...
5,290,619
def checkIfTitleExists(title): """ Checks if an item exists with the same unique title in db """ results = session.query(CategoryItem).filter_by(title=title).all() return len(results) > 0
5,290,620
async def test_select_update_liveview( hass: HomeAssistant, mock_entry: MockEntityFixture, viewer: Viewer, mock_liveview: Liveview, ): """Test select entity update (new Liveview).""" _, entity_id = ids_from_device_description( Platform.SELECT, viewer, VIEWER_SELECTS[0] ) state ...
5,290,621
def conv2d(x, filters, shape, padding="same", strides=(1, 1), activation="relu"): """ 2D Convolutional layers with Batch Normalization Arguments: x: Keras layer, the input to the feature map filters: Int representing the number of filters to use shape: Tuple with two integer val...
5,290,622
def writeBpImage(fname,image): """ Writes an image to a file with specified name. name: base name of image file; e.g., "tpgp" image: the image """ fileName = fname+".dat" aos = ArrayOutputStream(fileName) aos.writeFloats(image) aos.close() return image
5,290,623
def GroupByID(gff_data): """ Group GFF features into subsets based on ID Grouping is based on the ID attribute, which is assumed to be of the form '<prefix>:<name>:<index>' (e.g. 'CDS:YEL0W:3'). Consecutive features are determined to belong to the same gene if they have the same name and c...
5,290,624
def _clean_error_msg(self, msg): """converts a Powershell CLIXML message to a more human readable string """ # TODO prepare unit test, beautify code # if the msg does not start with this, return it as is if type(msg) == bytes and msg.startswith(b"#< CLIXML\r\n"): # for proper xml, we need to...
5,290,625
def create_carla_infos( root_path, info_prefix, max_prev_samples=10, seed=42, balance={'visible': 0.9, 'non_visible': 0.1} ): """Create info file of a carla generated dataset. Given the raw data, generate its related info file in pkl format. Args: root_path (str): Path of the data root. ...
5,290,626
def test_1(): """Test_1""" subprocess.run(["cwl-runner", r"--outdir=./tests", "./workflow/Retrieve_GC_workflow.cwl", "./tests/test_file_ex1_5_5.yml"]) assert filecmp.cmp("./tests/ex1_5_5_test.wig", "./tests/ex1_5_5.wig")
5,290,627
def cls(cls): """return a string with class name, description and attrs+methods+properties tables""" module = inspect.getmodule(cls) fullname = "`%s.%s`" % (module.__name__, cls.__name__) doc = readme_md.doc(cls) title = " - ".join(filter(None, [fullname, doc])) attrs = readme_md.tables.attrs(cl...
5,290,628
def parse_arguments(root_dir): """ Parse arguments from JSON parameter files. Args: root_dir: string: path to the directory containing the JSON files. Returns: namedtuple: hyperparameters. namedtuple: evaluation parameters. namedtuple: environment parameters. namedtuple: desi...
5,290,629
def spherical_harmonic(theta, phi, m=0, n=0): """Spherical harmonic of order `m` and degree `n`. .. note:: The degree `n` is often denoted `l`. .. seealso:: :func:`scipy.special.sph_harm` """ return sph_harm(m, n, phi, theta).real
5,290,630
def random_string(length: int = 12) -> str: """Generate a random string of fixed length.""" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length))
5,290,631
def axis_lw(): """Line width of the axes """ return 0.6
5,290,632
def color_lerp( color1: 'Color', color2: ColorInput, space: str, out_space: str, progress: Optional[Callable[..., float]], hue: str, premultiplied: bool ) -> InterpolateSingle: """Color interpolation.""" # Convert to the color space and ensure the color fits inside fit = not col...
5,290,633
async def place_control_rod(key: str, rod_number: int): """ Use your key and rod number to place given rod """ commander = next(filter(lambda c: c.uuid == key, commanders), None) reactor = next(filter(lambda r: r.uuid == key, reactors), None) if commander and reactor: result = reactor.ad...
5,290,634
def ctfCorrect(tiltseriesnumber, ctf_options): """ This corrects for ctf using ctfphaseflip. A defocus plot and a CTF plot are made. """ tiltdirname,tiltdir,seriesnumber,seriesname,tiltfilename,tiltfilename_full,raw_path,tiltstart,rawimagecount,maxtilt = variableSetup(ctf_options.rundir, tiltseriesnumber, prep="Fal...
5,290,635
def game_from_team_name(games, team_name, verbose=False): """ rn just takes in 1 game => double header issue for mlb """ for game in games: teams = teams_from_game(game) if team_name in teams: if verbose: print(f"found {team_name} game") return gam...
5,290,636
def define(host, port, database, word): """Look up a word using a dict server""" d = defer.Deferred() factory = DictLookupFactory("define", (database, word), d) from twisted.internet import reactor reactor.connectTCP(host, port, factory) return d
5,290,637
def assert_almost_equal(actual: numpy.matrix, desired: numpy.matrix): """ usage.scipy: 7 """ ...
5,290,638
def three_station_network_model(alpha1=0, alpha6=0, mu1=1, mu2=1, mu3=1, mu4=1, mu5=1, mu6=1, cost_per_buffer=np.ones((6, 1)), initial_state=np.zeros((6, 1)), capacity=np.ones((6, 1)) * np.inf...
5,290,639
def train(args, train_dataset, val_dataset, model, model_name): """ Parameters ---------- args : arguments train_dataset : dataloader (dataloader for the validation/test dataset). val_dataset : dataloader (dataloader for the validation/test dataset). model_DIFFPOOL : nn model (diffpool model...
5,290,640
def getActivePorts(): """ find the open ports - main part of the code from: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python """ if sys.platform.startswith('win'): candidatePorts = ['COM' + str(i + 1) for i in range(256)] elif sys.platform.startswith('linu...
5,290,641
def squares_in_rectangle(length, width): """This function is the solution to the Codewars Rectangle into Squares Kata that can be found at: https://www.codewars.com/kata/55466989aeecab5aac00003e/train/python.""" if length == width: return None squares = [] while length > 0 and width > ...
5,290,642
def response_to_bytes(resp): """ :param resp: urllib.classified_request.Response instance :return: bytes of response """ header_dict = dict(resp.info()) if isinstance(resp, urllib.error.HTTPError): header_dict["Status"] = '{} {}'.format(resp.code, resp.msg) headers_bytes = headers_di...
5,290,643
def build_fpn_mask_graph(rois, feature_maps, image_shape, pool_size, num_classes): """Builds the computation graph of the mask head of Feature Pyramid Network. rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized coordinates. feature_maps: List of featur...
5,290,644
def proc_kl(rv, kl, tarray, p, toplevel_arrays): """Handle a table spec keylist, modifying rv in place; returns target""" c = rv if len(kl) == 0: return c # all entries except last must be dicts for i in kl[:-1]: if i in c: if type(c[i]) not in [dict, list]: ...
5,290,645
def locate_config_file(): """ Return a path to a config to use accoding to standard preference rules """ print(f"Checking if ${LOCAL_CONFIG} is a file") if os.path.isfile(LOCAL_CONFIG): return LOCAL_CONFIG if os.path.isfile(HOME_DIR_CONFIG): return HOME_DIR_CONFIG if os.path.isfile(...
5,290,646
def display_text(text:str, size:int, color:tuple = (27, 34, 77), antialias:int = 1, fontpath:str = os.path.join('Assets', 'PoetsenOne-Regular.ttf'), background:bool=False, background_color:tuple = (255, 255, 255), **kwargs) -> pygame.Surface: """Displaying text Args: text (str): The text that is wa...
5,290,647
def relative_power_sqi(nn_intervals,freqs=None,pows=None,f_min=0.04,f_max=0.15): """ Compute the relative power with respect to the total power of the examined band. The function mimics features obtaining from the frequency domain of HRV. Main inputs are frequencies and power density - compute by using ...
5,290,648
def make_hpx_to_wcs_mapping(hpx, wcs): """Make the mapping data needed to from from HPX pixelization to a WCS-based array Parameters ---------- hpx : `~fermipy.hpx_utils.HPX` The healpix mapping (an HPX object) wcs : `~astropy.wcs.WCS` The wcs mapping (a pywcs.wcs object)...
5,290,649
def simulate_round(grid: list[list[int]]) -> tuple[list[list[int]], int, bool]: """Simulate a single round. * First, the energy level of each octopus increases by 1. * Then, any octopus with an energy level greater than 9 flashes. This increases the energy level of all adjacent octopuses by 1, includ...
5,290,650
def Main(): """Main entry point""" log_db = FLAGS.log_db() if FLAGS.graph_db: graph_db = FLAGS.graph_db() else: graph_db = None log_db_generator = RandomLogDatabaseGenerator() log_db_generator.PopulateLogDatabase( log_db, run_count=FLAGS.run_count, graph_db=graph_db )
5,290,651
def command_workshop_delete(ctx, name): """ Delete the custom resource describing a workshop. """ client = kube.client() workshop_resource = _resource_type( ctx, client, "training.eduk8s.io/v1alpha1", "Workshop" ) try: workshop_resource.delete(name=name) click.echo...
5,290,652
def keep_node_permissive(data): """Return true for all nodes. Given BEL graph :code:`graph`, applying :func:`keep_node_permissive` with a predicate on the nodes iterable as in :code:`filter(keep_node_permissive, graph)` will result in the same iterable as iterating directly over a :class:`BELGraph` ...
5,290,653
def probability_to_internal(external_values, constr): """Reparametrize probability constrained parameters to internal.""" return external_values / external_values[-1]
5,290,654
def get_os(): """Get system name. Returns: str: The system/OS name. e.g.: ``Linux`` or ``Windows``. """ return platform.system().lower()
5,290,655
def vdcnn(embedding_size, maxlen, max_features, filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation, max_pooling, mean_pooling, weighted_average_attention, concat_mode, dropout_embedding, conv_dropout, dense_dropout, dropout_mode, conv_k...
5,290,656
def angle(p0: Point, p1: Point, p2: Point) -> float: """ p1 is the center point; result is in degrees """ a = (p1.x-p0.x)**2 + (p1.y-p0.y)**2 b = (p1.x-p2.x)**2 + (p1.y-p2.y)**2 c = (p2.x-p0.x)**2 + (p2.y-p0.y)**2 return round(math.acos( (a+b-c) / math.sqrt(4*a*b) ) * 180/math.pi, 5)
5,290,657
def get_source_parser(type_source): """ Возвращает класс-парсер кода :param type_source: тип парсера :return: класс """ dict_source_parser = { 'python': PythonSourceParser } assert type_source in dict_source_parser, \ 'type_source must be in ({0})'.format(', '.join(dict_s...
5,290,658
def stop(ctx, provider, run_id): """Stop Experiment""" A2MLExperiment(ctx, provider).stop(run_id)
5,290,659
def test_class_registration(n_dispatch): """Test class registration.""" # instantiate the base class unregister_all() from pydeco.utils.parser import CONFIG CONFIG['N_DISPATCH'] = n_dispatch registered_wrappers = get_registered_wrappers_classnames() assert len(registered_wrappers) == 0 ...
5,290,660
def prepGeoJSON(geojson): """Loads GeoJSON into the mander library for accelerate processing later. Parameters: geojson -- The GeoJSON to load Returns: A string that can be passed in lieu of the original GeoJSON to take advatange of internal processing that has already been done. """ re...
5,290,661
def get_reserves() -> List[int]: """ Returns how many token_a and token_b tokens are in the pool. :return: a list of 2 ints, the value in the first index is reserve of token_a and the second value is the reserve of token_b """ return [get(SUPPLY_KEY + TOKEN_A).to_int(), get(SUPPLY_KEY + TOKEN_B).to...
5,290,662
def walk_values(hive, key_name, value_filter_regex = None, valuetypes = None, autoexpand = False): """ >>> list(walk_values(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\DrWatson", r"^(cr|dump)")) [('DumpSymbols', 0, 4), ('DumpAllThreads', 1, 4), ('CreateCrashDump', 1, 4), ('CrashDumpType', 1, 4)] >>> list...
5,290,663
def viz_view(view, ax=None, row_names=None, col_names=None, **kwargs): """Order rows according to clusters and draw line between clusters. Visualize this using imshow with two colors only. """ # Get data restricted to current view's outputs data_dict = get_view_data(view) data_arr = np.array(da...
5,290,664
def local_push(tx, rpc_user=None, rpc_password=None): """ Pushes a bitcoin transaction to the network using a local rpc server. :param tx: transaction to be pushed. :type tx: hex str :param rpc_user: rpc user (could be set in bitcoin.conf). :type rpc_user: str :param rpc_password: rpc password ...
5,290,665
def grib_index_get_long(indexid,key): """ @brief Get the distinct values of the key in argument contained in the index. The key must belong to the index. This function is used when the type of the key was explicitly defined as long or when the native type of the key is long. \b Examples: \ref...
5,290,666
async def test_do_api_call_async_unknown_method(): """ Asserts that the Databricks hook throws an exception when it attempts to make an API call using a non-existent method. """ hook = DatabricksHookAsync() hook.databricks_conn = MagicMock() hook.databricks_conn.host = "https://localhost" ...
5,290,667
def get_action_spec(): """Get the specs of the tensors expected by ``step(action)`` of the environment. Note: you need to finish all the config for environments and TrainerConfig.random_seed before using this function. Returns: nested TensorSpec: a spec that describes the shape and dtype o...
5,290,668
def run_notebook(nb_path, tmp_path, env=os.environ, kernel=None): """Execute a Jupyter notebook via nbconvert and collect output. Modified from https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/ Parameters ---------- nb_path : path-like The notebook file to execute. ...
5,290,669
def get_mx_hosts(domain): """Get all domain names for servers in MX records""" return [x.exchange for x in resolver.query(domain, 'MX')]
5,290,670
def post_data(sensor_data): """POST to /sensorData Experimental dev feature which uses timely-beliefs to create and save the data structure. """ beliefs = SensorDataSchema.load_bdf(sensor_data) response, code = save_to_db(beliefs) response.update(type="PostSensorDataResponse") return re...
5,290,671
def find_anomaly_periods( data: pd.DataFrame, time_column: str = "TimeGenerated", period: str = "1H", pos_only: bool = True, ) -> List[TimeSpan]: """ Merge adjacent anomaly periods. Parameters ---------- data : pd.DataFrame The data to process time_column : str, optional...
5,290,672
def intf_Contain(*args): """ * Compute if the triangle <P1> <P2> <P3> contain <ThePnt>. :param P1: :type P1: gp_Pnt :param P2: :type P2: gp_Pnt :param P3: :type P3: gp_Pnt :param ThePnt: :type ThePnt: gp_Pnt :rtype: bool """ return _Intf.intf_Contain(*args)
5,290,673
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle): """Construct a queued batch of images and labels. Args: image: 3-D Tensor of [height, width, depth] of type.float32 label: 1-D Tensor of type.int32 min_queue_examples: int32, ...
5,290,674
def rgb2gray(rgb): """ Convert a RGB image to a grayscale image Differences from cv2.cvtColor(): 1. Input image can be float 2. Output image has three repeated channels, other than a single channel Args: rgb: Image in RGB format Numpy array of shape (h, w...
5,290,675
def glsl_parse_preprocessor(source): """Parse preprocessor line.""" match = re.match(r'^\s*#\s*(\S+)\s+.*$', source) if match: if match.group(1) in g_directives: return GlslBlockPreprocessor(source) return None
5,290,676
def print_ofpt_packet_out(msg): """ Args: msg: OpenFlow message unpacked by python-openflow ; PAGE 107 MANUAL """ print('PacketOut: buffer_id: %s in_port: %s actions_len: %s' % (hex(msg.buffer_id.value), green(dissector.get_phy_port_no(msg.in_port.value)), ...
5,290,677
def q1(): """GDA """ """Run the Gaussian Discriminant Analysis on the spambase data. Use the k-folds from the previous problem (1 for testing, k-1 for training, for each fold) Since you have 57 real value features, each of the 2gaussians (for + class and for - class) will have a mean vector with 57 components...
5,290,678
def convert_to_example_temporal( image_datas, image_paths, image_shapes, labels, centers, gt3ds, scale_factors, start_pts, cams, poses=None, shape=None, phis=None, image_datas_og=None, time_pts=None): """...
5,290,679
def newchart(data): """ Determines the environment for generating a timeseries chart. Call this function """ # response metadata items meta = { 'variable': data['variable'], 'loc_type': data['loc_type'] } for item in nldas_variables(): if item[1] == data['variable']: ...
5,290,680
def conformance(source): """ Creates a function that does a shallow comparison between a given object and the `source` dictionary using :func:`conforms`. Examples: >>> conformance({'a': 1})({'b': 2, 'a': 1}) True >>> conformance({'a': 1})({'b': 2, 'a': 2}) False Arg...
5,290,681
def kitt(p : port, t=0.5): """Kitt display on the pins in the port. t is the sweep time. The pins in the port must be outputs. """ while True: for i in range(0, p.n): p.write(1 << i) time.sleep(1.0 * t / p.n) for i in range(p.n - 2, 0, -1): p.writ...
5,290,682
def send_password_changed_notice(user): """Sends the password changed notice email for the specified user. :param user: The user to send the notice to """ if config_value("SEND_PASSWORD_CHANGE_EMAIL"): subject = config_value("EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE") send_mail(subject, use...
5,290,683
def stack_v1( x: tf.Tensor, filters: int, blocks: int, stride1: int = 2, dilation_rate: int = 1, name: Optional[Text] = None, ) -> tf.Tensor: """Create a set of stacked ResNetv1 residual blocks. Args: x: input tensor. filters: integer, filters of the bottleneck layer in ...
5,290,684
def get_params(model): """Aggregates model parameters of all linear layers into a vector. Args: model: A (pre-trained) torch.nn.Module or torch.nn.Sequential model. Returns: The aggregated parameters. """ weights = list() biases = list() for module in model.modules(): ...
5,290,685
def _drawRunwayExtension(length, dashLength, crossInterval, crossWidth, points, layer, da): """Draw the runway extension lines """ bearing = da.bearing(points[0], points[1]) features = [] features.extend(_generateRunwayExtension( points[0], bearing + math.pi, length, da...
5,290,686
def as_series(alist, trim=True) : """Return arguments as a list of 1d arrays. The return type will always be an array of double, complex double. or object. Parameters ---------- [a1, a2,...] : list of array_like. The arrays must have no more than one dimension when converted. trim ...
5,290,687
def hist16bit(array, bins=64, step=None, low=None, high=None, use_numba=True): """ stepsize should be power of 2 array should be 8 or 16 bit integer """ if array.dtype == 'uint8': length = 256 offset = 0 elif array.dtype == 'int8': length = 256 ...
5,290,688
def filter_genes_cells(adata): """Remove empty cells and genes.""" sc.pp.filter_genes(adata, min_cells=1) sc.pp.filter_cells(adata, min_counts=2)
5,290,689
def get_circ_supply_on_chain(chain:str): """ chain: Allowed: ethereum ┃ avalanche ┃ bsc ┃ polygon ┃ arbitrum ┃ fantom ┃ harmony ┃ boba ┃ optimism ┃ moonriver ┃ aurora direction: Allowed: in ┃ out """ chain = chain.lower() chains = ["ethereum", "avalanche", "bsc", "polygon", "arbitrum", "fantom...
5,290,690
def test(epoch, max_epoch): """ Test model """ loss_meter = AverageMeter() acc_meter = AverageMeter() for ind, (x, target) in enumerate(testing_loader): # x is NxCxHxW => WxNx(HxC) x = preprocess_data(x) act_lengths = get_seq_length(x) # target is a list of `torch.In...
5,290,691
def find_response(triggers: List[Trigger], message: str, is_gauchito: bool): """ Returns the first matching trigger in a list of triggers given the message contents and whether or not the author is a gauchito. Returns None if the message matches none of the triggers """ for trigger in triggers:...
5,290,692
def create_sql_endpoint_class( name: str, method: str, url: str, sql: str, repository: DataRepository, query_parameters: List, tags: List, request_schema: type = None, response_schema: dict = None, description: str = None, is_from_template: bool = False, ): """ :para...
5,290,693
def loss(logits, labels): """Add L2Loss to all the trainable variables. Add summary for "Loss" and "Loss/avg". Args: logits: Logits from inference(). labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape [batch_size] Returns: Loss tensor of type float. """ # Calculate...
5,290,694
def make_production_app(): """ Configure logging before creating the application. Useful with application servers, where it's pretty impossible to run code other than the app factory. :return: standard app created by make_app """ configure_logging() return make_app()
5,290,695
def high_light(pattern, content, option): """ Will find pattern every pattern in content ignore upper or lower and highlight that pattern in content """ patterns = findall(pattern, content, IGNORECASE) if option != '--case-sensitive' else findall(pattern, content) for pattern in set(patterns): ...
5,290,696
def assert_array_almost_equal( x: numpy.ndarray, y: numpy.ndarray, decimal: int, err_msg: Literal["Size 512 failed"], ): """ usage.scipy: 8 """ ...
5,290,697
def test_game_find_word_length(board, test_word_guess, expected): """Test Word guesses""" assert(board.check_guess(test_word_guess) == expected)
5,290,698
def write_bintable(filename, data, header=None, comments=None, units=None, extname=None, clobber=False, primary_extname='PRIMARY'): """Utility function to write a fits binary table complete with comments and units in the FITS header too. DATA can either be dictionary, an Astropy Table, a...
5,290,699