content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def demander_nombre(mini: int = None, maxi: int = None) -> int: """ Demande un nombre à l'utilisateur, situé entre min et max. :param mini: le minimum :param maxi: le maximum :return: le nombre entrée par l'utilisateur """ message = 'Veuillez rentrer un nombre:' if mini is not None and m...
ac5b949af1ad4ede2f956c7da5d4c2136dc47b15
2,542
from datetime import datetime def temporal_filter(record_date_time, time_or_period, op): """ Helper function to perform temporal filters on feature set :param record_date_time: datetime field value of a feature :type record_date_time: :class:`datetime.datetime` :param time_or_period: the time ins...
9f76d6a6eb96da9359c4bbb80f6cfb1dfdcb4159
2,544
def convert_rgb2gray(image, convert_dic): """convert rgb image to grayscale Parameters ---------- image: array RGB image. Channel order should be RGB. convert_dic: dict dictionary key is str(rgb list), value is grayscale value Returns ------- image_gray: array Grayscale im...
0132719ef88d139d1d3da4e52312faef25443efd
2,548
def get_external_storage_path(): """Returns the external storage path for the current app.""" return _external_storage_path
a33704c5b3267a7211c94b5a3a8d8d73b3889d68
2,549
def blur(old_img): """ :param old_img: a original image :return: a blurred image """ blur_img = SimpleImage.blank(old_img.width, old_img.height) for x in range(old_img.width): for y in range(old_img.height): if x == 0 and y == 0: # Upper left cor...
771a6e906ea8b485d4166de311c17a441f469158
2,550
import re def generate_table_row(log_file, ancestry, official_only, code): """ Takes an imported log and ancestry and converts it into a properly formatted pandas table. Keyword arguments: log_file -- output from import_log() ancestry -- a single ancestry code official_only -- a boolean indica...
c72bdef2aafbc15c54b80337c80f03ae8d8f1e00
2,551
def read_preflib_file(filename, setsize=1, relative_setsize=None, use_weights=False): """Reads a single preflib file (soi, toi, soc or toc). Parameters: filename: str Name of the preflib file. setsize: int Number of top-ranked candidates that voters approve. ...
6feec6e786e47cdc11021021ffa91a1f96597567
2,552
def get_row(client, instance, file_=None): """Get one row of a family table. Args: client (obj): creopyson Client. instance (str): Instance name. `file_` (str, optional): File name. Defaults is currently active model. Returns: (dict): ...
c8e8c90a81d553d06ce9f78eb1be582e5b034ac6
2,553
def hospitalization_to_removed(clip_low=2, clip_high=32.6, mean=8.6, std=6.7): """ Returns the time for someone to either get removed after being hospitalized in days within range(clip_low, clip_high), of a truncated_norm(mean, std). """ return sample_truncated_norm(clip_low, clip_high, mean, st...
e1da5283e32b5734927436af72fdbd002c0844b1
2,554
def test_inheritance(): """ test inheritance from different module """ # test module test_data = doc.MatObject.matlabify('test_data') test_submodule = test_data.getter('test_submodule') sfdm = test_submodule.getter('super_from_diff_mod') ok_(isinstance(sfdm, doc.MatClass)) eq_(sfdm.b...
0f29de2ef67318010feed25ea0ffc08e2dc44162
2,555
from collections import Counter def split_mon_unmon(data, labels): """ Splits into monitored and unmonitored data If a data point only happens once, we also consider it unmonitored @return monitored_data, monitored_label, unmonitored_data """ occurence = Counter(labels) monitored_data, u...
b1d0cac2e12f4386bf04eb355811f230b18f38ca
2,556
def sum_and_count(x, y): """A function used for calculating the mean of a list from a reduce. >>> from operator import truediv >>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9] >>> truediv(*reduce(sum_and_count, l)) == 20.11111111111111 True >>> truediv(*fpartial(sum_and_count)(l)) == 20.11111111111111...
d43cc8dc39fb35afae4f6a4e32d34221d525f5d3
2,558
def animTempCustom(): """ Temporarily play a custom animation for a set amount of time. API should expect a full `desc` obect in json alongside a timelimit, in ms. """ colorList = request.form.get('colors').split(',') colorsString = "" for colorName in colorList: c = Color(colorName...
2d9cea92d7c1c93d73fcf9b325b7b58225b4ba13
2,559
from unittest.mock import Mock def mock_stripe_invoice(monkeypatch): """Fixture to monkeypatch stripe.Invoice.* methods""" mock = Mock() monkeypatch.setattr(stripe, "Invoice", mock) return mock
a88923ba6d4a6dda9bf3b2fcda3bb717efe36cee
2,560
def read_project(output_dir): """Read existing project data """ try: yaml = YAML() with open(project_yaml_file(output_dir), encoding='utf-8') as project: project_data = yaml.load(project) for key, value in project_data.items(): if value == None: ...
90cfd7d143176925d8a99f4d577bc7de9eb360e2
2,561
def bytes_to_int(byte_array: bytes) -> int: """ Bytes to int """ return int.from_bytes(byte_array, byteorder='big')
442452faeb1a4e7c346b6f4355095f179701f8f1
2,562
def ask(query, default=None): """Ask a question.""" if default: default_q = ' [{0}]'.format(default) else: default_q = '' inp = input("{query}{default_q}: ".format(query=query, default_q=default_q)).strip() if inp or default is None: return inp else: return defaul...
54564ee00749ddb2e5c409d781552f3ca5fcd847
2,563
def _clean_kwargs(keep_name=False, **kwargs): """ Sanatize the arguments for use with shade """ if "name" in kwargs and not keep_name: kwargs["name_or_id"] = kwargs.pop("name") return __utils__["args.clean_kwargs"](**kwargs)
326d849b030a11ebc21e364f6a05eef9ab019637
2,564
def calculate_pnl_per_equity(df_list): """Method that calculate the P&L of the strategy per equity and returns a list of P&L""" pnl_per_equity = [] # initialize the list of P&L per equity for df in df_list: # iterates over the dataframes of equities pnl = df['Strategy Equity'].iloc[-1] - df['Buy and...
4f6ac1b9f6a949215c6b805f05a65897393f3288
2,566
import http def search(q_str: str) -> dict: """search in genius Args: q_str (str): query string Returns: dict: search response """ data = {'songs': [], 'lyric': []} response = http.get( 'https://genius.com/api/search/multi?per_page=5', params={'q': q_str}, headers=hea...
7421220e43415fb17b29db26f1fc6902e88144a4
2,567
def geocode(level=None, names=None, countries=None, states=None, counties=None, scope=None) -> NamesGeocoder: """ Create a `Geocoder`. Allows to refine ambiguous request with `where()` method, scope that limits area of geocoding or with parents. Parameters ---------- level : {'country', 'state'...
25ab4ff7887d09a41c19b6ec8ee9057151483b2e
2,569
def fpAbs(x): """ Returns the absolute value of the floating point `x`. So: a = FPV(-3.2, FSORT_DOUBLE) b = fpAbs(a) b is FPV(3.2, FSORT_DOUBLE) """ return abs(x)
d69f5f07b651ed4466ff768601c77f90232b8827
2,570
from io import StringIO import json def volumes(container:str) -> list: """ Return list of 'container' volumes (host,cont) """ buf = StringIO() _exec( docker, 'inspect', '-f', "'{{json .Mounts}}'", container, _out=buf ) res = buf.getvalue().strip() vols_list = json.loads(res[...
5191df9ab4aa58a80fba90872da6091bc58f8be2
2,571
def names(): """Return stock summary information""" helper = SQLHelper() conn = helper.getConnection() repo = robinhoodRepository(conn) stockInfo = repo.getAllStocks() return json_response(stockInfo, 200)
d543ab5254e95e903e8b74db1ab5b0266859b083
2,572
def get_bot_group_config(bot_id): """Returns BotGroupConfig for a bot with given ID. Returns: BotGroupConfig or None if not found. Raises: BadConfigError if there's no cached config and the current config at HEAD is not passing validation. """ cfg = _fetch_bot_groups() gr = cfg.direct_matches...
025b2a9a91f2a744668fd6c438db0f5c4edd0a98
2,573
def add_utm(url_, campaign, source='notification', medium='email'): """Add the utm_* tracking parameters to a URL.""" return urlparams( url_, utm_campaign=campaign, utm_source=source, utm_medium=medium)
d428daf58db7b0b5d5dabfd4bac6f70e900bd311
2,574
def is_forest(G): """Return True if the input graph is a forest Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- True if the input graph is a forest Notes ----- For undirected graphs only. """ for graph in nx.connected_component_subg...
6aade3d2407b8af1cd8662b9efdc604d304341fe
2,575
def parse_uri(uri): """ This implies that we are passed a uri that looks something like: proto://username:password@hostname:port/database In most cases, you can omit the port and database from the string: proto://username:password@hostname Also, in cases with no username, you c...
5204d803a5d0f6995c49883a892bc6b22cef9443
2,577
def pwgen(pw_len=16): """Generate a random password with the given length. Allowed chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string( pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789' )
3c5a07440a6d3eee7c1bc9162089c434cfe6c45d
2,578
def compute_tree_distances(tree): """ Computes the matrix of pairwise distances between leaves of the tree """ num_leaves = len(get_leaves(tree)) - 1 distances = np.zeros([num_leaves, num_leaves]) for leaf in range(num_leaves): distance_dictionary, tmp = nx.multi_source_dijkstra(tree.to_...
b4bdd81e0f4c8d5577813f6e68ece9f0a8992e19
2,580
def create_rndm_backgr_selections(annotations, files, length, num, no_overlap=False, trim_table=False): """ Create background selections of uniform length, randomly distributed across the data set and not overlapping with any annotations, including those labelled 0. The random sampling is performe...
01eac8bc0a624b56d419ce3cb75744792af1472f
2,581
def GetPartition(partition_name, target_os): """Return the partition to install to. Args: partition_name: partition name from command-line {'primary', 'secondary', 'other'} target_os: 'fiberos' or 'android' Returns: 0 or 1 Raises: Fatal: if no partition could be determined...
b3f030779bd29bbe695ba3769372f4af700d7cb7
2,583
import aiohttp import json async def call_dialogflow(message, config, lang=DEFAULT_LANGUAGE): """Call the Dialogflow api and return the response.""" async with aiohttp.ClientSession() as session: payload = { "v": DIALOGFLOW_API_VERSION, "lang": lang, "sessionId": me...
e670748dc4d0318d047b0f0ded6d857597112d49
2,584
def gettgd(sat, eph, type=0): """ get tgd: 0=E5a, 1=E5b """ sys = gn.sat2prn(sat)[0] if sys == uGNSS.GLO: return eph.dtaun * rCST.CLIGHT else: return eph.tgd[type] * rCST.CLIGHT
c7231769b0e9be5287b2b2f76c8dcdc7bd409a89
2,585
def random_sign_uniform(shape, minval=None, maxval=None, dtype=dtypes.float32, seed=None): """Tensor with (possibly complex) random entries from a "sign Uniform". Letting `Z` be a random variable equal to `-1` and `1` w...
b942253c14438c72c19d648a0d0358d8cd280bd0
2,586
def ones_v(n): """ Return the column vector of ones of length n. """ return matrix(1, (n,1), 'd')
46936660025c1b5bd533b78143301d1218b568d7
2,587
def test_encrypt_and_decrypt_two(benchmark: BenchmarkFixture) -> None: """Benchmark encryption and decryption run together.""" primitives.decrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_decrypt primitives.encrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_encrypt def encrypt_and_decrypt() -> b...
1b632ae28f147fa4d98dcdda982bf3d17b2c17dd
2,588
def get_fy_parent_nucl(fy_lib): """Gets the list of fission parents from a fission yield dictionnary. Parameters ---------- fy_lib: dict A fission yield dictionnary """ fy_nucl = get_fy_nucl(fy_lib) fy_parent = [] sample_zamid = fy_nucl[0] sample = fy_lib[sample_zamid] ...
feb2ec2adfda4d9df4993cc89545564e4c0d1a54
2,590
from functools import partial import array def initialize ( is_test, no_cam ) : """job machine Tableをもとに個体、世代の初期設定""" jmTable = getJmTable ( is_test ) MAX_JOBS = jmTable.getJobsCount() MAX_MACHINES = jmTable.getMachinesCount() # makespan最小化 creator.create ( "FitnessMin", base.Fitness, weights=(-1.0,) ) # 個体はジョ...
f306cf9b5400ea92b92709bc6986d6b87ea909b2
2,591
def perform_variants_query(job, **kwargs): """Query for variants. :param job: API to interact with the owner of the variants. :type job: :class:`cibyl.sources.zuul.transactions.JobResponse` :param kwargs: See :func:`handle_query`. :return: List of retrieved variants. :rtype: list[:class:`cibyl....
c779080e2ef8c1900c293f70996e17bae932b142
2,592
import torch def get_model(share_weights=False, upsample=False): # pylint: disable=too-many-statements """ Return a network dict for the model """ block0 = [{'conv1_1': [3, 64, 3, 1, 1]}, {'conv1_2': [64, 64, 3, 1, 1]}, {'pool1_stage1': [2, 2, 0]}, {'conv2_1': [64, 128, 3, 1, 1...
364050799adc3312e4a46081e4a82338407f177b
2,593
def bootstrap(config_uri, request=None, options=None): """ Load a WSGI application from the PasteDeploy config file specified by ``config_uri``. The environment will be configured as if it is currently serving ``request``, leaving a natural environment in place to write scripts that can generate URLs an...
608629eb380765ebafa4009946a30b9f46de6ff9
2,594
def readSegy(filename) : """ Data,SegyHeader,SegyTraceHeaders=getSegyHeader(filename) """ printverbose("readSegy : Trying to read "+filename,0) data = open(filename).read() filesize=len(data) SH=getSegyHeader(filename) bps=getBytePerSample(SH) ntraces = (filesize-3600)/(SH['ns']*bps+240) # ntraces = 100...
5e3920255aa49c70e0e898b2d3915c05afc7f869
2,595
def planar_transform(imgs, masks, pixel_coords_trg, k_s, k_t, rot, t, n_hat, a): """transforms imgs, masks and computes dmaps according to planar transform. Args: imgs: are L X [...] X C, typically RGB images per layer masks: L X [...] X 1, indicating which layer pixels are valid pixel_coords_trg: [......
18f90706b996ee9ba81ab7142313dcaa761cf773
2,596
def convertDynamicRenderStates(data, builder): """ Converts dynamic render states. The data map is expected to contain the following elements: - lineWidth: float width for the line. Defaults to 1. - depthBiasConstantFactor: float value for the depth bias constant factor. Defaults to 0. - depthBiasClamp: float valu...
5c27ebd4401d8b6c0388bfe6f1973c137404ddf5
2,597
def binary_search(a, search_value): """ @name binary_search @param a array """ N = len(a) l = 0 r = len(a) - 1 while(True): try: result = binary_search_iteration(a, l, r, search_value) l, r = result except TypeError: return -1 if not re...
5fc2748a76d89c2559cda8bc9dacd16d90b2aa5e
2,598
from typing import Dict from typing import Any from typing import cast def _key_match(d1: Dict[str, Any], d2: Dict[str, Any], key: str) -> bool: """ >>> _key_match({"a": 1}, {"a": 2}, "a") False >>> _key_match({"a": 1}, {"a": 2}, "b") True >>> _key_match({"a": 2}, {"a": 1}, "a") False ...
8e76ee70c6209b357b13890a9fcf2b0b7d770c1b
2,599
def calculate(over): """Returns the value of the first triangle number to have over the specified number of divisors""" triangle = 0 count = sum(range(triangle)) while True: if num_divisors(count) > over: answer = count return answer triangle += 1 coun...
e7391bea108261bb2b7abc64cbdd6ba6285deaae
2,600
import numpy def convert_image_to_kernel(im: Image, oversampling, kernelwidth): """ Convert an image to a griddata kernel :param im: Image to be converted :param oversampling: Oversampling of Image spatially :param kernelwidth: Kernel width to be extracted :return: numpy.ndarray[nchan, npol, over...
fe1a2a81421a5f3c09e6c6439aeb7b52e217967f
2,601
def prob(X, w): """ X: Nxd w: dx1 --- prob: N x num_classes(2)""" y = tf.constant(np.array([0.0, 1.0]), dtype=tf.float32) prob = tf.exp(tf.matmul(X, w) * y) / (1 + tf.exp(tf.matmul(X, w))) return prob
b916f75bc3596bbbff701b6dbb3b43add0f06373
2,602
def get_date_strings(): """ Get date strings for last month and this month in "%Y%m" format, e.g. "202201" """ today = date.today() first = today.replace(day=1) last_month = first - timedelta(days=1) this_month_string = today.strftime("%Y%m") last_month_string = last_month.strftime("%Y%...
cc09f710d86efcc73a7e653d30cc2d590ba865e6
2,604
import torch from typing import Tuple def rotate( img: torch.Tensor, boxes: np.ndarray, angle: float, ) -> Tuple[torch.Tensor, np.ndarray]: """Rotate image around the center, interpolation=NEAREST, pad with 0 (black) Args: img: image to rotate boxes: array of boxes to rotate as we...
acd5c83a857b1bdb2312a078cfd972f9a1a0df9f
2,606
def _letterbox_image(img, w_in, h_in): """To get the image in boxed format.""" imc, imh, imw = img.shape if (w_in / imw) < (h_in / imh): new_w = w_in new_h = imh * w_in // imw else: new_h = h_in new_w = imw * h_in // imh resized = _resize_image(img, new_w, new_h) ...
918e96f3ac7f5b1c8f7177ad759dab0579763e77
2,607
def to_RRDB(**kwargs): """ Residual in Residual Dense Blocks """ kwargs["n_filer"] = (" ",) * len(kwargs["n_filer"]) # remove x label return _Box(fill="{rgb:white,1;black,3}", **kwargs)
2b1afd5f4a8c65364fcdee18fc8da3da71eade08
2,608
def continuous_agg_dict_features(n, n_feats, ks): """Listdict-like continuous aggregated features. Parameters ---------- n: int the number of the elements to create their features. n_feats: int the number of features. ks: int the number of perturbations. Returns ...
ec98930c124553a86ef50db58cf7e13107bf6e52
2,609
def counts_matrix(x, quantiles): """Count samples in strata Get eta, the number of samples in ``x`` binned by ``quantiles`` in each variable, for continuous variables. The shape of eta is the same as the shape of ``x``, and the shape of ``quantiles`` should be (``numpy.shape(x)[0] + 1``, ``numpy.sh...
935cd19913e420ea6713ca74ead19f720bdef782
2,610
import logging def get_xml_string(stream_pointer): """ This function checks for valid xml in a stream and skips bytes until it hits something that looks like xml. In general, this 'skipping' should never be used, as we expect to see well-formed XML from the server. stream_pointer: input strea...
3fa2e3d05bfc66cee592c4c40cc1e9349e512c3a
2,611
import re def parse_header(header): """Parse header div for pub. title, authors journal, year, and doi.""" # TITLE title = header.find('h1').text.strip() # JOURNAL journal = header.find('button').text.strip() # PUBLICATION YEAR pub_date = header.find('span', attrs={'class': "cit"}).text ...
70dc1defbd9e6098e0754164d0dd23c7c79074d6
2,612
def put_this_into_the_db(query, param): """put this value into the database see : find_by_exactly_this_query() Arguments: query {[type]} -- [description] param {[type]} -- [description] Returns: bool -- [description] """ # Connect to the database connection = pymysql.con...
08cebe330cea5f10189342c6f3ec4f9f7cc022e1
2,614
def _gen_new_aux_page(label: str, is_title: bool) -> str: """Generate latex for auxillary pages""" page = [] if is_title: page.append("\\thispagestyle{empty}") page.append("\\begin{center}") page.append("\t\\vfil") page.append("\t\\vspace*{0.4\\textheight}\n") page.append("\t\\Hug...
3ff31ae80f007fd5da2dd6153ea605978421c086
2,615
def expand_matrix_col(matrix, max_size, actual_size): """ add columns of zeros to the right of the matrix """ return np.append(matrix, np.zeros((matrix.shape[0], max_size - actual_size), dtype=matrix.dtype), axis=1)
23b20b443c880d1658eeec89910f9f3384576e6e
2,616
import logging def vms_list(access_token, config_id): """List FlexVM Virtual Machines""" logging.info("--> List FlexVM Virtual Machines...") uri = FLEXVM_API_BASE_URI + "vms/list" headers = COMMON_HEADERS.copy() headers["Authorization"] = f"Bearer {access_token}" body = {"configId": config_i...
eed35eefae4e26d743e0e96e791b6f5dd84d0c2f
2,617
from unittest.mock import patch def method_mock(cls, method_name, request): """ Return a mock for method *method_name* on *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, method_name) request.addfinalizer(_patch.stop) return _patch.start()
b14d991c42e0c05a51d9c193c3769b1e1e71dd1f
2,619
def get_eps_float32(): """Return the epsilon value for a 32 bit float. Returns ------- _ : np.float32 Epsilon value. """ return np.finfo(np.float32).eps
e0506637aa3f9c29dc33d1256ce21d7dc686a4cd
2,620
def distributions_to_params(nest): """Convert distributions to its parameters, keep Tensors unchanged. Only returns parameters that have tf.Tensor values. Args: nest (nested Distribution and Tensor): Each Distribution will be converted to dictionary of its Tensor parameters. Return...
bfa1cfd043bd46667de8ed07fd54fef959b272ae
2,621
def _return_xarray_system_ids(xarrs: dict): """ Return the system ids for the given xarray object Parameters ---------- xarrs Dataset or DataArray that we want the sectors from Returns ------- list system identifiers as string within a list """ return list(xarr...
8380d1c2ae9db48eb4b97138dcd910d58085073e
2,622
def sub(a, b): """Subtracts b from a and stores the result in a.""" return "{b} {a} ?+1\n".format(a=a, b=b)
dcc0ddfc9dbefe05d79dea441b362f0ddfe82627
2,623
def metrics_cluster(models = None, ytrain = None, ytest = None, testlabels = None, trainlabels = None, Xtrain = None, Xtest = None): """ Calculates Metrics such as accu...
c9c131385a47df3de511db0e85ece20131647d4e
2,624
def prune_cloud_borders (numpy_cloud, clearance=1.2 ): """Delete points at the clouds' borders in range of distance, restricting the x-y plane (ground)""" # get min/max of cloud cloud_max_x = np.max (numpy_cloud[:, 0]) cloud_min_x = np.min (numpy_cloud[:, 0]) cloud_max_y = np.max (numpy_cloud[:, 1]...
f208c9778343c3240803b52ff3e5f4701a8bb1cb
2,625
def factory(name, Base, Deriveds): """Find the base or derived class by registered name. Parameters ---------- Base: class Start the lookup here. Deriveds: iterable of (name, class) A list of derived classes with their names. Returns ------- class """ Derived =...
1bce29651004cf1f04740fd95a4f62c6c2277a72
2,626
def root_sum_square(values, ax_val, index, Nper, is_aper, is_phys, unit): """Returns the root sum square (arithmetic or integral) of values along given axis Parameters ---------- values: ndarray array to derivate ax_val: ndarray axis values index: int index of axis along...
2af20718dc4d7a6b8d40e939a46d140fda5bf375
2,627
import json def comment_on_tweet(): """" http://127.0.0.1:5000/user/comment_on_tweet body = { "id": "5da61dbed78b3b2b10a53582", "comments" : { "commenter" : "testuser2@myhunter.cuny.edu", "comment" : "comments against tweet : 7" ...
232854a883a4bbd99a46dc3dc46e9a47fb1993dc
2,628
def generate_git_api_header(event, sig): """ Create header for GitHub API Request, based on header information from https://developer.github.com/webhooks/. :param event: Name of the event type that triggered the delivery. :param sig: The HMAC hex digest of the response body. The HMAC hex digest is gene...
9b60d9eb6a8ea962bb7426970f2c2b82a229ef12
2,629
def var_gaussian(r, level=5, modified=False): """ Returns the Parametric Gauusian VaR of a Series or DataFrame If "modified" is True, then the modified VaR is returned, using the Cornish-Fisher modification """ # compute the Z score assuming it was Gaussian z = norm.ppf(level/100) if mod...
2ff13a6b222663a200b77e526475331bfacd9c07
2,630
import math def lnglat_to_tile(lon, lat, zoom): """Get the tile which contains longitude and latitude. :param lon: longitude :param lat: latitude :param zoom: zoom level :return: tile tuple """ lon, lat = truncate(lon, lat) n = 1 << zoom tx = int((lon + 180.0) / 360.0 * n) ty ...
84e1c103b03a2ec80a9585c8c852045c5d58cb76
2,631
from typing import Union from typing import Optional from typing import Callable from typing import Any def group_obs_annotation( adata: AnnData, gdata: AnnData, *, groups: Union[str, ut.Vector], name: str, formatter: Optional[Callable[[Any], Any]] = None, method: str = "majority", min...
fc9abd9a983d24869f46efb71d29cd2db53508da
2,632
def generate_languages(request): """ Returns the languages list. """ validate_api_secret_key(request.data.get('app_key')) request_serializer = GenerateLanguagesRequest(data=request.data) if request_serializer.is_valid(): get_object_or_404(TheUser, auth_token=request.data.get('user_token...
67856b4bac293e272debb0ac9f2a2e0c863f4cdb
2,634
def all_stocks(): """ #查询当前所有正常上市交易的股票列表 :return: """ data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') return data["symbol"].values
582381319bd0b613758f41de2005e192c802a923
2,635
import requests import json def getBotHash(userID, isCompile=False): """Gets the checksum of a user's bot's zipped source code""" params = {"apiKey": API_KEY, "userID": userID} if isCompile: params["compile"] = 1 result = requests.get(MANAGER_URL+"botHash", params=params) print("Gett...
700d5418212836e1ad20a3a336587436cf1e93de
2,636
def next_remote_buffer_uuid(number=1): """Return the next uuid of a remote buffer.""" global remote_buffer_counter if number == 1: ret = remote_buffer_counter else: ret = np.arange(remote_buffer_counter, remote_buffer_counter + number) remote_buffer_counter = (remote_buffer_counter +...
da31c68dd199ff765ec6eaab17912dd4e3ea8ee4
2,637
def ball_collide(i): """ This function will handle the ball collide interaction between brick and paddle :param i: (int) The index of the ball to interact :return: (Bool) If this ball collide with brick or paddle """ global score collide = False for j in range(2): for k in range(...
33ee97dde1302578067e16b8251e5c3787901697
2,638
from pathlib import Path import tqdm def gen_sparse_graph(destination_folder: Path, vertices_number: int, edge_probability: float) -> Path: """ Generates sparse graph :param destination_folder: directory to save the graph :type destination_folder: Path :p...
79369b7c436ca903e5cbc620b95d6425d5646a55
2,639
def read_csv(path): """Reads the CSV file at the indicated path and returns a list of rows. Parameters: path (str): The path to a CSV file. Returns: list[row]: A list of rows. Each row is a list of strings and numbers. """ with open(path, 'rb') as f: return decode_csv(f.re...
7b979a9e15ae07cbdb2733ec071ea82664df5bab
2,642
def obj_mask(im): """Computes the mask for an image with transparent background Keyword arguments: im -- the input image (must be RGBA) """ A = im.split()[-1] T = ImageOps.invert(A) return Image.merge("RGBA", (T, T, T, A))
bfcb6c9c8877dc2507bc9bc658eeb1140fc950bc
2,643
def rnn(rnn_type, inputs, length, hidden_size, layer_num=1, dropout_keep_prob=None, concat=True): """ Implements (Bi-)LSTM, (Bi-)GRU and (Bi-)RNN 在这个module中,rnn是主要的接口,所以把rnn放在上面 Args: rnn_type: the type of rnn, such as lstm inputs: padded inputs into rnn, usually a d*p or l*p mat...
80d06ed499c4668bd398efdf9358c8d72e2e3192
2,644
def find_expired(bucket_items, now): """ If there are no expired items in the bucket returns empty list >>> bucket_items = [('k1', 1), ('k2', 2), ('k3', 3)] >>> find_expired(bucket_items, 0) [] >>> bucket_items [('k1', 1), ('k2', 2), ('k3', 3)] Expired items are returned in the lis...
476fd079616e9f5c9ed56ee8c85171fcb0ddb172
2,645
import array def find_sprites(image=None, background_color=None): """ Find sprites @image: MUST be an Image object @background_color: optinal, whether tuple (RGB/ RGBA) or int (grayscale) """ def find_sprites_corners(sprite, label_map, numpy_array): columns = set() rows = set() ...
67a544e916ebd01fbddd16f755e386d820507433
2,646
def get_java_package(path): """Extract the java package from path""" segments = path.split("/") # Find different root start indecies based on potential java roots java_root_start_indecies = [_find(segments, root) for root in ["java", "javatests"]] # Choose the root that starts earliest start_...
253e503a146cffe6a8c00786539d8e3a2d6374f7
2,647
def get_plugin(): """Return the filter.""" return TextFilter
b0d43cab9c3b887fd9735ecfdc5372a8e2aefb49
2,649
import time def caltech256(root): """Caltech256 dataset from http://www.vision.caltech.edu/Image_Datasets/Caltech256 Pictures of objects belonging to 256 categories. About 80 to 800 images per category. Collected in September 2003 by Fei-Fei Li, Marco Andreetto, and Marc 'Aurelio Ranzato. ...
972cec00a3360fe0ace5b1fb8165e45718c137c1
2,650
def draw__mask_with_edge(cv2_image: np.ndarray, edge_size: int = 10) -> np.ndarray: """ From a color image, get a black white image each instance separated by a border. 1. Change a color image to black white image. 2. Get edge image from `cv2_image`, then invert it to separate instance by a border. ...
50a25b60fdfa83f8cd1ec707f4c0e63b3c621695
2,651
def get_functions(pdb_file): """Get the offset for the functions we are interested in""" methods = {'ssl3_new': 0, 'ssl3_free': 0, 'ssl3_connect': 0, 'ssl3_read_app_data': 0, 'ssl3_write_app_data': 0} try: # Do this the hard way to avoid ha...
e2a36d3799004c1f96d5bccb3c4f0a8ad3ce2607
2,652
import typing def empty_iterable() -> typing.Iterable: """ Return an empty iterable, i.e., an empty list. :return: an iterable :Example: >>> from flpy.iterators import empty_iterable >>> empty_iterable() [] """ return list()
904fe365abf94f790f962c9a49f275a6068be4f0
2,653
from re import M def nearest_pow_2(x): """ Finds the nearest integer that is a power of 2. In contrast to :func:`next_pow_2` also searches for numbers smaller than the input and returns them if they are closer than the next bigger power of 2. """ a = M.pow(2, M.ceil(M.log(x, 2))) b = M...
c9dba6f38badcedee02f7071fc5fcf82519dbdcb
2,654
def timestamp_preprocess(ds, column, name): """This function takes the timestamp in the dataset and create from it features according to the settings above Args: ds ([dataframe]): dataset column ([integer]): column index name ([string]): column name Returns: [dataframe]: dat...
18203f8e9a016d3302d5fe06d498d68403eb5805
2,655
def make_taubin_loss_function(x, y): """closure around taubin_loss_function to make surviving pixel positions availaboe inside. x, y: positions of pixels surviving the cleaning should not be quantities """ def taubin_loss_function(xc, yc, r): """taubin fit formula reference...
b11aae3586cb387a6e280f5b0e985dcf6364306e
2,656
def init_rf_estimator(): """ Instantiate a Random forest estimator with the optimized hyper-parameters. :return: The RandomForest estimator instance. """ rf = RandomForestClassifier( criterion=RF_CRIT, min_samples_leaf=RF_MIN_SAMPLES_LEAF, max_features='auto', n_estimators=RF_N_ESTS, n_jobs=-1) return r...
1171b5582869151823da29c61545c857e04ffed6
2,657
def dict_filter(d, exclude=()): """ Exclude specified keys from a nested dict """ def fix_key(k): return str(k) if isinstance(k, builtin_str) else k if isinstance(d, list): return [dict_filter(e, exclude) for e in d] if isinstance(d, dict): items = ((fix_key(k), v) for...
afa87c730fd105741a3bf95601d682fa817b903d
2,658
async def mongoengine_multiple_objects_exception_handler(request, exc): """ Error handler for MultipleObjectsReturned. Logs the MultipleObjectsReturned error detected and returns the appropriate message and details of the error. """ logger.exception(exc) return JSONResponse( Respo...
c0e3d8d25ee02b9240cbf02f532cb853cbc693ee
2,659
def _get_sample_times(*traces, **kwargs): """Get sample times for all the traces.""" # Set the time boundaries for the DataFrame. max_stop_time = max( [trace.stop_time() for trace in traces if isinstance(trace, Trace)] ) stop_time = kwargs.pop("stop_time", max_stop_time) min_start_time ...
3e20bed62017e8306b3489ec41b7f6cd59a4c916
2,660