content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_nums(image): """get the words from an image using pytesseract. the extracted words are cleaned and all spaces, newlines and non uppercase characters are removed. :param image: inpout image :type image: cv2 image :return: extracted words :rtype: list """ # pytesseract c...
0ff23d8363a14a46c7f6ffa2be130c6eb61409c8
3,642,373
def create_bag_of_vocabulary_words(): """ Form the array of words which can be conceived during the game. This words are stored in hangman/vocabulary.txt """ words_array = [] file_object = open("./hangman/vocabulary.txt") for line in file_object: for word in line.split(): ...
e3aadad2575e28b19b83158eb2127437c8aada89
3,642,374
import math def kato_ranking_candidates(identifier: Identifier, params=None): """rank candidates based on the method proposed by Kato, S. and Kano, M.. Candidates are the noun phrases in the sentence where the identifier was appeared first. Args: identifier (Identifier) params (dict) R...
c8a413118b599eb3cb9c9db877d7d489871d65a2
3,642,375
def _get_bag_of_pos_with_dependency(words, index): """Return pos list surrounding index Args: words (list): stanfordnlp word list object having pos attributes. index (int): target index Return: pos_list (List[str]): xpos format string list """ pos_list = [] def _get_gove...
02fc508583d79464161927080c1c55d308926274
3,642,376
def fix_time_individual(df): """ 1. pandas.apply a jit function to add 0 to time 2. concat date + time 3. change to np.datetime64 """ @jit def _fix_time(x): aux = "0" * (8 - len(str(x))) + str(x) return aux[:2] + ":" + aux[2:4] + ":" + aux[4:6] + "." + aux[6:] ...
8d0c99d3f485d852130f9f4fe7ab05bbcdd99557
3,642,377
def convolve_fft(data, kernel, kernel_fft=False, return_fft=False): """ Convolve data with a kernel. This is inspired by astropy.convolution.convolve_fft, but stripped down to what's needed for the expected application. That has the benefit of cutting down on the execution time, but limits its ...
64fc4c02f72c419f6c315f524597a32391ea7b8c
3,642,378
def friable_sand(Ks, Gs, phi, phic, P_eff, n=-1, f=1.0): """ Friable sand rock physics model. Reference: Avseth et al., Quantitative Seismic Interpretation, p.54 Inputs: Ks = Bulk modulus of mineral matrix Gs = Shear modulus of mineral matrix phi = porosity phic = cr...
ace533ee727cd4749ad210b13eec5193b74416b8
3,642,380
def get_available_currencies(): """ This function retrieves a listing with all the available currencies with indexed currency crosses in order to get to know which are the available currencies. The currencies listed in this function, so on, can be used to search currency crosses and used the retrieved d...
139f775943bc251149444c702cb4290d78a58a03
3,642,381
def mktemp(suffix="", prefix=template, dir=None): """User-callable function to return a unique temporary file name. The file is not created. Arguments are as for mkstemp, except that the 'text' argument is not accepted. This function is unsafe and should not be used. The file name refers to a file that ...
0785609c3284b0052fa31767d0df11476b28c786
3,642,382
def getTaskIdentifier( task_id ) : """Get tuple of Type and Instance identifiers.""" _inst = Instance.objects.get( id = task_id ) return ( _inst.type.identifier , _inst.identifier )
fb18be814330bd02205d355b3ebfb68f777ee9c2
3,642,383
def hessian_vector_product(loss, weights, v): """Compute the tensor of the product H.v, where H is the loss Hessian with respect to the weights. v is a vector (a rank 1 Tensor) of the same size as the loss gradient. The ordering of elements in v is the same obtained from flatten_tensor_list() acting on t...
35ef7772367f56fcded2e4173fe194cb28da3bc7
3,642,384
def clean_cells(nb_node): """Delete any outputs and resets cell count.""" for cell in nb_node['cells']: if 'code' == cell['cell_type']: if 'outputs' in cell: cell['outputs'] = [] if 'execution_count' in cell: cell['execution_count'] = None ret...
67dce7ecc3590143730f943d3eb07ae7df9d8145
3,642,385
def getProjectProperties(): """ :return: @rtype: list of ProjectProperty """ return getMetDataLoader().projectProperties
7f517a20d83002c41867bbc7911f775d64b21b88
3,642,387
def svn_client_cleanup(*args): """svn_client_cleanup(char dir, svn_client_ctx_t ctx, apr_pool_t scratch_pool) -> svn_error_t""" return _client.svn_client_cleanup(*args)
2a9921e8521e927e124633bb932b158a1f9abdf3
3,642,388
def model_chromatic(psrs, psd='powerlaw', noisedict=None, components=30, gamma_common=None, upper_limit=False, bayesephem=False, wideband=False, idx=4, chromatic_psd='powerlaw', c_psrs=['J1713+0747']): """ Reads in list of enterprise Pulsar instance an...
568f4951930fe6f8175417785c4503895f76bc88
3,642,389
def test_f32(heavydb): """If UDF name ends with an underscore, expect strange behaviour. For instance, defining @heavydb('f32(f32)', 'f32(f64)') def f32_(x): return x+4.5 the query `select f32_(0.0E0))` fails but not when defining @heavydb('f32(f64)', 'f32(f32)') def f32_(x): retu...
157560cc90e3f869d84198eeb26896a76157eb39
3,642,391
from typing import Union from pathlib import Path def get_message_bytes( file_path: Union[str, Path], count: int, ) -> bytes: """ 从 GRIB2 文件中读取第 count 个要素场,裁剪区域 (东北区域),并返回新场的字节码 Parameters ---------- file_path count 要素场序号,从 1 开始,ecCodes GRIB Key count Returns ...
6a2ad3a20e02283c2bffe31eb78cacf84d92ff6f
3,642,392
from typing import Union from typing import List import json def discover_climate_observations( time_resolution: Union[ None, str, TimeResolution, List[Union[str, TimeResolution]] ] = None, parameter: Union[None, str, Parameter, List[Union[str, Parameter]]] = None, period_type: Union[None, str...
b96fd2a0a9bcb9a7b50018a1b7e3ae7add3e3c63
3,642,393
def set_template(template_name, file_name, p_name): """ Insert template into the E-mail. """ corp = template(template_name, file_name, p_name) msg = MIMEMultipart() msg['from'] = p_name msg['subject'] = f'{file_name}' msg.attach(MIMEText(corp, 'html')) return msg
8745d9729ddbe159e0bca90dee198ce4e3efb489
3,642,394
import gettext def lazy_gettext(string): """A lazy version of `gettext`.""" if isinstance(string, _TranslationProxy): return string return _TranslationProxy(gettext, string)
9229c987d6b2f300f7225ea4b58f964c70e882fc
3,642,395
def toggleautowithdrawalstatus(status, fid, alternate_token=False): """ Sets auto-withdrawal status of the account associated with the current OAuth token under the specified funding ID. :param status: Boolean for toggle. :param fid: String with funding ID for target account :return: String ...
4df2be7801a23978c58b7ce8aec7e5fd30fb1e76
3,642,396
def load_avenger_models(): """ Load each instance of data from the repository into its associated model at this point in the schema lifecycle """ avengers = [] for item in fetch_avenger_data(): # Explicitly assign each attribute of the model, so various attributes can be ignored ave...
70740495be63a198cf5ec1308608955f52be46f0
3,642,397
import json import _json import _datetime def aggregate_points(point_layer, bin_type=None, bin_size=None, bin_size_unit=None, polygon_layer=None, time_step_interval=None, time_step_interval_un...
fe946d4273ed1ce4e4cd3e46d9f9a3e0ff5c6725
3,642,398
def scattered_embedding_lookup(params, values, dimension, name=None, hash_key=None): """Looks up embeddings using parameter hashing for each value in `values`. The i-th embedding component of...
a317d7d494bd9b9918f6f2354d854c2fbffc1c6c
3,642,399
from typing import Iterable from typing import Callable def get_features_and_labels(instances: Iterable[NewsHeadlineInstance], feature_generator: Callable[[NewsHeadlineInstance], dict[str]]) -> tuple[list[dict[str]], list[int]]: "...
56d2f1a0a18eb1d1f8ecf9547184ae873d0b60e3
3,642,401
def countBarcodeStats(bcseqs,chopseqs='none',bcs = ["0","1"],use_specific_beginner=None): """this function uses edlib to count the number of matches to given bcseqs. chopseqs can be left, right, both, or none. This tells the program to chop off one barcode from either the left, right, both, or non...
af19f5a77f241362d50245885ab15dabd5197dcd
3,642,402
def is_underflow(bin_nd, hist): """Retuns whether global bin number bin_nd is an underflow bin. Works for any number of dimensions """ flat1d_bin = get_flat1d_bin(bin_nd, hist, False) return flat1d_bin == 0
377c5a339f404ef4e55832f163952575f7b8d6a4
3,642,403
def deprecated_func_docstring(foo=None): """DEPRECATED. Deprecated function.""" return foo
f9c996c4f3735ed2767f0bbb139b1494e2a0fa39
3,642,404
def get_all_nodes(starting_node : 'NodeDHT') -> 'list[NodeDHT]': """Return all nodes in the DHT""" nodes = [starting_node] node = starting_node while node != starting_node: node = node.succ nodes.append(node) return nodes
91b2968b000abac3d6f9f51bad5889ccf0fe8388
3,642,405
import re def by_regex(regex_tuples, default=True): """Only call function if regex_tuples is a list of (regex, filter?) where if the regex matches the requested URI, then the flow is applied or not based on if filter? is True or False. For example: from aspen.flows.filter import by_rege...
a3d47690120a8091596047d73792b0d1f637132b
3,642,407
def deserialize(name): """Get the activation from name. :param name: name of the method. among the implemented Keras activation function. :return: """ name = name.lower() if name == SOFTMAX: return backward_softmax if name == ELU: return backward_elu if name == SEL...
133f01edaa678d60f85bf720590c0df3d1c552f3
3,642,408
def delete_item_image(itemid, imageid): """ Delete an image from item. Args: itemid (int) - item's id imageid (int) - image's id Status Codes: 204 No Content – when image deleted successfully """ path = '/items/{}/images/{}'.format(itemid, imageid) return delete(pa...
28d3c7bea85cd7132de6010def1c2ec41a9cfc82
3,642,409
def bytes_(s, encoding='utf-8', errors='strict'): # pragma: no cover """Utility to ensure binary-like usability. If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``s``""" if isinstance(s, text_type): return s.encode(encoding, errors) return...
269d315c1204be941766558fc3cbbc07c8e63657
3,642,410
from operator import inv import numpy def normal_transform(matrix): """Compute the 3x3 matrix which transforms normals given an affine vector transform.""" return inv(numpy.transpose(matrix[:3,:3]))
b7f7256b9057b9a77b074080e698ff859ccbefb2
3,642,412
async def async_unload_entry(hass, config_entry): """Unload OMV config entry.""" unload_ok = await hass.config_entries.async_unload_platforms( config_entry, PLATFORMS ) if unload_ok: controller = hass.data[DOMAIN][config_entry.entry_id] await controller.async_reset() hass...
60955e2aac51d211a296de0736f784c2332f855b
3,642,413
import typing import csv def create_prediction_data(validation_file: typing.IO) -> dict: """Create a dictionary object suitable for prediction.""" validation_data = csv.DictReader(validation_file) races = {} # Read each horse from each race for row in validation_data: race_id = row["Entry...
6ec67b277460feb5d80bf7a35e7bc40f3014e6ce
3,642,414
def username(request): """ Returns ESA FTP username """ return request.config.getoption("--username")
2393884c2c9f65055cd7a14c1b732fccf70a6e28
3,642,415
def complete_data(df): """Add some temporal columns to the dataset - day of the week - hour of the day - minute Parameters ---------- df : pandas.DataFrame Input data ; must contain a `ts` column Returns ------- pandas.DataFrame Data with additional columns `da...
be342df461c04fc4b7f5b757f8287973c8826bd8
3,642,416
import re def is_valid_mac_address_normalized(mac): """Validates that the given MAC address has what we call a normalized format. We've accepted the HEX only format (lowercase, no separators) to be generic. """ return re.compile('^([a-f0-9]){12}$').match(mac) is not None
7c4ea0a3353a3753907de21bbf114b2a228bb3c0
3,642,417
def get_Y(data): """ Function: convert pandas data table to sklearn Y variable Arguments --------- data: panadas data table Result ------ Y[:,:]: float sklearn Y variable """ return np.array((data["H"],data["sigma"])).T
d5e9d5b116fe8e82165d019c23394b6f1dfc4d9c
3,642,418
def get_bbox(mask, show=False): """ Get the bbox for a binary mask Args: mask: a binary mask Returns: bbox: (col_min, col_max, row_min, row_max) """ area_obj = np.where(mask != 0) bbox = np.min(area_obj[0]), np.max(area_obj[0]), np.min(area_obj[1]), np.max(area_obj[1]) i...
2e074d305d50334809eb0fe3e15def6fd4d21644
3,642,419
from pineboolib.core import settings def check_mobile_mode() -> bool: """ Return if you are working in mobile mode, searching local settings or check QtCore.QSysInfo().productType(). @return True or False. """ return ( True if QtCore.QSysInfo().productType() in ("android", "ios")...
99327efbc3d329218d027e4451aae1979a9ebccc
3,642,420
def check_for_overflow_candidate(node): """ Checks if the node contains an expression which can potentially produce an overflow meaning an expression which is not wrapped by any cast, which involves the operator +, ++, *, **. Note, the expression can have several sub-expression. It is the case of the expression (a...
77232f5d94a6cba6fef79bd51886145e2dfec4bf
3,642,421
import struct def parse_monitor_message(msg): """decode zmq_monitor event messages. Parameters ---------- msg : list(bytes) zmq multipart message that has arrived on a monitor PAIR socket. First frame is:: 16 bit event id 32 bit event value no pad...
df71541d34bc04b1ac25c6435b1b298394e27362
3,642,422
import toml import json def load_config(fpath): """ Load configuration from fpath and return as AttrDict. :param fpath: configuration file path, either TOML or JSON file :return: configuration object """ if fpath.endswith(".toml"): data = toml.load(fpath) elif fpath.endswith(".jso...
27c68c944a431b4d8b12c6b64609f33043363b03
3,642,423
def softmax_layer(inputs, n_hidden, random_base, drop_rate, l2_reg, n_class, scope_name='1'): """ Method adapted from Trusca et al. (2020). Encodes the sentence representation into a three dimensional vector (sentiment classification) using a softmax function. :param inputs: :param n_hidden: :p...
1f77d99d12c927c0d77e136098fe8f9c2bc458b8
3,642,424
def node2freqt(docgraph, node_id, child_str='', include_pos=False, escape_func=FREQT_ESCAPE_FUNC): """convert a docgraph node into a FREQT string.""" node_attrs = docgraph.node[node_id] if istoken(docgraph, node_id): token_str = escape_func(node_attrs[docgraph.ns+':token']) if...
8c6690e5fec41f98501060f5bf24ed823a2c31b6
3,642,425
def search(news_name): """method to fetch search results""" news_name_list = news_name.split(" ") search_name_format = "+".join(news_name_list) searched_results = search_news(search_name_format) sourcess=get_source_news() title = f'search results for {news_name}' return render_template('sea...
7521221b66a872b00310693a3ccc6c81013098a2
3,642,429
def encrypt_document(document): """ Useful method to encrypt a document using a random cipher """ cipher = generate_random_cipher() return decrypt_document(document, cipher)
9a7e4bd79a83df261c4f946f62ff9bf40bfbf068
3,642,430
def bootstrap_alert(visitor, items): """ Format: [[alert(class=error)]]: message """ txt = [] for x in items: cls = x['kwargs'].get('class', '') if cls: cls = 'alert-%s' % cls txt.append('<div class="alert %s">' % cls) if 'clos...
c2803176b2e1ed9b3d4aecd622eedcac673d4c42
3,642,431
def masked_mean(x, *, mask, axis, paxis_name, keepdims): """Calculates the mean of a tensor, excluding masked-out entries. Args: x: Tensor to take the mean of. mask: Boolean array of same shape as 'x'. True elements are included in the mean, false elements are excluded. axis: Axis...
3242e86f571af61909efa63bd60158aa0f8eba88
3,642,432
def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight): """This function helps position an image within a box. It first normalizes for two cases: - if the width is None, it assumes imWidth - ditto for height - if width or height is negative, it adjusts x or y and makes them positive ...
73a686f122ad31ee6693641e1ef386f13b67b4d8
3,642,433
import random def circle_area(radius: int) -> float: """ estimate the area of a circle using the monte carlo method. Note that the decimal precision is log(n). So if you want a precision of three decimal points, n should be $$ 10 ^ 3 $$. :param r (int): the radius of the circle :return (int): the ...
2c85759ffbf798749263fca368cdfd159d67028b
3,642,435
def Quantized_MLP(pre_model, args): """ quantize the MLP model :param pre_model: :param args: :return: """ #full-precision first and last layer weights = [p for n, p in pre_model.named_parameters() if 'fp_layer' in n and 'weight' in n] biases = [pre_model.fp_layer2.bias] #layer...
cd5b36c1b10567fee5a8b1f10679e6868f42f98f
3,642,436
def _super_tofrom_choi(q_oper): """ We exploit that the basis transformation between Choi and supermatrix representations squares to the identity, so that if we munge Qobj.type, we can use the same function. Since this function doesn't respect :attr:`Qobj.type`, we mark it as private; only thos...
da91aff35d891000773100b998b80dc5d998414f
3,642,437
def get_attention_weights(data): """Get the attention weights of the given function.""" # USE INTERACTIONS token_interaction = data['tokeninteraction'] df_token_interaction = pd.DataFrame(token_interaction) # check clicked tokens to draw squares around them clicked_tokens = np.array(data['final...
e3189bd67f3da6ee8c1173348eec249d9c8cfa9a
3,642,438
def save_ecg_example(gen_data: np.array, image_name, image_title='12-lead ECG'): """ Save 12-lead ecg signal in fancy .png :param gen_data: :param image_name: :param image_title: :return: """ fig = plt.figure(figsize=(12, 14)) for _lead_n in range(gen_data.shape[1]): curr_lea...
456fa204b20eee53645a900614877a6fb6a53e9c
3,642,439
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload an entry.""" component: EntityComponent = hass.data[DOMAIN] return await component.async_unload_entry(entry)
b4ae648493b63a27f5127139876cf0bca2a2dcbb
3,642,440
def run_random_climate(gdir, nyears=1000, y0=None, halfsize=15, bias=None, seed=None, temperature_bias=None, climate_filename='climate_monthly', climate_input_filesuffix='', output_filesuffix='', init_area_m2=None, unique_sample...
2887c1e62d3357e028c7be0539225bfb879323d9
3,642,442
from typing import Optional def sync_get_ami_arch_from_instance_type(instance_type: str, region_name: Optional[str]=None) -> str: """For a given EC2 instance type, returns the AMI architecture associated with the instance type Args: instance_type (str): An EC2 instance type; e.g., "t2.micro" region_n...
2289deea91c9a9dafa0492fac9230292b546e9b7
3,642,443
import math def atan2(y, x): """Returns angle of a 2D coordinate in the XY plane""" return math.atan2(y, x)
ede5a647c175bebf2800c22d92e396deff6077e2
3,642,444
def index_objects( *, ids, indexer_class, index=None, transforms=None, manager_name=None ): """ Index specified `ids` in ES using `indexer_class`. This is done in a single bulk action. Pass `index` to index on the specific index instead of the default index alias from the `indexed_class`. ...
c93ea99946bb1516a58bb39aa5d43b1644f4f4da
3,642,445
def get_attrs_titles_with_transl() -> dict: """Returns attribut titles and translation""" attr_titles = [] attrs = Attribute.objects.filter(show_in_list=True).order_by('weight') for attr in attrs: attr_titles.append(attr.name) result = {} for title in attr_titles: result[title] ...
167955e669ddb3f6d5bbbd48cc01d26155a9e4ba
3,642,446
def kde_KL_divergence_2d(x, y, h_x, h_y, nb_bins=100, fft=True): """Uses Kernel Density Estimator with Gaussian kernel on two dimensional samples x and y and returns estimated Kullback- Leibler divergence. @param x, y: samples, given as a (n, 2) shaped numpy array, @param h: width of the Gaussian k...
ce7ef19846dfd729fe5703aceaec69392f455ca6
3,642,447
def gml_init(code): """ Initializes a Group Membership List (GML) for schemes of the given type. Parameters: code: The code of the scheme. Returns: A native object representing the GML. Throws an Exception on error. """ gml = lib.gml_init(code) if gml == ffi.NULL: ...
5558f2db6a1c2269796cd52f675d5579ce357949
3,642,448
def before_run(func, force=False): """ Adds a function *func* to the list of callbacks that are invoked right before luigi starts running scheduled tasks. Unless *force* is *True*, a function that is already registered is not added again and *False* is returned. Otherwise, *True* is returned. """ ...
378604f6c574345682d8bd3d155ef8e4344aac27
3,642,449
def calc_z_scores(baseline, seizure): """ This function is meant to generate the figures shown in the Brainstorm demo used to select the 120-200 Hz frequency band. It should also be similar to panel 2 in figure 1 in David et al 2011. This function will compute a z-score for each value of the seizure p...
db3f6fbc42450658700ca2d120bf6faa31fccdfd
3,642,450
def get_column(data, column_index): """ Gets a column of data from the given data. :param data: The data from the CSV file. :param column_index: The column to copy. :return: The column of data (as a list). """ return [row[column_index] for row in data]
3fd5c8c76ccfed145aba0e685aa57ad01b3695a5
3,642,451
def analytic_solution(num_dims, t_val, x_val=None, domain_bounds=(0.0, 1.0), x_0=(0.5, 0.5), d=1.0, k_decay=0.0, k_influx=0.0, trunc_order=100, ...
0a920ec22fbe1ae3ff510ddd4389c1cf4ae0912d
3,642,452
def safe_gas_limit(*estimates: int) -> int: """Calculates a safe gas limit for a number of gas estimates including a security margin """ assert None not in estimates, "if estimateGas returned None it should not reach here" calculated_limit = max(estimates) return int(calculated_limit * constants...
439eca363dc1fe1f53972c69191513913feef39b
3,642,453
import typing def integer_years(dates: typing.Any) -> typing.List[int]: """Maps a list of 'normalized_date' strings to a sorted list of integer years. Args: dates: A list of strings containing dates in the 'normalized_date' format. Returns: A list of years extracted from "dates". ""...
cdf14f0a2fee197177f12ead43346dfd4eabb5ef
3,642,454
def add_wmts_gibs_basemap(ax, date='2016-02-05'): """http://gibs.earthdata.nasa.gov/""" URL = 'http://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi' wmts = WebMapTileService(URL) # Layers for MODIS true color and snow RGB # NOTE: what other tiles available?: TONS! #https://wiki.earthdata....
434ff85e1a721937ba83d0438bb7384d1a1f0600
3,642,455
import torch def encode_position( batch_size: int, axis: list, max_frequency: float, num_frequency_bands: int, sine_only: bool = False, ) -> torch.Tensor: """ Encode the Fourier Features and return them Args: batch_size: Batch size axis: List containing the size of eac...
06a81219b85006226069b288cce8602fc62e7119
3,642,456
def expr_erode(src, size = 5): """ Same result as core.morpho.Erode(), faster and workable in 32 bit. """ expr = _morpho_matrix(size, mm = 'min') return core.akarin.Expr(src, expr)
06f76f889cadcec538639ca1a920168c6a9ec467
3,642,457
def response_modification(response): """ Modify API response format. """ if ( status.is_client_error(response.status_code) or status.is_server_error(response.status_code) ) and (status.HTTP_400_BAD_REQUEST != response.status_code): return response # Modify the response d...
f8a3120f3a1671d71f32158b742212b896074bdc
3,642,458
import trace def process_source_lineage(grid_sdf, data_sdf, value_field=None): """ performs the operation to generate the """ try: subtypes = arcpy.da.ListSubtypes(data_sdf) st_dict = {} for stcode, stdict in list(subtypes.items()): st_dict[stcode] = subtypes[stcod...
298e615474debbb01addc583ae19fc1c5191084b
3,642,460
def class_to_mask(classes: np.ndarray, class_colors: np.ndarray) -> np.ndarray: """クラスIDの配列をRGBのマスク画像に変換する。 Args: classes: クラスIDの配列。 shape=(H, W) class_colors: 色の配列。shape=(num_classes, 3) Returns: ndarray shape=(H, W, 3) """ return np.asarray(class_colors)[classes]
c574594b18d312e9ce432b68c8c2ff4d73771e6f
3,642,461
from typing import List import logging def get_vocab(iob2_files:List[str]) -> List[str]: """Retrieve the vocabulary of the iob2 annotated files Arguments: iob2_files {List[str]} -- List of paths to the iob2 annotated files Returns: List[str] -- Returns the unique list of vocabula...
0dc2a1f969ed6f92b36b1b31875c855d5efda2d9
3,642,462
import numpy def taylor_green_vortex(x, y, t, nu): """Return the solution of the Taylor-Green vortex at given time. Parameters ---------- x : numpy.ndarray Gridline locations in the x direction as a 1D array of floats. y : numpy.ndarray Gridline locations in the y direction as a 1...
f47f4cdf11b81fe8b8c38ae50d708ec4361f7098
3,642,463
def static_initial_state(batch_size, h_size): """ Function to make an initial state for a single GRU. """ state = jnp.zeros([h_size], dtype=jnp.complex64) if batch_size is not None: state = add_batch(state, batch_size) return state
a803da5b0af0ce17fc7d1f303f6141416da6d120
3,642,464
def get_desklamp(request, index): """ A pytest fixture to initialize and return the DeskLamp object with the given index. """ desklamp = DeskLamp(index) try: desklamp.open() except RuntimeError: pytest.skip("Could not open desklamp connection") def fin(): desklamp...
8f00296f5625c8a80bb094d1e470936a0733b83e
3,642,465
import torch def conj(x): """ Calculate the complex conjugate of x x is two-channels complex torch tensor """ assert x.shape[-1] == 2 return torch.stack((x[..., 0], -x[..., 1]), dim=-1)
b22cfd3f12759f9b237099ca0527f0cbe9b99348
3,642,466
def label_clusters(img, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False): """ Label Clusters """ dim = img.dimension clust = threshold_image(img, min_thresh, max_thresh) temp = int(fully_connected) args = [dim, clust, clust, min_cluster_size, temp] processed_arg...
efe63ea0e71d3a5bf3b2f0a03f3c0f1c295c063b
3,642,467
def update_schema(schema_old, schema_new): """ Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_ne...
e97827ac0d8ee943b88fc54506af3f6fc8285d71
3,642,468
def get_estimators(positions_all, positions_relevant): """ Extracts density estimators from a judged sample of paragraph positions. Parameters ---------- positions_all : dict of (Path, float) A sample of paragraph positions from various datasets in the NTCIR-11 Math-2, and NTCIR-12 ...
b5f95247ff683e6e7e86d425ec64c988daacab60
3,642,469
def openbabel_force_field(label, mol, num_confs=None, xyz=None, force_field='GAFF', return_xyz_strings=True, method='diverse'): """ Optimize conformers using a force field (GAFF, MMFF94s, MMFF94, UFF, Ghemical) Args: label (str): The species' label. mol (Molecule, ...
9964d94d2601e5cd7871886e396778457bb6e2cd
3,642,470
def parse_flarelabels(label_file): """ Parses a flare-label file and generates a dictionary mapping residue identifiers (e.g. A:ARG:123) to a user-specified label, trees that can be parsed by flareplots, and a color indicator for vertices. Parameters ---------- label_file : file A flare...
23df49af14af720311b320f65894e995983365bf
3,642,471
def remove_background(data, dim="t2", deg=0, regions=None): """Remove polynomial background from data Args: data (DNPData): Data object dim (str): Dimension to perform background fit deg (int): Polynomial degree regions (None, list): Background regions, by default entire region ...
54141b6f28b7a21ebdf1b0b920af3bfea4303b07
3,642,472
def get_hmm_datatype(query_file): """Takes an HMM file (HMMer3 software package) and determines what data type it has (i.e., generated from an amino acid or nucleic acid alignment). Returns either "prot" or "nucl". """ datatype = None with open(query_file) as infh: for i in infh: ...
27653784b8a9fbae92226f8ea7d7b6e2b647765e
3,642,473
def detect_min_threshold_outliers(series, threshold): """Detects the values that are lower than the threshold passed series : series, mandatory The series where to detect the outliers threshold : integer, float, mandatory The threshold of the minimum value that will be consid...
6032693341073d101c0aad598a105f6cbc0ec578
3,642,474
from datetime import datetime def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw)
58479d70918dd287bfd29b1a15b6cd4dc1bfd695
3,642,475
def _to_str(x): """Converts a bool tensor to a string with True/False values.""" x = tf.convert_to_tensor(x) if x.dtype == tf.bool: return tf.where(x, 'True', 'False') return x
7919139e0f2cb19cd0856110e962acb616193ada
3,642,476
def inpaintn(x,m=100, x0=None, alpha=2): """ This function interpolates the input (2-dimensional) image 'x' with missing values (can be NaN of Inf). It is based on a recursive process where at each step the discrete cosine transform (dct) is performed of the residue, multiplied by some weights, and then th...
2fddabc6e512f9fc1ae7e8298f8d44582eaf7c46
3,642,477
def obtain_bboxs(path) -> list: """ obatin bbox annotations from the file """ file = open(path, "r") lines = file.read().split("\n") lines = [x for x in lines if x and not x.startswith("%")] lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces bboxs = [] for...
75ceaac4bd8500320007d2ffb4cf4c490bd29473
3,642,478
def Timeline_Integral_with_cross_before(Tm,): """ 计算时域金叉/死叉信号的累积卷积和(死叉(1-->0)不清零,金叉(0-->1)清零) 这个我一直不会写成 lambda 或者 apply 的形式,只能用 for循环,谁有兴趣可以指导一下 """ T = [Tm[0]] for i in range(1,len(Tm)): T.append(T[i - 1] + 1) if (Tm[i] != 1) else T.append(0) return np.array(T)
fdbd68e84e2a79a96c2078f92a7b69ab0138874e
3,642,479
from typing import Generator def list_image_paths() -> Generator[str, None, None]: """List each image path in the input directory.""" return list_input_directory(INPUT_DIRECTORIES["image_dir"])
bce70f2af3c42905a27a30bf97de0a993161130f
3,642,480
def a_star(graph: Graph, start: Node, goal: Node, heuristic): """ Standard A* search algorithm. :param graph: Graph A graph with all nodes and connections :param start: Node Start node, where the search starts :param goal: Node End node, the goal for the search :return: shortest_path: list|False Either a ...
ca25a15733d041cfca2560164ea8b047e55991b8
3,642,481
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True): """Take the model and model parameters, build and train the model""" # Build and compile model # To use other optimi...
af00f383311588525e66cff317908a99fa39859f
3,642,482
def gaussian_temporal_filter(tsincr: np.ndarray, cutoff: float, span: np.ndarray, thr: int) -> np.ndarray: """ Function to apply a Gaussian temporal low-pass filter to a 1D time-series vector for one pixel with irregular temporal sampling. :param tsincr: 1D time-series vecto...
54060dbfc84ce1738698fda893afb556b48396e4
3,642,483
import requests import json def get_mactable(auth): """ Function to get list of mac-addresses from Aruba OS switch :param auth: AOSSAuth class object returned by pyarubaoss.auth :return list of mac-addresses :rtype list """ url_mactable = "http://" + auth.ipaddr + "/rest/" + auth.version ...
8f81a03640d7a4ed0d6d70bcaf268b647dee987e
3,642,484