content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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_similar_genes_Quantiles( gene_expr: np.array, n_genes: int, candidate_quants: np.ndarray, candidate_genes: np.array, quantiles=(0.5, 0.75, 0.85, 0.9, 0.95, 0.97, 0.98, 0.99, 1), ): """Gets genes with a similar expression distribution as the inputted gene, by measuring distance be...
c327e78a08f8da73af896a2e496f6c24258cc271
2,603
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 logging def get_gpa(cookie, sno, year='', term=''): """ 获取已取得的总基点: 专必 公必 公选 专选 """ logging.debug('Getting gpa: %s %s %s %s', sno, year, term, cookie) url = 'http://uems.sysu.edu.cn/jwxt/xscjcxAction/xscjcxAction.action?method=getAllJd' query_json = """ { header: { ...
d586aab689e40be763ccb907a4673e2da500e8a2
2,605
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
import argparse def parse_arguments(): """Parse user args There are three subparsers, one for each mode: full, visit, and moab. Full mode runs both the visit and moab steps. Each parser should have a full help message, simplified usage statement, and examples. """ mode_examples = """ To view ...
9cd3809479ab49a53343c6a7007e34fbf08dc23b
2,613
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
def formulate_hvdc_flow(problem: LpProblem, angles, Pinj, rates, active, Pt, control_mode, dispatchable, r, F, T, logger: Logger = Logger(), inf=999999): """ :param problem: :param nc: :param angles: :param Pinj: :param t: :param logger: :param inf: :return: ...
b9fb1d6d7fdf19ee97f1b29f4e4b279130aab530
2,618
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
import os import yaml import json def load_pipeline(path, tunables=True, defaults=True): """Load a d3m json or yaml pipeline.""" if not os.path.exists(path): base_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.join('templates', path) path = os.path.join(base_path, p...
386683e91af1a5f568e329f70690e676c5c9383d
2,633
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
from pyapprox.cython.barycentric_interpolation import \ def multivariate_hierarchical_barycentric_lagrange_interpolation( x, abscissa_1d, barycentric_weights_1d, fn_vals, active_dims, active_abscissa_indices_1d): """ Parameters ---------- x : np.ndarray ...
da527f226ea2c95fcec160616b060eed08e83e87
2,640
import pandas as pd import os def deaths(path): """Monthly Deaths from Lung Diseases in the UK A time series giving the monthly deaths from bronchitis, emphysema and asthma in the UK, 1974-1979, both sexes (`deaths`), P. J. Diggle (1990) *Time Series: A Biostatistical Introduction.* Oxford, table A.3 A...
05ff7646d2c7a5a6368b9453ef7c8c80f1348b1c
2,641
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
import os def generate_seekr2_model_and_filetree(model_input, force_overwrite): """ Using the Model_input from the user, prepare the Model object and the filetree. Then prepare all building files for each anchor and serialize the Model to XML. """ model = common_prepare.model_factory(model_inp...
1309c8106f4b52b14c6b6c6760cefec5ea7749a5
2,648
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
import math def get_weak_model(op, diff_type, nonzero2nonzero_weight, zero2zero_weight=0, zero2nonzero_weight=math.inf, nonzero2zero_weight=math.inf, precision=0): """Return the weak model of the given bit-vector operation ``op``. Given the `Operation` ``op``, return the `WeakModel` of...
be34db3112ff7788bb96e6d6cc467d4d98d8af51
2,661
def get_temp(): """ 読み込んだ温度を返す """ return sensor.t
a4c7ed616af202599581cd47be87cb10ea571947
2,662
def load_clean_yield_data(yield_data_filepath): """ Cleans the yield data by making sure any Nan values in the columns we care about are removed """ important_columns = ["Year", "State ANSI", "County ANSI", "Value"] yield_data = pd.read_csv(yield_data_filepath).dropna( subset=important_c...
14c5facc947d1ff8bcc7714447e9da3b7842bcee
2,663
def create_element_mapping(repnames_bedfile): """Create a mapping of the element names to their classes and families""" elem_key = defaultdict(lambda : defaultdict(str)) with open(repnames_bedfile, "r") as bed: for line in bed: l = line.strip().split("\t") name = l[3] ...
d3bc0491625d318b8f049c71a10571c21caf03d8
2,664
def _get_CRABI_iterators(captcha_dataframe, train_indices, validation_indices, batch_size, image_height, image_width, character_length, catego...
7e01586f359860b5d1e461e9612b164e6cf9365f
2,665
import uuid def run(request, context): """Creates a template. Args: request (orchestrate_pb2.CreateTemplateRequest): Request payload. context: Context. Returns: A orchestrate_pb2.CreateTemplate with the status of the request. """ template = request.template print('Orchestrate.CreateTemplate ...
484de4399b23bbc71e35ad70b054c1a62c41952e
2,666
def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian to a 2D image. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optiona...
6ac3c7b7cba17baba719bd1d1fc87030f9c45dca
2,667
from typing import List from pathlib import Path import os def list_dir_files(path: str, suffix: str = "") -> List[str]: """ Lists all files (and only files) in a directory, or return [path] if path is a file itself. :param path: Directory or a file :param suffix: Optional suffix to match (case insens...
aaba7de5d5f67c5addc054010c5a2bd811475a3e
2,668
def to_roman(number): """ Converts an arabic number within range from 1 to 4999 to the corresponding roman number. Returns None on error conditions. """ try: return roman.toRoman(number) except (roman.NotIntegerError, roman.OutOfRangeError): return None
48fbe99caa527e711f8d0285577d96941a34b9c9
2,669
def GDAL_like(filename, fileout=""): """ GDAL_like """ BSx, BSy, Mb, Nb, M, N = 0,0, 0,0, 0,0 dataset1 = gdal.Open(filename, gdal.GA_ReadOnly) dataset2 = None if dataset1: band1 = dataset1.GetRasterBand(1) M, N = int(dataset1.RasterYSize), int(dataset1.RasterXSize) B ...
34d4ea83a7c7e1726aa1d5a4d89e16bbed50cdd1
2,670
def take_attendance(methodcnt): """global setup_bool if (setup_bool == False or methodcnt == False): print ("in if statement") setup_bool = True else:""" print ("checking in - F.R.") react_with_sound(attendance_final) client.CheckIn() return 2
0ecdf80e59de5d968f7adc042d6be369367f4195
2,671
def feature_selection(data, features): """ Choose which features to use for training. :param data: preprocessed dataset :param features: list of features to use :return: data with selected features """ return data[features]
6303e52a9c64acfbb5dcfd115b07b3bef2942821
2,672
def parse_docstring(docstring, line=0, filename='<string>', logger=None, format_name=None, options=None): # type: (str, int, Any, Optional[logging.Logger], Optional[str], Any) -> Tuple[OrderedDict[str, Arg], Optional[Arg]] """ Parse the passed docstring. The OrderedDict holding pars...
47cd0318f24ec1a26233ad6e98a398a4c9e95db6
2,673
def srCyrillicToLatin(cyrillic_text): """ Return a conversion of the given string from cyrillic to latin, using 'digraph' letters (this means that e.g. "nj" is encoded as one character). Unknown letters remain unchanged. CAVEAT: this will ONLY change letters from the cyrillic subset of Unicode. For in...
cd4850b6c0bcf9b27aa1340dc98956c026e8f557
2,674
def from_phone(func=None): """来自手机的消息(给自己发的) FriendMsg""" if func is None: return from_phone async def inner(ctx): assert isinstance(ctx, FriendMsg) if ctx.MsgType == MsgTypes.PhoneMsg: return await func(ctx) return None return inner
8e47e82e014d3d727a615e310997cd2c634ae821
2,675
from typing import Iterator from typing import Tuple from typing import List from typing import Callable import torch import sys def fit_and_validate_readout(data: Iterator[Tuple[Tensor, Tensor]], regularization_constants: List[float], get_validation_error: Callable[[Tuple[Tensor, Tensor]...
d179e70aa53da0ff38ede9bbbf3fbe58b81c2886
2,676
import pathlib def create_scan_message(): """Creates a dummy message of type v3.asset.file to be used by the agent for testing purposes. The files used is the EICAR Anti-Virus Test File. """ file_content = (pathlib.Path(__file__).parents[0] / 'files/malicious_dummy.com').read_bytes() selector = 'v...
e899e705fc022046876dd2a1584e7db74c4b7105
2,677
def is_permutation_matrix( m ): """ Test whether a numpy array is a `permutation matrix`_. .. _permutation_matrix: https://en.wikipedia.org/wiki/Permutation_matrix Args: m (mp.matrix): The matrix. Returns: (bool): True | False. """ m = np.asanyarray(m) return (m.nd...
7cfe48fd0cd36c4ff151ebe248c79e685ee99cc8
2,678
def create_security_role(connection, body, error_msg=None): """Create a new security role. Args: connection: MicroStrategy REST API connection object body: JSON-formatted definition of the dataset. Generated by `utils.formjson()`. error_msg (string, optional): Custom Error M...
fbae3596e0cdcc430b2a7a30fc9ed594f3717ba3
2,679
def dbm_to_w(dbm): """Convert dBm to W.""" return 10 ** (dbm / 10.) * sc.milli
b6b782f35a3a07a2f372958363609b3b0f00a43a
2,680
from operator import inv def lml(alpha, beta, Phi, Y): """ 4 marks :param alpha: float :param beta: float :param Phi: array of shape (N, M) :param Y: array of shape (N, 1) :return: the log marginal likelihood, a scalar """ N = len(Phi) M = len(Phi[0]) part1 = (-N*0.5)*np.l...
a6d17ed0f6c81958360687d5758cd8a35147dd56
2,681
from typing import Callable from typing import Any import os def convert_env_var(var_name: str, *, cast_type: Callable[..., Any] = float, default: Any = None) -> Any: """ Attempts to read an environment variable value and cast it to a type. For example it permits getting numeric value(s) from os.environ ...
8b01cdca21f32aad2471946c39a2fc5962e316ef
2,682
def balance_set(X, Y, adr_labels_size, nonadr_labels_size): """balances the set by doing up- and down -sampling to converge into the same class size # Arguments X - set samples Y - set labels adr_labels_size - ADR_MENTION_CLASS size nonadr_labels_size - NON_ADR_MENTION_CLASS siz...
e73468dd600a9d6f9b13a46356110d35fba8ce59
2,683
from pathlib import Path def load_det_lcia(result_dir, method, act_code, det_lcia_dict=None): """Return precalculated deterministic LCIA score""" result_dir = Path(_check_result_dir(result_dir)) method = _check_method(method) if not det_lcia_dict: det_lcia_dict = _get_det_lcia_dict(result_dir,...
c9ba6532f674bcbe988cdc645b7dd86a93ed27e5
2,684
def get_geometry(location, geolevel): """ Get geometry of a single location code/name """ if not utils.is_number(location) and location != "BR": assert geolevel, "You need to specify which geographic level this location is" location = ibgetools.ibge_encode(location, geolevel) if loca...
da53cfe7845c7adffbcbd941dc3f0b62bdb15e2f
2,685
def render_to_string(template, context={}, processors=None): """ A function for template rendering adding useful variables to context automatically, according to the CONTEXT_PROCESSORS settings. """ if processors is None: processors = () else: processors = tuple(processors) for processor in get_st...
678eab60113a05fba86591ee7bb47e26ecfb0b37
2,686
def find_node_names(structure): """ Return the names of the nodes for the structure """ # Look through all of the items in the structure for names # Check through each of the lists and sub-lists names=set() for i in xrange(len(structure)): if isinstance(structure[i],basestring): ...
812194e2d8dbd34741e9f03a6c775bb30f551341
2,687
import os def run_calcs(run_id, year, no_ef_countries, export_data=True, include_TD_losses=True, BEV_lifetime=180000, ICEV_lifetime=180000, flowtrace_el=True, allocation=True, production_el_intensity=679, incl_ei=False, energy_sens=False): """Run all electricity mix and vehicle calculations and exports results.""...
7bb80133ec3ee684c8db229f9f41940c994c3634
2,688
def handle_question(): """Save response and redirect to next question.""" # get the response choice choice = request.form['answer'] # add this response to the session responses = session[RESPONSES_KEY] responses.append(choice) session[RESPONSES_KEY] = responses if (len(responses) == l...
184dc816303f48e134320f602126d381ee820b59
2,689
from typing import Callable def makeNotePlayer(seq: Sequencer, out: PortInfo ) -> Callable[[int, bool], None]: """Returns a callable object that plays midi notes on a port.""" def playNote(note: int, enabled: bool) -> None: if enabled: seq.sendEvent(NoteOn(0, 0, note, 127), out) ...
7cb9741944f6f71fbfd55b825c2c7e4638bfa317
2,690
def se_resnet152(**kwargs): """TODO: Add Doc""" return _resnet("se_resnet152", **kwargs)
52dd9fa145f6216519282633aa54e6e17802aaa9
2,691
import base64 def file_to_attachment(filename): """ Convert a file to attachment """ with open(filename, 'rb') as _file: return {'_name':filename, 'content':base64.b64encode(_file.read()) }
9b64fe8a4329eae000cd76d58450c32644a736f6
2,692
def ratio_selection( strain_lst, ratio_lst, pressure_lst, temperature_lst, ratio_boundary, debug_plot=True, ): """ Args: strain_lst: ratio_lst: pressure_lst: temperature_lst: ratio_boundary: debug_plot: Returns: """ if debug_...
f4260649c50b33d9ee818ebdc0469d693720937d
2,693
def diff_mean(rolling_window, axis=-1): """For M5 purposes, used on an object generated by the rolling_window function. Returns the mean of the first difference of a window of sales.""" return np.diff(rolling_window, axis=axis).mean(axis=axis)
85294f16c89658eaca9562e1ff4652d5865a5a59
2,694
import numpy def noiseFraction(truth_h5, measured_h5, tolerance): """ Return the fraction of measured localizations that are greater than tolerance pixels from the nearest truth localization. Note: This will return 0 if there are no measured localizations. truth_h5 - A saH5Py.SAH5Py object with ...
282e8c835906cf218e6eb1ef94cbb595419419f5
2,695
import os def prepare(compute: dict, script_id: str): """Prepare the script :param compute: The instance to be attacked. :param script_id: The script's filename without the filename ending. Is named after the activity name. :return: A tuple of the Command Id and the script content """ os_type ...
547662decdc541ba398a273a91280ce9b60b2006
2,696
def compute_rigid_flow(depth, pose, intrinsics, reverse_pose=False): """Compute the rigid flow from target image plane to source image Args: depth: depth map of the target image [batch, height_t, width_t] pose: target to source (or source to target if reverse_pose=True) camera transformation matri...
5b01bfb9768bc1f180b06f599e71c4808c945854
2,697
def get_versions(script_name): """ 返回指定名称脚本含有的所有版本。""" versions = repository.get(script_name, None) if not versions: return None return sorted(versions, reverse=True)
4399c5531bbf0d10f750d64ce3a63e156d62ba1b
2,698
import os def data_static(filename): """ Get files :param filename: :return: """ _p, _f = os.path.split(filename) print(_p, _f) return flask.send_from_directory(os.path.join( '/Users/dmitryduev/_caltech/python/deep-asteroids/data-raw/', _p), _f)
ebaf91e16fc3f0a83da47c61723c62a03533fa1c
2,699