content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _combine_by_cluster(ad, clust_key='leiden'): """ Given a new AnnData object, we want to create a new object where each element isn't a cell, but rather is a cluster. """ clusters = [] X_mean_clust = [] for clust in sorted(set(ad.obs[clust_key])): cells = ad.obs.loc[ad.obs[clust_k...
2d48a9f504050604a679f35c06916c175e813ffe
3,642,021
def subsample_data(features, scaled_features, labels, subsamp): # This is only for poker dataset """ Subsample the data. """ # k is class, will iterate from class 0 to class 1 # v is fraction to sample, i.e. 0.1, sample 10% of the current class being iterated for k, v in subsamp.items(): ix = n...
3981fb0c793f64d52fc21cf2bbf87975bf97c786
3,642,022
def anomary_scores_ae(df_original, df_reduced): """AEで再生成された特徴量から異常度を計算する関数""" """再構成誤差を計算する異常スコア関数 Args: df_original(array-like): training data of shape (n_samples, n_features) df_reduced(array-like): prediction of shape (n_samples, n_features) Returns: pd.Series: 各データごとの異常スコア...
f6fe2dca7c10e19ee1e0a03a8d94c663ef5d77fd
3,642,023
import logging def latest_res_ords(): """Get last decade from reso and ords table""" filename = 'documentum_scs_council_reso_ordinance_v.csv' save_path = f"{conf['prod_data_dir']}/documentum_scs_council_reso_ordinance_v" df = pd.read_csv(f"{conf['prod_data_dir']}/{filename}", low_memory=False...
c23b26e878887758c6822164bcac33eb7c28f765
3,642,025
def langevin_coefficients(temperature, dt, friction, masses): """ Compute coefficients for langevin dynamics Parameters ---------- temperature: float units of Kelvin dt: float units of picoseconds friction: float collision rate in 1 / picoseconds masses: array...
a95ba22bda908fdd10171ed63eba1dc7906c0c1f
3,642,026
def get_description(): """ Read full description from 'README.md' :return: description :rtype: str """ with open('README.md', 'r', encoding='utf-8') as f: return f.read()
9a73c9dbaf88977f8c96eee056f92a7d5ff938fd
3,642,027
def qt_matrices(matrix_dim, selected_pp_indices=[0, 5, 10, 11, 1, 2, 3, 6, 7]): """ Get the elements of a special basis spanning the density-matrix space of a qutrit. The returned matrices are given in the standard basis of the density matrix space. These matrices form an orthonormal basis unde...
8e444fae5b936f4e20f615404712c91a5bbe3f4c
3,642,028
def get_signed_value(bit_vector): """ This function will generate the signed value for a given bit list bit_vector : list of bits """ signed_value = 0 for i in sorted(bit_vector.keys()): if i == 0: signed_value = int(bit_vector[i]) else: signed_...
6b2b9a968576256738f396eeefba844561e2d2c7
3,642,029
def get_number_from_user_input(prompt: str, min_value: int, max_value: int) -> int: """gets a int integer from user input""" # input loop user_input = None while user_input is None or user_input < min_value or user_input > max_value: raw_input = input(prompt + f" ({min_value}-{max_value})? ") ...
c9df4ac604b3bf8f0f9c2a35added1f23e88048e
3,642,032
def word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths): """ Calculate word saliency according to [Chuang2012]_ as ``saliency(w) = p(w) * distinctiveness(w)`` for a word ``w``. .. [Chuang2012] J. Chuang, C. Manning, J. Heer. 2012. Termite: Visualization Techniques for Assessing Textual Topic ...
47acaa848601192837eceef210389ada090b1fec
3,642,033
import json def parse_cl_items(s): """Take a json string of checklist items and make a dict of item objects keyed on item name (id)""" dispatch = {"floating":Floating, "weekly":Weekly, "monthly": Monthly, "daily":Daily } if len(s) == 0: ...
274374f8ad3048f7bf9f17ed7d43740a83900a63
3,642,034
def get_queue(queue, flags=FLAGS.ALL, **conn): """ Orchestrates all the calls required to fully fetch details about an SQS Queue: { "Arn": ..., "Region": ..., "Name": ..., "Url": ..., "Attributes": ..., "Tags": ..., "DeadLetterSourceQueues": ..., ...
b39ea959835fc3ae32042cabac4bc4f9b5f1c425
3,642,035
def mixed_float_frame(): """ Fixture for DataFrame of different float types with index of unique strings Columns are ['A', 'B', 'C', 'D']. """ df = DataFrame(tm.getSeriesData()) df.A = df.A.astype('float32') df.B = df.B.astype('float32') df.C = df.C.astype('float16') df.D = df.D.ast...
aaef420666cf714c45bb87bf7e1eb484a4c06f69
3,642,036
import unittest def create_parsetestcase(durationstring, expectation, format, altstr): """ Create a TestCase class for a specific test. This allows having a separate TestCase for each test tuple from the PARSE_TEST_CASES list, so that a failed test won't stop other tests. """ class TestParse...
b74dbb969743bc98e22bfd80677da7f02891391e
3,642,037
import time import traceback def draw_data_from_db(host, port=None, pid=None, startTime=None, endTime=None, system=None, disk=None): """ Get data from InfluxDB, and visualize :param host: client IP, required :param port: port, visualize port data; optional, choose one from port, pid and system :pa...
73aa86b18dff59fdf88eff0b173e32fa4f3ed3ed
3,642,038
def get_sample_generator(filenames, batch_size, model_config): """Set data loader generator according to different tasks. Args: filenames(list): filenames of the input data. batch_size(int): size of the each batch. model_config(dict): the dictionary containing model configuration. ...
2033e081addf26a8f9074591b2f8992f39ed86c1
3,642,039
def execute_batch(table_type, bulk, count, topic_id, topic_name): """ Execute bulk operation. return true if operation completed successfully False otherwise """ errors = False try: result = bulk.execute() if result['nModified'] != count: print( "bulk ...
954de6b5bfefcea7a7bfdebdc7cb7b1b1ba1dd95
3,642,040
def process_domain_assoc(url, domain_map): """ Replace domain name with a more fitting tag for that domain. User defined. Mapping comes from provided config file Mapping in yml file is as follows: tag: - url to map to tag - ... A small example domain_assoc.yml is included "...
29c0f81a4959d97cd91f839cbe511eb46872b5ec
3,642,041
def process_auc(gt_list, pred_list): """ Process AUC (AUROC) over lists. :param gt_list: Ground truth list :type gt_list: np.array :param pred_list: Predictions list :type pred_list: np.array :return: Mean AUC over the lists :rtype: float """ res = [] for i, gt in enumerate(...
2f1de3ba0d5f1154ef4a5888d01d398fd8533793
3,642,042
def transform( Y, transform_type=None, dtype=np.float32): """ Transform STFT feature Args: Y: STFT (n_frames, n_bins)-shaped np.complex array transform_type: None, "log" dtype: output data type np.float32 is expected Return...
96613eb77c20c1a09a3e41af176a36d2ce4d8080
3,642,043
def tol_vif_table(df, n = 5): """ :param df: dataframe :param n: number of pairs to show :return: table of correlations, tolerances, and VIF """ cor = get_top_abs_correlations(df, n) tol = 1 - cor ** 2 vif = 1 / tol cor_table = pd.concat([cor, tol, vif], axis=1) cor_table.column...
94cf5715951892375e92ada019476b9ae3d09577
3,642,044
import random def shuffled(iterable): """Randomly shuffle a copy of iterable.""" items = list(iterable) random.shuffle(items) return items
cd554d4a31e042dc1d2b4c7b246528a5184d558e
3,642,045
def test_rule(rule_d, ipv6=False): """ Return True if the rule is a well-formed dictionary, False otherwise """ try: _encode_iptc_rule(rule_d, ipv6=ipv6) return True except: return False
7435cb900117e4c273b4157b2f25ba56aefd1355
3,642,047
def intersects(hp, sphere): """ The closed, upper halfspace intersects the sphere (i.e. there exists a spatial relation between the two) """ return signed_distance(sphere.center, hp) + sphere.radius >= 0.0
9366824f03a269d0fa9e96f34260c621ad610d16
3,642,048
def invert_center_scale(X_cs, X_center, X_scale): """ This function inverts whatever centering and scaling was done by ``center_scale`` function: .. math:: \mathbf{X} = \mathbf{X_{cs}} \\cdot \mathbf{D} + \mathbf{C} **Example:** .. code:: python from PCAfold import center_sc...
e37d82e7da932ea760981bb5a472799cd5a4d3d9
3,642,049
def weighted_smoothing(image, diffusion_weight=1e-4, data_weight=1.0, weight_function_parameters={}): """Weighted smoothing of images: smooth regions, preserve sharp edges. Parameters ---------- image : NumPy array diffusion_weight : float or NumPy array, optional The...
3c861b9a8878f2d85d581d8f8d1f62cf017a7920
3,642,050
import random def get_random_tablature(tablature : Tablature, constants : Constants): """make a copy of the tablature under inspection and generate new random tablatures""" new_tab = deepcopy(tablature) for tab_instance, new_tab_instance in zip(tablature.tablature, new_tab.tablature): if tab_insta...
befa3a488e2ca53e37032ed102a12b250594bd90
3,642,051
def _staticfy(value): """ Allows to keep backward compatibility with instances of OpenWISP which were using the previous implementation of OPENWISP_ADMIN_THEME_LINKS and OPENWISP_ADMIN_THEME_JS which didn't automatically pre-process those lists of static files with django.templatetags.static.static(...
2ac932a178a86d301dbb15602f3b59edb39cf3c1
3,642,052
def compare_rep(topic, replication_factor): # type: (str, int) -> bool """Compare replication-factor in the playbook with the one actually set. Keyword arguments: topic -- topicname replication_factor -- number of replications Return: bool -- True if change is needed, else False """ ...
882b028d078e507f9673e3ead6549da100a83226
3,642,053
def verbosity_option_parser() -> ArgumentParser: """ Creates a parser suitable to parse the verbosity option in different subparsers """ parser = ArgumentParser(add_help=False) parser.add_argument('--verbosity', dest=VERBOSITY_ARGNAME, type=str.upper, choices=ALLOWED_VERBOSIT...
c24f0704f1632cc0af416cf2c0a3e65c6845566f
3,642,054
import snappi def b2b_config(api): """Demonstrates creating a back to back configuration of tx and rx ports, devices and a single flow using those ports as endpoints for transmit and receive. """ config = api.config() config = snappi.Api().config() config.options.port_options.location_pre...
60a838885c058f5c65d3b331082f525b2e04b5c7
3,642,055
def fib(n): """Return the n'th Fibonacci number.""" if n < 0: raise ValueError("Fibonacci number are only defined for n >= 0") return _fib(n)
4aee5fbb4c9a497ffc4f63529b226ad3b08c0ef4
3,642,057
def gen(n): """ Compute the n-th generator polynomial. That is, compute (x + 2 ** 1) * (x + 2 ** 2) * ... * (x + 2 ** n). """ p = Poly([GF(1)]) two = GF(1) for i in range(1, n + 1): two *= GF(2) p *= Poly([two, GF(1)]) return p
29e6b1f164d93b21a2d98352ff60c8cf7a8d5864
3,642,058
def get_prefix(bot, message): """A callable Prefix for our bot. This could be edited to allow per server prefixes.""" # Notice how you can use spaces in prefixes. Try to keep them simple though. prefixes = ['!'] # If we are in a guild, we allow for the user to mention us or use any of the prefixes in ...
35567d49b747f51961fad861e00d9f9524126641
3,642,059
def parse_discontinuous_phrase(phrase: str) -> str: """ Transform discontinuous phrase into a regular expression. Discontinuity is interpreted as taking place at any whitespace outside of terms grouped by parentheses. That is, the whitespace indicates that anything can be in between the left side an...
58fe394a08931e7e79afc00b9bb0e8e9981f3c81
3,642,060
def preprocess(frame): """ Preprocess the images before they are sent into the model """ #Read the image bgr_img = frame.astype(np.float32) #Opencv reads the picture as (N) HWC to get the HW value orig_shape = bgr_img.shape[:2] #Normalize the picture bgr_img = bgr_img / 255.0 #Co...
33a24a31ae9e25efb080037a807897f2762656c0
3,642,061
def draw_roc_curve(y_true, y_score, annot=True, name=None, ax=None): """Draws a ROC (Receiver Operating Characteristic) curve using class rankings predicted by a classifier. Args: y_true (array-like): True class labels (0: negative; 1: positive) y_score (array-like): Predicted probability o...
cf59a02c5f72f728b0d9179a4eee3f012da564df
3,642,062
def make_links_absolute(soup, base_url): """ Replace relative links with absolute links. This one modifies the soup object. """ assert base_url is not None # for tag in soup.findAll('a', href=True): tag['href'] = urljoin(base_url, tag['href']) return soup
52d328c944d4a80b4f0a027a3b72f2fcebc152a9
3,642,063
def get_predictions(model, dataloader): """takes a trained model and validation or test dataloader and applies the model on the data producing predictions binary version """ model.eval() all_y_hats = [] all_preds = [] all_true = [] all_attention = [] for batch_id, (data, label...
f58a5863c211a24665db7348606d39232ad8af19
3,642,064
def _parse_objective(objective): """ Modified from deephyper/nas/run/util.py function compute_objective """ if isinstance(objective, str): negate = (objective[0] == '-') if negate: objective = objective[1:] split_objective = objective.split('__') kind = split...
df8f23464cd04be9a3c61a2969200a0c98c4471e
3,642,066
def redirect_path_context_processor(request): """Procesador para generar el redirect_to para la localización en el selector de idiomas""" return {'language_select_redirect_to': translate_url(request.path, settings.LANGUAGE_CODE)}
fdb62f3079079d63c280d2b887468c7893aafcf8
3,642,067
def RightCenter(cell=None): """Take up horizontal and vertical space, and place the cell on the right center of it.""" return FillSpace(cell, "right", "center")
ce64a346658813ab281168864e357cec1ba09c0b
3,642,068
def name_standard(name): """ return the Standard version of the input word :param name: the name that should be standard :return name: the standard form of word """ reponse_name = name[0].upper() + name[1:].lower() return reponse_name
65273cafaaa9aceb803877c2071dc043a0d598eb
3,642,069
def getChildElementsListWithTagAttribValueMatch(parent, tag, attrib, value): """ This method takes a parent element as input and finds all the sub elements (children) containing specified tag and an attribute with the specified value. Returns a list of child elements. Arguments: parent = paren...
cae87e6548190ad0a675019b397eeb88289533ee
3,642,070
def f_engine (air_volume, energy_MJ): """Прямоточный воздушно реактивный двигатель. Набегающий поток воздуха попадает в нагреватель, где расширяется, А затем выбрасывается из сопла реактивной струёй. """ # Рабочее вещество, это атмосферный воздух: working_mass = air_volume * AIR_DENSITY ...
3d307622fca17f16f03e49bd7f8b5b742217ee37
3,642,071
def not_numbers(): """Non-numbers for (i)count.""" return [None, [1, 2], {-3, 4}, (6, 9.7)]
31f935916c8463f6192d0b2770c1034ee70a4fc5
3,642,072
import requests def get_agol_token(): """requests and returns an ArcGIS Token for the pre-registered application. Client id and secrets are managed through the ArcGIS Developer's console. """ params = { 'client_id': app.config['ESRI_APP_CLIENT_ID'], 'client_secret': app.config['ESRI_AP...
7b240ef57264c1a88f10f4c06c9492a71dac8c11
3,642,073
def default_validate(social_account): """ Функция по-умолчанию для ONESOCIAL_VALIDATE_FUNC. Ничего не делает. """ return None
634382dbfe64eeed38225f8dca7e16105c40f7c2
3,642,074
import requests def pull_early_late_by_stop(line_number,SWIFTLY_API_KEY, dateRange, timeRange): """ Pulls from the Swiftly APIS to get OTP. Follow the docs: http://dashboard.goswift.ly/vta/api-guide/docs/otp """ line_table = pd.read_csv('line_table.csv') line_table.rename(columns={"DirNum":"di...
a64ad2e5fe84ee5ab5a49c8122f28b693382cf8e
3,642,075
def create_build_job(user, project, config, code_reference): """Get or Create a build job based on the params. If a build job already exists, then we check if the build has already an image created. If the image does not exists, and the job is already done we force create a new job. Returns: t...
879ed02f142326b4a793bef2d8bcbc1de4faf64c
3,642,076
import json def create(ranger_client: RangerClient, config: str): """ Creates a new Apache Ranger service repository. """ return ranger_client.create_service(json.loads(config))
a53fa80f94960f89410a60aae04a04417491f332
3,642,077
def populate_glue_catalogue_from_metadata(table_metadata, db_metadata, check_existence = True): """ Take metadata and make requisite calls to AWS API using boto3 """ database_name = db_metadata["name"] database_description = ["description"] table_name = table_metadata["table_name"] tbl_de...
c09af0344b523213010af8fdbcc0ed35328f165e
3,642,078
def choose_komoot_tour_live(): """ Login with user credentials, download tour information, choose a tour, and download it. Can be passed to :func:`komoog.gpx.convert_tour_to_gpx_tracks` afterwards. """ tours, session = get_tours_and_session() for idx in range(len(tours)): print...
3be625643d6861c9aaff910506dce53e3f336e40
3,642,079
def root(): """ The root stac page links to each collection (product) catalog """ return _stac_response( dict( **stac_endpoint_information(), links=[ dict( title="Collections", description="All product collections", ...
0904122654a1ce71264489590a2a1813dad31689
3,642,080
def recursive_dict_of_lists(d, helper=None, prev_key=None): """ Builds dictionary of lists by recursively traversing a JSON-like structure. Arguments: d (dict): JSON-like dictionary. prev_key (str): Prefix used to create dictionary keys like: prefix_key. Passed by recursive ...
c615582febbd043adae6788585d004aabf1ac7e3
3,642,081
def same_shape(shape1, shape2): """ Checks if two shapes are the same Parameters ---------- shape1 : tuple First shape shape2 : tuple Second shape Returns ------- flag : bool True if both shapes are the same (same length and dimensions) """ if len(shap...
9452f7973e510532cee587f2bf49a146fb8cc46e
3,642,082
def get_reference(): """Get DrugBank references.""" return _get_model(drugbank.Reference)
b4d26c24559883253f3894a1c56151e1809e4050
3,642,083
def decode_matrix_fbs(fbs): """ Given an FBS-encoded Matrix, return a Pandas DataFrame the contains the data and indices. """ matrix = Matrix.Matrix.GetRootAsMatrix(fbs, 0) n_rows = matrix.NRows() n_cols = matrix.NCols() if n_rows == 0 or n_cols == 0: return pd.DataFrame() if m...
d3ffdd5f0d74a6e07b47fac175dae4ad6035cda8
3,642,085
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Track states and offer events for sensors.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) await component.async_setup(config) return True
eaeee6df6c8b632fb331884236f7b3b47d551683
3,642,086
def _all_lists_equal_lenght(values: t.List[t.List[str]]) -> bool: """ Tests to see if all the lengths of all the elements are the same """ for vn in values: if len(values[0]) != len(vn): return False return True
9fd7db874658822d7a48d5f27340e0dfd5a2d177
3,642,087
def wind_shear( shear: str, unit_alt: str = "ft", unit_wind: str = "kt", spoken: bool = False ) -> str: """Translate wind shear into a readable string Ex: Wind shear 2000ft from 140 at 30kt """ if not shear or "WS" not in shear or "/" not in shear: return "" shear = shear[2:].rstrip(uni...
b7aaf5253e251393a508de2d8080a5b3458c45f6
3,642,088
def root_hash(hashes): """ Compute the root hash of a merkle tree with the given list of leaf hashes """ # the number of hashes must be a power of two assert len(hashes) & (len(hashes) - 1) == 0 while len(hashes) > 1: hashes = [sha256(l + r).digest() for l, r in zip(*[iter(hashes)] * 2)]...
9036414c71e192a62968a9939d56f9523359c877
3,642,089
import json def DumpStr(obj, pretty=False, newline=None, **json_dumps_kwargs): """Serialize a Python object to a JSON string. Args: obj: a Python object to be serialized. pretty: True to output in human-friendly pretty format. newline: True to append a newline in the end of result, default to the ...
97ed8c722d8d9e545f29214fbc8a817e6cf4ca1a
3,642,090
def snake_case(s: str): """ Transform into a lower case string with underscores between words. Parameters ---------- s : str Original string to transform. Returns ------- Transformed string. """ return _change_case(s, '_', str.lower)
c4dc65445e424101b3b5264c2f14e0aa0d7bcd22
3,642,091
def multiple_workers_thread(worker_fn, queue_capacity_input=1000, queue_capacity_output=1000, n_worker=3): """ :param worker_fn: lambda (tid, queue): pass :param queue_capacity: :param n_worker: :return: """ threads = [] queue_input = Queue.Queue(queue_capacity_input) queue_output = ...
b9a989404b6f7e3aa6b028af5e55719364c62fd8
3,642,092
from typing import List from typing import Any def reorder(list_1: List[Any]) -> List[Any]: """This function takes a list and returns it in sorted order""" new_list: list = [] for ele in list_1: new_list.append(ele) temp = new_list.index(ele) while temp > 0: if new_li...
2e7dad8fa138b1a9a140deab4223eea4a09cdf91
3,642,093
def is_extended_markdown(view): """True if the view contains 'Markdown Extended' syntax'ed text. """ return view.settings().get("syntax").endswith( "Markdown Extended.sublime-syntax")
5c870fd277910f6fa48f2b8ae0dfd304fdbddff0
3,642,094
def match_command_to_alias(command, aliases, match_multiple=False): """ Match the text against an action and return the action reference. """ results = [] for alias in aliases: formats = list_format_strings_from_aliases([alias], match_multiple) for format_ in formats: tr...
74712b70cb5995c30c7948991d60954732e4bc16
3,642,096
def dan_acf(x, axis=0, fast=False): """ DFM's acf function Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other...
ec258af743184c09e1962f1445ec6971b4d0cfab
3,642,097
import re def set_selenium_local_session(proxy_address, proxy_port, proxy_username, proxy_password, proxy_chrome_extension, headless_browser, ...
4f70baeea220c8e4e21097a5a9d9d54a47f55c2e
3,642,098
def match(): """Show a timer of the match length and an upload button""" player_west = request.form['player_west'] player_east = request.form['player_east'] start_time = dt.datetime.now().strftime('%Y%m%d%H%M') # generate filename to save video to filename = '{}_vs_{}_{}.h264'.format(playe...
7d2e51ddfaafdff903a31b5662093ab423d8f3a1
3,642,099
def start_end_epoch(graph): """ Start epoch of graph. :return: (start epoch, end epoch). """ start = 0 end = 0 for e in graph.edges_iter(): for _, p in graph[e[0]][e[1]].items(): end = max(end, p['etime_epoch_secs']) if start == 0: start = p['s...
724726ec83d3a98539eed859ec584c6f1adb8567
3,642,100
def distance_metric(seg_A, seg_B, dx): """ Measure the distance errors between the contours of two segmentations. The manual contours are drawn on 2D slices. We calculate contour to contour distance for each slice. """ table_md = [] table_hd = [] X, Y, Z = seg_A.shape ...
4ae5de6428914c8352ae1c6cdd9e94183d9ea3f8
3,642,101
def tomographic_redshift_bin(z_s, version=default_version): """DES analyses work in pre-defined tomographic redshift bins. This function returns the photometric redshift bin as a function of photometric redshift. Parameters ---------- z_s : numpy array Photometric redshifts. version...
b4a21c111b8d5b5a34c018315f95cf18deb356af
3,642,102
def is_point_in_rect(point, rect): """Checks whether is coordinate point inside the rectangle or not. Rectangle is defined by bounding box. :type point: list :param point: testing coordinate point :type rect: list :param rect: bounding box :rtype: boolean :return: boolean check result """ x0, y0,...
d0c7a64138899f4e50b42dc75ea6030616d4dfec
3,642,103
def chinese_theorem_inv(modulo_list): """ Returns (x, n1*...*nk) such as x mod mk = ak for all k, with modulo_list = [(a1, n1), ..., (ak, nk)] n1, ..., nk most be coprime 2 by 2. """ a, n = modulo_list[0] for a2, n2 in modulo_list[1:]: u, v = bezout(n, n2) a, n = a*v*n2+a...
3d1398901b75ca8b21fb97af0acdfbd65fec0a3e
3,642,104
def compute_segment_cores(split_lines_of_utt): """ This function returns a list of pairs (start-index, end-index) representing the cores of segments (so if a pair is (s, e), then the core of a segment would span (s, s+1, ... e-1). The argument 'split_lines_of_utt' is list of lines from a ctm-edits ...
0d054d1f891127f0a27b20bfbd82ad6ce85dec39
3,642,105
def _classification(dataset='iris',k_range=[1,31],dist_metric='l1'): """ knn on classificaiton dataset Inputs: dataset: (str) name of dataset k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours dist_metric: (str) 'l1' or 'l2' ...
ce5d0516cffcb545787abe15c46fe086ff8e4991
3,642,107
def make_move(board, max_rows, max_cols, col, player): """Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updat...
62ecffbabb83e0ee4119b8b8dbead6bdaeb24fb6
3,642,109
def convert_timestamp(ts): """Converts the timestamp to a format suitable for Billing. Examples of a good timestamp for startTime, endTime, and eventTime: '2016-05-20T00:00:00Z' Note the trailing 'Z'. Python does not add the 'Z' so we tack it on ourselves. """ return ts.isoformat() + 'Z...
6b8d19671cbeab69c398508fa942e36689802cdd
3,642,110
def object_id(obj, clazz=None): """Turn a given object into an ID that can be stored in with the notification.""" clazz = clazz or type(obj) if isinstance(obj, clazz): obj = obj.id elif is_mapping(obj): obj = obj.get('id') return obj
617ae362af894c2f27cc6e032aad7f8df4c33a7c
3,642,111
def get_email_from_request(request): """ Get 'Authorization' from request header, and parse the email address using cpg-util """ auth_header = request.headers.get('Authorization') if auth_header is None: raise web.HTTPUnauthorized(reason='Missing authorization header') try: ...
353604d8021948f4cb6ed80d4fb8a9000b8457ce
3,642,112
def play(url, offset, text, card_data, response_builder): """Function to play audio. Using the function to begin playing audio when: - Play Audio Intent is invoked. - Resuming audio when stopped / paused. - Next / Previous commands issues. https://developer.amazon.com/docs/custom-s...
1a7159adc481d86c35c9206cf8525940b6d1ece3
3,642,113
from typing import List from typing import Dict def all_flags_match_bombs(cells: List[List[Dict]]) -> bool: """ Checks whether all flags are placed correctly and there are no flags over regular cells (not bombs) :param cells: array of array of cells dicts :return: True if all flags are placed cor...
67cc53d8b2ea3541112245192763a6c5f8593b86
3,642,114
def household_id_list(filelist, pidp): """ For a set of waves, obtain a list of household IDs belonging to the same individual. """ hidp_list = [] wave_list = [] wn = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g'} c=1 for name in filelist: print("Loading wave %d data..." % c) ...
8fd7b271034eb953c708ea38bd75ab4671f420cb
3,642,115
from typing import Tuple def biggest_labelizer_arbitrary(metrics: dict, choice: str, *args, **kwargs) -> Tuple[str, float]: """Given dict of metrics result, returns (key, metrics[key]) whose value is maximal.""" metric_values = list(metrics.values()) metric_keys = list(metrics.keys()) # print(items) big = m...
99f4a0f5233f33d80a328cef4e43f339813371a1
3,642,116
from typing import Optional from typing import Dict from typing import Any def _seaborn_viz_histogram(data, x: str, contrast: Optional[str] = None, **kwargs): """Plot a single histogram. Args: data (DataFrame): The data x (str): The name of the column to plot. contrast (str, optional)...
27aed8280c372273e02e7b49647b4e2285a81fa7
3,642,117
def str2bool( s ): """ Description: ---------- Converting an input string to a boolean Arguments: ---------- [NAME] [TYPE] [DESCRIPTION] (1) s dict, str The string which Returns: ---------- T...
cb68fe0382561d69fb332b75c99c01c5a338196f
3,642,118
def im_detect(net, im, boxes=None): """Detect object classes in an image given object proposals. Arguments: net (caffe.Net): Fast R-CNN network to use im (ndarray): color image to test (in BGR order) boxes (ndarray): R x 4 array of object proposals or None (for RPN) Returns: ...
f37cb46375f39b6baf839be5ec68388c79f47e16
3,642,119
def dispatch_error_adaptor(func): """Construct a signature isomorphic to dispatch_error. The actual handler will receive only arguments explicitly declared, and a possible tg_format parameter. """ def adaptor(controller, tg_source, tg_errors, tg_exceptions, *args, **kw): tg_for...
67be23f01c11d668d86f5e2b1afcfb76db79ea6c
3,642,121
import re def address_split(address, env=None): """The address_split() function splits an address into its four components. Address strings are on the form detector-detectorID|device-deviceID, where the detectors must be in dir(xtc.DetInfo.Detector) and device must be in (xtc.DetInfo.Device). @param addr...
c5d362c7fc6121d64ec6a660bcdb7a9b4b532553
3,642,122
import time def solveGroth(A, n, init_val=None): """ ... Parameters ---------- A: np.matrix dfajdslkf n: int ddddddd init_val: float, optional dsfdsafdasfd Returns ------- list of float: float: float: float: """ ep...
a8f4a3ea2274bd1a81565500683dea84378ccddc
3,642,123
def verify_any(func, *args, **kwargs): """ Assert that any of `func(*args, **kwargs)` are true. """ return _verify(func, 'any', *args, **kwargs)
618165e6a9f252ac2ddeffdb9defa34f2d281900
3,642,124
def can_create_election(user_id, user_info): """ for now, just let it be""" return True
06c8290b41b38a840b7826173fd65130d38260a7
3,642,125
from .path import Path2D def circle_pattern(pattern_radius, circle_radius, count, center=[0.0, 0.0], angle=None, **kwargs): """ Create a Path2D representing a circle pattern. Parameters ------------ pat...
b82d60c7a76f12349605191b16bf04d7899c3a3a
3,642,127
def boolean(input): """Convert the given input to a boolean value. Intelligently handles boolean and non-string values, returning as-is and passing to the bool builtin respectively. This process is case-insensitive. Acceptable values: True * yes * y * ...
09c09206d5487bf02e3271403e2ba67358e1d148
3,642,128
def find_horizontal_up_down_links(tc, u, out_up=None, out_down=None): """Find indices of nodes that locate at horizontally upcurrent and downcurrent directions """ if out_up is None: out_up = np.zeros(u.shape[0], dtype=np.int) if out_down is None: out_down = np.zeros(u.shape[0], d...
b61976a57d8dd850c26c7a9baff11483ccdb306f
3,642,129
def _compute_composite_beta(model, robo, j, i): """ Compute the composite beta wrench for link i. Args: model: An instance of DynModel robo: An instance of Robot j: link number i: antecedent value Returns: An instance of DynModel that contains all the new values...
0fa80859787a4e523402d10237b63e33ca0082f4
3,642,130
def pos(x, y): """Returns floored and camera-offset x,y tuple. Setting out of bounds is possible, but getting is not; mod in callers for get_at. """ return (flr(xo + x), flr(yo + y))
1a17648c074157c6164856f44cfa309923ca2226
3,642,131
from typing import List from typing import Dict from typing import Tuple def _check_blockstream_for_transactions( accounts: List[BTCAddress], ) -> Dict[BTCAddress, Tuple[bool, FVal]]: """May raise connection errors or KeyError""" have_transactions = {} for account in accounts: url = f'http...
a17a9204dc0d5f11b8c0352d15c871141e7bb09b
3,642,132