content
stringlengths
22
815k
id
int64
0
4.91M
def binary_get_bucket_for_node(buckets: List[KBucket], node: Node) -> KBucket: """Given a list of ordered buckets, returns the bucket for a given node.""" bucket_ends = [bucket.end for bucket in buckets] bucket_position = bisect.bisect_left(bucket_ends, node.id) # Prevents edge cases where bisect_left r...
5,336,000
def trajectory(identifier,x,y,path_save): """ Returns the trajectory of Identifier""" plt.figure() plt.plot(x, y, '.-') plt.plot(x[0], y[0], 'ro') plt.plot(x[-1], y[-1], 'go') plt.grid() plt.xlabel("x meters") plt.ylabel("y meters") plt.legend(['Trayectory','Initial Point','Final Poi...
5,336,001
def darken(color, factor=0.7): """Return darkened color as a ReportLab RGB color. Take a passed color and returns a Reportlab color that is darker by the factor indicated in the parameter. """ newcol = color_to_reportlab(color) for a in ["red", "green", "blue"]: setattr(newcol, a, facto...
5,336,002
def load_experiments(uuid_list, db_root, dbid): # pragma: io """Generator to load the results of the experiments. Parameters ---------- uuid_list : list(uuid.UUID) List of UUIDs corresponding to experiments to load. db_root : str Root location for data store as requested by the ser...
5,336,003
def fetch_all_tiles(session): """Fetch all tiles.""" return session.query(Tile).all()
5,336,004
def transaction_update_spents(txs, address): """ Update spent information for list of transactions for a specific address. This method assumes the list of transaction complete and up-to-date. This methods loops through all the transaction and update all transaction outputs for given address, checks ...
5,336,005
def count_tilings(n: int) -> int: """Returns the number of unique ways to tile a row of length n >= 1.""" if n < 5: # handle recursive base case return 2**(n - 1) else: # place each tile at end of row and recurse on remainder return (count_tilings(n - 1) + cou...
5,336,006
def _meters_per_pixel(zoom, lat=0.0, tilesize=256): """ Return the pixel resolution for a given mercator tile zoom and lattitude. Parameters ---------- zoom: int Mercator zoom level lat: float, optional Latitude in decimal degree (default: 0) tilesize: int, optional ...
5,336,007
def _generate_submit_id(): """Generates a submit id in form of <timestamp>-##### where ##### are 5 random digits.""" timestamp = int(time()) return "%d-%05d" % (timestamp, random.randint(0, 99999))
5,336,008
def draw_from_simplex(ndim: int, nsample: int = 1) -> np.ndarray: """Draw uniformly from an n-dimensional simplex. Args: ndim: Dimensionality of simplex to draw from. nsample: Number of samples to draw from the simplex. Returns: A matrix of shape (nsample, ndim) that sums to one al...
5,336,009
def py2melProc(function, returnType='None', procName='None', evaluateInputs='True', argTypes='None'): """ This is a work in progress. It generates and sources a mel procedure which wraps the passed python function. Theoretically useful for calling your python scripts in scenarios where Maya does not y...
5,336,010
def test_download_tile(): """ Tests the download_tile function. Tests the download_tile function which is supposed to return a base64 string when the as_base64 argument is set to true. We don't actually test the values of this function because it scales down dynamically based on the availability of...
5,336,011
def manhattanDistance( xy1, xy2 ): """Returns the Manhattan distance between points xy1 and xy2""" return abs( xy1[0] - xy2[0] ) + abs( xy1[1] - xy2[1] )
5,336,012
def delete_policy_command(): """ Command to delete an existing policy in Symantec MC :return: An entry indicating whether the deletion was successful """ uuid = demisto.args()['uuid'] force = demisto.args().get('force') delete_policy_request(uuid, force) return_outputs('Policy d...
5,336,013
def Linear(in_features, out_features, dropout=0.0, bias=True): """Weight-normalized Linear layer (input: B x T x C)""" m = nn.Linear(in_features, out_features, bias=bias) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return nn.utils.weight_norm(m)
5,336,014
def download_and_save_DistilBERT_model(name): """Download and save DistilBERT transformer model to MODELS_DIR""" print(f"Downloading: {name}") try: os.makedirs(MODELS_DIR + f"{name}") except FileExistsError as _e: pass model = DistilBertForQuestionAnswering.from_pretrained(f"{name}")...
5,336,015
def homogeneous_type(obj): """ Checks that the type is "homogeneous" in that all lists are of objects of the same type, etc. """ return same_types(obj, obj)
5,336,016
def crosscorr(f, g): """ Takes two vectors of the same size, subtracts the vector elements by their respective means, and passes one over the other to construct a cross-correlation vector """ N = len(f) r = np.array([], dtype=np.single) r1 = np.array([], dtype=np.single) r2 = np.arr...
5,336,017
def serialize_event(event): """ Serialization of Weboob ``BaseCalendarEvent`` object to schema.org representation. :param event: The Weboob ``BaseCalendarEvent`` object to serialize. """ serialized = { '@type': 'Event', '@context': 'http://schema.org/', 'identifier': eve...
5,336,018
def nearest_neighbors(point_cloud_A, point_cloud_B, alg='knn'): """Find the nearest (Euclidean) neighbor in point_cloud_B (model) for each point in point_cloud_A (data). Parameters ---------- point_cloud_A: Nx3 numpy array data points point_cloud_B: Mx3 numpy array model points ...
5,336,019
def ialign(images, reference=None, mask=None, fill_value=0.0, fast=True): """ Generator of aligned diffraction images. Parameters ---------- images : iterable Iterable of ndarrays of shape (N,M) reference : `~numpy.ndarray`, shape (M,N) Images in `images` will be aligned onto th...
5,336,020
def us_1040(form_values, year="latest"): """Compute US federal tax return.""" _dispatch = { "latest": (ots_2020.us_main, data.US_1040_2020), "2020": (ots_2020.us_main, data.US_1040_2020), "2019": (ots_2019.us_main, data.US_1040_2019), "2018": (ots_2018.us_main, data.US_1040_2018)...
5,336,021
def resolve_service_deps(services: list) -> dict: """loop through services and handle needed_by""" needed_by = {} for name in services: service = services.get(name) needs = service.get_tasks_needed_by() for need, provides in needs.items(): needed_by[need] = list(set(neede...
5,336,022
def rolling_window(series, window_size): """ Transforms an array of series into an array of sliding window arrays. If the passed in series is a matrix, each column will be transformed into an array of sliding windows. """ return np.array( [ series[i : (i + window_size)] ...
5,336,023
def reply_published_cb(sender, user, reply, trivial, **kwargs): """Send e-mail when a review reply is published. Listens to the :py:data:`~reviewboard.reviews.signals.reply_published` signal and sends an e-mail if this type of notification is enabled (through ``mail_send_review_mail`` site configuratio...
5,336,024
def ldns_key_set_inception(*args): """LDNS buffer.""" return _ldns.ldns_key_set_inception(*args)
5,336,025
def verifyIP(ip): """Verifies an IP is valid""" try: #Split ip and integer-ize it octets = [int(x) for x in ip.split('.')] except ValueError: return False #First verify length if len(octets) != 4: return False #Then check octet values for octet in octets: if octet < 0 or octet >...
5,336,026
def test_fixtures1(testapp): """ This test is not really exhaustive. Still need to inspect the sql log to verify fixture correctness. """ res = testapp.get('/awards').maybe_follow() items = res.json['@graph'] assert len(items) == 1 # Trigger an error item = {'foo': 'bar'} res = tes...
5,336,027
def bayesdb_deregister_backend(bdb, backend): """Deregister `backend`, which must have been registered in `bdb`.""" name = backend.name() assert name in bdb.backends assert bdb.backends[name] == backend del bdb.backends[name]
5,336,028
def get_datetime_now(t=None, fmt='%Y_%m%d_%H%M_%S'): """Return timestamp as a string; default: current time, format: YYYY_DDMM_hhmm_ss.""" if t is None: t = datetime.now() return t.strftime(fmt)
5,336,029
def is_firstline(text, medicine, disease): """Detect if first-line treatment is mentioned with a medicine in a sentence. Use keyword matching to detect if the keywords "first-line treatment" or "first-or second-line treatment", medicine name, and disease name all appear in the sentence. Parameters ---------- ...
5,336,030
def mac_address(addr): """ mac_address checks that a given string is in MAC address format """ mac = addr.upper() if not _mac_address_pattern.fullmatch(mac): raise TypeError('{} does not match a MAC address pattern'.format(addr)) return mac
5,336,031
def savez(d,filepath): """ Save a sparse matrix to file in numpy binary format. Parameters ---------- d : scipy sparse matrix The sparse matrix to save. filepath : str The filepath to write to. """ np.savez(filepath,row=d.row,col=d.col,data=d.data,shape=d.shape)
5,336,032
def py3_classifiers(): """Fetch the Python 3-related trove classifiers.""" url = 'https://pypi.python.org/pypi?%3Aaction=list_classifiers' response = urllib_request.urlopen(url) try: try: status = response.status except AttributeError: #pragma: no cover status = ...
5,336,033
def match(i, j): """ returns (red, white) count, where red is matches in color and position, and white is a match in color but not position """ red_count = 0 # these are counts only of the items that are not exact matches i_colors = [0]*6 j_colors = [0]*6 for i_c, j_c in zip(c...
5,336,034
def main(): """Do Something""" form = cgi.FieldStorage() vote = form.getfirst('vote', 'missing') ssw("Content-type: application/json\n") j = do(vote) ssw("\n") # Finalize headers ssw(json.dumps(j))
5,336,035
def time_delay_runge_kutta_4(fun, t_0, y_0, tau, history=None, steps=1000, width=1): """ apply the classic Runge Kutta method to a time delay differential equation f: t, y(t), y(t-tau) -> y'(t) """ width = float(width) if not isinstance(y_0, np.ndarray): y_0...
5,336,036
def Vstagger_to_mass(V): """ V are the data on the top and bottom of a grid box A simple conversion of the V stagger grid to the mass points. Calculates the average of the top and bottom value of a grid box. Looping over all rows reduces the staggered grid to the same dimensions as the mass poin...
5,336,037
def verify_l4_block_pow(hash_type: SupportedHashes, block: "l4_block_model.L4BlockModel", complexity: int = 8) -> bool: """Verify a level 4 block with proof of work scheme Args: hash_type: SupportedHashes enum type block: L4BlockModel with appropriate data to verify Returns: Boolean ...
5,336,038
def test_add_theme(test_client, sample_data): """ GIVEN a project WHEN add theme is called THEN the theme should appear in the get tasks reponse for that project """ theme_data = { 'project_id': 1, 'title': 'test theme' } r = test_client.post('/add_theme', json=theme_data) r2 = test_client.get(f'/get_tasks?p...
5,336,039
def Run(): """Does coverage operations based on command line args.""" # TODO: do we want to support combining coverage for a single target try: parser = optparse.OptionParser(usage="usage: %prog --combine-coverage") parser.add_option( "-c", "--combine-coverage", dest="combine_coverage", default=F...
5,336,040
def report_reply(report_id): """ Replies to an existing report. The email reply is constructed and sent to the email address that original reported the phish. Args: report_id - str - The urlsafe key for the EmailReport TODO: Make this a nice template or something """ report = Email...
5,336,041
def file_reader(file_name): """file_reader""" data = None with open(file_name, "r") as f: for line in f.readlines(): data = eval(line) f.close() return data
5,336,042
def train(model, data, params): """ Trains a model. Inputs: model (ATISModel): The model to train. data (ATISData): The data that is used to train. params (namespace): Training parameters. """ # Get the training batches. log = Logger(os.path.join(params.logdir, params.logfil...
5,336,043
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ account = model.authenticate(username, password) if account is None: return AuthResponse.no_account if not model.hasAssignedBlock(account): return AuthRespon...
5,336,044
def plot_energy_ratio( reference_power_baseline, test_power_baseline, wind_speed_array_baseline, wind_direction_array_baseline, reference_power_controlled, test_power_controlled, wind_speed_array_controlled, wind_direction_array_controlled, wind_direction_bins, confidence=95, ...
5,336,045
def dir_is_cachedir(path): """Determines whether the specified path is a cache directory (and therefore should potentially be excluded from the backup) according to the CACHEDIR.TAG protocol (http://www.brynosaurus.com/cachedir/spec.html). """ tag_contents = b'Signature: 8a477f597d28d172789f068...
5,336,046
def update_programmer_menu(arduino_info): """.""" programmer_names = arduino_info['programmers'].get('names', []) text = '\t' * 0 + '[\n' text += '\t' * 1 + '{\n' text += '\t' * 2 + '"caption": "Arduino",\n' text += '\t' * 2 + '"mnemonic": "A",\n' text += '\t' * 2 + '"id": "arduino",\n' ...
5,336,047
def first_position(): """Sets up two positions in the Upper left .X.Xo. X.Xoo. XXX... ...... Lower right ...... ..oooo .oooXX .oXXX. (X = black, o = white) They do not overlap as the Positions are size_limit 9 or greater. """ def position_moves(s): re...
5,336,048
def _create_teams( pool: pd.DataFrame, n_iterations: int = 500, n_teams: int = 10, n_players: int = 10, probcol: str = 'probs' ) -> np.ndarray: """Creates initial set of teams Returns: np.ndarray of shape axis 0 - number of iterations ...
5,336,049
def add_logger_filehandler(logger, filepath): """Adds additional file handler to the logger Args: logger: logger from `logging` module filepath: output logging file """ # create file handler which logs even debug messages fh = logging.FileHandler(filepath) fh.setLevel(logger.le...
5,336,050
def calculate_magnitude(data: np.ndarray) -> np.ndarray: """Calculates the magnitude for given (x,y,z) axes stored in numpy array""" assert data.shape[1] == 3, f"Numpy array should have 3 axes, got {data.shape[1]}" return np.sqrt(np.square(data).sum(axis=1))
5,336,051
def clean_str(string: str) -> str: """ Cleans strings for SQL insertion """ return string.replace('\n', ' ').replace("'", "’")
5,336,052
def _main() -> None: """urlretriveの進捗表示にtqdmを利用する。 Note: - 参考文献: tqdm – PythonとCLIの高速で拡張できるプログレスバー: `https://githubja.com/tqdm/tqdm` """ URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/00264/EEG%20Eye%20State.arff" with TqdmUpTo(unit="B", unit_scale=True, miniters=1, desc=UR...
5,336,053
def zeros(shape, name=None): """All zeros.""" return tf.get_variable(name=name, shape=shape, dtype=tf.float32, initializer=tf.zeros_initializer())
5,336,054
def test_julia_single_output_cpu_reducesum(): """ Feature: custom julia operator, multiple inputs, single output, CPU, GRAPH_MODE Description: pre-write xxx.jl, custom operator launches xxx.jl Expectation: nn result matches numpy result """ system = platform.system() if system != 'Linux': ...
5,336,055
def test_wf_ndstate_cachelocations_updatespl(plugin, tmpdir): """ Two wfs with identical inputs and node state (that is set after adding the node!); the second wf has cache_locations and should not recompute the results """ cache_dir1 = tmpdir.mkdir("test_wf_cache3") cache_dir2 = tmpdir.mkdir("t...
5,336,056
def parseTemplate(bStream): """Parse the Template in current byte stream, it terminates when meets an object. :param bStream: Byte stream :return: The template. """ template = Template() eof = endPos(bStream) while True: currPos = bStream.tell() if currPos <eof: d...
5,336,057
def explode(req: str): """Returns the exploded dependency list for a requirements file. As requirements files can include other requirements files with the -r directive, it can be useful to see a flattened version of all the constraints. This method unrolls a requirement file and produces a list of str...
5,336,058
def test_account_purchase_history_default_list(session, client, jwt, app): """Assert that the endpoint returns 200.""" token = jwt.create_jwt(get_claims(), token_header) headers = {'Authorization': f'Bearer {token}', 'content-type': 'application/json'} # Create 11 payments for i in range(11): ...
5,336,059
def plot_word_wpm_distribution(word_speeds, filter_func=lambda c: True): """Plots a distribution over average speeds of unique words.""" df = pd.read_csv( word_speeds, header=None, names=["word", "duration", "wpm", "timestamp"] ) gdf = list(filter(lambda t: filter_func(t[0]), df.groupby(["word"...
5,336,060
def run1b(): """Run the Task2B program""" # Initialize stations = build_station_list() # stations: [(name, ...), (), ...] centre = (52.2053, 0.1218) distance_sort_list = stations_by_distance(stations, centre) # Build dictionary that maps station to town name_town_dict = {} for sta...
5,336,061
def draw_lidar( pc, color=None, fig=None, bgcolor=(0, 0, 0), pts_scale=0.3, pts_mode="sphere", pts_color=None, color_by_intensity=False, pc_label=False, pc_range=[], ): """ Draw lidar points Args: pc: numpy array (n,3) of XYZ color: numpy array (n) of inte...
5,336,062
def load_circuit(filename:str): """ Reads a MNSensitivity cicuit file (.mc) and returns a Circuit list (format is 1D array of tuples, the first element contains a Component object, the 2nd a SER/PAL string). Format of the .mc file is: * each line contains a Component object init string (See Com...
5,336,063
def get_output_attribute(out, attribute_name, cuda_device, reduction="sum"): """ This function handles processing/reduction of output for both DataParallel or non-DataParallel situations. For the case of multiple GPUs, This function will sum all values for a certain output attribute in various batch...
5,336,064
def get_ref_aidxs(df_fs): """Part of the hotfix for redundant FCGs. I did not record the occurrence id in the graphs, which was stupid. So now I need to use the df_fs to get the information instead. Needs to be used with fid col, which is defined in filter_out_fcgs_ffs_all. """ return {k: v for ...
5,336,065
def set_clear_color(color='black'): """Set the screen clear color This is a wrapper for gl.glClearColor. Parameters ---------- color : str | tuple | instance of Color Color to use. See vispy.color.Color for options. """ gl.glClearColor(*Color(color).rgba)
5,336,066
def format_info(info): """ Print info neatly """ sec_width = 64 eq = ' = ' # find key width key_widths = [] for section, properties in info.items(): for prop_key, prop_val in properties.items(): if type(prop_val) is dict: key_widths.append(len(max(list(p...
5,336,067
def server_handle_hallu_message( msg_output, controller, mi_info, options, curr_iter): """ Petridish server handles the return message of a forked process that watches over a halluciniation job. """ log_dir_root = logger.get_logger_dir() q_child = controller.q_child model_str, model_...
5,336,068
def logger(status=False, perf_time=None): """Show the log of the app :param status: show status of app. :param perf_time : show the time passed for generate files """ file = open("build_log.txt", "a") if not status: file.write("Failed " + str(datetime.datetime.now()) + "\n") else: ...
5,336,069
def pBottleneckSparse_model(inputs, train=True, norm=True, **kwargs): """ A pooled shallow bottleneck convolutional autoencoder model.. """ # propagate input targets outputs = inputs # dropout = .5 if train else None input_to_network = inputs['images'] shape = input_to_network.g...
5,336,070
def CoarseDropout(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False, random_state=None, mask=None): """ Augmenter that sets rectangular areas within images to zero. In contrast to Dropout, these areas can have larger sizes. (E.g. you m...
5,336,071
def main(): """ The whole sett-up. Here everything is called. """ wn = turtle.Screen() ourTurtle = turtle.Turtle() size = 600 # width is 90% of screen, height is 80% of screen. Screen appears at the center of screen wn.setup(width=0.9, height=0.9, startx=None, starty=None) ourTurtl...
5,336,072
def chenneling(x): """ This function makes the dataset suitable for training. Especially, gray scale image does not have channel information. This function forces one channel to be created for gray scale images. """ # if grayscale image if(len(x.shape) == 3): C = 1 N, H, W =...
5,336,073
def _get_ordered_label_map(label_map): """Gets label_map as an OrderedDict instance with ids sorted.""" if not label_map: return label_map ordered_label_map = collections.OrderedDict() for idx in sorted(label_map.keys()): ordered_label_map[idx] = label_map[idx] return ordered_label_map
5,336,074
def eight_interp(x, a0, a1, a2, a3, a4, a5, a6, a7): """``Approximation degree = 8`` """ return ( a0 + a1 * x + a2 * (x ** 2) + a3 * (x ** 3) + a4 * (x ** 4) + a5 * (x ** 5) + a6 * (x ** 6) + a7 * (x ** 7) )
5,336,075
def create_ec2_instance(image_id, instance_type, keypair_name, user_data): """Provision and launch an EC2 instance The method returns without waiting for the instance to reach a running state. :param image_id: ID of AMI to launch, such as 'ami-XXXX' :param instance_type: string, such as 't2.micro'...
5,336,076
def get_pop(state): """Returns the population of the passed in state Args: - state: state in which to get the population """ abbrev = get_abbrev(state) return int(us_areas[abbrev][1]) if abbrev != '' else -1
5,336,077
def GitHub_post(data, url, *, headers): """ POST the data ``data`` to GitHub. Returns the json response from the server, or raises on error status. """ r = requests.post(url, headers=headers, data=json.dumps(data)) GitHub_raise_for_status(r) return r.json()
5,336,078
def subsample(inputs, factor, scope=None): """Subsample the input along the spatial dimensions. Args: inputs: A `Tensor` of size [batch, height_in, width_in, channels]. factor: The subsampling factor. scope: Optional variable_scope. Returns: output: A `Tensor` of size [batc...
5,336,079
def password_reset(*args, **kwargs): """ Override view to use a custom Form """ kwargs['password_reset_form'] = PasswordResetFormAccounts return password_reset_base(*args, **kwargs)
5,336,080
def update_tab_six_two( var, time_filter, month, hour, data_filter, filter_var, min_val, max_val, normalize, global_local, df, ): """Update the contents of tab size. Passing in the info from the dropdown and the general info.""" df = pd.read_json(df, orient="split") ...
5,336,081
async def blog_api(request: Request, year: int, month: int, day: int, title: str) -> json: """Handle blog.""" blog_date = {"year": year, "month": month, "day": day} req_blog = app.blog.get(xxh64(unquote(title)).hexdigest()) if req_blog: if all( map(lambda x: re...
5,336,082
def coherence_score_umass(X, inv_vocabulary, top_words, normalized=False): """ Extrinsic UMass coherence measure Parameter ---------- X : array-like, shape=(n_samples, n_features) Document word matrix. inv_vocabulary: dict Dictionary of index and vocabulary from vectorizer. ...
5,336,083
def quiz_f(teq): """ Function to fill in the blank quiz Params: teq: dict """ # Init LED happy image display.show(Image.HAPPY) # This is an advanced topic as well however this little function # cleans out the unnecessary global objects or variables on what # we cal...
5,336,084
def _splitaddr(addr): """ splits address into character and decimal :param addr: :return: """ col='';rown=0 for i in range(len(addr)): if addr[i].isdigit(): col = addr[:i] rown = int(addr[i:]) break elif i==len(addr)-1: col=addr...
5,336,085
def checksum(data): """ :return: int """ assert isinstance(data, bytes) assert len(data) >= MINIMUM_MESSAGE_SIZE - 2 assert len(data) <= MAXIMUM_MESSAGE_SIZE - 2 __checksum = 0 for data_byte in data: __checksum += data_byte __checksum = -(__checksum % 256) + 256 try: ...
5,336,086
def as_character( x, str_dtype=str, _na=np.nan, ): """Convert an object or elements of an iterable into string Aliases `as_str` and `as_string` Args: x: The object str_dtype: The string dtype to convert to _na: How NAs should be casted. Specify np.nan will keep them unc...
5,336,087
def test_logger(request: HttpRequest) -> HttpResponse: """ Generate a log to test logging setup. Use a GET parameter to specify level, default to INFO if absent. Value can be INFO, WARNING, ERROR, EXCEPTION, UNCATCHED_EXCEPTION. Use a GET parameter to specify message, default to "Test logger" ...
5,336,088
def cvm_informes (year: int, mth: int) -> pd.DataFrame: """Downloads the daily report (informe diario) from CVM for a given month and year\n <b>Parameters:</b>\n year (int): The year of the report the function should download\n mth (int): The month of the report the function should download\n <b>R...
5,336,089
def remoteness(N): """ Compute the remoteness of N. Parameters ---------- N : Nimber The nimber of interest. Returns ------- remote : int The remoteness of N. """ if N.n == 0: return 0 remotes = {remoteness(n) for n in N.left} if all(remote % 2...
5,336,090
def breakfast_analysis_variability(in_path,identifier, date_col, time_col, min_log_num=2, min_separation=4, plot=True): """ Description:\n This function calculates the variability of loggings in good logging day by subtracting 5%,10%,25%,50%,75%,90%,95% quantile of breakfast time from the 50% breakfast t...
5,336,091
def _sdss_wcs_to_log_wcs(old_wcs): """ The WCS in the SDSS files does not appear to follow the WCS standard - it claims to be linear, but is logarithmic in base-10. The wavelength is given by: λ = 10^(w0 + w1 * i) with i being the pixel index starting from 0. The FITS standard uses a natura...
5,336,092
def request_records(request): """show the datacap request records""" address = request.POST.get('address') page_index = request.POST.get('page_index', '1') page_size = request.POST.get('page_size', '5') page_size = interface.handle_page(page_size, 5) page_index = interface.handle_page(page_index...
5,336,093
def custom_db(app, CustomMetadata): """Database fixture.""" InvenioDB(app) if not database_exists(str(db_.engine.url)): create_database(str(db_.engine.url)) db_.create_all() yield db_ db_.session.remove() db_.drop_all()
5,336,094
def extendCorrespondingAtomsDictionary(names, str1, str2): """ extends the pairs based on list1 & list2 """ list1 = str1.split() list2 = str2.split() for i in range(1, len(list1)): names[list1[0]][list2[0]].append([list1[i], list2[i]]) names[list2[0]][list1[0]].append([list2[i], list...
5,336,095
def _device_name(data): """Return name of device tracker.""" if ATTR_BEACON_ID in data: return "{}_{}".format(BEACON_DEV_PREFIX, data['name']) return data['device']
5,336,096
def get_share_path( storage_server: StorageServer, storage_index: bytes, sharenum: int ) -> FilePath: """ Get the path to the given storage server's storage for the given share. """ return ( FilePath(storage_server.sharedir) .preauthChild(storage_index_to_dir(storage_index)) ...
5,336,097
def focal_loss_with_prob(prob, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): """A variant of Focal Loss used in TOOD.""" target_one_hot = prob.new_zeros(len(prob), len(prob[0]) + 1) target_one_hot = target_one_hot.scatter_(1, target.unsqueez...
5,336,098
def root_key_from_seed(seed): """This derives your master key the given seed. Implemented in ripple-lib as ``Seed.prototype.get_key``, and further is described here: https://ripple.com/wiki/Account_Family#Root_Key_.28GenerateRootDeterministicKey.29 """ seq = 0 while True: private_ge...
5,336,099