content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_uploads_from_model(instance, attr): """Replaces attachment files from model to a given location, returns list of opened files of dict {file:'file',date:date,name:'filename'}""" ats = [] files = getattr(instance, attr) for fl in files.all(): ats.append({"file": File(fl.file)...
5de237811454c1c62634576dfdcd79bd51d13211
61,700
import pathlib def check(root: pathlib.Path = pathlib.Path(".")): """Checks that all toml files parse and that values match the template value types.""" possible_templates = list(root.glob("*.template.toml")) if len(possible_templates) > 1: raise ValueError("Only one template supported") i...
4ef6b98aa7306bf5db92d94b2deaa269f4ea7470
61,701
def remove_prefix(string: str, prefix: str): """ Removes a prefix from a string if present. Args: string (`str`): The string to remove the prefix from. prefix (`str`): The prefix to remove. Returns: The string without the prefix. """ return string[len(prefix) :] if stri...
598e1b9b863d342e757e54cf94035da63e3ace1f
61,702
import functools def input_handling(func): """Decorator that handles input naming for interpolations.""" @functools.wraps(func) def wrapper_input_handling(*args, **kwargs): # unpack args phi, theta, target_theta_levels, phi_dim, theta_dim, target_dim = args # pop kwargs used for...
9aa73218776d9ffa29d878036825c906fc428521
61,703
import torch import time def dist_prediction_visualization(model): """ TODO refactor """ val_transform = transform.Compose([ transform.Crop([473, 473], crop_type='center', padding=mean, ignore_label=255), transform.ToTensor(), transform.Normalize(mean=mean, std=std)]) val_d...
7c79368b779ce6301bc9ce3cfeb69477cc5dadb9
61,704
def get_params(opt_over, net, net_input, downsampler=None): """ Returns parameters that we want to optimize over. :param opt_over: comma separated list, e.g. "net,input" or "net" :param net: network :param net_input: torch.Tensor that stores input `z` :param downsampler: :return: """ ...
b8a3c26b5307c0ba584e3841a2d98f337c618bf8
61,705
def _top_k(distance_profile, k, exclusion_zone, option): """ Finds top k discords or motifs given an exclusion zone. The exclusion zone acts as a buffer between a found index on the left and right hand side. For example, if you set the exclusion zone to 4 and a motif or discord was found at index ...
922439992b77bf5852f37d8241c803fc04e05040
61,706
def coa_nonirrigated_cropland_fba_cleanup(fba, **kwargs): """ When using irrigated cropland, aggregate sectors to cropland and total ag land. Doing this because published values for irrigated harvested cropland do not include the water use for vegetables, woody crops, berries. :param fba: :return: ...
7e7495afef48fb7e772ecc92b76d22a82a6049c7
61,707
def write_tlv(data: dict): """Convert a dict to TLV8 bytes. NB: This simple implementation assumes all values are bytes! """ tlv = b"" for key, value in data.items(): tag = bytes([int(key)]) length = len(value) pos = 0 # A tag with length > 255 is added multiple tim...
e0da4f6374507e4f5b83b48826b7d7f31fd47dd5
61,708
import torch def stensor(data, stable_dims=(), dtype=None, device=None, requires_grad=False, pin_memory=False): """ Constructs a STensor from input data and a partition index placement Args: data: Initial data for the stensor. Can be a list, tuple, NumPy ``ndarray``, scal...
0c3307a94f341fa698e5b620b711089d5c9c3f4d
61,709
def mulmat(X,Y): """ Multiplies a matrix X to a matrix Y NOTE: Does no checks any matrix sizes. Parameters ---------- X(list) : The X list as matrix Y(list) : The Y list as matrix Returns ------- list : Result multiplied matrix X*Y """ result = matrix(len(X), len(Y[0])...
887e7c7c7563abb636affb9c5634fb7f9a7fe0fe
61,710
import math def softplus(x): """Softplus activation function Args: x (float): input value Returns: float: output value """ try: return math.log(1 + math.exp(x)) except OverflowError: return 0 if x < 0 else 1
637f5bb5b504c2215e7213bbce06e937f13ea080
61,711
def _find_corners(cluster, cluster_type, n_fast=12, threshold_fast=0.1, method='suppression'): """ find 2 corners in the cluster Method: 'farthest' from the center of mass 'largest' between all the corners """ # Find the corners with the corner_fast method # Be sure there are no holes i...
68f87879c0fe923cb7ca196b202bc97de65924d9
61,712
def is_admin(identity=None): """Returns True if |identity| (or current identity if None) is an admin. Admins are identities belonging to 'administrators' group (see model.ADMIN_GROUP). They have no relation to GAE notion of 'admin'. See 'is_superuser' for asserting GAE-level admin access. """ return is_gr...
0939eeea105c70ed5632e0e9b69243b4c3df4f76
61,713
def create_parser(): """ :return: """ parser = ArgumentParser(add_help=True, parents=[get_parent_parser()]) parser.add_argument( "--scenario_id", help="The scenario ID. Required if " "no --scenario is specified.", ) parser.add_argument( "--scenario", help="Th...
9545faf73a4416bd4ac32d5e94de9c6b41ea2280
61,714
from typing import Optional from typing import Any def nested_get(dct: dict, *keys: str) -> Optional[Any]: """Multi-level get helper function.""" for key in keys: dct = dct.get(key, {}) return dct if dct else None
cd881389157d67365793240e1e2e0b39f4bc1726
61,715
def data_preprocess(filename, mode='Train', training_data=None): """ :param filename: str, the filename to be read into pandas :param mode: str, indicating the mode we are using (either Train or Test) :param training_data: DataFrame, a 2D data structure that looks like an excel worksheet :return: Tuple(data, label...
115efaa45ff4abaf0d6a6b59eb7fa6fcdf28db82
61,716
from typing import Optional from typing import Any def scatter( hist: BootstrapHistogram, ax: Optional[MplAxes] = None, **kwargs: Any ) -> Any: # """ Scatter plot of the bootstrap samples. The scatter-point x-coordinate within a bin drawn from a uniform random distribution. Parameters -----...
a06ec1ef4b68108a85e31e41b9b1e139d515662d
61,717
def get_ml_eng(): """ Returns a started matlab engine. The engine is started and set to the correct directory for Monocap. The startup code for Monocap is then run to ensure all necessary files are added to the path. Returns ------- eng : engine.matlabengine.MatlabEngine ...
86856231111efef6d9fccc3d9fed6cb526d490ca
61,718
def train_test_data(dataframe, target_variable_name, train_size=.8, random_state=42): """ Returns dataframes of training and test sets Use this function if implementing cross validation with sklearn :param dataframe: pandas.DataFrame :param target_variable_name: str :param train_size: float from...
373494f59c1a68d8504fd13f8d028bdd478f37a2
61,719
import os import tqdm def get_faust_test(data_dir, n_scan_points=10000): """ Get FAUST test scans Parameters ---------- data_dir : str path to FAUST dataset directory (../MPI-FAUST/) n_scan_points: int number of points to take from the scan Returns ------- scans : num...
9daf04e24fd37d42b056eaf4f5bcc167ee892d97
61,720
def only_moto(request): """Return True if only moto ports are to be used for mock services.""" return request.config.option.only_moto
1ab211925a411d4999a22e77d819da88b4477ed6
61,721
def get_nframes(video_name, last_frame, nframes = 10): """ Extracts nframes from video to create training batches. :param video_name: absolute path to video :param last_frame: frame of interest :param nframes: number of frames to take :return: array of size nframes x width x height x RGB, with ...
adb00d890a2c2c5e2d4fabe0e2d6dc25e18766ab
61,722
import os def correct_path (namespace_path, database_path=DATABASE_PATH, tokens_path=TOKENS_DICT): """Относительные пути к базе данных и рабочему словарю переводятся в абсолютные. Таким образом скрипт можно запускать из любого каталога. """ if namespace_path is database_path: database_pat...
f8f0fcff63e5cf258d733cc24634f590263e221f
61,723
def validate_permissions( hass, minimum_permissions, token_path=DEFAULT_CACHE_PATH, filename=TOKEN_FILENAME ): """Validate the permissions.""" permissions = get_permissions(hass, token_path, filename) if not permissions: return False for minimum_perm in minimum_permissions: permissi...
ccbf14b17a78410f775ecd38d2a762bab5179271
61,724
def find(sub_str, target_str): """[summary] 字符串查找 Arguments: sub_str {str} -- substring target_str {str} -- target string Returns: bool -- if substring is found in target string """ return sub_str in target_str # in operator用的是Boyer–Moore算法,最坏情况O(mn), 最好情况O(n/m) ...
d26e4ad79eaf913d81126d7647036b857de5ed6d
61,725
def _source_step(func): """ Transform a iterator factory to a pipeline source :Warning: The step ignores its in_queue and only writes to the out_queue. :Parameters: `func` : callable iterator :Return: New step class :Rtype: ``type`` """ class _SourceStep(AbstractStep): ...
dc8a6e53add8c24075a96a2a3e1b188f51903ae5
61,726
import math def num_to_thaiword(number: int) -> str: """ This function convert number to Thai text :param int number: an integer number to be converted to Thai text :return: text representing the number in Thai :rtype: str :Example: >>> from pythainlp.util import num_to_thaiword ...
77e7021cfc36886b76af9c5ae93c0d4c40dfa005
61,727
def parse_arguments(cfg): """ Uses `argparse` to parse the command line arguments. Parameters ---------- cfg: dict Configuration dictionary. Returns ------- out: Namespace Command line arguments. """ p = ap.ArgumentParser(description="Create proxies for Blender VSE usin...
e9f9170b68f9fbafcae699d5b9f60ac0aebabbbe
61,728
def check_faces_in_caption(photo): """Checks if all faces are mentioned in the caption.""" comment = photo.comment if photo.getfaces() and not comment: return False for face in photo.getfaces(): parts = face.split(" ") # Look for the full name or just the first name. if (...
eed03439df84a1ddd4cb7bcbb269af7c60adfcb5
61,729
import requests def get_pound_price(product='drvSummary'): """Get price value (nominally in pence) and convert to Pound format if necessary. :param product: str (product type) :return: decimal (price in pounds) """ LOGGER.debug("STARTED: get_pound_price product: {}".format(product)) response ...
9576c591f5fa99f2c9807f807cc375b987a55f53
61,730
def create_light_sensor(): """ Create a new light sensor. :return: New sensor object. """ temp = build.Light() temp.current_value = float(input("\n" + Lang["< Insert current value >"] + "\n\n>>")) clear() temp.sampling_freq = float(input("\n" + Lang["< Insert sampling frequency >"] + "\n...
52a2f9316401c62215e55f8f9249c84ae9bfde9a
61,731
def prcs_blast_rslts_xml(filepath, args): """ Processes the blast results stored in an xml file and then scrapes online databases for ec numbers. :param filepath: The filepath of the blast results xml file. :param args: A python dictionary of command line arguments :return: The results of ...
5fa2365a99f50bdce6a5f5a5f3a6cfed4e5b8dc6
61,732
from licensedcode.match_seq import MATCH_SEQ def filter_spurious_matches( matches, trace=TRACE_FILTER_SPURIOUS, reason=DiscardReason.SPURIOUS, ): """ Return a filtered list of kept LicenseMatch matches and a list of discardable matches given a `matches` list of LicenseMatch by removing mat...
c051d2fa8166e0f5c5ed4c715bd6799942a39595
61,733
def fuses(**kwargs): """ Función que define las configuraciones del PIC seleccionado Las configuraciones disponibles son: wdt: Watchdog \n mclr: MCLR \n debug: Debug enable \n lvp: \n fosc: Oscilador :return: None """ if "build" in kwargs.keys(): if kwargs["build"]...
9edaafd197136e760cbbaf6b8963c63671797edd
61,734
import yaml import os from operator import add def do_query(archives, config_file=None, logger=None, context=None): """ The query counts as a “hit” every time that finds a page with a particular term from a lexicon and it groups the results by years. config_file must be the path to a lexicon fil...
364de4d5c3e51ded409c8365face02f810a4dec7
61,735
from typing import Any from typing import IO from typing import List from re import A import abc def wait(*l: Fiber[Any, Any, Any]) -> IO[R, E, List[Result[R, A]]]: """ Wait until these Fibers finish. Return the list of Result in the same order. :param l: :return: """ if len(l) == 1 and is...
205130d88643f29b3bd7f6d8b6609fd18700aa4d
61,736
def mp_move_files(multiprocessing_pool_vars): """ Moves the file as given with multiprocessing_pool_vars (iterable) multiprocessing_pool_vars: [filename, from_dir, to_dir] :param multiprocessing_pool_vars: :returns: list """ filename = multiprocessing_pool_vars[0] from_dir = multiprocessing_...
d8bf3fbd1cd77aff75a259ee311ab1a29ca6ab7b
61,737
import json def add ( data ): """Process JSON string to add to data set""" if util_json_bad(data): raise BadJsonError(data) return t = json.loads(data, strict=False) name = t["dataset"] keys = t["keys"] values = t["values"] if util_key_bad(keys): raise BadKey...
9182f0cfa77231b02d4f7f70e68c8989c73d7fed
61,738
def LfromS(seq): """ Compute Schroder function value L from a given sequence. This performs the calculation by plodding through the algorithm given in the paper. Humans can easily recognize the relation between elements of S and length of runs of 0s or 1s in the binary representation of L. Knowing that, the...
6adf8c0b6f8e12d7e6a79efcb38c628ef0b29031
61,739
import numpy def negative_binary_f_two(func, c, x, y): """Test negative values as input to func as second argument.""" x = x + (-4) z = func(c, x) z = numpy.clip(z, 0, 63).astype(numpy.int32) + y return z
aec636cbf7c8733ce5584381d8be5bd25cf7d167
61,740
import os def choose_template(argv): """Return name of template to use.""" if len(argv) == 2: return DIR_PATH + "/templates/" + argv[1] templates = os.listdir(DIR_PATH + '/templates') print("Available Templates\n===============") for i in range(len(templates)): print("{}: {}".form...
cf262995306a7f047b78a6511d0e959b9e6441df
61,741
import os import pprint import appdirs def check_links_from_file(input_file: str = DEFAULT_LINKS_CSV, output_file: str = DEFAULT_RESULTS_CSV, print_each: bool = False, open_results_when_done = True, viewer = DEFAUL...
cf573d15efd5813988fd339d28061d1ee58f29f0
61,742
def prop_test(data, prop_0, alternative = 'equal', alpha = 0.05): """ This function is used to implement the prop_test Input params: data (dataframe of boolean): dataframe restricted to the specified column to evaluate prop_0 (float) : values of the alternative testing ...
5b0094d6cf53e4709fe379196a6c8a80670d4d45
61,743
from re import T def task(): """ RESTful CRUD controller """ tablename = "project_task" table = s3db[tablename] # Custom Method to add Comments s3mgr.model.set_method(module, resourcename, method="discuss", action=discuss) statuses = resp...
b6c4e613a042cebc029023f309e0b55df5b45525
61,744
import os import subprocess def indexVG( vg: str, vcf: str, threads: int, verbose: bool, debug: bool ) -> int: """Construct the XG and GBWT indexes for the given genome variation graph. These indexes are required to query the genome when extracting motif occurrence candidates. ...
f101c681ff014a53318d77b8363f50071795665a
61,745
def interpret_where_clause( interpreter, speaker, where_d, memory_type="ReferenceObject", ignore_self=False ): """ where_d is a sentence (nested dict/list) of the recursive form COMPARATOR, TRIPLE, or {CONJUNCTION, [where_clauses]} where each CONJUCTION is either "AND", "OR", or "NOT" """ ...
3f8e24ffe3cb44fe9c96d7535c1b9ee381979210
61,746
def generate_point(): """ X: [tRexX,tRexY,speed,obsX,obsY] Y: [passReward,jumpReward] """ X = np.array([ np.random.normal(23,1), # tRex X np.random.uniform(0,90), # tRex Y np.random.uniform(6,12), # speed np.random.uniform(-50,700), # obs1 X np.rando...
13a8482247e0b1f58f8fb7dce317c2ade9e9f04b
61,747
import torch def nms (boxes, nms_thresh): """ None Max Separetion """ if len (boxes) == 0: return boxes det_confs = torch.zeros (len (boxes)) for i in range (len (boxes)): det_confs [i] = 1 - boxes [i][4] _, sortIds = torch.sort (det_confs) out_boxes = [] for i in range (...
6d2d152a87f5f595a541ca03d870e8a89de671db
61,748
def _compute_coords(shape, xyz_resolution=1, origin='center'): """Returns the real_coordinates of an image with the given shape at the given resolution as a single numpy array of shape (*shape, len(shape)).""" axes = _compute_axes(shape, xyz_resolution, origin) meshes = np.meshgrid(*axes, indexing='i...
7d460c7ed6a5c292eb732be4e9d2a58c2298d16b
61,749
def read_db_config(filename=CONFIG_FILE, section=DBTYPE): """ Read database configuration file and return a dictionary object :param filename: name of the configuration file :param section: section of database configuration :return: a dictionary of configuration parameters """ # create parser an...
e6a2837f2d11389e6f2680041f73de0fa17dc5af
61,750
import requests def send_message_to_telegram(msg='hi'): """in: str, out: str""" METHOD_NAME = 'sendMessage' for my_id in TELEGRAM_ID_LIST: data_to_send = { 'chat_id': my_id, 'text': msg } header = { 'Content-Type': 'application/x-www-form-urlen...
5818d863b5abd8bc3640c135528320953c74ea3e
61,751
import sys import os def get_instl_launch_command(): """ @return: returns the path to this """ launch_command = None exec_path = get_path_to_instl_app() if getattr(sys, 'frozen', False): launch_command = utils.quoteme_double(os.fspath(exec_path)) elif __file__: if os_family...
e5afadb22a85420871b84863ffc30b2689031158
61,752
import json def get_track_info(item_id): """ A function that gets track name information from item id :param item_id: the item id to find :return: the String type name of track """ f = open(str(dir_path) + r"/metadata/json/track.json", encoding="utf-8") data = json.load(f) try: ...
1a444ae09dc3a9966039f9a226a4d9630e7c207d
61,753
from typing import Dict from typing import Any def find_class(klass, dictionary: Dict[str, Any]): """ Given a dictionary, find the best-fit class among the subclasses of the supplied class. """ dictionary_keys = key_strings_from_dict(dictionary) classes = all_visible_subclasses(klass) clas...
9c6736467aec269f83033cc3da2e457e1ff094a1
61,754
def get_text_channel( guild: discord.Guild, *text_channel_names: str ) -> discord.TextChannel: """ Get the first text_channel found in @names or raise an Exception. """ for name in text_channel_names: text_channel = discord.utils.get(guild.text_channels, name=name) if text_channel: ...
b3ae871d341608a10c6c70fb3da907e4fb56797a
61,755
import itertools def generate_full_symmops(symmops, tol): """ Recursive algorithm to permute through all possible combinations of the initially supplied symmetry operations to arrive at a complete set of operations mapping a single atom to all other equivalent atoms in the point group. This assum...
bd84b75af146fbb444fe7a8d58c13c4589971ef7
61,756
def use_snippets(document, position): """ Determine if it's necessary to return snippets in code completions. This returns `False` if a completion is being requested on an import statement, `True` otherwise. """ line = position['line'] lines = document.source.split('\n', line) act_lines...
1cf60c6979e374a478d69802b9c89c68de635033
61,757
import random def contest(other): """contests human ability""" return random.randint(1, 20) > round(other.advantage / 5)
a87cc2ffc7d01f493d99b3808735f7954847caaa
61,758
def rs(hass): """Return CommandCover instance.""" return cmd_rs.CommandCover( hass, "foo", "command_open", "command_close", "command_stop", "command_state", None, )
04e7e846a019dd4b47fb93ac12b857013713043a
61,759
def _preprocess_arguments(domain, funcs, config): """ Preprocess domain arguments and configuration file. """ # Preprocess config argument converted_cp_to_euclidean = False if isinstance(config, str): config = load_config_file(config) if domain is None: domain = config.domain # The function if con...
a2193d83d2301e240ac35c6276e9cffc77600913
61,760
def load_simulated_gaussian(partition='complete', **kwargs): """ Synthetic data with a Gaussian (non-linear) log-risk function. For more information, see [#katzman1]_ as well as the accompanying README. Parameters ---------- partition: string Partition of the data to load. ...
1fdb49ee518a94b3d1f0dbb0ad9aff740a865439
61,761
import numpy import os def persistence_diagrams_of_filtrated_cubical_complex(filtrated_cubical_complex: numpy.array, limit_dimensions: int=None, dual: bool=True, ...
876ec04faf8615b3e7ad374da20be2d9a4972aa2
61,762
import sys def caller_name(): """Return the name of the caller, e.g. a function. Returns ------- str The name of the caller as a string """ # pylint: disable=protected-access return sys._getframe(1).f_code.co_name
5d28ab91cf8efe9ee06a7da349a51bb013c1b67b
61,763
def encode_target(target): """Apply one-hot-encoding to encode target values. Author: Jernej Vivod (vivod.jernej@gmail.com) Args: target (numpy.ndarray): target variable values. Returns: numpy.ndarray: one-hot-encoded target variable values. """ # Encode data using one-hot-e...
4e07eec0f8210bd686ea390f04c1e276abfad7fd
61,764
import socket import time import sys def receiveData(sock, size): """Retrieve a given number of bytes from a socket. It is expected the socket is able to supply that number of bytes. If it isn't, an exception is raised (you will not get a zero length result or a result that is smaller than what you as...
fbec124f2e305c7c63316c4af11ee593e35f090c
61,765
def build_auth_args(request): """ 组装认证信息 """ # auth_args 用于ESB身份校验 auth_args = {} if request is None: return auth_args ignore_fields = ["rtx"] for key, value in get_oath_cookies_params().items(): if value in request.COOKIES and key not in ignore_fields: auth_...
b15ccdd81d2d23ffa196d074ac391344b22e9561
61,766
import argparse from typing import Any def reapplyMutexGroups( mutexGroups: list[argparse._MutuallyExclusiveGroup], actionGroups: list[Any] ): """_argparse stores mutually exclusive groups independently... of all other groups. So, they must be manually re-combined with the groups/subgroups to which they were ori...
23116a28f1be85427da304a229ef719279f2a286
61,767
def check_mean_greater(alpha, N, mean, n): """ H0: m <= m_0 H1: m > m_0, where m_0 = N.mean Returns True if H0 is rejected in favor of H1, and False if cannot reject H0. :param object N: distribution. """ assert(0 < alpha < 1.0) # significance level assert(n > 0) # sample size ...
9af7f75716b82067230c88a76b40b731e19449cd
61,768
def list_even(obj): """ Return a list of all even integers in obj, or sublists of obj, if obj is a list. If obj is an even integer, return a list containing obj. Otherwise return en empty list. @param int|list obj: possibly nested list of ints, or int @rtype: list[int] >>> list_even(...
8b94f8983f9c8d19163de875089697f6cdab8114
61,769
def get_output_data_file(given_filename, run_directory, application_name): """ Get the csv file where results will be written. This method checks if the user defined a custom filename. If not, it returns the default. Important: if the file exists, it will be overwritten. :param given_filename: the f...
bab5f5410d138aebb8a065201665b35edb1bcbb0
61,770
def encrypt(backup: str, password: str) -> str: """Encrypts a database backup Pararameters:\n backup (str): name of the database backup password (str): encrypting password Returns:\n str: cryptogram of the encryption None: an error ocurred """ ...
a3b0db8db360a2bb99af7aa4cdc727f4293be7e5
61,771
def operator_as_argument(statement): """This looks at various possible fixes when the bad token is an operator. The following cases are considered: 1. operator instead of comma 2. operator instead of equal sign """ if not statement.bad_token.is_operator() or statement.prev_token == "def": ...
95ec70aff8c27f626b258ad0d21d9fecfa6347d4
61,772
async def api_req_add(req: Request, data: Body, authorized: bool = Depends(verify_token)): """Добавить данные в бд""" if authorized: try: return {"status_code": 200, "result": DB._add_data(authorized, data)} except: raise HTTPException(status_code=500, detail="Ошибка серв...
794a8c17889ef55d0e4ba10e080e1e2911f50acc
61,773
async def infer_Jinv(self, engine, x): """Infer the return type of primitive `Jinv`.""" return await compute_jinv_type(x)
498fa68608aa5e0655c84bdf305af75e7565b531
61,774
from sys import path def pickled_data_container_exists(filename_pickle): """Check whether pickled data container exists at expected path """ if not path.exists(filename_pickle + '_train.pk'): return False elif not path.exists(filename_pickle + '_validation.pk'): return False elif n...
b119454dbc9d098dd5bdfca38f93dc93cc02ccbb
61,775
from typing import Sequence def count_increases_pairwise(readings: Sequence[int]) -> int: """Count the number of times a reading increases.""" counter = 0 for previous_reading, current_reading in iterate_window(readings, 2): if current_reading > previous_reading: counter += 1 ret...
1ec02d072d5c654f684403cab10058dc6f42bc53
61,776
def load_repository_url() -> str: """Return repository URL.""" return load_repository().remote().url.split(".git")[0]
38c62540dc8e765f2aaec59764a29beacc11eaaa
61,777
def calibrate_box(bbox, reg): """校准box 参数: bbox:pnet生成的box reg:rnet生成的box偏移值 返回值: 调整后的box是针对原图的绝对坐标 """ bbox_c = bbox.copy() w = bbox[:, 2] - bbox[:, 0] + 1 w = np.expand_dims(w, 1) h = bbox[:, 3] - bbox[:, 1] + 1 h = np.expand_dims(h, 1) reg_m = np.hstack([w,...
9829a856cd1c0bbf4becd9436e423384e40b8c35
61,778
import random def get_random_testcases(input_directory, max_testcases): """Returns list of |max_testcases| testcases.""" testcases_list = get_testcases(input_directory) return random.SystemRandom().sample(testcases_list, max_testcases)
3f1736bbea946372f20b6b26cdb8a2ab1ca39f95
61,779
def ppo_sharpe_port(cov=None, pre=None, as_dense=True): """ Max Sharpe ratio portfolio using cov-implied returns :param cov: Covariance matrix :param pre: Precision matrix :param as_dense: If false, will return weights in dict formet :return: np.array of weights """ return pp...
2712ba9a61a3005963c60352f00455cb00200c56
61,780
import os from sys import stderr def get_output_file(filename, data_dict, sep): """Create or open the output file. If a new file is being created, add a header line. """ header_line = sep.join(data_dict.keys()) x = 1 while True: # Loop will break at a return statement if os.pa...
99924f245c377a604bcc76856a90ea3446a536a0
61,781
def constraints_from_table(table, power_spectrum, boxlen): """Load a table containing constraints and convert it into a list of Constraint objects. Also needs the power spectrum of the CRF that you're going to build, because it needs to determine the spectral parameters. Finally, we need the boxsize (i...
de9930b7e108717a944637f0b8e2ef6b627c3d4a
61,782
from valid8 import validate_io, ValidationError, ValidationFailure def test_usage_custom_validators(): """ """ def is_mod_3(x): """ A simple validator with no parameters """ return x % 3 == 0 def is_mod(ref): """ A validator generator, with parameters """ def is_mod_ref...
97758f1d2a5cc95f7c72a6567a110d9c07b866fb
61,783
import smtplib import os def send_researchinfo( new_addresses, link="http://ntuhss.az1.qualtrics.com/jfe/form/SV_ePZ13fZ4kPrF0wt", to_send=False, filename="poster.jpg", filetype="image", ): """ Parameters ---------- new_addresses: list List of email addresses. link: str...
455a9201934ad76a0696ed097436213f1870563a
61,784
import warnings def astype(x, dtype, var, stacklevel=3): """Return `x` or a copy of `x`, with its type converted to `dtype`. `var` is the name of `x` as seen by users of a public API, which may be used in a warning message. `stacklevel` corresponds to the number of frames to skip when reporting the wa...
cc769b17958b663c22ac4f7e5fc884ef88d64edc
61,785
import jieba def _jieba_extract(addr, sequential): """基于结巴分词进行提取""" result = Pca() pos = 0 truncate = 0 def _set_pca(pca_property, name, full_name): """pca_property: 'province', 'city' or 'area'""" in_order = True if sequential: property_orders = [ 'province', ...
fe77f48801409aa59ae8159e1ba240c2d249fe1e
61,786
def remap_mtext_position(position, mtext_src, mtext_dst): """ Remap the given position from one mtext to a *similar* position in another. """ line_num, x, y = position line = mtext_src.lines[line_num] # TODO: ehh should change this to 'speical/generated lines' if line.type: projecti...
4677942fb2e4ff24873018341effbdea53c5d2f8
61,787
def get_trader_violation(model, trader_id, trade_type): """Get trader violation""" if (trader_id, trade_type) in model.V_TRADER_TOTAL_OFFER.keys(): return sum(model.V_CV_TRADER_OFFER[trader_id, trade_type, i].value for i in range(1, 11)) else: return 0.0
1ef4822345bd16e17d0b351148275a288fc281a5
61,788
def compute_pm_hull_vertices(image): """Get PyMunk vertices that enclose the alpha channel of a given RGBA image.""" alpha = np.array(image)[:,:,3] nonzero_points = cv2.findNonZero(alpha) hull = cv2.convexHull(nonzero_points).squeeze() # Flip the y-axis since it points up in PyMunk hull[:, 1] = ...
ae89d3c945840cb529a056d39048cb5a9b9b7b79
61,789
def to_yaml(template, clean_up=False, long_form=False): """ Assume the input is JSON and convert to YAML """ data = load_json(template) if clean_up: data = clean(data) return dump_yaml(data, clean_up, long_form)
08d5a55f57025fe4c171ac8a26fc75d333bc47d6
61,790
def _ccd_product_from_pixel(pixel): """Creates a ccd-product for a given pixel Runs the ccd operation on a pixel and converts the results into a dataset Args: pixel: An xArray dataset with dimensions latitude, longitude, and time with dims of 1x1xt Returns: An xArray dataset with the ...
de1f0c57cce5ea26cc6c09e56ecc142c79852b7c
61,791
def doc_metadata(metadata_filename): """ """ data = pd.read_csv(metadata_filename, usecols=['doc_id', 'year','title']) return data
f57f8874c46267835556f00703b9602c74fe421f
61,792
def GetAtomicWeightsForFingerprint(refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity): """ Calculates the atomic weights for the probe molecule based on a fingerprint function and a metric. Parameters: refMol -- the reference molecule probeMol -- the probe molecule fpFunct...
33ed51e80215027d0f5b4318789edced6926ea10
61,793
def read_skeleton(filename): """ Imports the data from the given .skel file Parameters: filename (string): The name of the .skel file Return: (Array, Array, Array): The skeleton joints, the joints radius and the skeleton bones """ with open(filename) as file: joint...
aa6d94cd4cf4e32419f26bb354697de245440994
61,794
def patched_connect(sock, address): """ Intercepting function for _socket.socket.connect returns _socket.socket.connect's result """ hostname, port = address[:2] if hostname not in dns_cache: dns_cache[hostname] = resolve(hostname, port) hostname = dns_cache[hostname] return og_c...
a6149e9a6e00e3de96173497b8d7bbf3c6d239e0
61,795
def readCsvIntoDataframe(source, csv_schema, csv_header=False): """ Params: source: String. Path of source csv file to read. csv_schema: StructType. Data schema. csv_header: Boolean. Set true if file inlcudes header. False by default. """ validateInput(source,...
074e538c228c8f117f54ffcd3588ac1b11df43f4
61,796
def shorter(item): """Make a string shorter. item -- a unicode string.""" if len(item) > 2: return item[:-2] + u'\u2026' # ellipsis return item
d3d9f678c5055e43f2120c1779bbd41066c8684d
61,797
def patchedOpenExcepRasingMockSteam(monkeypatch): """ A fixture that creates an open stream that raises a ValueError when read from. Streams indicate they have been closed by raising a ValueError. """ def raiser(self): raise ValueError monkeypatch.setattr(MockStream, "closed", False) ...
80072e4650539aeee0f481ffc41770f500881b70
61,798
def route_con(lst): """ Функция для получения списка лучшего пути :param lst: list -- список кортежей лучшего пути :return result: list -- список лучшего пути """ result = [] for elem in range(len(lst)): if elem == 0: result.append(lst[elem][0]) result.append(...
dae6a3613c5908615b1504b9960a6981d84b3224
61,799