content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def acquire_lease(lease_id, client_id, ttl=DEFAULT_LOCK_DURATION_SECONDS, timeout=DEFAULT_ACQUIRE_TIMEOUT_SECONDS): """ Try to acquire the lease. If fails, return None, else return lease object. The timeout is crudely implemented with backoffs and retries so the timeout is not precise :param ...
77de69b03dab5d529872c66bc2a5648d656c829c
3,642,000
def create_index(conn, column_list, table='perfdata', unique=False): """Creates one index on a list of/one database column/s. """ table = base2.filter_str(table) index_name = u'idx_{}'.format(base2.md5sum(table + column_list)) c = conn.cursor() if unique: sql = u'CREATE UNIQUE INDEX IF...
38b71cededb8500452cd3eac53609cc4ee384566
3,642,001
from typing import Type from typing import Any import inspect def produce_hash(self: Type[PCell], extra: Any = None) -> str: """Produces a hash of a PCell instance based on: 1. the source code of the class and its bases. 2. the non-default parameter with which the pcell method is called 3. the name of...
859f51600a9cc4da8ba546afebf0ecdf20959ec8
3,642,002
def boxes3d_kitti_fakelidar_to_lidar(boxes3d_lidar): """ Args: boxes3d_fakelidar: (N, 7) [x, y, z, w, l, h, r] in old LiDAR coordinates, z is bottom center Returns: boxes3d_lidar: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center """ w, l, h, r = boxes3d_lidar[:, 3:4], bo...
139a3da3ac8e6c09a376d976d0e96a8d91f9a74a
3,642,003
def combine_per_choice(*args): """ Combines two or more per-choice analytics results into one. """ args = list(args) result = args.pop() new_weight = None new_averages = None while args: other = args.pop() for key in other: if key not in result: result[key] = other[key] else:...
63e482a60b521744c94d80b0b8a740ff74f4b197
3,642,004
import string def prepare_input(dirty: str) -> str: """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(d...
5c55ba770e024b459d483fd168978437b8d48c21
3,642,005
def calc_center_from_box(box_array): """calculate center point of boxes Args: box_array (array): N*4 [left_top_x, left_top_y, right_bottom_x, right_bottom_y] Returns: array N*2: center points array [x, y] """ center_array=[] for box in box_array: center_array.append...
1f713a2f6900678ad1760ea60456bbf44b9f06af
3,642,006
import scipy def getW3D(coords): """ ################################################################# The calculation of 3-D Wiener index based gemetrical distance matrix optimized by MOPAC(Not including Hs) -->W3D ################################################################# """ ...
25fb1596b0d818d7f7f120289a79ccbf9b4f1ae4
3,642,007
from typing import Any from typing import Sequence def state_vectors( draw: Any, max_num_qudits: int = 3, allowed_bases: Sequence[int] = (2, 3), min_num_qudits: int = 1, ) -> StateVector: """Hypothesis strategy for generating `StateVector`'s.""" num_qudits, radixes = draw( num_qudits_a...
b81059843f94cb1c36581ac0a7dd5d3c17f39839
3,642,008
def ProcessChainsAndLigandsOptionsInfo(ChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue, LigandsOptionName = None, LigandsOptionValue = None): """Process specified chain and ligand IDs using command line options. Arguments: ChainsAndLigandsInfo (dict): A dictionary containing information ...
0bdadbc08512957269a179df24c1202a56870d42
3,642,009
def oa_filter(x, h, N, mode=0): """ Overlap and add transform domain FIR filtering. This function implements the classical overlap and add method of transform domain filtering using a length P FIR filter. Parameters ---------- x : input signal to be filtered as an ndarray h : F...
41fa7aaf7a57e0f6c363eb1efa7413b2a1a34d47
3,642,010
from typing import Optional from typing import Iterable import re def get_languages(translation_dir: str, default_language: Optional[str] = None) -> Iterable[str]: """ Get a list of available languages. The default language is (generic) English and will always be included. All other languages wil...
a25c9c2672f4f8d96cffc363aa922424b031aea7
3,642,011
def calculate_direction(a, b): """Calculates the direction vector between two points. Args: a (list): the position vector of point a. b (list): the position vector of point b. Returns: array: The (unnormalised) direction vector between points a and b. The smallest magnitude of an e...
9e0297560bb48d57cd4e1d5f12788a62ae7d9b3b
3,642,012
def argmin(a, axis=None, out=None, keepdims=None, combine_size=None): """ Returns the indices of the minimum values along an axis. Parameters ---------- a : array_like Input tensor. axis : int, optional By default, the index is into the flattened tensor, otherwise along ...
d289cf508720c5d93ef1622d3e960e9063ab5131
3,642,013
import json def parse_game_state(gs_json: dict) -> game_state_pb2.GameState: """Deserialize a JSON-formatted game state to protobuf.""" if 'provider' not in gs_json: raise InvalidGameStateException(gs_json) try: map_ = parse_map(gs_json.get('map')) provider = parse_provider(gs_json['provider']) ...
d78868c24807a3cac469b87990e5a74f88876eb5
3,642,014
def state2bin(s, num_bins, limits): """ :param s: a state. (possibly multidimensional) ndarray, with dimension d = dimensionality of state space. :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit...
8c0a1d559a332b1a015bde78c9eca413eeae942c
3,642,015
def _fix_json_agents(ag_obj): """Fix the json representation of an agent.""" if isinstance(ag_obj, str): logger.info("Fixing string agent: %s." % ag_obj) ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}} elif isinstance(ag_obj, list): # Recursive for complexes and similar. ...
be73467edc1dc30ac0be1f6804cdb19cf5f942bf
3,642,016
def vflip(img): """Vertically flip the given CV Image. Args: img (CV Image): Image to be flipped. Returns: CV Image: Vertically flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be CV Image. Got {}'.format(type(img))) return cv2.flip(img, 1)
7b678327a15876a98e0622eacc012f86a8ffd432
3,642,017
def list_pending_tasks(): """List all pending tasks in celery cluster.""" inspector = celery_app.control.inspect() return inspector.reserved()
3d1785dd9ac8fd91f1f0ceb72eeb7df5671b55d5
3,642,018
def get_attack(attacker, defender): """ Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whe...
3ec24ab34a02c2572ee62d1cc18079bdb7ef10ee
3,642,019
def colored(s, color=None, attrs=None): """Call termcolor.colored with same arguments if this is a tty and it is available.""" if HAVE_COLOR: return colored_impl(s, color, attrs=attrs) return s
a8c4f56e55721ec464728fbe9af4453cd98400ba
3,642,020
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 os def merge_runs(input_dir1, input_dir2, map_df, output, arguments): """ :param input_dir1: Directory 1 contains mutation counts files :param input_dir2: Directory 2 contains mutation counts files :param map_df: A dataframe that maps the samples to be merged :param output: output directory...
d2e27bb99d7e6e75110a1ed9a51ab285ee2c39d2
3,642,024
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 values_to_colors(values, cmap, vmin=None, vmax=None): """ Function to map a set of values through a colormap to get RGB values in order to facilitate coloring of meshes. Parameters ---------- values: array-like, (n_vertices, ) values to pass through colormap cmap: array-like, (n...
d26bcf4daaeb5247a11576547cdce8417b8d4b19
3,642,030
from typing import List import sys def _clean_sys_argv(pipeline: str) -> List[str]: """Values in sys.argv that are not valid option values in Where """ reserved_opts = {pipeline, "label", "id", "only_for_rundate", "session", "stage", "station", "writers"} return [o for o in sys.argv[1:] if o.startswit...
551f4fdca5d7cc276b03943f3679cc2eff8ce89e
3,642,031
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
from ray.autoscaler._private.constants import RAY_PROCESSES from typing import Optional from typing import List from typing import Tuple import psutil import subprocess import tempfile import yaml def get_local_ray_processes(archive: Archive, processes: Optional[List[Tuple[str, bool]]] = N...
7ed76d4e93198ce0afef0fbf5cf5b37a7b92e0ed
3,642,046
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
import os def apply_patch(ffrom, fpatch, fto): """Apply given normal patch `fpatch` to `ffrom` to create `fto`. Returns the size of the created to-data. All arguments are file-like objects. >>> ffrom = open('foo.mem', 'rb') >>> fpatch = open('foo.patch', 'rb') >>> fto = open('foo.new', 'wb')...
b847f7641bdd34c935d2f88fd8ca114abb0b4033
3,642,056
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 _getPymelType(arg, name) : """ Get the correct Pymel Type for an object that can be a MObject, PyNode or name of an existing Maya object, if no correct type is found returns DependNode by default. If the name of an existing object is passed, the name and MObject will be returned If a va...
b303bebfc5c97ac6a969c151cb78de7f28523476
3,642,065
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
import collections def __parse_search_results(collected_results, raise_exception_finally): """ Parses locally the results collected from the __mapped_pattern_matching: - list of ( scores, matched_intervals, unprocessed_interval, rank_superwindow, <meta info>, <error_info>) Th...
5e7bad5a745d76b6d0a9b45a3c36df846051c1bc
3,642,084
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
from typing import Dict from typing import List from typing import Any import random import logging def _generate_graph(rule_dict: Dict[int, List[PartRule]], upper_bound: int) -> Any: """ Create a new graph from the VRG at random Returns None if the nodes in generated graph exceeds upper_bound :return...
8bcc3c93c0ff7f1f895f3970b9aa16c7f6293e68
3,642,095
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