content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def custom_client_datalist_json_path(datalist_json_path: str, client_id: str, prefix: str) -> str: """ Customize datalist_json_path for each client Args: datalist_json_path: default datalist_json_path client_id: e.g., site-2 """ # Customize datalist_json_path for each c...
fb21864a18e105bbfe73cbec75ebcfd4ac52910b
17,700
from typing import List def parse_mint_studies_response(xml_raw) -> List[MintStudy]: """Parse the xml response to a MINT find DICOM studies call Raises ------ DICOMTrolleyError If parsing fails """ try: studies = ElementTree.fromstring(xml_raw).findall( MintStudy.x...
465d9156be75144bacd1c84316660ea48a3f276e
17,701
def lookup_no_interp(x, dx, xi, y, dy, yi): """ Return the indices for the closest values for a look-up table Choose the closest point in the grid x ... range of x values xi ... interpolation value on x-axis dx ... grid width of x ( dx = x[1]-x[0]) (same for y) re...
cdee658cc50af9ba25902bdbe4274cd49a5c5d89
17,702
def advertisement_data_complete_builder(list_of_ad_entries): """ Generate a finalized advertisement data value from a list of AD entries that can be passed to the BLEConnectionManager to set the advertisement data that is sent during advertising. :param list_of_ad_entries: List of AD entries (can be bu...
c0f9040c36216cb519706c347d6644405fae0b7f
17,703
def process_vocab_table(vocab, vocab_size, vocab_threshold, vocab_lookup, unk, pad): """process vocab table""" default_vocab = [unk, pad] if unk in vocab: del vocab[unk] i...
fa4860aac095d531e39008da99d42059e38716ec
17,704
def get_mag_msg(stamp, mag): """ Get magnetometer measurement as ROS sensor_msgs::MagneticField """ # init: mag_msg = MagneticField() # a. set header: mag_msg.header.stamp = stamp mag_msg.header.frame_id = '/imu_link' # b. mag: ( mag_msg.magnetic_field.x, mag_ms...
ffa661ae168136fcbf626e08f85e19ba356a2e26
17,705
async def UserMeAPI( current_user: User = Depends(User.getCurrentUser), ): """ 現在ログイン中のユーザーアカウントの情報を取得する。<br> JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセスできない。 """ # 一番よく使う API なので、リクエスト時に twitter_accounts テーブルに仮のアカウントデータが残っていたらすべて消しておく ## Twitter 連携では途中で連携をキャンセルした場合に仮のア...
0a884c54d1e01b5ae9a31848b081566d35830de6
17,706
def midpt(pt1, pt2): """ Get the midpoint for two arbitrary points in space. """ return rg.Point3d((pt1[0] + pt2[0])/2, (pt1[1] + pt2[1])/2, (pt1[2] + pt2[2])/2 )
324e9fd6fe6ea257a130fcfe51eb73bf0957e57c
17,707
from collections import defaultdict from astropy.io import fits import siteUtils from bot_eo_analyses import make_file_prefix, glob_pattern,\ from bot_data_handling import most_common_dark_files def dark_current_jh_task(det_name): """JH version of single sensor execution of the dark current task.""" get_a...
a2d627b21340382018826bb583ad31c8509f9bbe
17,708
import re def get_sid_list (video_source_filename): """This returns a list of subtitle ids in the source video file. TODO: Also extract ID_SID_nnn_LANG to associate language. Not all DVDs include this. """ cmd = "mplayer '%s' -vo null -ao null -frames 0 -identify" % video_source_filename (command_...
adcbb7e3790c12fd55b17cca2d4ffd87593a78d0
17,709
def tweetnacl_crypto_box_open(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_box_curve25519xsalsa2...
5b69127c70d3286c2c54b898d541db9f90c1ff51
17,710
def balanced_parentheses_checker(symbol_string): """Verify that a set of parentheses is balanced.""" opening_symbols = '{[(' closing_symbols = '}])' opening_symbols_stack = data_structures.Stack() symbol_count = len(symbol_string) counter = 0 while counter < symbol_count: current_...
04624d403f5af94c42122258df28363cb8bcf20d
17,711
from typing import Optional def _wrap_outcoming( store_cls: type, wrapped_method: str, trans_func: Optional[callable] = None ): """Output-transforming wrapping of the wrapped_method of store_cls. The transformation is given by trans_func, which could be a one (trans_func(x) or two (trans_func(self...
5ea4782f528c7822d8906cde415cc318353b54ba
17,712
import math def quantize(x): """convert a float in [0,1] to an int in [0,255]""" y = math.floor(x*255) return y if y<256 else 255
b941a11d0d6af3162c964568e2d97c8d81cd1442
17,713
import logging def initialize_logger(prefix): """ Initialization of logging subsystem. Two logging handlers are brought up: 'fh' which logs to a log file and 'ch' which logs to standard output. :param prefix: prefix that is added to the filename :return logger: return a logger instance """ ...
a6883736b17b9dc213bf4d26fd153fc8d0e11025
17,714
def interpolate(x, x_data, y_data, left_slope=0.0, right_slope=0.0, dtype=None, name=None): """Performs linear interpolation for supplied points. Given a set of knots whose x- and y- coordinates are in `x_data` and `y_d...
38c1f3eff92a203894b45add718c354e431c9b03
17,715
from typing import Optional import pickle def login(token_path: str) -> Optional[Credentials]: """ Trigger the authentication so that we can store a new token.pickle. """ flow = InstalledAppFlow.from_client_secrets_file( 'gcal/credentials.json', SCOPES) creds = flow.run_local_server(port=0...
72c7164297cfc17c661253f9496f8323cc3f217c
17,716
import requests def get_auth_token(context, scope): """ Get a token from the auth service to allow access to a service :param context: context of the test :return: the token """ secret = get_client_secret(context) data = { 'grant_type': 'client_credentials', 'scope': scope...
d36e66ed08f637f93b2f9226e7ccaeb9cbe07a2c
17,717
def getDefaultFontFamily(): """Returns the default font family of the application""" return qt.QApplication.instance().font().family()
408aa406d09dcc788bff46c3346307713f5b0fdf
17,718
def result(a, b, operator): """This function return result""" lambda_ops = { "+": (lambda x,y: x+y), "-": (lambda x,y: x-y), "*": (lambda x,y: x*y), "/": (lambda x,y: x/y), "//": (lambda x,y: x//y), "%": (lambda x,y: x%y), } r = False error = '' ...
febfacf3aa94bc15931cf79979329b3b1a5c7bc5
17,719
import torch def batched_nms(boxes, scores, idxs, nms_cfg, class_agnostic=False): """Performs non-maximum suppression in a batched fashion. Modified from https://github.com/pytorch/vision/blob /505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39. In order to perform NMS independentl...
153e9d8aba307c0a63cc6cc3045bb004f3c8445f
17,720
def get_deconv_filter(f_shape): """ reference: https://github.com/MarvinTeichmann/tensorflow-fcn """ width = f_shape[0] heigh = f_shape[0] f = ceil(width/2.0) c = (2 * f - 1 - f % 2) / (2.0 * f) bilinear = np.zeros([f_shape[0], f_shape[1]]) for x in range(width): for y in range...
ec0a5617ad149708d195ab4701860f12ef695de1
17,721
def twitter_split_handle_from_txt(tweet): """ Looks for RT @twitterhandle: or just @twitterhandle in the beginning of the tweet. The handle is split off and returned as two separate strings. :param tweet: (str) The tweet text to split. :return: (str, str) twitter_handle, rest_of_t...
1f98e5e5f2c1369ca673e6b15114f379786d1e8f
17,722
def points(piece_list): """Calculating point differential for the given board state""" # Args: (1) piece list # Returns: differential (white points - black points) # The points are calculated via the standard chess value system: # Pawn = 1, King = 3, Bishop = 3, Rook = 5, Queen = 9 # King = 100 (arbitrarily la...
d8f36fd887a846a20999a0a99ad672d2902473d4
17,723
def grid_sampler(x, grid, name=None): """ :alias_main: paddle.nn.functional.grid_sampler :alias: paddle.nn.functional.grid_sampler,paddle.nn.functional.vision.grid_sampler :old_api: paddle.fluid.layers.grid_sampler This operation samples input X by using bilinear interpolation based on flow field gri...
06c57d6e6d0a476b42b2472284368352fbd48bc3
17,724
import os import subprocess def fpack (filename): """fpack fits images; skip fits tables""" try: # fits check if extension is .fits and not an LDAC fits file if filename.split('.')[-1] == 'fits' and '_ldac.fits' not in filename: header = read_hdulist(filename, get_data=False, ge...
6b02bdf88130a00bffc216c68f714a1719b306ca
17,725
def SpecSwitch(spec_id): """ Create hotkey function that switches hotkey spec. :param spec_id: Hotkey spec ID or index. :return: Hotkey function. """ # Create hotkey function that switches hotkey spec func = partial(spec_switch, spec_id) # Add `call in main thread` tag func = tag_...
20ba2ae59d717866474c236d0d97273755a035c8
17,726
def get_package_version() -> str: """Returns the package version.""" metadata = importlib_metadata.metadata(PACKAGE_NAME) # type: ignore version = metadata["Version"] return version
a24286ef2a69f60871b41eda8e5ab39ba7f756c0
17,727
def safe_name(dbname): """Returns a database name with non letter, digit, _ characters removed.""" char_list = [c for c in dbname if c.isalnum() or c == '_'] return "".join(char_list)
2ce4978c3467abaddf48c1d1ab56ed773b335652
17,728
def _parse_mro(mro_file_name): """Parse an MRO file into python objects.""" # A few helpful pyparsing constants EQUALS, SEMI, LBRACE, RBRACE, LPAREN, RPAREN = map(pp.Suppress, '=;{}()') mro_label = pp.Word(pp.alphanums + '_') mro_modifier = pp.oneOf(["in", "out", "src"]) mro_type = pp.oneOf([ ...
cf2561d1b72c2899fa495c2e83b683b7980b47ab
17,729
import math def tabulate_stats(stats: rl_common.Stats) -> str: """Pretty-prints the statistics in `stats` in a table.""" res = [] for (env_name, (reward_type, reward_path)), vs in stats.items(): for seed, (x, _log_dir) in enumerate(vs): row = { "env_name": env_name, ...
e853de6ac15e639d7348ee5a423afbdbbf296e7f
17,730
def LLR_binom(k, n, p0, EPS=1E-15): """ Log likelihood ratio test statistic for the single binomial pdf. Args: k : number of counts (numpy array) n : number of trials p0 : null hypothesis parameter value Returns: individual log-likelihood ratio values """ phat = ...
a423b81a374398b88881ee45a665e7f9a648c4c1
17,731
def concatenate_shifts(shifts): """ Take the shifts, which are relative to the previous shift, and sum them up so that all of them are relative to the first.""" # the first shift is 0,0,0 for i in range(2, len(shifts)): # we start at the third s0 = shifts[i-1] s1 = shifts[i] s1.x += s0.x s1.y +=...
f4b0a41db1db78e3b5f25ca198fdb6cebd6476ca
17,732
import json import hashlib def users(user_id=None, serialize=True): """ The method returns users in a json responses. The json is hashed to increase security. :param serialize: Serialize helps indicate the format of the response :param user_id: user id intended to be searched :return: Json forma...
b939860a7e8794f8e53f63594a3000a0425cb319
17,733
def course_units_my(user): """ Get all course units assign to a teacher available persisted in DB :return: tuple with - Course units data - list of success messages - list of error messages """ success = [] data = set([attendance.course_unit for attendance in ...
c2541ab4cdfe91ffba809ac6c295cdddd66ffa54
17,734
def get_world_size(): """TODO Add missing docstring.""" if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size()
f277e157466ea9ebd8d06b552ce1bc544cf78e60
17,735
def get_namenode_setting(namenode): """Function for getting the namenode in input as parameter setting from the configuration file. Parameters ---------- namenode --> str, the namenode for which you want to get the setting info Returns ------- conf['namenodes_setting'][namenode] --...
e389d7a20a7b0ef7f32b51c7bb31068cb152fc2b
17,736
from typing import Tuple def cds(identity: str, sequence: str, **kwargs) -> Tuple[sbol3.Component, sbol3.Sequence]: """Creates a Coding Sequence (CDS) Component and its Sequence. :param identity: The identity of the Component. The identity of Sequence is also identity with the suffix '_seq'. :param seque...
15d99917b840cf2881e1a90c1835c356622511a7
17,737
import os import json def all_scenes(): """List all scenes Returns: list of Scene objects """ global _scene_json if _scene_json is None: with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "scenes.json")) as fh: _scene_json = json.loads(fh.read()) ret = [] for s in _scene...
815216bab4ed9cfdf6b88b4438a275d36beceaca
17,738
import math def calc_innovation(xEst, PEst, y, LMid): """ Compute innovation and Kalman gain elements """ # Compute predicted observation from state lm = get_landmark_position_from_state(xEst, LMid) delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] y_angle = math.atan2(delta[1, 0], d...
146695c107c46d2736d0e4ecc191d9a399ca8159
17,739
from typing import Any def next_key(basekey: str, keys: dict[str, Any]) -> str: """Returns the next unused key for basekey in the supplied dictionary. The first try is `basekey`, followed by `basekey-2`, `basekey-3`, etc until a free one is found. """ if basekey not in keys: return baseke...
e1da51c79fd465088294e053fdc970934268211b
17,740
import yaml def load_mmio_overhead_elimination_map(yaml_path): """ Load a previously dumped mmio overhead elimination map """ with open(yaml_path, "r") as yaml_file: res = yaml.safe_load(yaml_file.read()) res_map = { 'overall': res[0]['overall'], 'per_model': res[1]['per_m...
ae0ead1aa8c9f26acad9a23a35791592efbfe47e
17,741
from MoinMoin.util import diff_html from MoinMoin.util import diff_text def execute(pagename, request): """ Handle "action=diff" checking for either a "rev=formerrevision" parameter or rev1 and rev2 parameters """ if not request.user.may.read(pagename): Page(request, pagename).send...
7305385a84c561fc6c5a8b0e8c52635cf19c77d6
17,742
def SetBmaskName(enum_id, bmask, name): """ Set bitmask name (only for bitfields) @param enum_id: id of enum @param bmask: bitmask of the constant @param name: name of bitmask @return: 1-ok, 0-failed """ return idaapi.set_bmask_name(enum_id, bmask, name)
2a134b496214d7f8e8887dc5a3ca93264da08f5b
17,743
import math def angle_to(x: int, y: int) -> int: """Return angle for given vector pointing from orign (0,0), adjusted for north=0""" #xt,yt = y,x #rad = math.atan2(yt,xt) rad = math.atan2(x,y) if rad < 0.0: rad = math.pi + (math.pi + rad) return rad
545cfa3769da10eea2138132295e3387c4556b39
17,744
import sys import os def sp_args(): """Apply quirks for `subprocess.Popen` to have standard behavior in PyInstaller-frozen windows binary. Returns ------- dict[str, str or bool or None] The additional arguments for `subprocess` calls. """ if sys.platform.startswith('win32'): ...
76d50f2f6e745e486187900efab0e6d58e0fe292
17,745
import torch def adj(triples, num_nodes, num_rels, cuda=False, vertical=True): """ Computes a sparse adjacency matrix for the given graph (the adjacency matrices of all relations are stacked vertically). :param edges: List representing the triples :param i2r: list of relations :param i2n...
8531170c20c39011efcc7a2223c4da49c41ffabb
17,746
def join_b2_path(b2_dir, b2_name): """ Like os.path.join, but for B2 file names where the root directory is called ''. :param b2_dir: a directory path :type b2_dir: str :param b2_name: a file name :type b2_name: str """ if b2_dir == '': return b2_name else: return b2...
20f4e6e54f7f3b4a1583b503d4aa2d8995318978
17,747
def actual_line_flux(wavelength,flux, center=None,pass_it=True): """Measure actual line flux: parameters ---------- wavelength: float array flux: float array center: float wavelength to center plot on output parameters ----------------- flux in line integrated over ...
6d4d36e6e632e605158da704cc1e3462cdc173e1
17,748
def _too_many_contigs(ref_file): """Check for more contigs than the maximum samblaster deduplication supports. """ max_contigs = 32768 return len(list(ref.file_contigs(ref_file))) >= max_contigs
03a01719b634d6eea143306f96cae6ea26e3f1f9
17,749
def survival_regression_metric(metric, outcomes_train, outcomes_test, predictions, times): """Compute metrics to assess survival model performance. Parameters ----------- metric: string Measure used to assess the survival regression model performance. Options include:...
244767ca0533af2fe792fe226fb2a9eb5e166201
17,750
import signal def _get_all_valid_corners(img_arr, crop_size, l_thresh, corner_thresh): """Get all valid corners for random cropping""" valid_pix = img_arr >= l_thresh kernel = np.ones((crop_size, crop_size)) conv = signal.correlate2d(valid_pix, kernel, mode='valid') return conv > (corner_thresh...
6e357a6585e8485de74e01ced62eedcbfe33bdec
17,751
def remove_dup(a): """ remove duplicates using extra array """ res = [] count = 0 for i in range(0, len(a)-1): if a[i] != a[i+1]: res.append(a[i]) count = count + 1 res.append(a[len(a)-1]) print('Total count of unique elements: {}'.format(count + 1)) return ...
8286c07098c078cd61d4890cd120723b9e9f04e7
17,752
def mjd2crnum(mjd): """ Converts MJD to Carrington Rotation number Mathew Owens, 16/10/20 """ return 1750 + ((mjd-45871.41)/27.2753)
233f91e6de4c5105732fc2c8f9f33d054491e1d2
17,753
def poly_print_simple(poly,pretty=False): """Show the polynomial in descending form as it would be written""" # Get the degree of the polynomial in case it is in non-normal form d = poly.degree() if d == -1: return f"0" out = "" # Step through the ascending list of co...
903f9d4a703e3f625da5f13f6fe084e8894d723b
17,754
def parse_file_(): """ Retrieves the parsed information by specifying the file, the timestamp and latitude + longitude. Don't forget to encode the plus sign '+' = %2B! Example: GET /parse/data/ecmwf/an-2017-09-14.grib?timestamp=2017-09-16T15:21:20%2B00:00&lat=48.398400&lon=9.591550 :param fileName:...
be54ab0dc3b9ec0a0f5462684f66d209e6e72728
17,755
def make_model(drc_csv: str, sat_tables: list, sector_info_csv: str, ia_tables=None, units_csv='', compartments_csv='', locations_csv='') -> model.Model: """ Creates a full EE-IO model with all information required for calculations, JSON-LD export, validation, etc. :param ...
f990f1617de29f75e4f86acc7647f7d9a06bfa53
17,756
def newNXentry(parent, name): """Create new NXentry group. Args: parent (h5py.File or h5py.Group): hdf5 file handle or group group (str): group name without extension (str) Returns: hdf5.Group: new NXentry group """ grp = parent.create_group(name) grp.attrs["NX_class"]...
1529fbe80ca8a23f8cd7717c5df5d7d239840149
17,757
from datetime import datetime def _build_europe_gas_day_tzinfo(): """ Build the Europe/Gas_Day based on the CET time. :raises ValueError: When something is wrong with the CET/CEST definition """ zone = 'Europe/Gas_Day' transitions = _get_transitions() transition_info_cet = _get_transition...
abc83bc3096c0dacfb7d9be88fdf4043ee328cf1
17,758
from typing import Set from typing import Optional from typing import List from typing import Dict def prepare_variants_relations_data( queryset: "QuerySet", fields: Set[str], attribute_ids: Optional[List[int]], warehouse_ids: Optional[List[int]], ) -> Dict[int, Dict[str, str]]: """Prepare data ab...
37c275898bb69fc61cbdddf2f4914ac77f22e7ed
17,759
import torch def vnorm(velocity, window_size): """ Normalize velocity with latest window data. - Note that std is not divided. Only subtract mean - data should have dimension 3. """ v = velocity N = v.shape[1] if v.dim() != 3: print("velocity's dim must be 3 for ba...
69f3c8cd6a5628d09a7fd78f3b5b779611a68411
17,760
import torch def valid_collate_fn(data): """Build mini-batch tensors from a list of (image, caption) tuples. Args: data: list of (image, caption) tuple. - image: torch tensor of shape (3, 256, 256). - caption: torch tensor of shape (?); variable length. Returns: im...
3eabc71d3ae68d4ca24d1a146be4fab8543c8566
17,761
def parse_statement(tokens): """ statement: | 'while' statement_list 'do' statement_list 'end' | 'while' statement_list 'do' 'end' | 'if' if_body | num_literal | string_literal | builtin | identifier """ if tokens.consume_maybe("while"): condition = parse_...
dfa26e4b834104a85b7266628fb6635c86e64b09
17,762
def vector_to_pytree_fun(func): """Make a pytree -> pytree function from a vector -> vector function.""" def wrapper(state): return func(Vector(state)).pytree return wrapper
79cc16c0e9187fc3bb944f40433ba1bd7850cb6e
17,763
def _filter_contacts(people_filter, maillist_filter, qs, values): """Helper for filtering based on subclassed contacts. Runs the filter on separately on each subclass (field defined by argument, the same values are used), then filters the queryset to only keep items that have matching. """ peop...
704396156370596433e78be1bb7bf5b4a77f284d
17,764
def viz_property(statement, properties): """Create properties for graphviz element""" if not properties: return statement + ";"; return statement + "[{}];".format(" ".join(properties))
518d4a662830737359a8b3cb9cec651394823785
17,765
def create_fsl_fnirt_nonlinear_reg(name='fsl_fnirt_nonlinear_reg'): """ Performs non-linear registration of an input file to a reference file using FSL FNIRT. Parameters ---------- name : string, optional Name of the workflow. Returns ------- nonlinear_register : nipype.pip...
dcb723e8fc33df2c8cc167c2bedc72f802d124c5
17,766
def _subspace_plot( inputs, output, *, input_names, output_name, scatter_args=None, histogram_args=None, min_output=None, max_output=None ): """ Do actual plotting """ if scatter_args is None: scatter_args = {} if histogram_args is None: histogram_args = {} if min_output ...
720092b24f1675f4f4c64c206cd7cad8b3a6dee6
17,767
import os import inspect def preload_template(fname, comment='#'): """Preloads a template from a file relative to the calling Python file.""" comment = comment.strip() if not os.path.isabs(fname): previous_frame = inspect.currentframe().f_back caller_fname, _, _, _, _ = inspect.getframein...
054d89ae06f3aa3c93fe72e3788ca750bc8578d4
17,768
import platform import subprocess import re def detect_windows_needs_driver(sd, print_reason=False): """detect if Windows user needs to install driver for a supported device""" need_to_install_driver = False if sd: system = platform.system() #print(f'in detect_windows_needs_driver system:...
52e681152442b27944396bf35d6a7c80a39b8639
17,769
def install_microcode_filter(*args): """ install_microcode_filter(filter, install=True) register/unregister non-standard microcode generator @param filter: - microcode generator object (C++: microcode_filter_t *) @param install: - TRUE - register the object, FALSE - unregister (C++: ...
e51c4f5bcc749692bd69c0d9024e6e004da9e9ac
17,770
def get_marvel_character_embed(attribution_text, result): """Parses a given JSON object that contains a result of a Marvel character and turns it into an Embed :param attribution_text: The attributions to give to Marvel for using the API :param result: A JSON object of a Marvel API call result :r...
ed315c2581de86f539c7a08ff6c37e9a889f2670
17,771
def get_or_create_dfp_targeting_key(name, key_type='FREEFORM'): """ Get or create a custom targeting key by name. Args: name (str) Returns: an integer: the ID of the targeting key """ key_id = dfp.get_custom_targeting.get_key_id_by_name(name) if key_id is None: key_id = dfp.create_custom_targ...
36211d5a383d54fde3e42d30d81778008343c676
17,772
def positive(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in positive") return Array._new(np.positive(x...
2caa9b1714c549e390dba494a748aa86d5077d67
17,773
import csv def read_loss_file(path): """Read the given loss csv file and process its data into lists that can be plotted by matplotlib. Args: path (string): The path to the file to be read. Returns: A list of lists, one list for each subnetwork containing the loss values over ti...
8e861f0bf46db5085ea2f30a7e70a4bdfa0b9697
17,774
from typing import Union def number2human(n: Union[int, float]) -> str: """ Format large number into readable string for a human Examples: >>> number2human(1000) '1.0K' >>> number2human(1200000) '1.2M' """ # http://code.activestate.com/recipes/578019 # >>> by...
26e99ca6b3cf51bf554018e1c97a1c8bebd51811
17,775
def binomial_confidence_interval(successes, trials, error_rate): """Computes a confidence interval on the true p of a binomial. Assumes: - The given `successes` count outcomes of an iid Bernoulli trial with unknown probability p, that was repeated `trials` times. Guarantees: - The probability (over the ...
03caf19e30a4b280c6b060b7ba4b1166b526feec
17,776
def try_parse_func_decl(start, end): """Parse a function declarator between start and end. Expects that tokens[end-1] is a close parenthesis. If a function declarator is successfully parsed, returns the decl_node.Function object. Otherwise, returns None. """ open_paren = find_pair_backward(end ...
1bcdce513fdaf6e28e034ba1578bd271a00c31a5
17,777
import contextlib def eth_getBlockTransactionCountByNumber(block_number: int) -> int: """ See EthereumAPI#get_block_transaction_count_by_number. """ with contextlib.closing(EthereumAPI()) as api: return api.get_block_transaction_count_by_number(block_number)
d4fbd368bb49854ceee589ba20c956275ece95c6
17,778
from typing import List from typing import Any from typing import NamedTuple def day(db: Database, site: str = 'test', tag: str = '', search_body: str = '') -> List[Any]: """ 戻り値 名前付きタプルのリスト # xxx List[DayCount] するにはclass DayCount(NamedTuple) 必要 pypy… """ tag_where = '' body_where = '' param = [site] # type: L...
c60a4a8aabc546a2dc7b412d73c1d0a97d7ccc25
17,779
import os def xml_files_list(path): """ Return the XML files found in `path` """ return (f for f in os.listdir(path) if f.endswith(".xml"))
27cc2769e34f55263c60ba07a92e181bfec641ab
17,780
import math def ppv2( aim_stars=None, speed_stars=None, max_combo=None, nsliders=None, ncircles=None, nobjects=None, base_ar=5.0, base_od=5.0, mode=MODE_STD, mods=MODS_NOMOD, combo=None, n300=None, n100=0, n50=0, nmiss=0, score_version=1, bmap=None ): """ calculates ppv2 returns (pp, aim_...
c4cc793b7eb2acc45ca83762f946a476452a5e34
17,781
import os def frame_shows_car(base_dir, frame, data_dir): """Return True if frame shows car. """ sem_seg = cv2.imread(os.path.join(base_dir, "semantic_segmentation/semantic_segmentation" + str(frame) + ".png"), -1) class_id_dict = pre_processing.get_dict_from_file(data_dir, "class...
0759b556f6b985a7aca8384d7071a38ee387e190
17,782
def p_portail_home(request): """ Portail d'accueil de CRUDY """ crudy = Crudy(request, "portail") title = crudy.application["title"] crudy.folder_id = None crudy.layout = "portail" return render(request, 'p_portail_home.html', locals())
a883cafd84b1ce24ead37ebbe6c0e3a15ea476c6
17,783
import os def generate_image_list(dir_path, max_dataset_size=float("inf")): """ Traverse the directory to generate a list of images path. Args: dir_path (str): image directory. max_dataset_size (int): Maximum number of return image paths. Returns: Image path list. """ ...
b92efed79dd9c0904c01d4ffa21ec30f7da57bd7
17,784
def A_norm(freqs,eta): """Calculates the constant scaling factor A_0 Parameters ---------- freqs : array The frequencies in Natural units (Mf, G=c=1) of the waveform eta : float The reduced mass ratio """ const = np.sqrt(2*eta/3/np.pi**(1/3)) return const*freqs**-(7/6)
74947e34efd7b6b0bb31aac35c9932623d4a28aa
17,785
from typing import IO from typing import Counter from operator import sub def task1(input_io: IO) -> int: """ Solve task 1. Parameters ---------- input_io: IO Day10 stream of adapters joltage. Return ------ int number of differentes of 1 times number of diferences...
b566a79013f442b7216118458958212186e57f07
17,786
import json import logging import sys def get_logger(name, log_dir, config_dir): """ Creates a logger object Parameters ---------- name: Name of the logger file log_dir: Directory where logger file needs to be stored config_dir: Directory from where log_config.json needs to be read Ret...
511623057b7e98adbaea628d495afee4c217fcb1
17,787
def get_total_balance(view_currency='BTC') -> float: """ Shows total balance for account in chosen currency :param view_currency: currency for total balance :return: total balance amount for account """ result = pay.get_balance() balance_dict = result.get('balance') total = 0 for cur...
9e595eceac7df63779cd8c8e6d155092ec76a36e
17,788
import binascii def bin_hex(binary): """ Convert bytes32 to string Parameters ---------- input: bytes object Returns ------- str """ return binascii.hexlify(binary).decode('utf-8')
41f9c8a498aa3628f64cf59c93896f42d8dfd56a
17,789
def build_format(name: str, pattern: str, label: bool) -> str: """Create snippet format. :param name: Instruction name :param pattern: Instruction regex pattern """ snip: str = f"{name:7s}" + pattern.format(**SNIPPET_REPLACEMENTS) snip = snip.replace("(", "") snip = snip.replace(")", "") ...
ec25ecf4f2d46db398c389b479620e0cbcf30ee2
17,790
import torch def make_observation_mapper(claims): """Make a dictionary of observation. Parameters ---------- claims: pd.DataFrame Returns ------- observation_mapper: dict an dictionary that map rv to their observed value """ observation_mapper = dict() for c in...
43052bd9ce5e1121f3ed144ec48acf20ad117313
17,791
def toCSV( dataset, # type: BasicDataset showHeaders=True, # type: Optional[bool] forExport=False, # type: Optional[bool] localized=False, # type: Optional[bool] ): # type: (...) -> String """Formats the contents of a dataset as CSV (comma separated values), returning the resulting CSV a...
9d998891a9712f42af8744513c1f61540eee0e2e
17,792
def add_record(session, data): """ session - data - dictionary {"site":"Warsaw"} """ skeleton = Skeleton() skeleton.site = data["site"] skeleton.location = data["location"] skeleton.skeleton = data["skeleton"] skeleton.observer = data["observer"] skeleton.obs_date = data["obs_dat...
f91df4459b37b7df4d313fd01323451bf897a754
17,793
def hue_angle(C): """ Returns the *hue* angle :math:`h` in degrees from given colour difference signals :math:`C`. Parameters ---------- C : array_like Colour difference signals :math:`C`. Returns ------- numeric or ndarray *Hue* angle :math:`h` in degrees. Exa...
599f594eff92280df06a4c6ef88ccf286f146475
17,794
def get_submodel_list_copasi(model_name: str, model_info: pd.DataFrame): """ This function loads a list of Copasi model files, which all belong to the same benchmark model, if a string with the id of the benchmark model id is provided. It also extracts the respective sbm...
ea889e5ea836131d8febc94dd69806b2acf47559
17,795
def GetNextBmask(enum_id, value): """ Get next bitmask in the enum (bitfield) @param enum_id: id of enum @param value: value of the current bitmask @return: value of a bitmask with value higher than the specified value. -1 if no such bitmasks exist. All bitmasks are so...
d2c415e1a3ad63c651dc2df771dbe43a082613d9
17,796
def annotate_link(domain): """This function is called by the url tag. Override to disable or change behaviour. domain -- Domain parsed from url """ return u" [%s]"%_escape(domain)
26b5c8979cc8cd7f581a7ff889a907cf71844c72
17,797
def kmeans(data, k, num_iterations, num_inits=10, verbose=False): """Execute the k-means algorithm for determining the best k clusters of data points in a dataset. Parameters ---------- data : ndarray, (n,d) n data points in R^d. k : int The number of clusters to separat...
3cc3681ac0d0306fc7dce2da5757e6c162f7c457
17,798
def point_on_bezier_curve(cpw, n, u): """ Compute point on Bezier curve. :param ndarray cpw: Control points. :param int n: Degree. :param u: Parametric point (0 <= u <= 1). :return: Point on Bezier curve. :rtype: ndarray *Reference:* Algorithm A1.4 from "The NURBS Book". """ b...
3e4a494ff9ffabf6ad0d2711beba0e55647e7071
17,799