content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_config( config_path=None, _get_color_from_vdir=get_color_from_vdir, _get_vdir_type=get_vdir_type): """reads the config file, validates it and return a config dict :param config_path: path to a custom config file, if none is given the default l...
6f55ccc2af681382af2e89d746f0db7bbdeb6269
62,100
import os def get_input_fn(training, batch_size, ncf_dataset, data_dir, dataset, repeat=1): """Input function for model training and evaluation. The train input consists of 1 positive instance (user and item have interactions) followed by some number of negative instances in which the items ...
5b4a914a5c311193157fd49c777bc6d6b96ff970
62,101
from datetime import datetime import string def format_time(date_time: datetime) -> string: """ A function that reformats datetime objects into a string usable to find the web element :param date_time: A datetime object :return: Returns the formatted date time object """ str_date = date_time.s...
e0f63cb03c16d8e5434ef6f3a00b7030052e3051
62,102
def read_string(file): """ Считывает строковое значение из undeflated EFD файла. :param file: Обрабатываемый файл :type file: BufferedReader :return: Строковое значение :rtype: string """ # Длина строки в символах str_len = unpack('I', file.read(4))[0] # Длина в байтах. Каждый с...
b00d73c44d803dbd3f0aebd0094f788a769026db
62,103
def findAuROC( genome ): """ This function computes the area under the ROC curve of a ChIP-seq experiment where read count ratios are employed to distinguish between bound and unbound regions. """ labels = np.zeros(genome.shape[0],dtype=np.bool) direct = genome['binding'] == "direct" lab...
520f896c3368ec7fd97c0d6b9f13f45231e3cbfd
62,104
def random_hecke_operator(M, t=None, p=2): """ Return a random Hecke operator acting on `M`, got by adding to `t` a random multiple of `T_p` INPUT: - ``M`` - modular symbols space - ``t`` - None or a Hecke operator - ``p`` - a prime OUTPUT: Hecke operator prime EXAMPLES:: ...
b6d2b8cc6defd5245ce26de1512ff946be77df0c
62,105
from typing import Dict def map_graph(graph: nx.MultiDiGraph, mapping: Dict, preserve: bool = True) -> nx.MultiDiGraph: """ Remap node identifiers in a networkx.MultiDiGraph based on a provided mapping. For nodes, the old identifier is saved as `source_curie` attribute. In case of edges, - if the...
154c71bf4a28144732ba18e09be5fa64ced05b69
62,106
def is_abstract_method(method): """ @type: method: object @param: A method object. """ return getattr(method, '__isabstractmethod__', False)
09c83f409ec4d9fa1e00d6b60d81f78cb8c8dbd3
62,107
def register(): """ register route """ try: # if request is GET method return register page if request.method == "GET": return render_template("register.html") # parse data schema = AuthRegisterDto() data = schema.load(parse_request()) username = data...
936dba69d071d4482305888190f79514096c7afa
62,108
def transfer_from_taoyuanagrichannel_to_ncsist(): """ Real Name: Transfer From TaoYuanAgriChannel To NCSIST Original Eqn: Transfer From ShiMenReservoir To HouChiWeir*Ratio NCSIST At HouChiWeir*(1-Channel Transfer Loss Rate) Units: m3 Limits: (None, None) Type: component Subs: None """ ...
3af2367af305d65743e95c12f752f1d9f9f01cd0
62,109
def _get_config_parameter(config, section, parameter_name, default_value): """ Get the parameter if present in the configuration otherwise returns default value. :param config the configuration parser :param section the name of the section :param parameter_name: the name of the parameter :param...
2431c37eab3396b79f4f9e649a7cc25fc27208dc
62,110
from pathlib import Path def preprocess_images(files, to_folder, size=None, mode=None, suffix='.png', pre_crop_rect=None, prepend=True, parent_name=True, verbose=False, skip_creation=False): """Preprocess image files and put them in a folder with prepended serial number...
309929e96c50f68a239b9dccbc36a807cdd7dcf0
62,111
def synchronous( tlockname ): """A decorator to place an instance based lock around a method """ def _synched(func): @wraps(func) def _synchronizer(self,*args, **kwargs): tlock = self.__getattribute__( tlockname) tlock.acquire() try: return fu...
b18617ab4565a4c2363bac038452a25848867409
62,112
def project_hidden(x, projection_tensors, hidden_size, num_blocks): """Project encoder hidden state into block_dim using projection tensors. Args: x: Encoder hidden state of shape [-1, hidden_size]. projection_tensors: Projection tensors used to project the hidden state. hidden_size: Dimension of the l...
ea8fbac158ac9f16e4db70f34aec3dca5d4a0d7e
62,113
from pathlib import Path import shutil import importlib import os def build_doc( package_name, doc_folder, output_dir, clean=True, version="main", version_tag="main", language="en", notebook_dir=None, is_python_module=False, watch_mode=False, ): """ Build the documentat...
75f2c71b819f61b25255cccc7644ec94b07c3680
62,114
def representatives(poly): """should return all crossing non-equvalent representatives of a polyhedron.""" tt = canonical(makesingle(poly)) print("**") ae = all_embeddings(tt) print("ae ") ff = [facesfromrotation(r) for r in ae] print("ff") tts = [stringsfromfaces(r) for r in ff] pri...
b747d50b96eeb69b6541ff19808652b6f69fb4b6
62,115
def sg2d_fit(x, fwx, fwy, x0, y0, offset, order, amplitude): """ 2D Super-Gaussian formula to used with curve_fit """ X, Y = x[0], x[1] return amplitude*gauss2D(X, Y, fwx, fwy, x0, y0, offset, order/2, int_FWHM=False)
caeb55880dcfc4e370ef685b361e500fbcd535a5
62,116
def make_meetings_str(room, start, end, days_yn): """ Make a string that tells the days and times when a class section meets. Spaces are filled with @, which need to be fixed once the string has been encapsulated in a cell. """ room_str = f'{room}: ' if room != '' else room day_list = set() for i ...
4898a666399f2d44818ddbabe9158e2c9c05818b
62,117
def _normalize_ab_allele_names(ab_allele_names): """ A helper for `get_compact_ab_allele_names` """ try: res = mhcnames.parse_classi_or_classii_allele_name(ab_allele_names) except Exception as e: msg = str(e) logger.warning(msg) return None if len(res) != 2:...
2710218b869ad6e47e58164b01dafa01bb37a922
62,118
def get_all_slidable_moves(starting_hex: tuple, board_piece_locations: set[tuple], is_spider_move: bool = False) -> set[tuple]: """ Given a starting hex location, find all hexes that may be slid to. This is relevant to the Ant and Spider pieces. For the ant, return the exhaustive list of all contiguous slid...
184b70f88b416f3abf6b834a19fe4240d38fc1ea
62,119
def setup_config(config: dict) -> dict: """ Setup configuration for the image generation, many settings are based on the load_pretrained_ffhq.sh file from the U-NetGAN github. Don't change these settings if you dont know what you are doing. Args: config (dict): Dictionary with the configura...
cb7e75fa1c700dcfb238c071c791e52927056721
62,120
def map_d2_d1_to_t1(tpdm, opdm): """ Map the 2-RDM and 1-RDM to the T1-matrix :param tpdm: :param opdm: :return: """ dim = opdm.shape[0] t1 = np.zeros_like((dim, dim, dim, dim, dim, dim), dtype=tpdm.type) for p, q, r, i, j, k in product(range(opdm.shape[1]), repeat=6): # Not...
acbcbcee85d3bddbeae49e1ef94c20d2323bc655
62,121
import json import time def get_dump(url): """ Retrieves a json file from the given URL and loads it into memory """ for i in xrange(1, 4): # 3 retries try: response = urllib2.urlopen(url) json_str = response.read() dump = json.loads(json_str) re...
6fc054b7b89928edffb962ef5c48613b7f24a0cd
62,122
import requests def api_retrieve_organization(org_id): """ Allows the client to call "retrieve" method on the server side to retrieve the organization from the ledger. Args: org_id (str): The uuid of the organization Returns: type: str String representing JSON obj...
dec1cadc22c39ccaa144f0cfc6dfa6fa86afb8d8
62,123
def getSnapshotPath(date): """ """ return ql.DATASTORE_PATH + "/%s" % date.strftime("%Y%m%d")
e69e2b573f8ac1f4ff723b96bf26d64c30929406
62,124
def _build_binned_configs( condition: list, min_threshold: float, windows: list, agg_func: dict, bin_size=30, **kwargs ): """ Creates configurations for binned pipelines. """ configs = [] for window in windows: for w in range(window[0], window[1], bin_size): ...
8baf8d50e3d0a53764a17beea933e36c04fca4fe
62,125
from datetime import datetime def list_organization(): """オーガナイゼーション一覧取得 Returns: response: HTTP Respose """ globals.logger.debug('CALL list_organization') try: with dbconnector() as db, dbcursor(db) as cursor: # select実行 fetch_rows = da_organization.selec...
8516d8c33205d7e8b052f226a35c7d61dbc71ca6
62,126
def interp(query, *args): """ Interpolate the provided arguments into the provided query, using the DB-API's default conversions, with the additional 'RAW' support from modu.sql.RAW2Literal @param query: A query string with placeholders @type query: str @param args: A list of query...
3050555ff0f990992714acf2374c11360176ccb8
62,127
import os def GetLocalInstanceHomeDir(local_instance_id): """Get local instance home dir according to instance id. Args: local_instance_id: Integer of instance id. Return: String, path of instance home dir. """ return os.path.join(_ACLOUD_CVD_TEMP, GetLoca...
33a5d1e8df4281c43c5da75b8d66afc63d60d404
62,128
import re def calc_decomp_sz(data): """Calculate--without decompressing--the decompressed size of data when all nested markers are applied. """ data = re.sub('\s', '', data) decomp_sz = 0 while len(data): marker_start = data.find('(') if marker_start >= 0: decomp_sz...
8b42ce97e02abd09dcf98d80bc5f6bd069d6ce62
62,129
from typing import Dict def generate_character_values( rng: IRandNumGenerator, n_likes: int = 3, n_dislikes: int = 3 ) -> CharacterValues: """Generate a new set of character values""" # Select Traits total_traits: int = n_likes + n_dislikes traits = [str(trait.value) for trait in rng.sample(list(V...
c060e0b49b6966cc51805598772c0ecc1df7156a
62,130
def collect_output(mr_out_dir, out_file=None): """ Return all mapreduce output in ``mr_out_dir``. Append the output to ``out_file`` if provided. Otherwise, return the result as a single string (it is the caller's responsibility to ensure that the amount of data retrieved fits into memory). """...
075fe5f2f44137fd706a6b72285412d119ca093f
62,131
def make_bool(x_var): """turn an array of ints into array of bool""" if x_var > 0: return True return False
ce2f4d51d6126df7723aa90b7b717d613feaad2f
62,132
def as_escaped_unicode_literal( text: str ) -> str: """Convert the given ``text`` into a string of escaped Unicode hexadecimal. Args: text (:obj:`str`): The string to convert. :rtype: :obj:`str` A string with each character of the given ``text`` converted ...
2fc72bb8875023d86561552e9c64e55f5a99dfc1
62,133
def compute_top_minus_index_spread(mean_returns, market_index): """ Computes the difference between the mean returns of two quantiles. Optionally, computes the standard error of this difference. Parameters ---------- mean_returns : pd.DataFrame DataFra...
8da2a1c0d316bd78f5f6efdc93dfdac6ee81a2e7
62,134
def get_widedeep_net(configure): """ Get network of wide&deep model. """ wide_deep_net = WideDeepModel(configure) loss_net = NetWithLossClass(wide_deep_net, configure) train_net = TrainStepWrap(loss_net) eval_net = PredictWithSigmoid(wide_deep_net) return train_net, eval_net
0d605a5523596a9f7323aee8c423920f3cba5463
62,135
def rollback_event(db): """ Test fixture that uses a ``MagicMock`` as an event listener for database session rollbacks. Useful for counting rollback events using ``rollback_event.call_count``. """ counter = mock.MagicMock() sa.event.listen(db.session, "after_rollback", counter) return count...
852f74e7dbf126dee73545cf7196efe21b1a1a7b
62,136
def adler32(space, string, start=rminiz_oxide.ADLER32_DEFAULT_START): """ adler32(string[, start]) -- Compute an Adler-32 checksum of string. An optional starting value can be specified. The returned checksum is an integer. """ ustart = r_uint(start) checksum = rminiz_oxide.adler32(string,...
5840ba5dd6c39b6a973e1c8d5e02831f462d9dce
62,137
from openpype.lib import get_workfile_template_key import io def compute_session_changes( session, task=None, asset=None, app=None, template_key=None ): """Compute the changes for a Session object on asset, task or app switch This does *NOT* update the Session object, but returns the changes required...
34f6a812a9c3f745dadf7697bac5c2c6d26ce215
62,138
import sys def match_chr_to_genome(dataframe, genome, strvar): """ Used to match formatting between regionsFile input and genome for chromosome denotations. Some genomes contain the string "chr" and some do not. Args: dataframe (pandas object): dataframe created from create_dataframe() functi...
12876e89057526938cf4676eec3d77359135936e
62,139
from typing import Dict import os def enable_alert(repo: Dict) -> int: """ Enable vulnerability alerts on a single repo. """ repo_topics = get_topics(repo) repos_to_ignore = [ repo.name in ["mapit"], "no-security-advisories" in repo_topics, repo.isArchived, ] if o...
2c18408e2ee2340330d3001cc2b5d3dfcc9e7e19
62,140
import json def execute_statement(connect_info: Client, statement: str) -> JsonDict: """Calls the execute statement endpoint of df-df_connect. Args: statement: the SQL statement to be executed connect_info: A Client object for establishing session and loading jdbc parameters Returns: ...
aaa916c53666c1f18231e29fa55a174658b37366
62,141
def pytest_exception_interact(node, call, report): """ Set a different exit code on uncaught exceptions. """ global unhandled_exit exctype, value, traceback = call.excinfo._excinfo if exctype == AssertionError: return report unhandled_exit = node.config.getoption('--unhandled-exc-ex...
0206a848c9324fe40fe1875e18a28f1b0e8f9def
62,142
def relabel(image): """Given a labeled image, relabel each of the objects consecutively image - a labeled 2-d integer array returns - (labeled image, object count) """ # # Build a label table that converts an old label # into # labels using the new numbering scheme # unique_lab...
5944b1b5da71ac7169c40c80ffe615cc821a1f02
62,143
def parseContent(content): """解析上报的设备信息,返回 kv 数据对""" data={} # print 'Content:',content cap = '[VERSION]' if content.find(cap) == 0: ver = content.split(cap)[-1] data['ver'] = ver cap = 'IMEI:' if content.find(cap) == 0: items = map(lambda _:_.strip(),content.split(...
44cd0c1099809682d07ad1eda2d3d77f27bf7f9e
62,144
def get_counter(data, base): """ See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java. """ b0 = data[base] b1 = data[base + 1] b2 = data[base + 2] b3 = data[base + 3] counter = b3 position = (b1 << 8) + b2 return counter, position
fa960648edce84a465be3b588b265e14d817067d
62,145
import httpx import typing def endorsement_response( request: httpx.Request, asset_type_id: str, asset_id: str, hashed_claim: str, endorser_id: str, request_id: str, node_id: str, ) -> typing.Dict[str, typing.Union[str, typing.List[str]]]: """Simualate response for creating an entity."...
399d49cf01811364612cebdba7e5deeef9ba7c58
62,146
def he_normal(weight_shape): """ Initialize network weights `W` using the He normal initialization strategy. Notes ----- The He normal initialization strategy initializes the weights in `W` using draws from TruncatedNormal(0, b) where the variance `b` is .. math:: b = \\frac{2}{\\...
43938f26112ec5e74b2a46d9eb08167cfd9a7b52
62,147
def update_get_space_ids(ems_rooms): """ Get R25 space_ids for EMS Rooms. :param ems_rooms: A collection of ems_client.models.Room :return: A dictionary of Room.id: space_id """ space_ids = {} for room in ems_rooms: if room.active and room.external_reference is not None: ...
f2a88e4ca93ef3a5076c56b3b008df4dff72acaf
62,148
def match_identifier_in_cache(identifier, db_instance): """Return list of matches for the given identifier in the file database. Args: identifier: identifier to use as a reference if the corresponding data is already cached db_instance: Connected Database file with `DBConnect()`. Returns: ...
8bde79befd613fc4719536baa28294f79aa43f8e
62,149
import sys import multiprocessing def _is_spawning_semantics(): """True if we are on spawning semantics.""" return sys.platform == 'win32' or \ multiprocessing.get_start_method(allow_none=True) == 'spawn'
6c69639577e5ef8874d1c8b415901d7f1fa65f97
62,150
from typing import Optional from typing import Dict from typing import Union from typing import Any def apply(df: pd.DataFrame, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> Dict[str, Any]: """ Discovers a footprint object from a dataframe (the footprints of the dataframe are returned...
6f0fbf7b72d08dbc0f0f6bb44ee6f61d586112af
62,151
def psy_const_of_psychrometer(psychrometer, atmos_pres): """ Calculate the psychrometric constant for different types of psychrometer at a given atmospheric pressure. Based on FAO equation 16 in Allen et al (1998). :param psychrometer: Integer between 1 and 3 which denotes type of psychromet...
e19e8c6d675d8a743a2be0444a90497a99150019
62,152
def create_four_axes_figure(figsize=(10,8)): """生成一个含有4个坐标轴的figure,并返回坐标轴列表 :param figsize: (宽, 高) :return: (ax1, ax2, ax3, ax4) """ rect1 = [0.05, 0.50, 0.9, 0.45] rect2 = [0.05, 0.35, 0.9, 0.15] rect3 = [0.05, 0.20, 0.9, 0.15] rect4 = [0.05, 0.05, 0.9, 0.15] fg=figure(f...
4aad07347f84d879c470bbbba70659b606dbc356
62,153
def _setupdirstate(ui): """Modify the dirstate to prevent stat'ing excluded files, and to prevent modifications to files outside the checkout. """ def walk(orig, self, match, subrepos, unknown, ignored, full=True): match = matchmod.intersectmatchers(match, self._sparsematcher) return or...
cb901b8048d3620ed4dd61f1385a752b812db5bc
62,154
def test_declarative_forms(): # language=rst """ Declarative forms ----------------- You can create forms declaratively, similar to Django forms. There are some important differences between iommi forms and Django forms in this mode, maybe the most important being that in iommi you can pass a calla...
ec2fbc5d13f53dd6508ca05641f83b5e9ae88a49
62,155
import glob def read_corpus(): """ 读原始数据 """ src = [] tgt = [] data_path = glob.glob("./corpus/文言文翻译/*") for p in data_path: dir = p.split("/")[:-1] dir = "/".join(dir) # print(dir) name = p.split("/")[-1] if "翻译" in name: # 找到了一个翻译文件 ...
cc225268c90be6fbfca59f36b81d2520a65c6f95
62,156
import argparse import importlib from datetime import datetime def train_parser_args(): """ parser_args for training """ parser = argparse.ArgumentParser(description='Training infos') parser.add_argument('--config_file',type=str,default='experiments/Data_WFLW/HIHC_64x8_hg_l2.py',help="relativ...
2a6aac651ca103cc20b8e47ce4468a281dbd0e01
62,157
def gen_sym_axial_vector(sym_ops, x, y, z): """ Transform axial vector by symmetry operations Usage: uvw = gen_symcen_pos(sym_ops,cen_ops,x,y,z) sym_ops = [n*'x,y,z'] array of string symmetry operations cen_ops = [m*'x,y,z'] array of string centring operations x,y,z = fractional coo...
1c20a97662030646318a3d828a8372becc4b1e5a
62,158
def ipr_record(): """ ipr template. """ record_dtype = np.dtype([('target_record_class', np.ubyte), ('target_instrument_group', np.ubyte), ('target_record_subclass', np.ubyte), ('target_record_offset', np.uint32)]) ...
c39449e36bef0a7fc7da493433ea5a4d32be43c1
62,159
def classify(df, model_dir, num_of_processes): """ Makes prediction Args: df (pandas.DataFrame) model_dir (str): path to dir where models are locaded num_of_processes (int): the number of processes Returns: df (pandas.DataFrame) : with prediction """ df = calculate_pr...
002a2bfafdf655bab21c03ceecdd440729f77a3b
62,160
def stitch(input_directory, input_filename, output_directory, imagej_instance): """ Use the BigStitcher plugin to stitch together the series at input_filepath. See Fuse.ijm for the ImageJ macro code. Args: input_directory (Union[str, pathlib.Path]): Directory in which input microscopy fi...
5e6e1775d65af8dd295bd59ceda4da7dc0556126
62,161
def _get_mounts(): """ List mounted filesystems. """ mounts = {} with salt.utils.files.fopen("/proc/mounts") as fhr: for line in salt.utils.data.decode(fhr.readlines()): device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split( " " ) ...
8a62536ae58c56ab106cecf5b36707594605d024
62,162
def get_role_class(expected_rolename): """ <Purpose> Return the role class corresponding to 'expected_rolename'. The role name returned by expected_meta_rolename() should be the name passed as an argument to this function. If 'expected_rolename' is 'Root', the class RootFile is returned. ...
3ea6947af974c8dce56c18178d5ff76b35b6de04
62,163
def sub64(a,b): """Return a 64-bit integer difference of `a` and `b`.""" return(np.subtract(a, b, dtype=np.uint64))
1aad62ee3710faee68fdbd4444c7577be30cf0df
62,164
def get_basename(basename, out_log): """ Checks if provided basename value is correct """ bsn = str(basename) if basename == '': fu.log('No basename provided, default value %s assigned' % get_default_value('basename'), out_log) bsn = get_default_value('basename') return bsn
c2a2635f792895294fb17d8197658aa3754d8c98
62,165
def M(*args, **kwargs) -> dict: """Join objects to dict""" result = {} for arg in args: if isinstance(arg, dict): result.update(arg) if hasattr(arg, "__dict__"): result.update(dict(arg)) return result | kwargs
87cd7bfecc746f70e56b39239d66a63a93fe9a1c
62,166
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the Unifi Protect components.""" return True
ecea5b98f7c3d464454f42cccaad7400a4bced36
62,167
from typing import Union from typing import Literal from typing import AnyStr import os from typing import Callable def load_data_from_tfds_or_ml_prepare( *, dataset_name: Union[ Literal[ "boston_housing", "cifar10", "cifar100", "fashion_mnist", ...
3654b06cbec45813d2e36b74044ccbcbfa1e1459
62,168
import math def fd_jenkinson(in_file, rmax=80., out_file=None): """ Compute the :abbr:`FD (framewise displacement)` [Jenkinson2002]_ on a 4D dataset, after ``3dvolreg`` has been executed (generally a file named ``*.affmat12.1D``). :param str in_file: path to epi file :param float rmax: the de...
f45a39c9549a30769cd37d823824a12951a928df
62,169
def cymdtoymd(str): """cymdtoymd(str) -> string Convert a legal CCSDS time string with the date expressed as a month and day to a simple time string with the date expressed as a month and day.""" try: (year, mon, day, hour, min, sec) = cymdtoaymd(str) ymd = aymdtoymd(year, mon, day, hour, min, sec) exce...
2443beb1f7b25b406c5fc29a7f93aced6079b52a
62,170
from typing import Any def _substitute_none_val(data: Any): """Trakt represents null-value as {}. Change it to None.""" if data == {}: return None if isinstance(data, list): data = [_substitute_none_val(v) for v in data] if isinstance(data, dict): data = {k: _substitute_none_v...
3995f49272117fce66afbf1087e8e4a2240b2392
62,171
from typing import Union from re import T from typing import List def ensure_list(value: Union[T, List[T], None]) -> List[T]: """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value]
a083b131412737043a03c528042e5746d50e1a00
62,172
def tofov(i, shape=None, var_params=None): """Check whether i is tensor or initialization function or tf.Variable; return tf.Variable; Parameters ------- i : tensor or function or tf.Variable Tensor or function to initialize tensor shape : list or tuple or None Shape of tensor t...
404346f85f338a40a34e920208ec2428de7dacca
62,173
import torch def decomposed_kl(z, mu, logvar): """Decompose KL term in VAE loss. Decomposes the KL divergence loss term of the variational autoencoder into three terms: 1. index code mutual information 2. total correlation 3. dimension-wise KL None of these terms can be computed exactly when...
a6bd216329a919b48c977c65f977f37c20d49318
62,174
def _preprocess_data(df, use_preprocessdata=False, save_path=None): """Preprocess task speccific pipeline. Args: df (DataFrame): target pandas DataFrame object. use_preprocessdata (bool): Wheter or not to use local preprocess file loading save_path (str): local preprocess file path R...
bd6adb1e381e1bd10da83b2531148faa6ca9c6d2
62,175
def exemplar_selection(x, m): """ Parameters ---------- x: the features, n * dimension m: the number of selected exemplars Returns ---------- pos_s: the position of selected exemplars """ pos_s = [] comb = 0 mu = np.mean(x, axis=0, keepdims=F...
30e36b9019e8bd29fbc7a936ea58d72026ae09bb
62,176
def run_accuracy_check(nvars_list, problem_params, order_stencil): """ Routine to check the error of the Laplacian vs. its FD discretization Args: nvars_list: list of nvars to do the testing with problem_params: dictionary containing the problem-dependent parameters Returns: a ...
0b4183889ca945dee8171f317903798dc55eafdb
62,177
def spof(img1, img2): """ symmetric phase-only filter""" F1 = np.fft.rfft2(img1, axes=(0,1)) F2 = np.fft.rfft2(img2, axes=(0,1)) R = F1*np.conj(F2) R = R/(np.sqrt(np.abs(R))+1e-5) r = np.fft.irfft2(R, axes=(0,1)) shift_r = np.fft.fftshift(r, axes=(0,1)) return shift_r
96cdf91b7ff6a3b7974add3c49216a27aebd899b
62,178
def get_neighbors(device, neigh_type='cdp'): """Gets neighbors from a device Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py neigh_type (str): lldp or cdp Returns: list: ordered list of dicts (dict per...
9bdf980a5510778134c317ec13becc39517b4bb7
62,179
def mean_image_subtraction(image, means=(_R_MEAN, _G_MEAN, _B_MEAN)): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [hei...
56ad92792ff36a7ac5af266171933d2b440281a4
62,180
def topologicalMeasures(gg=x.Graph()): """A detailed info about one and only graph. Information about date, number of friends, friendships, interactions, etc. Average degree, average clustering, etc. Input: networkx Graph Used by: P.renderLegacy.topologicalTextualCharacterization.Analysis() ...
0d3be03e173d3b76c7d07fa0a8e6bcfd45f1badf
62,181
import tqdm def mod(dividends, divisor): """ return dividends (array) mod divisor (double) """ output = np.zeros(len(dividends)) for i in tqdm(range(len(dividends))): output[i] = dividends[i] done=False while (not done): if output[i] >= divisor: o...
832d913bbb25a9cb7170b26a4f0aaa3a6ab357ed
62,182
import requests from bs4 import BeautifulSoup def get_department_names(): """Gets a list of unibo's departments parsing a webpage""" dep_resp = requests.get(constant.DEPURL) dep_soup = BeautifulSoup(dep_resp.content, from_encoding=get_encoding(dep_resp), features="html5lib") depts = dep_soup.find("div...
3105a8ce94832b26e121f2b910fd2142214bb7e6
62,183
import os def run_chroot( root, cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=True, binds=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel="quiet", l...
077e2e76d9e0451e0f2f28769f39da80521e40d3
62,184
def ScanAllTorsionsInMol(Mol, TorsionsMolInfo, MolNum = None): """Peform scans on all torsions in a molecule.""" if TorsionsMolInfo["NumOfMatches"] == 0: return Mol, True Mol = AddHydrogens(Mol) MolName = RDKitUtil.GetMolName(Mol, MolNum) FirstTorsionMode = OptionsInfo["FirstTors...
35ef56af5448f9fd2be1e0d11b9ab16b1c285c21
62,185
def calcSimilarity(s1List, s2List, tiles, treshold): """Calculates Similarity and returns list [similarity:float, suspectedPlagiarism:bool]""" #compute similarity similarity = sim(s1List, s2List, tiles) #check if it is suspected plagiarism suspPlag = similarity >= treshold return [similarity, ...
e523639685dcd37614b9740169497cb67b1109b6
62,186
def rivers_with_station(stations): """For a list of MonitoringStation objects, return a set of rivers which have a monitoring station""" rivers = [] for station in stations: rivers.append(station.river) return set(rivers)
a9af1a64acf0b5dbc89cecad83c3f654e77e74a8
62,187
def calculate_tax(income): """Implement the code required to make this function work. Write a function `calculate_tax` that receives a number (`income`) and calculates how much of Federal taxes is due, according to the following table: | Income | Tax Percentage | | ------------- | ----------...
fce9ad9ac9d88b1821a1772b6cc5bb9259ba7ae5
62,188
def Asin(x, target=utils.CCE): """ Computes the trignometric inverse sine of `x` element-wise. asin(x) = | arcsin(sqrt(1-x^2)) - HALF_PI, x belongs to [-1, -sqrt(2)/2) | the 15th order taylor expansion, x belongs to [-sqrt(2)/2, sqrt(2)/2) | HALF_PI - arcsin(sqrt(1-x^2)), x belo...
923573eb9c83101516a3007b7c7c6446c2582304
62,189
import click def afterhours(args=None): """Console script for podcasts.""" click.echo("Replace this message by putting your code into " "podcasts.cli.main") return recommendations(url="http://feeds.harvardbusiness.org/harvardbusiness/after-hours")
cce35cfcd7824358f54894729df1647d5d55dde6
62,190
import sqlite3 from typing import Dict def get_cid2nid(db: sqlite3.Connection) -> Dict[int, int]: """Mapping card ID to note ID. Args: db: Database (:class:`sqlite3.Connection`) Returns: Dictionary """ cards = get_table(db, "cards") _cid2nid = dict(zip(cards["id"], cards["ni...
27252043a59a0e640c8ab247f805e7c04627ebbd
62,191
import collections import gzip from pathlib import Path def validate_fastq(fq, fq2=None): """Validate FASTQ files.""" input_fastq = fq if fq2: input_fastq = fq + fq2 # Reduce the probability of uploading the FASTQ files with the same # content multiple times (as multiple lanes or mates)...
e17161d9f0ab36cc80ba6066b48ff3272deeeb0a
62,192
import numpy def mult_rasters_op(array_a, array_b, nodata_a, nodata_b, target_nodata): """Mult a*b and account for nodata.""" result = numpy.empty(array_a.shape) result[:] = target_nodata valid_mask = ( ~numpy.isclose(array_a, nodata_a) & ~numpy.isclose(array_b, nodata_b)) result[valid_mas...
e354c057214a419142071c1f66b750ad900935fa
62,193
import collections def frequency(input_list): """ Finds the occurances of elements in a list. Works with numbers not consisting of numbers as well. :param input_list: list or tuple >>> frequency([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) Counter({4: 4, 3: 3, 2: 2, 1: 1}) """ return collections....
417dcd493da11f72609e4c4aa3c4edfb35e921aa
62,194
def get_linked_domains(domain, include_deleted=False): """ :param domain: :return: List of ``DomainLink`` objects for each domain linked to this one. """ manager = DomainLink.all_objects if include_deleted else DomainLink.objects return list(manager.filter(master_domain=domain).all())
42b2ab4ffce3e73473e74f29e91dcb43c16895db
62,195
def to_normal_strokes(big_stroke): """Convert from stroke-5 format (from sketch-rnn paper) back to stroke-3.""" l = 0 for i in range(len(big_stroke)): if big_stroke[i, 4] > 0: l = i break if l == 0: l = len(big_stroke)-1 result = np.zeros((l+1, 3)) result[:, 0:2] = big_stroke[0:l+1, 0:2]...
dfb15825d24d76f6a1a784eaabe9543da7dcefa8
62,196
def deposit(owner_id, amount, reference=None): """Deposit given amount into the wallet.""" assert amount.amount > 0, "The amount must be positive." wallet_obj = get_wallet(owner_id, amount.currency) qs = models.Wallet.objects.get(id=wallet_obj.id).transactions trx_obj = qs.create(amount=amount, ref...
cdbb7fdebc2d695a1000344e7a814d3379f045c8
62,197
def array_to_dict(result_array, regions): """Convert an array with regions to dict with region as key Arguments --------- result_array : array Results in region_array regions : list List with all regions (order is the same) Returns -------- result_dict : dict ...
263e69179983eec525bba9f79f1ed02539e1d647
62,198
def setup(): """Raspberry Pi GPIO setup.""" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) power_button = 3 if data['args']['gpio-mode'] == 'BOARD': GPIO.setmode(GPIO.BOARD) power_button = 5 GPIO.setup(power_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) for pin in gpio_setup: ...
ab312721721e7168692cddc61dca8477cdd4a89c
62,199