content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def colorize_level(level): """A simple filter a text using a boostrap color.""" classes = { "INFO": "text-info", "WARNING": "text-warning", "CRITICAL": "text-danger" } if level not in classes: return level return "<p class='%s'>%s</p>" % (classes[level], level)
fd86e46fdcf49fd5fc519b2cdfa15dae2d438460
676,660
import json def is_json_serializable(item): """ Test if an object is serializable into JSON :param item: (object) The object to be tested for JSON serialization. :return: (bool) True if object is JSON serializable, false otherwise. """ # Try with try-except struct. json_serializable = Tru...
80841498f649100770836efc2141a8f78c97c0bb
676,661
def _unpack_image(pixels): """Flatten out pixels and returns a tuple. The first entry is the size of each pixel.""" unpacked_pixels = [] try: for pix in pixels: for val in pix: unpacked_pixels.append(val) return len(pixels[0]), bytes(unpacked_pixels) except ...
8816dd185c2b163a8ddc6f526534ceae7e8a8952
676,662
from bs4 import BeautifulSoup def make_fileDesc(text): """ ============================ Parsing fileDesc information ============================ Args: :param: text(str): raw_infos """ soup = BeautifulSoup(text, "html.parser") element = { "titleStmt": ["titl...
2b9415b2d9be9168073582b774d1b49ac709e103
676,663
def center_crop(img, output_size): """ image transform :param img: :param output_size: :return: img """ if isinstance(output_size, int): output_size = (int(output_size), int(output_size)) image_width, image_height = img.size crop_height, crop_width = output_size c...
079ca3c315c8b95cee44e040780070675b43946f
676,664
import os import re import json def getTankROI(path, camId): """ Loads the JSON camera parameters and reads the Region of Interest that has been manually set """ # Load json file with open(os.path.join(path, "cam{}_references.json".format(camId))) as f: data = f.read() # Remove comme...
579d11d1883e5ff27d9d442655ca901f041ea83f
676,665
import re def count_from_string(string): """Takes a string and returns word count""" # replace all extra whitespace string = re.sub("\s{2,}", " ", string) # consider as a word only if it contains a letter or a number count = len( [ word for word in string.split(" ")...
391de6dbc270d58913e210d9e3b14a0e025c1035
676,666
def min_row_data_rate_list(dataframe,value): """Fonction faisant la somme des éléments de ligne et retournant une liste d'indices de lignes avec un taux de remplissage minimal""" """La valeur de vérification conditionnelle dépend d'un projet, A CHANGER!!!!!!!!""" rows_list = [] for i in dataframe....
690ff4014fd7070ef7027b721b527932040d4c8a
676,667
def Declares(node): """Variable scope in lambda function If variables Examples: >>> print(matlab2cpp.qscript("x = 4; f = @() x+2")) x = 4 ; f = [x] () {x+2 ; } ; """ # handle in Lambda return ""
66ac075a9cc56f3b3b07af0b3d034ffe20068e8a
676,668
import math def getLOG(rawEMGSignal): """ LOG is a feature that provides an estimate of the muscle contraction force.:: LOG = e^((1/N) * sum(|xi|)) for x i = 1 --> N * Input: * raw EMG Signal * Output = * LOG :param rawEMGSignal: the raw EMG signal :type ...
3a4b4f67b56bb1718b4e5cb4698a47d155515627
676,669
from datetime import datetime def parse_element_time(element): """Extract and format time from an html element.""" unixtime = int(element.find(class_="odate")["class"][1].split("_")[1]) return datetime.utcfromtimestamp(unixtime).strftime("%Y-%m-%d %H:%M:%S")
a9f22d8b5cf12533c3e5bf1c2d842e8812ae0291
676,670
import math def calculateTierSize(imageWidth, imageHeight, tileSize=256): """ The function calculate the number of tiles per tier Arguments: imageWidth {Float} imageHeight {Float} tileSize {Integer} Default is 256 pixel Return: {Array} """ tierSizeInTiles = [] ...
f66efdc2070afd1fe91fd631fe87c8d4e03961ad
676,671
import os import pandas def load_gtf_cache(filename): """Load GTF cache file produced by gff2table :Paramters: - filename: (str) path to .h5 gtf cache file :Returns: DataFrame of annotations """ if os.path.exists(filename): store = pandas.HDFStore(filename, 'r') assert len(s...
65b0263570942299631276cbc740e9db4f92ddff
676,672
def namefags_select(cursor,POSTCOUNT_MIN,POSTCOUNT_MAX,IGNORE_NAMES): """Собирает данные неймфагов с выборкой по минимальному числу постов.""" namefags_select = [ ] namefags = cursor.execute("SELECT number,name,tripcode,posts,links,postcount FROM namefags").fetchall() for nametuple in namefags: ...
f6d639454cdfe7188b4ca4d445e81c6c0107b939
676,673
def convert_type2label(types, type_to_label_dict): """ Convert types to labels INPUTS: types-> list of types type_to_label dictionary-> dictionary of cell types mapped to numerical labels RETURN: labels-> list of labels """ types = list(types) labels...
0dceb64cae98940308cec9e60ffda6cf63998e5c
676,674
import torch def assign_types(probability_predictions, type_indexes, threshold=0.5): """ :param probability_predictions: batch x total_type_len :param type_indexes: batch x type_len :return: list of pairs of true type indexes and predicted type indexes """ device = 'cuda' if torch.cuda.is_avai...
cc589469744a012c565eb7ede320b272343e4678
676,676
from datetime import datetime def last_leap_year(date=None): """ Return the last complete leap year from today or a specified date. """ if date is None: date = datetime.utcnow() leap = (date.year - 1) - ((date.year - 1) % 4) return leap
26242dafa6cf0472c59fc0a25005efade34a517f
676,678
import random def generate_multikernel_benchmark(number, min_threads, max_threads, min_blocks, max_blocks, min_spin_ns, max_spin_ns, kernel_count): """ Returns a dict that, when converted to JSON, will work as a benchmark configuration for the multikernel.so benchmark. The multikernel.so benchmark wil...
1ec3de08ca5620f583b371689b3d567a83e89d40
676,679
def date_parser(dates): """ The function that formats a date, removing the time(hh:mm:ss) and return the date as yyyy-mm-dd """ # use the split method to separate the date and time # use list comprehension to return formated date return [i.split(' ', 1)[0] for i in dates]
7d07d8e4cd5abf42e9b0794ab4793e5e081dfa61
676,680
def to_uri(uri_data): """ Convenient function to encase the resource filename or data in url('') keyword Args: uri_data (str): filename or base64 data of the resource file Returns: str: the input string encased in url('') ie. url('/res:image.png') """ return ("url('...
927cacdacf6fff7f7efba148cfc75c35bfdcbc1f
676,681
import hashlib def password_hash(password: str) -> bytes: """Create a hash of a password to transform it to a fixed-length digest. Note this is not meant for secure storage, but for securely comparing passwords. """ return hashlib.sha256(password.encode()).digest()
712908e55d1534570c3d1a8906ed7c05070bb0e6
676,683
def parseBox(line): """ Take a line of the form "NxNxN" and parse it into a sorted tuple (length, width, height). Keyword arguments: line --- a string to be parsed as box specifications """ dimensions = sorted(map(int, line.split("x"))) return (dimensions[2], dimensions[1], dimensions[0])
31765d2dede570348a9e80fe986b248e10b34f27
676,685
def __check_if_complete(fpath): """Checks if job is complete.""" is_complete = False with open(fpath, "r") as f: for i, l in enumerate(f): if "Program complete" in l: is_complete = True break else: is_complete = False return is_comp...
c717af9290fc580d4db60554189b845229256942
676,688
def _Backward4_T_hs(h, s): """Backward equation for region 4, T=f(h,s) Parameters ---------- h : float Specific enthalpy [kJ/kg] s : float Specific entropy [kJ/kgK] Returns ------- T : float Temperature [K] References ---------- IAPWS, Revised Suppl...
61469e320ee1c2e9041942dee87675c728a52fd6
676,689
from pathlib import Path from typing import List def read_property_names(file_name: Path, column: str = "rvalue") -> List[str]: """Read the rvalues from the table.""" with open(file_name, 'r') as f: data = f.readlines() return [" ".join(x.split()[:-4]) for x in data[1:]]
d2e7b59e389feb5f93a1519ace0d7d1d5f0c1bce
676,690
def compare_users(user1, user2): """Comparison util for ordering user search results.""" # Any verified user is ranked higher if user1["is_verified"] and not user2["is_verified"]: return -1 if user2["is_verified"] and not user1["is_verified"]: return 1 return 0
506358b674a594938fef70da1d0c26b89040e15e
676,691
def string_list_handler(option_value=None): """Split a comma-separated string into a list of strings.""" result = None if option_value is not None: result = option_value.split(',') return result
7bcc310cbefb1ee2099fd176f6e901b75abdcf05
676,692
import random def omikuji() -> str: """ 乱数を用いておみくじを行う関数 strが返ります :return str: おみくじの結果 """ value = random.random() # notifer.output(f'おみくじに挑戦!\nvalue={value}') if value < 0.001: return '大吉' elif value < 0.004: return '中吉' elif value < 0.007: ret...
afff76bcb08088c7c01b6bfe28d4e1f11f45b7e4
676,693
def IsImageFile(ext): """IsImageFile(ext) -> bool Determines if the given extension corresponds to an image file (jpg, bmp, or png). arguments: ext string corresponding to extension to check. returns: bool corresponding to whether it is an image file. ...
ce3c555e2fcc6c6ad5858242307beda10b3ccf68
676,694
def ensure_support_staging_jobs_have_correct_keys( support_and_staging_matrix_jobs: list, prod_hub_matrix_jobs: list ) -> list: """This function ensures that all entries in support_and_staging_matrix_jobs have the expected upgrade_staging and eason_for_staging_redeploy keys, even if they are set to fals...
3852500882732ac0f92dfc5d526c0fe23d9a9388
676,695
def oneliner(): """ three_digit_numbers = range(100, 1000) products = [ x*y for x in three_digit_numbers for y in three_digit_numbers ] is_palindrome = lambda x: str(x) == str(x)[::-1] return max(p for p in products if is_palindrome(p)) """ return max( p ...
3b1c4831c3d2b802e3383ba350942b6edb4b3b2e
676,696
import itertools def signal_3D(mu, n): """ Generate signal power consumption S reference values for all messages mu. Parameters: mu -- 2D list of bool, size n x 2^n n -- integer Return: S -- 3D list of integers, size 2^n x 2^n x 2^n """ # All K possibilities K = list(itertools.product([bool(0), bool(1)]...
d152166ea35f38144e417814b32247377c12c1c1
676,697
def readlines_with_strip(filename): """Reads lines from specified file with whitespaced removed on both sides. The function reads each line in the specified file and applies string.strip() function to each line which results in removing all whitespaces on both ends of each string. Also removes the newli...
ef2c0e08fb29d42a2724ba42a90c4c6a694bac35
676,698
def convert_channels_to_int(channel: str): """ 1 (1-bit pixels, black and white, stored with one pixel per byte) L (8-bit pixels, black and white) P (8-bit pixels, mapped to any other mode using a color palette) RGB (3x8-bit pixels, true color) RGBA (4x8-b...
8edf0f229f1e0d0a7ea2452cb5d4afa23573a6ef
676,699
import uuid def generate_username(): """Generate a new password. :returns: new username """ return str(uuid.uuid1())
c543439d997456a1b6fdfde94ab61e3cb04ae7a4
676,702
def _clean_commit_id(commit_id: str) -> str: """Get the correct commit ID for this commit. It will trim the short_id since mach and the components are using a different commit id format (7 chars long). """ return commit_id[:7]
f045b8d9f97b9974b94d3f424531dbfc61425a3a
676,703
def opp(c): """ >>> opp('x'), opp('o') ('o', 'x') """ return 'x' if c == 'o' else 'o'
a8fc12176414ca741eb99adcca716378377d92af
676,705
from typing import Counter def most_frequent(List): """Counts the most_frequent element in list""" occurence_count = Counter(List) return occurence_count.most_common(1)[0][0]
33a7cc95758ad12922ad1221c5e992925bddb401
676,707
def get_allinfo_tuple(member): """Returns tuple with the member's complete information for posting.""" contactinfo = member.contactinfo department = '?' try: department = member.department[0].department.name_fld except: pass return (member.preferredName_fld, member....
229bee6d448128ea8e248d1065a43ca2580850f9
676,708
def CountBenchmarks(benchmark_runs): """Counts the number of iterations for each benchmark in benchmark_runs.""" # Example input for benchmark_runs: # {"bench": [[run1, run2, run3], [run1, run2, run3, run4]]} def _MaxLen(results): return 0 if not results else max(len(r) for r in results) return [(name, _M...
ee7845b613fbdca71d91720d886478af142d2a74
676,709
def window(x, win_len, win_stride, win_fn): """ Apply a window function to an array with window size win_len, advancing at win_stride. :param x: Array :param win_len: Number of samples per window :param win_stride: Stride to advance current window :param win_fn: Callable window function. Takes ...
95ac180a57b6f0e3ca4517bdc8559f8875e94f94
676,710
def to_devices(tensors, device, **kwargs): """ helper function to send tensors to device """ return (tensor.to(device, **kwargs) for tensor in tensors)
8c23841dabaef29b7670bb3f5a9a17a9c87d97b5
676,711
def type_check(test_dataframe): """ :param test_dataframe: pandas data frame :return: bool, whether all values in same column have same type. """ for col in test_dataframe.columns: for i in range(len(test_dataframe[col])): elem = test_dataframe[col][i] if type(elem)...
0295c757d872362cede3c7f96245f807b5a930c2
676,712
def kahn(ADT): """Topological sort powered by Kahn's Algorithm""" #find all edges edges=[] for i in ADT.vertex(): for j in ADT.edge(i): edges.append((i,j)) #find vertices with zero in-degree start=[i[0] for i in edges] end=[i[1] for i in edges] queue=set(sta...
261c33a430a51fa2bac770f588a39abeaf1ad8c8
676,713
def msb(n): """! @brief Return the bit number of the highest set bit.""" ndx = 0 while ( 1 < n ): n = ( n >> 1 ) ndx += 1 return ndx
1ea0582aec974f12ebf9ac84dabc6a4aecaaafdc
676,714
def getdispatchrepo(repo, proto, command): """Obtain the repo used for processing wire protocol commands. The intent of this function is to serve as a monkeypatch point for extensions that need commands to operate on different repo views under specialized circumstances. """ viewconfig = repo.ui...
a6d8d3d4bf94808d74b626f4bd0c6d09314c814a
676,715
def iswritable(f): """ Returns True if the file-like object can be written to. This is a common- sense approximation of io.IOBase.writable. """ if hasattr(f, 'writable'): return f.writable() if hasattr(f, 'closed') and f.closed: # This mimics the behavior of io.IOBase.writable...
8d60aab30bf8cd304f10020cc0e93af1e5030a6d
676,716
def write_tetrahedron(loc, mat, sideLen=-1.0, perpBiSec=-1.0, height=0.0, orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0): """ @brief Writes a tetrahedron. @param loc The location of the tetraheadrons barycenter @param mat The material @param ...
70c64699cf8f35378368f6b6ae1524feb27f7de5
676,717
def length(value): """ Gets the length of the value provided to it. Returns: If the value is a collection, it calls len() on it. If it is an int, it simply returns the value passed in""" try: if isinstance(value, int): return value else: result = len(...
ff52d92c5b9377ff14dcb7b5ac2b532da07c4074
676,718
import torch def normalize_adj(mx): """Row-normalize matrix: symmetric normalized Laplacian""" rowsum = mx.sum(1) r_inv_sqrt = torch.pow(rowsum, -0.5).flatten() r_inv_sqrt[torch.isinf(r_inv_sqrt)] = 0. r_mat_inv_sqrt = torch.diag(r_inv_sqrt) return torch.mm(torch.mm(mx, r_mat_inv_sqrt).transp...
269425b30b50f5e35b7d7fbb70e892f5024b769e
676,719
from typing import List def batch_inference_result_split(results: List, keys: List): """ Split inference result into a dict with provided key and result dicts. The length of results and keys must match :param results: :param keys: :return: """ ret = {} for result, key in zip(resul...
e7b977cf92fd8b5adad12b6aee839e4df3d7b0aa
676,720
def read_ip_config(filename): """Read network configuration information of kvstore from file. The format of configuration file should be: [ip] [base_port] [server_count] 172.31.40.143 30050 2 172.31.36.140 30050 2 172.31.47.147 30050 2 172.31.30.180 30050 2 Note t...
10b8087b66b4424c95acaf023a6c1cd693ed4368
676,721
def hex2dec(value): """ 'ff' -> 255 ; 'af fe' -> (175, 254) ; ('af', 'fe) -> (175, 254) """ if type(value) == str: value = value.strip() if ' ' not in value: return int(value, 16) else: return hex2dec(value.split(' ')) else: return tuple(int(item, 16) ...
206027f7c28e0d1c96e46d31ee2ed400afc760fe
676,722
def get_table_row(table, td_text): """ Find a row in a table that has td_text as one column's text """ td = table.find('td', string=td_text) if td is None: return None return td.find_parent('tr')
3254cd06244a1eb66364be3fee3addb22ce202ce
676,723
def forgiver_reclassifier(original_classifier, p): """Function to reclassify the strategy""" if p not in (0, 1): original_classifier["stochastic"] = True return original_classifier
9ee084ec0883170c5e62b4501851c1f57d847158
676,724
def get_least(columns) -> list: """Returns list of least common values for each column""" return [0 if column.count("0") < column.count("1") else 1 for column in columns]
7f3bdffb5d367c6128b135aa67d9e489445245a4
676,725
def breakpoint_callback(frame, bp_loc, dict): """This callback is registered with every breakpoint and makes sure that the frame containing the breakpoint location is selected """ # HACK(eddyb) print a newline to avoid continuing an unfinished line. print("") print("Hit breakpoint " + str(bp_loc)) ...
309bb7c0d7a18d5adb3a6bf8821e8296b29417d1
676,726
import os def find_in_parent(dir, targets, fallback=None): """Recursively search in parent directories for a path to a target file.""" for i in os.listdir(dir): if i in targets: return os.path.abspath(os.path.join(dir, i)) if os.path.abspath(dir) == '/': if fallback: ...
11c9710fb0bd3ad6073bf00dd81d85fef95c4473
676,727
def _checkRole(user_roles, roles): """ Check given role is inside or equals to user roles """ if user_roles is None: return False # Roles is a list not a single element if isinstance(roles, list): found = False for r in roles: if r in user_roles: found...
c83946bb3e8153b484fef683307fe8aae2465426
676,728
import ipaddress def filter_ipv4(ip): """Validate IP address from YAML variables.""" try: ipaddress.ip_address(ip) return ip except ValueError: return "!!! Not valid ip address !!!"
6a331ce7831b9cd5d2d3b04ab97f27f0c16b7f4a
676,729
import pathlib def _stringify_path(path_or_buffer): """Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer """ try: _PATHLIB_INSTALLED = True except ImportError: ...
172e0faab6ca67f7d0f15577909e4027a33d9d8c
676,730
import random def Gen_M(strings, columns): # рандомная генерация матрицы по указанному кол-ву столбцов и строк """ Функция, которая генерирует случайную матрицу n*m :params strings: количество строк в матрице :params colums: количество столбцов в матрице :return matrix: сгенерирован...
5ac66a32f26e5251301139e9a305f7887341b7c8
676,731
import os def file_list(redis, taskfile_dir, task_id): """Returns the list of files attached to a task""" task_dir = os.path.join(taskfile_dir, task_id) if not os.path.isdir(task_dir): return [] return os.listdir(task_dir)
d384916835f61a0dfee25e75a5ab240f27a8f6dd
676,732
def _get_gmt_dict(filename): """Parse gmt files and get gene sets.""" with open(filename, 'r') as f: content = [line.strip().split('\t') for line in f] return {pathway[0]: pathway[2:] for pathway in content}
e9d13bfc189d825d1632f17f17f549257efd49e9
676,733
def EqualSpacedColmunTable(items, table_width=80, table_indent=2, column_pad=2): """Construct a table of equal-spaced columns from items in a string array. The number of columns is determined by the data. The table will contain at ...
4de98787512ba367729959c44f6563323bfbc7b8
676,735
def sort_words(boxes): """Sort boxes - (x, y, x+w, y+h) from left to right, top to bottom.""" if(len(boxes) == 0): return [] mean_height = sum([y2 - y1 for _, y1, _, y2 in boxes]) / len(boxes) #boxes.view('i8,i8,i8,i8').sort(order=['f1'], axis=0) current_line = boxes[0][1] lines = [...
3f0a793d9472052b9ec899275f0ada8238a15158
676,736
def coo_plan_tol(): """Tolerance in meters (maximum accepted difference against a reference value) of computed grid coordinates as per document "Help_TransDatRO_code_source_EN.pdf", page 3 """ return 0.003
c5db019abd4deb418a70f2a51f5e8ee7d4e0c0db
676,737
def make_voc_seed_func(entry_rate, start_time, seed_duration): """ Create a simple step function to allow seeding of the VoC strain at a particular point in time. """ def voc_seed_func(time, computed_values): return entry_rate if 0. < time - start_time < seed_duration else 0. return voc_se...
9e9936580d6acb379cc2e4f7dc70f6fd59133040
676,738
import socket def init_socket(port): """ Init socket at specified port. Listen for connections. Return socket obj. Keyword arguments: port -- port at whicch to init socket (int) """ connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection_socket.bind(('', port)) connection_socket.l...
19552577a5a075b6532d66783cc744071dad80c8
676,739
from typing import List def _split_list(string: str) -> List[str]: """Assumes an input of the form `[s1, s2, s3, ..., sn]`, where each si may itself contain lists.""" assert string[0] == "[" and string[-1] == "]" nesting_depth = 0 all_strings = [] current_string = "" for character in strin...
1cfd741a3c36db4ccd3e9ca1acc2d00d192e1087
676,740
def get_model_state_dict(model): """Get model state dict.""" return {k: v for k, v in model.state_dict().items()}
f9733a39a9fc6a65804a83751e2650c9606a8b8a
676,741
import ast def calculate_issues_count(issues: str) -> int: """ Parse issues list and calculate number of issues. """ return len(ast.literal_eval(issues))
b556960bcd2bc2d693719ce9c1369d2a0253dd4c
676,743
def _contains_isolated_cores(label, cluster, min_cores): """Check if the cluster has at least ``min_cores`` of cores that belong to no other cluster.""" return sum([neighboring_labels == {label} for neighboring_labels in cluster.neighboring_labels]) >= min_cores
042a117981ec1e6215b855c0bb7b11f34087183f
676,744
from typing import Optional def upper(value) -> Optional[str]: """Converter to change a string to uppercase, if applicable""" return value.upper() if isinstance(value, str) else None
6b20c10bbe89878fb2e39386602dadf526be395f
676,745
def _call_member(obj, name, args=None, failfast=True): """ Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute args : dict, optional, default=None ...
48ddd9b3a2350a5b4a82beb81f5e0d7f89d42a8b
676,746
def xcorr_signals(signals): """ Parameters ---------- signals : ndarray JxM vector of stacked input signals Returns ------- xcorr_matrix : ndarray JxJ matrix of cross correlation results """ xcorr = signals.dot(signals.conj().T) return xcorr
31132d9604723e02d211cd3648fdb038e42349dc
676,747
def replace(file: str, data: str) -> bool: """Update contents in the file, even if there was no change.""" with open(file) as fh: original_content = fh.read() start = original_content.find("# START") end = original_content.find("# END") if start == -1 or end == -1: return False ...
1829b9a9400efc5fa2c068c079a2706a7ff5620c
676,748
def doc_view(request): """View for documentation route.""" return { 'page': 'Documentation' }
eceb49907078999d6d3b9348ae4d953061d6968b
676,749
def most_similar_vecs(docs, i, model, topn=10): """Obtain the most similar N vectors for a vector""" new_vector = model.infer_vector(docs[i][0]) return model.docvecs.most_similar([new_vector], topn=topn)
8dc2752c31d98b3315f5b548371bbf40a44318c4
676,750
def move_zeros(array): """.""" original_array = array[:] num_zeros = 0 for i, obj in enumerate(original_array): try: if int(obj) == 0 and not (obj is False): value = int(array.pop(i - num_zeros)) array.append(value) num_zeros += 1 ...
0299fddc1f27bf55dfce5a6d6109d4dc7dbb9168
676,751
from typing import List def bounding_box_to_polygon( left: float, bottom: float, right: float, top: float ) -> List[List[float]]: """ Transform bounding box to polygon :param left: left bound :param bottom: bottom bound :param right: right bound :param top: top bound :return: polygon ...
cc8a6a0884af87f9588c1fe54c73e7936dc67f7c
676,752
def sanitize_path(path: str): """清除路径中的无效字符""" path = path.replace("/", "、").replace("\\", "、").replace("|", "&").replace(":", ":") for char in ["~", '"', "?", "*", "<", ">", "{", "}"]: path = path.replace(char, "") return path
072f250f44ed2bbb3cbb637e920d9c78b273c39a
676,755
def get_list_actions(func): """ Add references action to alias list display """ def inner(self, *args, **kwargs): list_actions = func(self, *args, **kwargs) list_actions.append(self._get_references_link) return list_actions return inner
a62df832f6be91e6b9ef9f49a2410b28b01adbfd
676,756
def _link_gold_predicted(gold_list, predicted_list, matching_fn): """Link gold standard relations to the predicted relations A pair of relations are linked when the arg1 and the arg2 match exactly. We do this because we want to evaluate sense classification later. Returns: A tuple of two dicti...
3d53c7541c267c2a4a278d800c65af0c769caede
676,757
def _label_fn_binary(fpath): """ Function for labeling the data for the other models. """ if "NOT_" in fpath: return 0 else: return 1
81f2185d9612882bdba28b01a35c293b7ab4489c
676,758
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return f"{prefix}{num}{suffix}"
ba2822c26b447e294e76ad4c61a8c7da0501816e
676,759
def totalLinhas(df, query_txt:str='index == index'): """ Devolve o total de linhas do dataframe """ df=df.query(query_txt) n, _ = df.shape return n
939c3b1de6f734ba373854c6b90d4b382dd4c6f2
676,760
import os import requests import random def get_article_from_pocket(): """Get one dict data from Pocket's articles randomly.""" consumer_key = os.getenv('POCKET_CONSUMER_KEY') access_token = os.getenv('POCKET_ACCESS_TOKEN') url = 'https://getpocket.com/v3/get' payload = { 'consumer_key': c...
bd031eb58039b25209e402cd92736c4c46dbe4dd
676,761
def fix_name(team_name): """Expand team names from the values in JSON""" if 'wings' in team_name: team_name = 'Red Wings' elif 'jackets' in team_name: team_name = 'Blue Jackets' elif 'leafs' in team_name: team_name = 'Maple Leafs' elif 'knights' in team_name: team_nam...
b00371ae744c004fdbc6853a92e7a80365b8ca22
676,762
import os def get_files_in_folder(path): """ Get the paths of files in a folder If path is already a file, return a value containing this value :param path: str :return: list of str """ if os.path.isfile(path): return [path] else: return [os.path.join(path, file_name) ...
73ee0bcc10b7cd52c45d57d9a5e54d6ce4a2281f
676,763
def get_related_major_courses(related_major_soup): """ :param related_major_soup: SoupParser.soup_jar['연계전공'] :return: ["일본어경제국제통상연계전공", ...] """ lecture_dropdown = related_major_soup.find_all('div', {'style': 'height:10em;'})[1] ret = [] for i in lecture_dropdown.find_all('div', {...
9cdfa527dee997224e136112680415bdec7ca83e
676,764
def get_region_dict(region, maxRegionSize=None, tilesource=None): """Return a dict corresponding to region, checking the region size if maxRegionSize is provided. The intended use is to be passed via **kwargs, and so either {} is returned (for the special region -1,-1,-1,-1) or {'region': region_dic...
8b38a160bb11f9f6be572855f6c7202ee6caea7e
676,765
def initialize_back_prop(AL, Y, AL_prime, Y_prime): """ Initialize backward propagation Arguments: :param AL -- output of the forward propagation L_model_forward()... i.e. neural net predictions (if regression) i.e. neural net probabili...
135a442cb6258bf1e7f24c1edd8cf535e57e514f
676,766
def verbrepl(matchobj, verbs): """ a function to be used in re.sub, replaces non-verbs tagged as verbs into n.count """ entry = matchobj.group(1) if entry not in verbs: return entry+'/n.count ' else: return matchobj.group(0)
43a97b7ae0b51f0c4367d072e29805d2d0f45a6a
676,767
import re def _LooksLikeAProjectName(project): """Heuristics testing if a string looks like a project name, but an id.""" if re.match(r'[-0-9A-Z]', project[0]): return True return any(c in project for c in ' !"\'')
eab1695ecb24ddc6a81353eddd3c129c076d1493
676,768
def fast_get_std_name(n, index_syn): """ :param n: :param index_syn: :return: """ return index_syn[n]
4e05f99530ba9d45f88854aa7d36a76562be3475
676,769
def cosine(coordinate_p, coordinate_q): """余弦距离又叫余弦角度 :param coordinate_p: p坐标 :param coordinate_q: q坐标 :return: 余弦距离 """ numerator, denominator = 0, 1 # 分子和父母 for x, y in zip(coordinate_p, coordinate_q): numerator += x * y q = [x ** 2 for x in coordinate_q] p = [y ** 2 for...
e2e415f374d2f34649652ba6532f3d9e62f67969
676,770
def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res
42b0ab7d87491570e67e1c85581f8634e1a8edaf
676,771
def replaceline(f, match, lines): """Replace matching line in file with lines.""" for i in range(len(f)): if match in f[i]: return f[:i] + lines + f[i+1:] return f
b6a3216c6d1e9f383b985a2c679f696ede54436f
676,772
def _generate_daily_price_view_sql(): """ Generate the SQL query required to create the InstanceDataLastPointView view """ return """ CREATE VIEW instancedatadailypriceview AS SELECT provider, instanceType, region, operatingSystem,...
66f17e6060505e4b70478476656f332a7c4eab2f
676,773