content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_public_suffix (domain): """ get_public_suffix("www.example.com") -> "example.com" Calling this function with a DNS name will return the public suffix for that name. Note that if the input does not contain a valid TLD, e.g. "xxx.residential.fw" in which "fw" is not a valid TLD, the retu...
8982df4677f1a1853fa328973cfc00c17796e3d8
18,800
from scipy.interpolate import interp1d def interpol(data,x): """ Resamples data by given factor with interpolation """ # Resamples data by given factor by interpolation x0 = np.linspace(0, len(data)-1, len(data)) x1 = np.linspace(0, len(data)-1, len(data)*x-(x-1)) f = interp1d(x0, data) ...
85cb9c9d776abc8317edbf1df5935e78ac774c02
18,801
import torch def convert_to_torch_tensors(X_train, y_train, X_test, y_test): """ Function to quickly convert datasets to pytorch tensors """ # convert training data _X_train = torch.LongTensor(X_train) _y_train = torch.FloatTensor(y_train) # convert test data _X_test = torch.LongTensor(X_test)...
0d40fe19c977b25e3a2571adc98790d7058a77d9
18,802
def api_auth(func): """ If the user is not logged in, this decorator looks for basic HTTP auth data in the request header. """ @wraps(func) def _decorator(request, *args, **kwargs): authentication = APIAuthentication(request) if authentication.authenticate(): return ...
624c997dae9da9b698b1dccbd5293027d54d0fc8
18,803
def object_miou(y_true, y_pred, num_classes=cfg.num_classes): """ 衡量图中目标的iou :param y_true: 标签 :param y_pred: 预测 :param num_classes: 分类数量 :return: miou """ confusion_matrix = get_confusion_matrix(y_true, y_pred, num_classes) # Intersection = TP Union = TP + FP + FN # IoU = TP / ...
1051fe488fb4b16760bb256265d11b33aa613743
18,804
import datetime def post_discussion(title: str, content: str, path: str, top: bool, private: bool = False): """ 发送讨论 参数: title:str 讨论题目 content:str 内容 path:str 路径 top:bool 是否置顶 返回 { "code":-1,//是否成功执行 "discussion_id":"成功执行时的讨论ID", "message":"错误信息" } ...
b633da456a8ca05d592efb3e1dd16c8a7a465e23
18,805
import glob import json def logs_handler(request): """Return the log file on disk. :param request: a web requeest object. :type request: request | None """ log.info("Request for logs endpoint made.") complete_log_path = 'genconf/state/complete.log' json_files = glob.glob('genconf/state/*....
d422dbc4394a31a4b92f531cc01f377020069ddd
18,806
from operator import and_ def _get_fields_usage_data(session): """ Obtaining metrics of field usage in lingvodoc, the metrics are quantity of all/deleted dictionary perspectives using this field (also with URLs) and quantity of lexical entries in such dictionary perspectives Result: dict ...
d57fb6fd0c07e22ac62ba63e5ba5b72189481aed
18,807
import os import errno import fnmatch def output_is_new(output): """Check if the output file is up to date. Returns: True if the given output file exists and is newer than any of *_defconfig, MAINTAINERS and Kconfig*. False otherwise. """ try: ctime = os.path.getctime(output) ...
a6d251799ee82fc89c0fdd0c231b1253215a2ae0
18,808
def test_merge_batch_grad_transforms_same_key_same_trafo(): """Test merging multiple ``BatchGradTransforms`` with same key and same trafo.""" def func(t): return t bgt1 = BatchGradTransformsHook({"x": func}) bgt2 = BatchGradTransformsHook({"x": func}) merged = Cockpit._merge_batch_grad_tr...
10aade423092d39e6a7d754c0ceecfdb53226b53
18,809
import atexit import time def main(selected_ssids, sample_interval, no_header, args=None): """ Repeatedly check internet connection status (connected or disconnected) for given WiFi SSIDs. Output is writen as .csv to stdout. """ wireless_connections = [ c for c in NetworkManager.Settings....
f47e13bdb994e450b8bb77e26e0da3d25014032f
18,810
def getNarrowBandULAMIMOChannel(azimuths_tx, azimuths_rx, p_gainsdB, number_Tx_antennas, number_Rx_antennas, normalizedAntDistance=0.5, angleWithArrayNormal=0, pathPhases=None): """This .m file uses ULAs at both TX and RX. - assumes one beam per antenna element the first co...
bb201abaca60e2855e86a41d9c581599b9ab0c22
18,811
def get_pybricks_reset_vector(): """Gets the boot vector of the pybricks firmware.""" # Extract reset vector from dual boot firmware. with open("_pybricks/firmware-dual-boot-base.bin", "rb") as pybricks_bin_file: pybricks_bin_file.seek(4) return pybricks_bin_file.read(4)
7d504e7e6e6ca444932fd61abb701a010a259254
18,812
def nSideCurve(sides=6, radius=1.0): """ nSideCurve( sides=6, radius=1.0 ) Create n-sided curve Parameters: sides - number of sides (type=int) radius - radius (type=float) Returns: a list with lists of x,y,z coordinates fo...
d64668ae2fdbd2dc06b36fb2523e09a8cc380d6f
18,813
def _get_corr_mat(corr_transform, n_dim): """ Input check for the arguments passed to DirectionalSimulator""" if corr_transform is None: return np.eye(n_dim) if not isinstance(corr_transform, np.ndarray) or corr_transform.ndim < 2: err_msg = "corr_transform must be a 2-D numpy array" ...
94909cc43322e8eebf14942cd39817d10bd744fa
18,814
def get_flowline_routing(NHDPlus_paths=None, PlusFlow=None, mask=None, mask_crs=None, nhdplus_crs=4269): """Read a collection of NHDPlus version 2 PlusFlow (routing) tables from one or more drainage basins and consolidate into a single pandas DataFrame, returning the `FROMCOMID` an...
c79d943b35f236f9d2bddbc6c9e2f470ac6ba0fc
18,815
from typing import Callable from typing import Optional from datetime import datetime import pytz def df_wxyz( time_slot_sensor: Sensor, test_source_a: BeliefSource, test_source_b: BeliefSource ) -> Callable[[int, int, int, int, Optional[datetime]], BeliefsDataFrame]: """Convenient BeliefsDataFrame to run tes...
64928090a7fa58cc1f6a6e4928025c426c17e799
18,816
def not_posted(child, conn) -> bool: """Check if a post has been already tooted.""" child_data = child["data"] child_id = child_data["id"] last_posts = fetch_last_posts(conn) return child_id not in last_posts
5be321bf838a22cfcd742c0ddf48eb00ec1e35bf
18,817
def parse_img_name(path): """parse image by frame name :param name [str] :output img_lists """ code = path.split('\\')[-1].split('.')[0] vid_id = path.split('\\')[-2] rcp_id = path.split('\\')[-3] seg_id = int(code[:4]) frm_id = int(code[4:]) return rcp_id, vid_id, seg_id, frm_id
6e0a140934c584400365f12feb8a86cfea3bbb2b
18,818
def get_bspline_kernel(x, channels, transpose=False, dtype=tf.float32, order=4): """Creates a 5x5x5 b-spline kernel. Args: num_channels: The number of channels of the image to filter. dtype: The type of an element in the kernel. Returns: A tensor of shape `[5, 5, 5, num_channels, num_channels]`. """...
1696e3a9077c672becda474de98750f45d1fe3d4
18,819
from .protocols import Stock_solution,MonoDispensing_type1,MonoDispensing_type2,MultiBase,SMTransfer,ReactionQC,QCSolubilise,DMATransfer,\ def gen_prot_dict(): """ :param input_list: :return: """ PostWorkupTransfer,Workup,PostWorkupQCAndTransfer,PostWorkupDMSOAddition,BaseT3PMulti, PoisedReact...
64c4c88f684297ea7e658015d225481005315527
18,820
def f(x): """ 예측해야 하는 함수입니다. """ return np.matmul(x * np.absolute(np.sin(x)), np.array([[2], [1]]))
228e8f431f7c071ad1587b76c73495296e1331f3
18,821
def create_frame_coords_list(coords_path): """ :param coords_path: [int] :type coords_path: list :return: int, [int] :rtype: tuple """ id_number = coords_path[0] fr_coordinates = [None]*int((len(coords_path) - 1) / 3) # excluding the index 0 (which is the id) the number of triples ...
ca835c04b67789903a74e6882434c570f33647ab
18,822
import types import sys def parse_args(): """ Parses command-line arguments and returns a run configuration """ runconfig = types.SimpleNamespace() runconfig.ssl = False runconfig.port = None runconfig.connection_string = None i = 1 try: while i < len(sys.argv): ...
cf05d2b88c4bf9c81d107dba50d399be1cee5e7a
18,823
def arcToolReport(function=None, arcToolMessageBool=False, arcProgressorBool=False): """This decorator function is designed to be used as a wrapper with other GIS functions to enable basic try and except reporting (if function fails it will report the name of the function that failed and its arguments. If a re...
673dd42bd96a0f5aede5ca0593efaa02d630e2e5
18,824
def check_for_pattern(input_string): """ Check a string for a recurring pattern. If no pattern, return False. If pattern present, return smallest integer length of pattern. Warning: equal_divisions discards the remainder, so if it doesn't fit the pattern, you will get a false postive...
6d6e32c7228ef3cec4107a3354fe53b90ef69e04
18,825
import logging def get_xml_namespace(file_name,pkg_type): """Get xml's namespace. Args: file_name: The path of xml file. Returns: xml_namespace: The namespace of xml. for example: xml file content: ... <config xmlns="urn:ietf:params:xml:n...
401bf5c321b5626d7b7171e2270df04863a01d61
18,826
def build_successors_table(tokens): """Return a dictionary: keys are words; values are lists of successors. >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.'] >>> table = build_successors_table(text) >>> sorted(table) [',', '.', 'We', 'an...
92206bf3dd40518c23c6fb98e22dc818912c5bcc
18,827
import math def _rolling_nanmin_1d(a, w=None): """ Compute the rolling min for 1-D while ignoring NaNs. This essentially replaces: `np.nanmin(rolling_window(T[..., start:stop], m), axis=T.ndim)` Parameters ---------- a : numpy.ndarray The input array w : numpy.ndarray, ...
37229440ba632d1ddadc55a811f9abca1c8e3132
18,828
def get_model_init_fn(train_logdir, tf_initial_checkpoint, initialize_last_layer, last_layers, ignore_missing_vars=False): """Gets the function initializing model variables from a checkpoint. Args: train_logdir: Log direc...
7fdd1bcff59fc01dff2f1ef49eda4bd29b162ea2
18,829
import time def tokenize_protein(text): """ Tokenizes from a proteins string into a list of strings """ aa = ['A','C','D','E','F','G','H','I','K','L', 'M','N','P','Q','R','S','T','V','W','Y'] N = len(text) n = len(aa) i=0 seq = list() timeout = time.time()+5 for i...
7dba531023aef97dcbfb37af75a9a1459a1e94d2
18,830
from typing import Callable def read_xml_string() -> Callable[[int, int, str], str]: """Read an XML file to a string. Subsection string needs to include a prepending '-'.""" def _read_xml_string(number: int, year: int, subsection: str) -> str: xmlfile = f"tests/data/xmls/session-{number:03}-{year}{su...
2b4e4c3585e26138e5fecf820699e97e1011a842
18,831
def compute_mean_std_data(filelist): """ Compute mean and standard deviation of a dataset. :param filelist: list of str :return: tuple of floats """ tensor_list = [] for file in filelist: img = Image.open(file) img_np = np.array(img).ravel() tensor_list.append(img_np....
57c8d5e9294e291e9897ac0e865a661319123965
18,832
def ConstVal(val): """ Creates a LinComb representing a constant without creating a witness or instance variable Should be used carefully. Using LinCombs instead of integers where not needed will hurt performance """ if not isinstance(val, int): raise RuntimeError("Wrong type for ConstVal") ...
d715564ea09224590be827d3e32043c4b66c5cfd
18,833
def filter_required_flat_tensor_spec(flat_tensor_spec): """Process a flat tensor spec structure and return only the required subset. Args: flat_tensor_spec: A flattened sequence (result of flatten_spec_structure) with the joined string paths as OrderedDict. Since we use OrderedDicts we can safely c...
aa55e790cd335030cf2c821dd006213db022b78a
18,834
def callback(photolog_id): """ twitter로부터 callback url이 요청되었을때 최종인증을 한 후 트위터로 해당 사진과 커멘트를 전송한다. """ Log.info("callback oauth_token:" + request.args['oauth_token']); Log.info("callback oauth_verifier:" + request.args['oauth_verifier']); # oauth에서 twiter로 부터 넘겨받은 인증토큰을 세션으로 부터 가져온다. ...
3dcca97278cf20f819fa357b85e971dae9a6dac8
18,835
def calc_adjusted_pvalues(adata, method='fdr_by'): """Calculates pvalues adjusted per sample with the given method. :param data: AnnData object annotated with model fit results. :param method: Name of pvalue adjustment method (from statsmodels.stats.multitest.multipletests). :return: AnnData ob...
0097ceca4918ef4a4c4376c092b040752f408036
18,836
def create_model(model_type='mobilenet'): """ Create a model. :param model_type: Must be one of 'alexnet', 'vgg16', 'resnet50' or 'mobilenet'. :return: Model. """ if model_type is 'alexnet': net = mdl.alexnet(input_shape, num_breeds, lr=0.001) elif model_type is 'vgg16': net ...
44ab632eff28e40b5255094e2009b479e042b00b
18,837
def generate_voter_groups(): """Generate all possible voter groups.""" party_permutations = list(permutations(PARTIES, len(PARTIES))) voter_groups = [VoterGroup(sequence) for sequence in party_permutations] return voter_groups
16c55002600bf76178c529f1140fb28831d5065e
18,838
import logging def add_image_fuzzy_pepper_noise(im, ration=0.1, rand_seed=None): """ generate and add a continues noise to an image :param ndarray im: np.array<height, width> input float image :param float ration: number means 0 = no noise :param rand_seed: random initialization :return ndarray: ...
9bbf38b1d4fd16011dc884e98a25e8d872fef534
18,839
import random def generator(fields, instance): """ Calculates the value needed for a unique ordered representation of the fields we are paginating. """ values = [] for field in fields: neg = field.startswith("-") # If the field we have to paginate by is the pk, get the...
3d6f3837e109720ec78460dcd56b6cf1b3ddc947
18,840
from typing import Any from typing import Union def token_hash(token: Any, as_int: bool = True) -> Union[str, int]: """Hash of Token type Args: token (Token): Token to hash as_int (bool, optional): Encode hash as int Returns: Union[str, int]: Token hash """ return _hash((...
3adfc8dce2b37b86376d47f8299cb6813faab839
18,841
import six import base64 from datetime import datetime def generate_totp_passcode(secret): """Generate TOTP passcode. :param bytes secret: A base32 encoded secret for TOTP authentication :returns: totp passcode as bytes """ if isinstance(secret, six.text_type): secret = secret.encode('utf-...
2f0392e86b5d84970ec43bbd4d647ca29345a373
18,842
def all_ndcubes(request): """ All the above ndcube fixtures in order. """ return request.getfixturevalue(request.param)
906412ebe9a26de5cfddcb1d1431ab014c8084c6
18,843
from pathlib import Path import warnings def read_xmu(fpath: Path, scan: str='mu', ref: bool=True, tol: float=1e-4) -> Group: """Reads a generic XAFS file in plain format. Parameters ---------- fpath Path to file. scan Requested mu(E). Accepted values are transmission ('mu'), flu...
e5889fa309b7fb836cc5b7ea50f8987a647f00a2
18,844
def filter_order_by_oid(order, oid): """ :param order: :type order: :class:`tests.testapp.testapp.trading.models.Order` :param oid: Order ID :type oid: int """ return order.tid == oid
bf84e2e9f2fa19dc19e1d42ceef92dd3050d1e89
18,845
from skaldship.passwords.utils import process_password_file, insert_or_update_acct import logging def process_pwdump_loot(loot_list=[], msf=None): """ Takes an array of loot records in loot_list, downloads the pwdump file and adds the users. """ db = current.globalenv['db'] #cache = current.g...
57448b24350dd66271906ba5fcdc0e4453d898e9
18,846
def has_poor_grammar(token_strings): """ Returns whether the output has an odd number of double quotes or if it does not have balanced parentheses. """ has_open_left_parens = False quote_count = 0 for token in token_strings: if token == '(': if has_open_left_parens: ...
b35c6af0ec771ac22ff66d9ca875f5d916cb9489
18,847
def run(main, *, debug=False): """ Since we're using asyncio loop to run wait() in irder to be compatible with async calls, here we also run each wait in a different thread to allow nested calls to wait() """ thread = RunnerThread(main, debug=debug) thread.start() thread.join() if thread...
47c70c887e456ac69f5c767bf0f1e56c050f8f4b
18,848
import pandas as pd def csv_dataset_reader(path): """ This function reads a csv from a specified path and returns a Pandas dataframe representation of it, and renames columns. :param path: Path to and name of the csv file to read. :return: A Pandas dataframe. """ data = pd.read_csv(path, s...
59a298c50bf060809ebbebc5d0ff3d9670e84244
18,849
def get_daily_blurb_info(): """Get daily blurb info.""" html, ss_image_1day_file, ss_image_1year_file = _scrape() return _parse(html, ss_image_1day_file, ss_image_1year_file)
ffe84accebda5780e55d34e58137288d02bc072d
18,850
import torch def generate_random_ring_element(size, ring_size=(2 ** 64), **kwargs): """Helper function to generate a random number from a signed ring""" # TODO (brianknott): Check whether this RNG contains the full range we want. rand_element = torch.randint( -(ring_size // 2), (ring_size - 1) // ...
6e7ea30e5b4ccbde7dc48d1fe8fa51468344c335
18,851
def otsu_binarization(img): """ Method to perform Otsu Binarization :param img: input image :return: thresholded image """ ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th2
99953288b893d56e17a9e9654393aa284eaae4b7
18,852
def rosstack_depends_1(s): """ @param s: stack name @type s: str @return: A list of the names of the stacks which s depends on directly @rtype: list """ return rosstackexec(['depends1', s]).split()
e917c62c628498e1f100c045bf8e966ea3bfd355
18,853
def _config_file_is_to_update(): """ Ask the user if the configuration file should be updated or not. :return: Returns True if the user wants to update the configuration file and False otherwise. :rtype: bool """ if yes_or_no_input("Do you want to save the account on the configuration file?") ==...
e14be78e150e28b87a0e8f179cc86f4a240a60d3
18,854
import subprocess def countbam(sortedbam, outdir): """calculates the raw counts from a BAM index parameters ---------- sortedbam string, the name of the sorted bam file outdir string, the path of the output directory returns ---------- counts_file = file containing the ...
de60c7af2a479d00487a1891a64c926f9a2e0ae0
18,855
def funcScrapeTableWunderground(html_tree, forecast_date_str): """ """ # This will get you the Wunderground table headers for future hour conditions columns = html_tree.xpath("//table[@id='hourly-forecast-table']/thead//button[@class='tablesaw-sortable-btn']") rows = html_tree.xpath("//table[@i...
aa6745565e8fa01df8b8f52f1314ee7bf1a434a8
18,856
from re import S def as_finite_diff(derivative, points=1, x0=None, wrt=None): """ Returns an approximation of a derivative of a function in the form of a finite difference formula. The expression is a weighted sum of the function at a number of discrete values of (one of) the independent variable(...
4b76eae0578434a9a087b08f01eefbcd3018bc01
18,857
def is_prime(pp: int) -> bool: """ Returns True if pp is prime otherwise, returns False Note: not a very sophisticated check """ if pp == 2 or pp == 3: return True elif pp < 2 or not pp % 2: return False odd_n = range(3, int(sqrt(pp) + 1), 2) return not any(not pp % ...
f8661a7f625c198dd1d0b5b477aea22f50596a39
18,858
def createChromosome( totQty, menuData ): """ Creates the chromosome with Qty assigned to Each Dish such that sum of all Qty equals to the number of dishes to be ordered totQty = Number of Dishes to be Ordered returns chromosome of dish id and corresponding quantity """ chromosome = [] ...
6dae9c5a610a50df67e18f2034513a090088e524
18,859
def add_residual(transformed_inputs, original_inputs, zero_pad=True): """Adds a skip branch to residual block to the output.""" original_shape = original_inputs.shape.as_list() transformed_shape = transformed_inputs.shape.as_list() delta = transformed_shape[3] - original_shape[3] stride = int(np.ceil(origina...
e32897c6e80873b863fbc3358eaec8b6191086f0
18,860
def _find_bad_channels_in_epochs(epochs, picks, use_metrics, thresh, max_iter): """Implements the fourth step of the FASTER algorithm. This function attempts to automatically mark bad channels in each epochs by performing outlier detection. Additional Parameters --------------------- use_metri...
6b4a0acc1eb4e1fc4f229cc237e071bf87047b5e
18,861
def solution(A): # O(N^2) """ For a given value A, compute the number with the fewest number of squared values and return them within an array. eg. 26 can be computed with squared values [25, 1] or [16, 9, 1], but the answer is only [25, 1] as ...
56f899d94cfc07a412a357a305553ad0ed8af092
18,862
import time from sys import path from pathlib import Path def gmrt_guppi_bb(rawfile, npol=2, header=None, chunk=None, samples_per_frame=4096, nchan=1): """ To read gmrt raw voltages file of GWB to convert to guppi raw :USAGE: -------- $ gmrt_raw_toguppi [-h] [-f FILENAME] [-c CHUNK] [-hdr HEADER]...
cc135ec0dfeec0fe9f946ca1eac57bc979e024ea
18,863
def get_device_path(): """Return device path.""" if is_gce(): return None devices = get_devices() device_serial = environment.get_value('ANDROID_SERIAL') for device in devices: if device_serial == device.serial: return device.path return None
5bd8bf47859c3721e47cfc45b49aaa06bed4159e
18,864
def pattern_maker(size, dynamic): """ Generate a pattern with pixel values drawn from the [0, 1] uniform distribution """ def pattern(): return np.random.rand(size) def static(): a_pattern = pattern() def fn(): return a_pattern return fn return...
3fd256fe3f8c7669faec8a7d1757a334a51145ba
18,865
def RMSE(a, b): """ Return Root mean squared error """ return np.sqrt(np.square(np.subtract(a, b)).mean())
7d853535fb9e4072f983f05ad192cc38f2bbea8e
18,866
def alpha_a_b(coord, N, silent=True): """Calculate alpha, a, b for a rectangle with coordinates coord and truncation at N.""" [x0, x1, y0, y1] = coord a = 0 for zero in zeros[:N]: a += exp(-zero*y0)/abs(complex(0.5, zero)) b = 0 for zero in zeros[N:]: b += exp(-zero*y0)/abs(...
41cc57c16a7526bf7a88503ea9315872062b8ac5
18,867
from typing import Any from typing import Optional def asdataset( dataclass: Any, reference: Optional[DataType] = None, dataoptions: Any = None, ) -> Any: """Create a Dataset object from a dataclass object. Args: dataclass: Dataclass object that defines typed Dataset. reference: D...
4baf2df39f906f2b1981cb597cb6430e95bb1ca1
18,868
def get_edge_size(reader: ChkDirReader, chunks: list[ChunkRange], tilesize: int) -> int: """Gets the size of an edge tile from an unknown chunk""" for chunk in chunks: data: bytes = deflate_range(reader, chunk.start, chunk.end, True) if data is None: continue try: ...
54da5c4adafbcccae4cee9112e35470a97172b00
18,869
import time import torch def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False): """Test model with multiple gpus. This method tests model with multiple gpus and collects the results under two different modes: gpu and cpu modes. By setting 'gpu_collect=True' it encodes results to gpu ...
8ec9bf7efcd126485a8066c7d5932b0c84c44b63
18,870
def toRegexp(exp,terminate=False,lower=False): """ Case sensitive version of the previous one, for backwards compatibility """ return toCl(exp,terminate,wildcards=('*',),lower=lower)
d550164d7d2a628a0b0bcf37f5ee95de958fc2e5
18,871
def marker_used_in_game(marker_id: int) -> bool: """ Determine whether the marker ID is used in the game. :param marker_id: An official marker number, mapped to the competitor range. :returns: True if the market is used in the game. """ return any([marker_id in marker_range for marker_range in ...
437d5b8c3ff80683e3f19d5cb3786243c6e430b3
18,872
def iround(x): """ Round an array to the nearest integer. Parameters ---------- x : array_like Input data. Returns ------- y : {numpy.ndarray, scalar} The rounded elements in `x`, with `int` dtype. """ return np.round(x).astype(int)
64837773f12eb096ede5d8963360ab28427b015d
18,873
def multiLineManager(pentadList = [], debugMode = False): """ Takes the complete list of pentads and returns this list once every multilines being put on a single line. That's ALL. """ output = [] currentStatement = "" presentChar = 'a' startingLine = 0 i = 0 state = "Nothing" fo...
d1a5853ddbb94c94a2440b99148023ecd3f8abde
18,874
def get_ec2_conn(): """ Requried: env.aws_region, env.aws_access_key, env.aws_secret_access_key return conneciton to aws ec2 """ conn = boto.ec2.connect_to_region( env.aws_region, aws_access_key_id=env.aws_access_key, aws_secret_access_key=env.aws_secret_access_key ...
5c2014f7d1a3ba465ec7f205ac34a5c1feeb2aac
18,875
import tqdm import sys def eval_nominal_domain(pool: SamplerPool, env: SimEnv, policy: Policy, init_states: list) -> list: """ Evaluate a policy using the nominal (set in the given environment) domain parameters. :param pool: parallel sampler :param env: environment to evaluate in :param policy: ...
0376438fc48b9442532edc8c57572a6fe87ccbc9
18,876
def create_final_comment_objects(): """Goes through the final comments and returns an array of objects.""" arr = [] # Stores objects for line in final_file: row = line.split(",") # Set object variables for each object before adding it to the array comment_number, commen...
02107ba5ebc23e5a8db1c30fa8709793e1fcbe7e
18,877
import re def normalise_target_name(name, used=[], max_length=None): """ Check that name[:max_length] is not in used and append a integer suffix if it is. """ def generate_name(name, i, ml): # Create suffix string i_name = '' if i == 0 else '_' + str(i) # Return con...
bffc78525d766cbb941382b6f7dd9371cffee492
18,878
def construct_pairwise_df(sr: pd.Series, np_fun): """Constructs an upper diagonal df from all pairwise comparisons of a sr""" sr = sr.sort_index() _mat = np.triu(np_fun(sr.to_numpy() - sr.to_numpy()[:, None]), k=1) _mat[np.tril_indices(_mat.shape[0])] = None return pd.DataFrame(_mat, index=sr.index....
bfef4a9c64e619e2d70efb3dea1fde9da5894634
18,879
def privacy(request): """This returns the privacy policy page""" return render(request=request, template_name="registration/privacy.html")
c3467b0f670facb152c1f2cd793e6dd46301bc25
18,880
def seq_search(items, key): """顺序查找""" for index, item in enumerate(items): if item == key: return index return -1
1271555aea5f7291ebb3679a219d4b3eb81d87a7
18,881
import os def _check_moog_files (fp,mode='r',clobber=True,max_filename_length=None): """ Takes a moog keyword and extracts from the moogpars """ # - - - - - - - - - - - - filepath if fp is None: return # - - - - - - - - - - - - check file mode if mode not in ('r','w'): raise Val...
20698622c1718a8765cd30f687f3550044adc358
18,882
def parse_prediction_key(key): """The "name" or "key" of a predictor is assumed to be like: `ProHotspotCtsProvider(Weight=Classic(sb=400, tb=8), DistanceUnit=150)` Parse this into a :class:`PredictionKey` instance, where - `name` == "ProHotspotCtsProvider" - `details` will be the dict: {"Weigh...
4d971da8097a237f6df8d96bb407c9706c6ed8f6
18,883
def tick2dayfrac(tick, nbTicks): """Conversion tick -> day fraction.""" return tick / nbTicks
50d01778f62203d37e733a6b328455d3ea10e239
18,884
import os def load_esol_semi_supervised(unlabeled_size=0.1, seed=2666): """ Parameters ---------- unlabeled_size : (Default value = 0.1) seed : (Default value = 2666) Returns ------- """ esol_labeled = pinot.data.esol() # Get labeled and unlabeled data es...
e0263bb5acabc48a50bab215bd7933583a952d0d
18,885
from datetime import datetime def get_business_day_of_month(year, month, count): """ For a given month get the Nth business day by count. Count can also be negative, e.g. pass in -1 for "last" """ r = rrule(MONTHLY, byweekday=(MO, TU, WE, TH, FR), dtstart=datetime.datetime(year, mon...
f0322df24f63ee836cf4f98099ccc0e4eff20c67
18,886
def inpolygon(wkt, longitude, latitude): """ To determine whether the longitude and latitude coordinate is within the orbit :param wkt(str): the orbit wkt info :param longitude: to determine whether the longitude within the orbit :param latitude: to determine whether the latitude within the orbit :r...
b844361f2fb3002a1d6df2a0301d19cc5b75470d
18,887
def matrixMultVec(matrix, vector): """ Multiplies a matrix with a vector and returns the result as a new vector. :param matrix: Matrix :param vector: vector :return: vector """ new_vector = [] x = 0 for row in matrix: for index, number in enumerate(row): x += numb...
8a03b3acfec0d91fcf0d2c85b4e2bdd4f3053dd2
18,888
def get_dev_value(weight, error): """ :param weight: shape [N, 1], the importance weight for N source samples in the validation set :param error: shape [N, 1], the error value for each source sample in the validation set (typically 0 for correct classification and 1 for wrong classification) """ ...
740dbd755cf540b0133ddf321207ea0bbd74fc83
18,889
def biLSTM(f_lstm, b_lstm, inputs, dropout_x=0.): """Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Var...
dc3cdc07a20e4ae5fbe257a81d92f15fb51333d9
18,890
import torch def refer_expression(captions, n_ground=1, prefix="refer expressions:", sort=True): """ n_ground > 1 ground_indices [1, 0, 2] source_text refer expressions: <extra_id_0> red crayon <extra_id_1> Yellow banana <extra_id_2> black cow target_text <vis_extra_id_1>...
57919ee416dbb981dbb7f03163beec779785cc2f
18,891
def url_to_filename(base, url): """Return the filename to which the page is frozen. base -- path to the file url -- web app endpoint of the page """ if url.endswith('/'): url = url + 'index.html' return base / url.lstrip('/')
35084e8b5978869bf317073c76bafc356a7d9046
18,892
def _msd_anom_3d(time, D_alpha, alpha): """3d anomalous diffusion function.""" return 6.0*D_alpha*time**alpha
e5204c52368202665e4dd4acd7d86096349c0d29
18,893
import json def make_json_response(status_code, json_object, extra_headers=None): """ Helper function to serialize a JSON object and add the JSON content type header. """ headers = { "Content-Type": 'application/json' } if extra_headers is not None: headers.update(extra_headers...
4857b806819e44b7a77e0a9a51df7b4fe6678656
18,894
import os def tmp_envfile(tmp_path, monkeypatch): """Create a temporary environment file.""" tmp_file_path = tmp_path / "setenv.txt" monkeypatch.setenv("GITHUB_ENV", os.fspath(tmp_file_path)) return tmp_file_path
04deab16ce4b0e115e9fdc9b65a023f7c63f054f
18,895
from datetime import datetime def calc_dst_temerin_li(time, btot, bx, by, bz, speed, speedx, density, version='2002n', linear_t_correction=False): """Calculates Dst from solar wind input according to Temerin and Li 2002 method. Credits to Xinlin Li LASP Colorado and Mike Temerin. Calls _jit_calc_dst_temer...
f333217e34656c4566a254c1c383191f11e8c3d0
18,896
import os def parsestrfile(str_inpath): """Returns dictionary containing :class:`~gemmi.Structure` objects and another one with the file names. :param str_inpath: Either a directory or file path. :type str_inpath: str :raises KeyError: More than one structure file containing same identifier. :ret...
e46d7242df1c2aab7e06f29db31d15e4085ecee0
18,897
import os import json def handle_import(labfile, labjs): """랩 파일이 참고하는 외부 랩 파일 가져오기. Args: labfile (Str): 랩파일 경로 labjs (dict): 랩 데이터 """ if 'import' not in labjs: return labjs if '_imported_' not in labjs: labjs['_imported_'] = [] adir = os.path.dirname(labf...
3b6f833e5e4044c3fd7fdead6ed1678bc945234b
18,898
def reconstruct(vars_to_reconstruct, scheme, order_used): """ Reconstructs all variables using the requested scheme. :param vars_to_reconstruct: The variables at the cell centers. :type vars_to_reconstruct: list of list of double :param Reconstruction.Scheme scheme: The reconstruction scheme to us...
b1e3cd8b8ed91b6c7ccdd5d6903fbce3109a3871
18,899