content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from scipy import ndimage def resample_ortho_sca(raw_image, raw_ulx, raw_uly, raw_pixel_size, x, y): """ Resample geosca image to new map grids. Arguments: raw_image: 2D array Raw geosca image data. raw_ulx, raw_uly: float Map coordinates of the upper-left corner of the...
5ce862c8215f283eafc0275a1c3d3efce3fdb581
3,624,200
from desitarget.myRF import myRF def isQSO_highz_faint(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None, objtype=None, release=None, dchisq=None, maskbits=None, primary=None, south=True): """Definition of QSO target for highz (z>2.0) faint QSOs. Returns a bo...
35cdde817cefcc8ce29aaa54c53373b71467bcc2
3,624,201
def obter_posicoes_jogador(tab, peca): """ Devolve as posicoes ocupadas pelo jogador. :param tab: tabuleiro :return: tuplo Recebe um tabuleiro, e devolve um tuplo com todas as posicoes ocupadas pelo jogador no tabuleiro inserido. """ return tuple(pos for pos in obter_posicoes() if pecas_i...
af5db2e3b3508aecdc0b923ad98f0631263affef
3,624,202
def find_true_link(s): """ Sometimes Google wraps our links inside sneaky tracking links, which often fail and slow us down so remove them. """ # Convert "/url?q=<real_url>" to "<real_url>". if s and s.startswith('/') and 'http' in s: s = s[s.find('http'):] return s
4d9824f0f67c5e463833f40e7db8365d5312fe46
3,624,203
from typing import List from typing import Optional import os import re def generate_png_stem(fnames: List[str], smiles_on_command_line: Optional[List[str]], config: Smiles2PngConfig) -> str: """Generate a stem for generated png files. Complicated by the fact that inpu...
d76d130b25492967c8074c7c2a1d235eeb623b06
3,624,204
def _get_block_indices(y): """ y is a length n_verts vector of labels returns a length n_verts vector in the same order as the input indicates which block each node is """ block_labels, block_inv, block_sizes = np.unique( y, return_inverse=True, return_counts=True ) n_blocks = l...
74a2fe1114040a61a19a9f387fdd43e21e3394c0
3,624,205
from typing import Tuple def _unmerge_points( board_points: Tuple[int, ...] ) -> Tuple[Tuple[int, ...], Tuple[int, ...]]: """Return player and opponent board positions starting from their respective ace points.""" player: Tuple[int, ...] = tuple( map( lambda n: 0 if n < 0 else n, ...
25965e023030266cc92e6b1456483204ad2c863a
3,624,206
def abort_training(config, instance_id, submission_id): """ Stop training a submission. This is done by killing the screen where the training process is. Parameters ---------- instance_id : str instance id submission_id : int submission id """ cmd = 'screen -S ...
df928352e33f094da9cbf67462438b19d292b68d
3,624,207
import logging import re def get_renamed_job_folder_from_list(job_id, file_list): """ Get renamed job folder from list of filenames Parameters ---------- job_id : int job_id to check the existence of a renamed job folder for file_list : list List of filenames to check the exis...
87ad27278d3a4019c0e8708448562fa9247e54f6
3,624,208
from re import T def elu(x, alpha=1.0): """ Exponential linear unit # Arguments x: Tensor to compute the activation function for. alpha: scalar """ _assert_has_capability(T.nnet, 'elu') return T.nnet.elu(x, alpha)
36a232625ca849148a36a796abe3bebaf24c265f
3,624,209
from consts import REGION import requests import logging def guess_region(local_client): """ 1. read the consts.py 2. try read the battlenet db OR config get the region info. 3. try query https://www.blizzard.com/en-us/user 4. failed return "" """ if REGION: return REGION try:...
39a7fa720690da755239ae7f77bf6162a1bd9761
3,624,210
import logging import pprint def textfsm_to_pd(srt, name, adj): """ Parses routing table in textfsm format as returned by netmiko :param srt: Source routing table :param name: Name of the router :param adj: Adjacency information :return: Routing table as pandas dataframe """ logger = ...
7cc17ec258c1f21086646d61f08e5db72d469ca8
3,624,211
def set_categorical_variables(column_names, categorical_variables=None): """ Set categorical variables. This helper functions determines a logical boolean vector based on the column names and the designation for which ones are categorical variables. :param column_names: A list of strings; ...
1226796265e0a93515ff6d3c43666ffece416d21
3,624,212
import time def compute_features(lyrics, tdm_indices): """Create new superficial lyrics features. Return df with the new features in columns and one row per track.""" start = time.time() total_num_words = np.zeros(len(tdm_indices)) tdm = lyrics['tdm'].toarray() for i in range(len(tdm_indices)...
9aca78dfa8abfa77211320ac29a5012468fc3a27
3,624,213
import json def from_json_string(my_str): """Returns an object (Python data structure) represented by a JSON string: Arguments: my_str (obj) -- json str Returns: obj -- object """ return json.loads(my_str)
cb013514b62456d6c628cf4ebea475b54851dfa4
3,624,214
def getProgress(): """Get progress of jackalify.""" global it global max_it return (it * 100 // max_it) if max_it > 0 else 0
b0557d94e7c61fa06e69e3c1790adb2ebb37d256
3,624,215
import math def generate_round(): """ Генерируем раунд. Returns: str: question Вопрос пользователю str: result Правильный ответ на вопрос """ first_num, second_num = generate_question() question = "{one} {two}".format(one=first_num, two=second_num) answer = str(math.gcd(fi...
3dc6292e379ac2067fae5d06dd524385c70a3af2
3,624,216
def filter_separation(catalogue, T_observed, antenna=None, separation_deg=1, sunmoon_separation_deg=10): """ Removes targets from the supplied catalogue which are within the specified distance from others or either the Sun or Moon. @param catalogue: [katpoint.Catalogue] @param T_observed: UTC times...
1e2aa84c2f0a185fd2cd3b940b88724cdd46528c
3,624,217
def cconv_transpose_backprop_filter( filter, out_positions, out_importance, extent, offset, inp_positions, inp_features, inp_neighbors_index, inp_neighbors_importance, inp_neighbors_row_splits, neighbors_index, neighbors_importance, neighbors_row_splits, out_features_gradient, align_corn...
8fc8df9f9a1a050beabcca66ed0862ea0ce277b0
3,624,218
from typing import Any def to_str(object_: Any) -> str: """ >>> to_str(b"ass") 'ass' >>> to_str("ass") 'ass' >>> to_str(None) '' >>> to_str({"op": "oppa"}) "{'op': 'oppa'}" """ if object_ is None: return "" if isinstance(object_, bytes): return object_....
1e6606db7ad2f4dee219d84703cae49c2c6566fc
3,624,219
def _create_dummy_adata(n_obs: int) -> AnnData: """ Create a testing :class:`anndata.AnnData` object. Call this function to regenerate the ground truth objects. Parameters ---------- n_obs Number of cells. Returns ------- :class:`anndata.AnnData` The created adata ...
c0f1f30bd91e6958028d50ee4355dfecba2bcfb2
3,624,220
from typing import Dict from typing import Optional async def fetch_stats_data(label: str) -> Dict[str, Optional[float]]: """Get available stats in Redis.""" try: return await get_stats_dict(label) except NotFoundError: raise HTTPException(404)
dce03f9051b257e777005fda5e476e4b559e4f5f
3,624,221
def get_bse(da, da_peak_times): """ Takes an xarray DataArray containing veg_index values and calculates the vegetation value base (bse) for each timeseries per-pixel. The base is calculated as the mean value of two minimum values; the min of the slope to the left of peak of season, and the min of...
3edaf6156bd9fdae15c3bf845eb3deb293489cfb
3,624,222
def approx_2rd_deriv(f_x0,f_x0_minus_1h,f_x0_minus_2h,h): """Backwards numerical approximation of the second derivative of a function. Args: f_x0: Function evaluation at current timestep. f_x0_minus_1h: Previous function evaluation. f_x0_minus_2h: Function evaluations two timesteps ago....
b5c93902bf39d32bf84db38476f8fab4772f5fc9
3,624,223
def ind_from_latlon(lats,lons,lat,lon,verbose=False): """Find the nearest neighbouring index to given location. Args: lats (2d array): Latitude grid lons (2d array): Longitude grid lat (float): Latitude of location lon (float): ...
32f35810f0e857061b95f593a26880e561378596
3,624,224
def get_dict_key_by_value(val, dic): """ Return the first appeared key of a dictionary by given value. Args: val (Any): Value of the key. dic (dict): Dictionary to be checked. Returns: Any, key of the given value. """ for d_key, d_val in dic.items(): if d_val ==...
d01522a61d7a0549ed54bfcb620da10857d67ae7
3,624,225
import json def isJson(var=''): """ Check json >>> isJson(var='') False >>> isJson('') False >>> isJson('{}') True """ result = True try: json.loads(var) except Exception as e: result = False return result
dc146fff1449df844ce0ac00607d77b5e2dc4370
3,624,226
def count_ontarget_samples(df, human_readable=False): """ Function to count usable samples. Parameters ---------- df: DataFrame human_readable: Boolean, optional default=False Returns ------- ontarget_counts: DataFrame MultiIndexed if human_readable, otherwise ...
3bb2532017089ab08ac53422baaa55a5b38ee4e3
3,624,227
def export_obj(mesh, include_normals=True, include_color=True, include_texture=True): """ Export a mesh as a Wavefront OBJ file Parameters ----------- mesh : trimesh.Trimesh Mesh to be exported Returns ----------- export : str OBJ ...
c9679f7fe7536dfa3b4f69bee0e223d264d15001
3,624,228
def parse_csv_data(csv_filename: str) -> list: """This function will take the csv data from the csv file and return it as a list """ dataframe = pd.read_csv(csv_filename) return dataframe.values.tolist()
7b54ceafdd0687c5c823b8b83237ba268f244780
3,624,229
def classification_three_depth_manual_pipeline(): """ Returns pipeline with the following structure: logit \ knn \ rf / knn -> final prediction rf -> qda / Where rf - xg boost classifier, logit - logistic regression, knn - K nearest neighbors classifier, qda - discriminant...
48c57a177bc269e2b4d9157fa812734cec8fb164
3,624,230
def convert_ref_to_link (match): """Converts a reference to a model object to an HTML link. :param match: match on a reference :type match: `re.MatchObject` """ model_name = match.group('model') obj_id = match.group('id') if model_name == 'site': try: site = sculpture.m...
6015ea39e252a66c89af018414828a229f042fb0
3,624,231
import heapq def find_many_shortest_paths(source_node, target_nodes, get_edges, max_path_cost=None): """ Like `find_shortest_path`, except that it finds shortest paths between the source node to a list of target nodes. It returns a list of tuples (path, path_cost). If a path is not found, the cor...
0bd408ba16d8fe0dbf2b5b9aa9584d77874767cb
3,624,232
def convertToMapPic(byteString, mapWidth): """convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.""" data = [] line = "" for idx,char in enumerate(byteString): line += str(ord(char)) if ((idx+1)%mapWidth)==0: data.append(...
f6d78db10efc041cb55208f5428c99c25bd5ab5d
3,624,233
def compute_edge_costs(probs, edge_sizes=None, z_edge_mask=None, beta=.5, weighting_scheme=None, weighting_exponent=1.): """ Compute edge costs from probabilities with a pre-defined weighting scheme. Arguments: probs [np.ndarray] - Input probabilities. edge_sizes [np.ndar...
ba6c1f6f680a38667a34844ed81250d04f570ca8
3,624,234
def correlation_coefficient(lagged_x, y, lag): """ Routine to determine the correlation coefficient between two data series with a certain lag shift on one of the series Input: lagged_x: The series that will be shifted by a certain lag y: The series that will not be affected by the lag shift lag: The number o...
2aa125609bdd544e4575d5130e42549ffb1cc346
3,624,235
def phar_from_mol(ligand): """Create Pharmacophore from given pybel.Molecule object.""" if not isinstance(ligand, pybel.Molecule): raise TypeError("Invalid ligand! Expected pybel.Molecule object, got " "%s instead" % type(ligand).__name__) matches = {} for (phar, pattern...
9d0c0c5356009d682354a6b3bd5634fd8da32c7f
3,624,236
def solve(data): """Solves an instance of the flow shop scheduling problem""" # We initialize the strategies here to avoid cyclic import issues initialize_strategies() global STRATEGIES # Record the following for each strategy: # improvements: The amount a solution was improved by this strate...
3ade7cc7b6c04e52e273868bfe87715dbfa50731
3,624,237
import urllib def player_embed_url(key, player, format='js'): """ Return a signed URL pointing to a player initialised with a specific media item. :param key: JWPlatform key for the media. :param player: JWPlatform player key. :param format: (optional) Either ``'js'`` or ``'html'`` depending on w...
0784baa06e4ca98ccc32c430a0099d07bda1fd94
3,624,238
import codecs def __regex_parse_documents_from_file(file_path, encoding='latin-1'): """Loads all documents from the given SGML file using REGEX and returns them """ # read whole file content = None with codecs.open(file_path, 'r', encoding=encoding) as file: content = file.read() ...
eeb673d85d8a0dff410460c87e90d0ff4ee9f3b0
3,624,239
def tone_to_note(tone): """Convert a tone to a music21 note.""" if not isinstance(tone, Tone): raise ValueError('{} is not a Tone instance'.format(tone)) if isinstance(tone, Rest): return note.Rest(quarterLength=tone.duration) if isinstance(tone, (Frequency, Vector)): p = pitch...
1dc3e018a9767b82bf07041d05cd9d38ace02d5d
3,624,240
from typing import Tuple from typing import Dict from typing import Any import json def _extract_multipart_params( data: MultiDictProxy, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """Validate and extract the operations and map fields from the data. :param data: the data from which extract fields :ty...
77843d910141bd0c745c8afc2604273be1a4385d
3,624,241
def build_metadata(sequence, prefix, idx, keys, metadata_type="synergy"): """when adding non NN sequences, make metadata to match up sequences """ # generate for all keys metadata = {} for key in keys: metadata[key] = 0 # adjust some manually metadata[DataKeys.SEQ_METADATA] = "featu...
521f93ce7675ef44dac3753d4da4cee7b2c48834
3,624,242
import csv def _read_file_to_dict(path): """ Load the problems and the corresponding labels from the *.txt file. :param path: The full path to the file to read :return: The dictionary with the problem names as keys and the true class labels as values """ label_dict = {} with open(path, 'r'...
83bd3b04afc995176dc4dfefb9863b9f1ba09888
3,624,243
def histograms(): """ histograms page """ _js_resources = Resources(mode="cdn", log_level='info').render_js() _css_resources = Resources(mode="cdn", log_level='info').render_css() _histograms = server_document(FLASK_URL + '/bkapp-histograms', resources=None) return render_template("embed.html", ...
0701ae3082dba94dc8120a008ad346601db59b3e
3,624,244
def closest_val(val, arr): """ Finds the closest value in `arr` to `val` Parameters ------------- val: int or float value to be looked at arr: numpy.ndarray numpy array used for finding closest value to `val` Returns ------------- idx_choice: int index for ...
c69e76061cf5ed78ed4ac4f4604307b8ba5c9db0
3,624,245
def generate_prior(dist, **kwargs): """Generate a Prior distribution. The parameter ``kwargs`` is used to pass hyperpriors that are assigned to the parameters of the prior to be built. Parameters ---------- dist: str, int, float If a string, it is the name of the prior distribution wit...
1ed3096a060e0aa8dc9c08686a9cf654ef6f8221
3,624,246
import pybtas def thc_via_cp3(eri_full, nthc, thc_save_file=None, first_factor_thresh=1.0E-14, conv_eps=1.0E-4, perform_bfgs_opt=True, bfgs_maxiter=5000, random_start_thc=True, verify=False): """ THC-CP3 performs an SVD decomposition of the eri matrix followed by a CP decomposition via py...
468ef4a35331d5442ccba2356da83c616bb37045
3,624,247
def sla_list_safe_domain(cluster, percentage, duration): """usage: sla_list_safe_domain [--exclude_file=FILENAME] [--exclude_hosts=HOSTS] [--grouping=GROUPING] [--include_file=FILENAME] [--include_hosts=HOSTS] [--list_jobs] [--min_job...
7e8fe5057fe8bfb7deb8db38c8699491be703ee9
3,624,248
def check_safety_line(path, safety_line): """Return true if the file starts with the safety line.""" with open_file(path, "r") as file: return file.readline().rstrip('\n') == safety_line
0b40bdeec6597bb63c45371ba1471140b4c1a470
3,624,249
import os import lzma import gzip def zopen(filename, mode): """Open filename.xz, filename.gz or filename.""" filenamexz = str(filename) if str(filename).endswith(".xz") else str(filename) + '.xz' filenamegz = str(filename) if str(filename).endswith(".gz") else str(filename) + '.gz' if os.path.exists(...
d0a0c6221b9c73d5e13d6eaa84c321a6d332720b
3,624,250
def make_input(subject, attribute): """Generates the HTML for an input field for the given attribute. 'subject' can be None to set up an empty form for a new subject.""" name = attribute.key().name() return ATTRIBUTE_TYPES[attribute.type].make_input( name, subject and subject.get_value(name), at...
78319d66ebf7b93609837d16172a5c0cb789e7d7
3,624,251
import copy def hs_mod_opti_step(x_n, x, u, u_n, F, dt, params): """ Must be equal to zero in order to fulfill the implicit scheme Returns ------- res : Numpy array or Casadi array Residue to minimize """ dim = vec_len(x) // 2 f = F(x, u, params)[dim:] f_n = F(x_n, u_n, p...
95fee7c69fcafba07237a9a5e2ba19911d9e45d2
3,624,252
import httpx import async_timeout async def async_setup_platform( homeassistant, config, async_add_entities, discovery_info=None ): """Set up the Enphase Envoy sensor.""" ip_address = config[CONF_IP_ADDRESS] monitored_conditions = config[CONF_MONITORED_CONDITIONS] name = config[CONF_NAME] user...
41c774d896cfe3cdbff0d28508b8fefb564450a7
3,624,253
def window_rowcol(lon_arr, lat_arr, bbox=None): """Get the row bounds and col bounds of a box in lat/lon arrays Returns: (row_top, row_bot), (col_left, col_right) """ if bbox is None or len(bbox) == 0: return (0, len(lat_arr)), (0, len(lon_arr)) left, bot, right, top = bbox lat...
0d4781d5f7dd656ea80d71444eedb3209fe6c307
3,624,254
def success() -> int: """Represent `200` success status code""" return _success
101d26355154808571dcb003c7c17982f798f215
3,624,255
def close_connection(self, connection): """Summary Method closes a specific connection or the class scoped connection if none specified. Args: connection (ibm_db.connection, optional): connection to close Returns: boolean: Success or fail of connection closing """ re...
aa0367e4230b372a6d9c75557933aad832a7a736
3,624,256
def pa(text, nlp, language_code='en'): """Percentage of Adjectives in text.""" pa = None doc = nlp(text) words_num, _ = word_counter(text, language_code) adjectives = [token.lemma_ for token in doc if token.pos_ == 'ADJ'] adjectives_num = len(adjectives) if words_num != 0: pa = ...
c371f4f22a86edb93ada0c8b1136f3abf5344db8
3,624,257
import numpy as np import typing def less_than(lhs: typing.SupportsFloat, rhs: typing.SupportsFloat): """Compare the left-hand-side to the right-hand-side. Follows the Numpy logic for normalizing the numeric types of *lhs* and *rhs*. """ dtype = int if any(isinstance(operand, float) for operand i...
5f862e669a2795a32b831e0590284bd1235c0747
3,624,258
def is_revoked(jti: str) -> bool: """ Returns True if a given token is revoked. """ b = TokenBlocklist.query.filter_by(jti=jti).first() return b is not None
45bc02e981878f76007664062be85af915081403
3,624,259
from typing import Union def gen_neutral_srcmap_func(original_text: Union[StringView, str], original_name: str = '') -> SourceMapFunc: """Generates a source map functions that maps positions to itself.""" if not original_name: original_name = 'UNKNOWN_FILE' return lambda pos: SourceLocation(original_name...
6036ada29b4bb24805f92608e5522da0d643af1c
3,624,260
import requests def get_request(url: str, headers: dict) -> requests.Response: """ Wrapper for requests.get call to use refresh token :param url: request URL :param headers: request headers :return: requests.Response """ response = requests.get(url, headers=headers) if response.status_...
c44722543e62ddbd8d3d95e6934d45d7000e5e6c
3,624,261
def geometric_progression_for_stepsize(x, update, dist, randomimg, params): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary, """ epsilon = dist / np.sqrt(params['cur_iter']) def phi(epsilon): new = x ...
453688872ae3cde305abe61a91c44808c4f32ca8
3,624,262
def trace(fn): """Decorator that marks a function to be traced.""" fn.should_trace = True return fn
598d81b2f4050b78cd42c835c5ce3bcc41c87541
3,624,263
def ape_update_bios_firmware_version(cookie, in_config): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ApeUpdateBIOSFirmwareVersion") method.cookie = cookie method.in_config = in_config xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
47b25c8232993e3e0f0c2f358e480cbdc208ea75
3,624,264
def squish_sound(src, percent): """Squish an audio file.""" sr, sound = wav.read(src) # Stretch the sound by the given percentage squish = rb.pyrb.time_stretch(sound, sr, 1 + percent) # Add silence to produce a sound with the same length as the original silence = np.zeros(len(sound) - len(squish...
59f9bd5e5543641669dbd0987adad81bdeaf2c7e
3,624,265
def create_tables_command(schema_file): """create one table for existing database :param number_of_companies: number_of_companies :type number_of_companies: int :param schema_file: schema file :type schema_file: json """ command_list = [] for table_name in TABLE_LIST: schema = g...
5a8150d412235eb4216322fabc2644a96882bc16
3,624,266
import os import json def _conf(): """Try load local conf.json """ fname = os.path.join(os.path.dirname(__file__), "conf.json") if os.path.exists(fname): with open(fname) as f: return json.load(f)
bdc4376e9fd6b5721cba54d48d07d12ab907223c
3,624,267
def get_key(key): """ Get key :param: key - Color key """ return key.replace('-', '')
62aa5a9c08994ced2ec0c5da283d408685d8f583
3,624,268
import csv def readPlumes(filename, logger=None): """ read plumes from filename that contains plume time and lat lon """ if logger is not None: logger.info("reading {}".format(filename)) with open(filename,'rt') as fin: plumes = list(csv.DictReader(fin, skipinitialspace=True)) ...
2bf6ee36807e970b5180f7075fa1b1e70493bb5d
3,624,269
def __dense_p(name, x, w=None, output_dim=128, initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, bias=0.0): """ Fully connected layer :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope. :param x: (tf.tensor) The input to the layer (...
f298dea87476c83d590a8b844e6ff64484d30586
3,624,270
def get_sm_tag_from_alignedseg(aln): """Get 'sm' tag from AlignedSegment.""" try: return aln.get_tag('sm') except Exception as e: raise ValueError("Could not get 'sm' tag from {aln}".format(aln=aln))
ca23604f724f75bf4c399374547f1468c6c5df9b
3,624,271
import requests def get_image_info(url): """Returns the content-type, image size (kb), height and width of an image without fully downloading it. :param url: The URL of the image. """ try: r = requests.get(url, stream=True) except requests.ConnectionError: return None im...
d3e3453e27ff6392808cf3c10e3da98573c4d394
3,624,272
def limdrift(g, tau, acyrus=0.25): """ Use Cyrus Umrigar's algorithm to limit the drift near nodes. :parameter g: a [nconf,ndim] vector :parameter tau: time step :parameter acyrus: the maximum magnitude :returns: The vector with the cut off applied and multiplied by tau. """ tot = np.li...
97845ff4f6d450129c6adae54ce5baa9be1d5667
3,624,273
def service2(backends_mapping, custom_service, service_settings2, service_proxy_settings, lifecycle_hooks): """ We need second service to test with because we want to test deletion of active docs and that needs to be tested on separate service. """ return custom_service(service_settings2, service_pr...
eca7cfe0869f051aa03494bfd9ec0e0083c856c0
3,624,274
import argparse def parse_arguments(args_to_parse): """ Parse the command line arguments. Arguments: args_to_parse: CLI arguments to parse """ parser = argparse.ArgumentParser( description='Split the two CTM files (*.stm) (alignment files) into the respective lattice file dire...
978b83b96ecbbd562c4f675bfb64b32c5e624246
3,624,275
def random_noise_image(img, new_dims, new_scale, interp_order=1 ): """ Add noise to an image Args: im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. new_scale : (min, max) tuple of new scale. interp_order : interpolation order, default is l...
68468399c220e4b92dd2b831e3932b4c62f4645d
3,624,276
def get_fixed_length_string(string: str, length=20) -> str: """ Add spacing to the end of the string so it's a fixed length. """ if len(string) > length: return f"{string[: length - 3]}..." spacing = "".join(" " for _ in range(length - len(string))) return f"{string}{spacing}"
e77f3c7ed72efc3b86d378fa6cf9bde4eae95647
3,624,277
import numpy def V3(meanFalse, meanTrue, sample): """ This NMC distance metric scores samples by considering a point that is halfway {meanFalse, meanTrue}, then calculating the cosine of the angle {sample, halfway, meanTrue}. Points towards meanTrue get a score of close to +1, while points towards mea...
ad94501d57a24ff07b2dd21bc4965ea495f0f7c7
3,624,278
def choicelist_choices(): """Return a list of all choicelists defined for this application.""" l = [] for k, v in CHOICELISTS.items(): if v.verbose_name_plural is None: text = v.__name__ else: text = v.verbose_name_plural l.append((k, text)) l.sort(key=la...
b4c25fb816a59a083d98870bd84124e29a114acb
3,624,279
def store_inspection_outputs(annotation_iterators, return_value) -> BackendResult: """ Stores the inspection annotations for the rows in the dataframe and the inspection annotations for the DAG operators in a map """ annotations_df = build_annotation_df_from_iters(singleton.inspections, annotation_i...
e0f328c0141f2e559ab7ce0d33ab5ffad6c3dbf9
3,624,280
def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None: """ Given two lists of rotated boxes of size N and M, compute the IoU (intersection over union) between __all__ N x M pairs of boxes. The box order must be (x_center, y_center, width, height, angle). Args: boxes1, box...
2627a250118f92b553c8f667103bf8fe551a3f9f
3,624,281
def specific_gravity(temp, salinity, pressure): """Compute seawater specific gravity. sg = C(p) + β(p)S − α(T, p)T − γ(T, p)(35 − S)T units: p in “km”, S in psu, T in ◦C C = 999.83 + 5.053p − .048p^2 β = .808 − .0085p α = .0708(1 + .351p + .068(1 − .0683p)T) γ = .003(1 − .059p − .012(1 − ....
37ee32d3842cd5f9645449b23feb4d8315536fe2
3,624,282
def rollaxis(tensor, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer `moveaxis`. Parameters ---------- a : Tensor Input tensor. axis : int ...
703c617db089bb75a3deee38b637173313ddb6bd
3,624,283
from typing import Optional from typing import Union from pathlib import Path from typing import Dict from typing import List import os def snapshot_download( repo_id: str, *, revision: Optional[str] = None, repo_type: Optional[str] = None, cache_dir: Union[str, Path, None] = None, library_nam...
7a5470ef840c43dd5d64d104deb4a7c3986e6b3a
3,624,284
def cdc_long_spec( topic:str, key_schema_name:str, key_schema_version:str, value_schema_name:str, value_schema_version:str, ): """ Create a CdcSpec opaque object (necessary for one argument in a call to consume*ToTable) via explicitly specifying all configuration opti...
39baa718d0cde6f0007e152b9ce1de0056313fec
3,624,285
def record(MyRecord, db): """Create a record instance of MyRecord.""" return MyRecord.create({'title': 'test'})
f4216400ceddaf415fbad97d74e8f55b35835511
3,624,286
def reciprocal_mod(input_x, input_m): """ # Based on a simplification of the extended Euclidean algorithm :param input_x: :param input_m: :return: """ assert 0 <= input_x < input_m intermediate_y = input_x input_x = input_m intermediate_a = 0 intermediate_b = 1 while in...
2d35399fbd84509012600efd1c5663b123cb9b2a
3,624,287
def sort_by_expl_var(u, z, v, hrf_rois): # pragma: no cover """ Sorted the temporal the spatial maps and the associated activation by explained variance. Parameters ---------- u : array, shape (n_atoms, n_voxels), spatial maps z : array, shape (n_atoms, n_times_valid), temporal components ...
782560007126239cc3ba0f666622553ff91751de
3,624,288
def np(self): """ Returns numpy array of the object. It returns coordinates,(and ids for line and polygon) XY coordinates are always place last. Note ---- x:x-coordinate y:y-coordinate lid: line id pid: polygon id cid: collection id Output ------ ndarray: 2D array shape: Point, (npoi...
3c636f0c34676af38d65ca1527e868b070f7e57b
3,624,289
def _common_gpipe_transformer_fprop_meta(p, inputs, *args): """GPipe FPropMeta function.""" # TODO(huangyp): return accurate estimate of flops. py_utils.CheckShapes((inputs,)) flops_per_element = 5 src_time, source_batch, dim = inputs flops = flops_per_element * src_time * src_time * source_batch * dim ar...
03782b693bb1af259d7f8c838bd7e9be32627427
3,624,290
def random_closure(a, N=1000): """Sample a random fiber orientation and compute fourth order tensor. Parameters ---------- a : 3x3 numpy array Second order fiber orientation tensor. Returns ------- 3x3x3x3 numpy array Fourth order fiber orientation tensor. """ orie...
7c8a797b35b17c3eb93ebd5b520c2076e1135cd4
3,624,291
def get_tt_data(df): """ Returns training and test for given workload X_train, X_test are pandas dataframes y_* are 1d numpy array :param workload: :return: X_train, X_test, y_train, y_test """ # Drop fields df = df.drop('CPUTime', axis=1) df = df.drop('UsedMEM', axis=1) ...
6eb7d5390cee8ec9c0ee2125db0273ae503b0437
3,624,292
def recomposite_from_log_components(log_reflectance, log_shading): """Combines log_reflectance and log_shading to produce an rgb image. I = R x S = e^(log_reflectance + log_shading) Args: log_reflectance: [B, H, W, 3] Log-reflectance image log_shading: [B, H, W, 1 or 3] Log-shading image Returns: ...
0acfa6ca848cecba0c0172d4fd12abb451095a87
3,624,293
def nrepeat(ts): """ Return the length of consecutive runs of repeated values Parameters ---------- ts: DataFrame or series Returns ------- Like-indexed series with lengths of runs. Nans will be mapped to 0 """ if isinstance(ts,pd.Series): return _nrepeat(ts) ...
1a80d86dd14a83a316a2130baf75e9540d3d5e71
3,624,294
def check_transform_series(X_list, y): """Returns X, y that have been transformed into numpy arrays. This mirrors the sktime implementation. Args: X_list: pandas DataFrame The array is presented by pandas. y: pandas DataFrame The array is presented by pandas. Re...
b3f9a9d47a2a85d930fcea26e6846222281ffcea
3,624,295
from typing import Optional import os def ensure_cpu_count(use_threads: bool = True) -> int: """Get the number of cpu cores to be used. Note ---- In case of `use_threads=True` the number of threads that could be spawned will be get from os.cpu_count(). Parameters ---------- use_threads :...
31e00fd7d5a9e7c91cdee97adb0cfa95a4679ee9
3,624,296
def scale_all(dat, scl_prms, min_out, max_out, standardize): """ Uses the provided scaling parameters to scale the columns of dat. If standardize is False, then the values are rescaled to the range [min_out, max_out]. """ dat_dtype = dat.dtype fets = dat_dtype.names num_scl_prms = len(sc...
1038b25c8b40eb981d8b60c5565f349f6a8cd0ed
3,624,297
def ard_netcdf_encoding(ard_ds, metadata, **encoding_kwds): """ Return encoding for ARD NetCDF4 files Parameters ---------- ard_ds : xr.Dataset ARD as a XArray Dataset metadata : dict Metadata about ARD Returns ------- dict NetCDF encoding to use with :py:meth:`...
ba7d785658c2fe3b068eb4b5e8436a1cc06a1513
3,624,298
def recommendation_response(agent, resource_id, recency_limit, scale, logger): """ Giving back the direct XP as the recommendation on other agent in the point of view from agent. :param agent: The agent which calculates the popularity. :type agent: str :param resource_id: The URI of the evaluated r...
c9d962f4b5d4afa2e8d3557ddb936904a4d00f67
3,624,299