content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def decode_seat_string(seat): """ Test data BFFFBBFRRR: row 70, column 7, seat ID 567. FFFBBBFRRR: row 14, column 7, seat ID 119. BBFFBBFRLL: row 102, column 4, seat ID 820. Seat string is 10 bits binary B = 1 F = 0 R = 1 L = 0 """ bin_seat_number = seat.replace('B', '...
8de3852c2fa3c22c5b1f70b898bf0390365f0e51
627,401
def identifying_col_pos_ele(ip_1): """ The task of this function is to identify the coloured elements position ,column value holding the element and sublists where the elements are present Arguments: sublist_seq- A sublist of input grid. Return:Position of coloured elements present in each sublist, Va...
99466b45720f13103b8ad0d4604adf4475a4712a
627,402
import string import numpy as np import pandas as pd def letters_to_hours_and_vice_verse(symbol): """A - 0 hours, B- 1 hours, until X = 23 hours""" hour_letters = [x.upper() for x in string.ascii_letters][:24] hour_numbers = np.arange(0, 24) hour_string_dict = dict(zip(hour_letters, hour_numbers)) ...
dac5d6947b2c3ef7a16e843165b49c23e596e049
627,403
def time2levels(tstamp): """Given a :class:`datetime.datetime` object, return a list of directory levels (as strings). For example, given "2013-09-08 13:01:44", return ['2013', '09', '08', '13', '01'] """ return [tstamp.strftime(xx) for xx in ('%Y', '%m', '%d', '%H', '%M')]
d4e83672b9dd613f16f1b34a4103584413621e09
627,405
import tempfile import csv import sys def csvsplit(reader, max_size): """Split into smaller CSV files of maximum size and return the filenames. """ max_size = max_size * 1024 * 1024 # convert to bytes writer = None current_size = 0 split_filenames = [] # break CSV file into smaller merge...
89612b11d1647d295907d0320c40608866291c00
627,406
def generate_fiscal_period(context): """ Generate fiscal period based on the date provided """ reporting_end_date = context.current_parameters['reporting_end_date'] period = 0 if reporting_end_date: period = (reporting_end_date.month + 3) % 12 period = 12 if period == 0 else period r...
f7c8be1bec930a4d73fda8a1d48c60637aa28f7c
627,407
def github_2fa_callback(): """ Prompt for two-factor code """ # http://github3py.readthedocs.org/en/master/examples/two_factor_auth.html code = '' while not code: # The user could accidentally press Enter before being ready, # let's protect them from doing that. code = in...
5daf77457e1be30a7f21fd379ebd72d0ad940f46
627,408
def create_ngrams(corpus_tokens, n): """Funktion, die aus den gegebenen Token saemtliche Ngramme der Laenge n extrahiert und in einer Liste speichert. Input: 1. corpus_tokens (list): Text als Liste von Tokens 2. n (int): Laenge der Ngramme Return: 1. ngrams(list): Liste von Ngrammen"...
4f72d0c70036ef12ae7e950dfb54a811d613da42
627,409
import os def get_files_list(directory): """Returns a list of files in a directory (recursively).""" files_list = [] for (root, _, files) in os.walk(directory): for filename in files: file_path = os.path.join(root, filename) if not os.path.isfile(file_path): continue files_list.app...
d5fcfc7b4da8da7acf61c9281f86d8c7b5643f91
627,410
def string_reverse(input_string): """Reverses a string. Parameters ---------- input_string : str Holds the string to be reversed Returns ---------- reversed_string : str The reversed string """ reversed_string = input_string[::-1] re...
9da711b18f43730d2d7275363829f92eac5fea6b
627,411
import configparser def open_inifile(ini_file): """ inifileをオープンし、パーサーを返す。 :param ini_file:str :return:ConfigParser """ print("INI:open %s" % ini_file) config = configparser.ConfigParser() config.read(ini_file) return config
180148859f149f5e51c9412966fa9cc30d710a03
627,412
def binary_search_ge(x, search_list): """ binary search for the first value from a list, whose value is greater or equal to x :param x: float, the number to compare with :param search_list: sorted list of numbers. :return: float, the first value in the list satisfying the condition. """ # it...
5b59386f4204552299bf5cfe97992fe44f71f714
627,413
def extract_bounds(bounds): """ Extract coordinate tuples from bound objects. """ res = [] for bound in bounds: coords = [] for vertex in bound.vertices: coords.append((vertex.x, vertex.y)) res.append(coords) return res
08689797d0857f69b4cd2fae26aed43fe7e7fa11
627,414
def _GenerateDeviceKVMId(dev_type, dev): """Helper function to generate a unique device name used by KVM QEMU monitor commands use names to identify devices. Since the UUID is too long for a device ID (36 chars vs. 30), we choose to use only the part until the third '-' with a disk/nic prefix. For example if...
79c9924e0b56b8e5dd2572205db84c12ae6a587a
627,415
def f_pitch(p, pitch_ref=69, freq_ref=440.0): """Computes the center frequency/ies of a MIDI pitch Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb Args: p (float): MIDI pitch value(s) pitch_ref (float): Reference pitch (default: 69) freq_ref (float): Frequency of reference pitch (de...
f9567016b1db983ab72d19c898c910a3cd4fed2a
627,416
def tailcuts_clean(geom, image, picture_thresh=7, boundary_thresh=5, keep_isolated_pixels=False): """Clean an image by selection pixels that pass a two-threshold tail-cuts procedure. The picture and boundary thresholds are defined with respect to the pedestal dispersion. All pixels that ...
9d1d288e969102fabde7a94635ad426fa638ade4
627,417
import math def elu_distance(a, b): """计算两点之间的欧氏距离并返回 :param a: list of float :param b: list of float :return: float """ x = sum([pow((a_-b_), 2) for a_, b_ in zip(a, b)]) return math.sqrt(x)
09b5e00a3c5b3c0935235ac6cf60fbffaa3a3193
627,418
import click def validate_relay(context, param, value): """ Validates presence of relay by name. """ relays = context.obj.api.relays() relay = next((r for r in relays if r["name"] == value), None) if relay is None: error = "Relay \"%s\" does not exist" % value ...
644e12abed2e308209aa4d756b9e189a3b287d97
627,419
def summarize_consensus(consensus): """ Return 'high', 'medium' or 'low' as a rough indicator of consensus. """ cons = int(100 * consensus) if cons >= 70: return "high" elif cons >= 30: return "medium" else: return "low"
4ca0357f96376d5326ea1d629c1aeee2810729bf
627,420
def fromargskw(argskw, argspecs, slf_or_clsm = False): """Turns a linearized list of args into (args, keywords) form according to given argspecs (like inspect module provides). """ res_args = argskw try: kwds = argspecs.keywords except AttributeError: kwds = argspecs.varkw if...
44057f5f9006706a5233d6438d5b809a3e46a35c
627,421
def jitter(img): """ jitter s = int(1 * thres * 0.01) 官方参数为0.01 个人觉得这个没必要加,没看出来有啥效果,觉得是图片文字下移 """ w, h, _ = img.shape print(w, h) if h > 10 and w > 10: thres = min(w, h) print("thres:", thres) s = int(1 * thres * 0.1) print("s:", s) src_img = i...
0bb8c87f4b6df2b4c32d5decc09b89aa02530e57
627,422
def _build_tool_path(d): """Build the list of tool_path for the CROSSTOOL file.""" lines = [] for k in d: lines.append(" tool_path {name: \"%s\" path: \"%s\" }" % (k, d[k])) return "\n".join(lines)
5dc12a1089943dea384ec30cce39d0fd5db4df95
627,423
import time def get_current_time(): """ # Desc : Function returns current date and time # Input : None # Output: Return current date and time in specific format for all log messages """ currentTime=time.strftime("%d-%m-%Y %H:%M:%S") return currentTime
a54d67154b7620c6078b3c4c4d6aa21d876d5b15
627,424
def median(series, n): """中位数: 求series在n个周期内居于中间的数值""" median_data = series.rolling(n).median() return median_data
c984ba52407d8a3c78ac89dd04e4cb054af13ea7
627,425
def run_removecomments(nexus_obj, log): """ Removes comments from the trees in a nexus :param nexus_obj: A `NexusReader` instance :type nexus_obj: NexusReader :return: A NexusReader instance with the comments removed. """ new = [] for tree in nexus_obj.trees: new.append(nexus_o...
cabb479f003edb51369478174f7218625ecf8ad1
627,426
import torch def squash(x, dim): """ Non-linear activation, that squashes all vectors to have norm < 1 """ norm_sq = torch.sum(x ** 2, dim, keepdim=True) norm = torch.sqrt(norm_sq) return (norm_sq / (1.0 + norm_sq)) * (x / norm)
557199cf7761d0c1524de5e328ffaf5270c43a3e
627,428
def AAPIPostManage(time, timeSta, timeTrans, acycle): """Execute commands after an Aimsun simulation step.""" return 0
8a747c701dfb935e35015b62e7562acb2065e8f5
627,429
def identical_version(new, existing): """ Validates if current version signature is same as version provided by build scripts """ if new == existing: return True return False
a894b2dbb70dfaea3a0d647daeda2f2ada52d5fb
627,430
def slash_count(l): """Check the slash count""" l= str(l) if l.count('/')<5: return 0 elif l.count('/')>=5 and l.count('/')<=7: return 2 else: return 1
749f52e9b092fd7a77246ec993176a21b4f719ce
627,431
def list_eni_attached_secgroups(ec2) -> list: """ List security groups attached to Elastic Network Interfaces """ network_interfaces = [] next_token = None has_next = True while has_next: args = {'MaxResults': 1000} if next_token is not None: args['NextToken'] = n...
933504fa1067668cbffb1820194ec8497185fbfb
627,432
def get_constraint(obj, name): """ Get a constraint vith the given name for the given object. If constraint is not specified for the object returns None. """ for c in obj.constraints: if c.type.name == name: return c
ef963f63a3a62f97a5c5d39b0f2944af6cd7c487
627,433
def has_possible_duplicates(results): """Returns True if it detects that there are possible duplicate records in the results i.e. identical full name.""" full_names = set() for result in results: if result.full_name in full_names: return True full_names.add(result.full_name) ...
6f96973fbb964ef4cfc8f2e5fe984640fd5d928d
627,434
def add_doc_manual(soup, title, url): """ Adds a new document to the list of references """ doc_tag = soup.new_tag('li') a_tag = soup.new_tag('a', href=url) a_tag.string = title doc_tag.insert(0, a_tag) return doc_tag
095a655ceb53392b6b4c2a3832ffe9325bc67721
627,435
def groupcollide(group1, group2, dokill1, dokill2): """ **pyj2d.sprite.groupcollide** Return dictionary of sprites in group1 with list of sprites in group2 that intersect. The dokill argument is a bool, True removes sprites that collide from all groups. """ collide = {} collision = Fals...
fdeb5d65277109b3beee57e2a9e4615905490768
627,436
from typing import Dict from typing import Any def get_timestamp_feature_name(feature_map: Dict[str, Any]) -> str: """ Analyses the feature map config and returns the name of the label feature (e.g. item_id) """ timestamp_feature_name = list(k for k, v in feature_map.items() if v["dtype"] == "timestam...
7c778473db92ea5ae41e8686f6e21c7ebe9b4541
627,437
def make_good_size(): """ Returns a string a valid size to store as custom data (<= 20MB). """ return "1" * 19 * 1024 * 1024
2adc1d844365c25c39b1a9d729b1967fcd5605fe
627,439
def padding_size(num: int) -> int: """Calculates base64 padding size as per RFC4648.""" # according to https://tools.ietf.org/html/rfc4648#section-4 # only three cases can exist mapping = { 0: 0, # no padding 2: 2, # two padding characters 3: 1, # one padding character } ...
d6762621d3e92eee48e2dc9c2bb20f6993c58424
627,440
def transform(value, subject_number): """ Then, perform the following steps: * Set the value to itself multiplied by the subject number. * Set the value to the remainder after dividing the value by 20201227. """ return (value * subject_number) % 20201227
5bc63e6220ff92260f72ec42d5c96344a606d9d1
627,441
def get_slack_text(): """ Return Slack text """ return r""" Go here to generate a Slack legacy token: https://api.slack.com/custom-integrations/legacy-tokens """
d0a8ea2edbcc71853919802d8e00115677d0c1df
627,442
import re def remove_tokens_with_nonletters(tokens) -> list: """ Inputs a list of tokens, outputs a list of tokens without tokens that includes numbers of special caracters. ['foo','bar','124','34euros'] -> ['foo','bar'] Parameters ---------- tokens : list list of tokens to be cle...
80f615d33650240aac11e65c4d02f2ff04b59863
627,443
def convert_bbox_xywh_to_yminxmin(cv2_rects): """Convert cv2_rects (x, y, w, h) to bbox_coord (ymin, xmin, ymax, xman) Args: cv2_rects: Returns: bbox_coord """ x, y, w, h = cv2_rects ymin, xmin, ymax, xmax = y, x, y + h, x + w tf_bbox_coord = (ymin, xmin, ymax, xmax) re...
362b2ee5c1b0905fa85e513acda993899c93f51f
627,444
from datetime import datetime import calendar def string_fmt_time_to_seconds(string_format_time): """ utility function to convert a string format time to epoch seconds """ dt = datetime.strptime(string_format_time, "%Y-%m-%d %H:%M:%S") epoch_seconds = calendar.timegm(dt.utctimetuple()) return epoch_se...
4b63507ec4f47b3c571a1dffaba2dba8235ee971
627,445
def get_input_channels(shape): """ Helper for temporary issues with PyTorch shape inference. Args: shape (Tuple): Shape tuple. Returns: int: Num input channels. """ # Have batch rank from placeholder space reconstruction: if len(shape) == 4: # Batch rank and channel...
990948171024b1e6bfbc384c446ba5ada0fec663
627,446
def _push(node): """ Push load away from the current node if possible. If a neighboring node which is "closer" to the target can accept more load push it to the node. If no such node is found push fails meaning a relabel has to be executed. """ success = False for edge in node.outgoing_...
c654f2671fb4726525ae601807b551e0c74c6735
627,447
def _intents_from_messages(messages): """Return all intents that occur in at least one of the messages.""" # set of distinct intents distinct_intents = {m.data["intent"] for m in messages if "intent" in m.data} return distinct_intents
4b832585e0498111e1d15bd9ff6552526f9e9623
627,448
import re import os def _replace_env_var(path): """ replace all $VAR with the environment variable value """ return re.sub(r'\$[a-zA-Z_][a-zA-Z0-9_]*', lambda match: os.environ[match.group()[1:]], path)
d4eb682a989375340e82a9251acfe04b9a1d3ffd
627,450
import copy def multiply_variable(self, c, i, in_place = False): """ Replace the variables `x_i` by `c*x_i` in the quadratic form (replacing the original form if the in_place flag is True). Here `c` must be an element of the base_ring defining the quadratic form. INPUT: `c` -- an el...
fccb5423e31fdc71db9e1d5864d66baf94cf5fe5
627,451
from pathlib import Path def has_tests(module: str): """Test if a module has tests. Module format: homeassistant.components.hue Test if exists: tests/components/hue """ path = Path(module.replace(".", "/").replace("homeassistant", "tests")) if not path.exists(): return False if n...
79c473e0732aff3bf43bebfd2de1bf939e98ee2f
627,452
def sales_velocity(units_sold_last_12m, number_of_days_in_stock, velocity_days=30): """Return the sales velocity of a product for a given number of days. Args: units_sold_last_12m (int): Total number of units sold in the past 12 months. number_of_days_in_stock (int): Total number of days in the...
517864c2e4f9286a3231f0ea622c77b5fdd703c6
627,453
import ast def applyTypeConversions(settingObj, value): """ Coerce value to proper type given a valid setting object. Useful in converting XML settings with no type info (all string) as well as in GUI operations. """ if settingObj.underlyingType == list and not isinstance(value, list): ...
5c959f448ac72eea99e44b5d9bf130a32bbc86ab
627,454
from typing import Counter def extract_colors(img, pbar): """Returns all color tuples from the image""" colors = Counter() for row in img: colors.update([tuple(t) for t in row if sum(t) > 5 and sum(t) < 750]) return colors
ff1368e41059ce66ddf288a30cdb26a121093a12
627,455
import difflib def diff(old_s, new_s): """Returns operations necessary to transform old_s into new_s. Note: We optimize for the (hypothetically)common case where edits will be localized to one small area of a large file. """ limit = min(len(old_s),len(new_s)) # Find first index (counting from the start) ...
a626f97ef40c329361a277152206bd1cc56fc5b5
627,456
def add_model_field_foreign_key_to_schema(schema, options): """ :param schema: :param options: expected format, e.g for a Site code foreign key: { 'schema_field': 'Site Code', # the schema field name (or column name) 'model': 'Site', 'model_field': 'code' } :return: ...
2e0a4b1227f34e9358117e71ca695309d8e64694
627,457
def xrange_params(xrangeobj): """Returns a 3 element tuple describing the xrange start, step, and len respectively Note: Only guarentees that elements of xrange are the same. parameters may be different. e.g. xrange(1,1) is interpretted as xrange(0,0); both behave the same though w/ iteration "...
102f99ca45003276397c969dc4f853f4cd977a17
627,458
import re def first_match(regex, string): """Given a regex and a string to search, this function simply returns the first match, if there is one.""" match = re.search(regex, string) return match.group(0) if match else None
7b3ec6150297d34cb4002509f585881c4dd0e993
627,459
def pilotnet_crop(image): """assumes 320x240 input, resizes to 200x66""" # (original - target) # rows: (240 - 66) / 2 == 87 # columns: (320 - 200) /2 == 60 return image[87:-87, 60:-60]
b127e683e360a016ab14e218df486012d09905aa
627,460
def shift(a, b, n): """a and b are vectors n is number of points of a to cut off anew and bnew will be the same length.""" # la, lb = a.size, lb = b.size anew = a[range(0 + n, len(a)), :] if len(anew) > len(b): anew = anew[range(0, len(b)), :] bnew = b else: bnew =...
9c8f038e743ec0c7cb1f74086b1c4de945d94711
627,461
def type2str(cls): """Convert type to type name.""" return cls.__qualname__
391d9eb85e6693be87b682fb30166b06ae636936
627,462
import argparse def init_args(): """ :return: """ parser = argparse.ArgumentParser() parser.add_argument('--image_dataset_dir', type=str, default='H:/Other_DataSets/TuSimple/test_set/', help='The source nsfw data dir path') parser.add_argument('--json_file_name', type=...
33b6ceaeed3d1f9ea752733b03c9b642f58ea05c
627,463
def get_filtered_alleles_df_that_have_allele(allele_name, alleles_df): """Returns reduced alleles DF containing only entries that contain the given allele. """ alleles_df_t = alleles_df.transpose() alleles_df_t_filtered_has_allele = alleles_df_t[ alleles_df_t[allele_name] == 1] retur...
9c1291d1a22d7066472020d58a2d8e01a870b995
627,464
def copy_parameters(model): """Copy a models parameters. This is a helper function to copy a model's parameters and initialize each copied tensor so as to hold all zeros. The returned tensors reside on the same device as that of the corresponding tensor in model.parameters(). Args: $mode...
5d3fc2e00b92788c03bd60a128905af717b9f241
627,465
def get_layer_idx_for_vit(name, num_layers): """ Assign a parameter with its layer id Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33 """ if name in ["cls_token", "pos_embed"]: return 0 elif name.startswith("patch_embed"): return 0 eli...
bf6f6a024aabf207918089fe3de6a454014a3c99
627,466
import torch def same_padding(images, ksizes, strides, rates): """ Input: Output: Description: """ assert len(images.size()) == 4 batch_size, channel, rows, cols = images.size() out_rows = (rows + strides[0] - 1) // strides[0] out_cols = (cols + strides[1] - 1) // strides[1] ...
4ae20e727e069911ffe9512607000b6413b6f940
627,468
import os def zipImagesFiles(images, files): """ Genera una lista de tuplas emparejando cada imagen con su correspondiente archivo de QuPath. """ data = [] for img in os.listdir(images): qp = "" for file in os.listdir(files): if os.path.splitext(img)[0] == os....
6f07fb3931ca9821012477cdfadbe3b9addda5b9
627,469
import os def app_installed(app_name): """checks if app installed""" paths = ["/Applications/" + app_name, "~/Applications/" + app_name] for path in paths: if os.path.isdir(path): return path return
e9934075a43ae92507181c2281546c334cdf7d1a
627,470
def AptGetServiceName(vm): """Returns the name of the mysql service.""" return 'mysql'
ba2899267fd2511a31e481acd6daf11020c7e44e
627,471
from typing import OrderedDict def _add_minmers(minmers: dict) -> dict: """ Read through minmer results and create column for top hit. Args: minmers (dict): Mash and Sourmash results against RefSeq and GenBank Returns: dict: Top hit description for each set of databases """ r...
3f381bed8d5f940c1f475230f217f6abfb024cf9
627,472
def get_version_info(): """Provide the package version""" VERSION = '0.0.1' return VERSION
8a8c6feccd446ad2371d07f18a35b02e76804bfa
627,473
import tarfile def gather_tgz(input_files, output_file): """ Deprecated, use ZIP files instead where possible. """ with tarfile.open(output_file, mode="w:gz") as tgz_out: for tgz_file in input_files: with tarfile.open(tgz_file, mode="r:gz") as tgz_in: for member in ...
e45a862e03c2bf08b71f4e6940b0dd1a2d5aa0c4
627,474
def join_overlapping(s, e): """Join overlapping intervals. Transforms a list of possible overlapping intervals into non-overlapping intervals. Parameters ---------- s : list List with start of interval sorted in ascending order e : list List with end of interval. Retur...
3a6379de72a17217e8e523d316046346ef409c19
627,476
import torch def neginf(dtype: torch.dtype) -> float: """ Return a representable finite number near -inf for a dtype. """ return -1e20
d9b613e815f84e18045b4367fc39404127c04ace
627,477
def page_number(request, page_total): """Gets the current page number of a media list. 'request' is expected to have one query parameter, 'page', containing a page number (with the first page being page 1); if it does not exist, it is taken to be 1. This page number may be outside the bounds dicta...
6deab9a107cfc36d6afb1b771734579af581b602
627,478
def address_taken_pruning(ander_json, AT_json): """ finding out spurious indirect call edges by identifying un-address taken callee functions @ander_json: SVF andersen point-to analysis results @AT_json: functions that are address taken """ address_taken_diff = {} for caller in ander_json.ke...
3ad791a0e92dd86802c33cc47bb9ed0e79f0262b
627,479
def dumper(obj): """Utility function to convert objects to json From: https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable E.g. use to convert dict of histogrammar objects to json Use as: .. code-block:: python js = json.dumps(hists, default=dumper) w...
dba1c5901508787d3a7228150e254f0ac34a5608
627,480
def non_empty(d): """ Check whether the `collection` is none or empty. """ return d is not None and len(d) > 0
1104ce6610cf336501f47ee7f22d5e769658b05c
627,481
def words_no_results(): """Load test data fixture.""" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words
0f7dcafbbbfa440a5e22138f73617a1fb01ffa6d
627,482
import requests def get_gas(): """Scrap the web to obtain data relative to gas on ethereum platform Returns: [dictionnary]: return a dictionnary with 2 keys : "gas" and "gasPrice". gas (int) is the average gas used in Gwei for Swap on Uniswap V2 gasPrice (int) is the current gas price...
79519c24c2580d4f5250e6b52978abed8376271a
627,483
def render_video(video_instance, width=320, height=240): """ This is a intelligent inclusion tag that will try do determine what kind of video ``video_instance`` is, and then render the correct HTML for this video. ``width`` and ``height`` refers to the width and height of the video. Example U...
f4c7ee650d5980ce1b670458f4386ecc55b47bf7
627,484
def vecs_add(v1, v2): """Add two vectors 'v1' and 'v2'.""" return v1 + v2
6183fdc9f92f9ba3592643292b2635a5bccd570e
627,485
def _add_extension_feed_item(client, customer_id, callout_text, language_code): """Creates a new extension feed item for the callout extension. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. callout_text: a str of text for a hotel callout feed ...
e181c5d0ac6a993568732cca23500a4e82919c5c
627,486
def stars_amount_counter(board: list) -> int: """Counts amount of stars in the given board. >>> stars_amount_counter(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ "7 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 9****"]) 36 """ stars = 0 for i in range(9): for j in...
57c87b29d0c2b9f583ee2fd30c79802d6075df3a
627,488
def sieve(n): """ Generate the list of primes below n Parameters ---------- n: int Limit """ ps = [] a = [False] * 2 + [True] * n for i in range(2, int(n+1)): if a[i]: for j in range(i*i, n+1, i): a[j] = False ps.append(i) retur...
81254d13832a0165eeb99a8efa9e3a21bd6fafbb
627,490
def a2dtimems(s): """Converts 'HH:MM:SS.mmm' to milli-seconds""" tokens = s.split('.') if len(tokens) == 0: return 0 elif len(tokens) == 1: return int(tokens[0]) else: s = tokens[0] msec = int(tokens[1]) tokens = s.split(':') l = len(tokens) if l==0: ...
9074a8db97990333acdc791a307eee9bf2ae0374
627,491
def number_zero_pad(num: int, length: int) -> str: """.""" if length < len(str(num)): message = ( 'The length you provided is shorter than the number. ' + 'Please provide a length that is at least as long as the given number.' ) raise ValueError(message) zero...
78c8b6be0087803f8bd576b00281941b721d2000
627,492
def get_shape_input(): """Get shape of the dataset for NSL-KDD""" return (None, 125)
b2ed6ebf967cfb7340969909bc850f5b94af4d59
627,494
def atoms(gra): """ atoms, as a dictionary """ atm_dct, _ = gra return atm_dct
8bc9d0edd8462e1590d86900025e146a528228bf
627,495
import os import tarfile def tar_gz(source_dir, out_path, keep_structure=True): """Create a tar file from a directory of files :param source_dir: path to directory to tar gz :param out_path: path to output file or directory :param keep_structure: keep directory structure """ assert os.path.isd...
277f83fcb4a6e73c32f6efd2a8c671fa38431b16
627,496
def merge_clouds(pc1, pc2): """Add Gaussian noise to pc. Merge two point clouds inputs: pc1 - a list of numpy 3 x 1 matrices that represent one set of points. pc2 - a list of numpy 3 x 1 matrices that represent another set of points. outputs: pc_out - merged point cloud ""...
fb5a9e9393a7a8fd358b54982c3185a012168967
627,497
def find_lcs(strings): """ Find longest common substring of all strings in list """ num_strings = len(strings) # Take first word from array as reference len_0 = len(strings[0]) results = set() for i in range(len_0): for j in range(i + 1, len_0 + 1): # generating all possi...
e36c385ed31af02282f9d2c4e491b9c048f835b3
627,498
import re def _EscapePerfResult(s): """Escapes |s| for use in a perf result.""" return re.sub(r'[\:|=/#&,]', '_', s)
c966bf4ffd482c27467731ca84395effe9e4fc7e
627,499
def area_triangle(b, h): """ Returns the area of a triangle given its base and its height """ area = b * h / 2 return area
a9bdd783f1a43fe73bcd7338120ffaef4863fac6
627,500
def create_char_vocab(input_data): """create char vocab from input data""" sentence_separator = "|" char_vocab = {} for paragraph in input_data: sentences = paragraph.strip().split(sentence_separator) for sentence in sentences: words = sentence.strip().split(' ') ...
01a9919b9cb9a5b4fd92e6a0255e2f6771865238
627,501
from typing import Any import pathlib def to_path(source: Any) -> pathlib.Path: """Converts 'source' to a pathlib.Path. Args: source (Any): source to convert to a pathlib.Path. Raises: TypeError: if 'source' is a type that is not registered. Returns: pathlib.Path: derive...
1e0cf017d7a523641e812b10181ae78ecef477f0
627,502
def delete_address(address): """ Delete an Address. :param gce: An initialized GCE driver object. :type gce: :class: `GCENodeDriver` :param params: Dictionary of parameters needed by the module. :type params: ``dict`` :return: Tuple with changed status and address. :rtype: tuple in ...
071c670e27606f9a69e6c62749f8e1c6678a85d3
627,503
def calculate_throughput(RTdata_dict,min_samplelogs): """ # Desc : Function calculates average throughput for each instance # Input : Dictionary with processed data from each instance, Minimum number of samples that has been processed # Output: Returns average throughput list for all the instances """ ...
2d98c8b82ff5b5e60567bb6efd3dca5f2fa09549
627,504
def _ArgbToRgbaTuple(argb): """Convert from a single ARGB value to a tuple containing RGBA. Args: argb: Signed 32 bit integer containing an ARGB value. Returns: RGBA tuple. """ unsigned_argb = argb % 0x100000000 return ((unsigned_argb >> 16) & 0xFF, (unsigned_argb >> 8) & 0xFF, ...
fae533892b25a193c7d664f59161a8deef1931a1
627,505
import os import sys def setup(): """Add path to this file to sys.path""" app_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(app_dir) sys.path.insert(0, app_dir) return app_dir
a7a5a4ca4db71b960ae820f1495633b21b4f1fc1
627,506
def part1(data): """Return least fuel to move all submarines to same position. Fuel to go from current position c to desired position d is abs(d - c). """ numbers = list(map(int, data.split(','))) numbers.sort() n = len(numbers) middle = n // 2 if n % 2: # odd length media...
08c3584665cce3ab24a22c7000e9279481efc736
627,507
def read_chromsizes(fp): """ :param fp: :return: """ bounds = dict() with open(fp, 'r') as infile: for line in infile: if not line.strip(): continue name, size = line.strip().split() bounds[name] = int(size) assert bounds, 'No bound...
0e5fe938c352aeea56d65971bcff55a2adb8221f
627,508
from datetime import datetime def editor_reg_date(identity: dict, global_userinfo: dict): """ Normalize registration date from either oauth or global_userinfo as datetime.date object. Parameters ---------- identity : dict global_userinfo : dict Returns ------- datetime.date ""...
871d0267c3f27945f5fbe1193cb7c66d93d942dd
627,509