content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_start_timestamp_mapping(file_path): """Get mapping of video name id to star timestamp.""" mapping = {} with open(file_path) as f_in: for line in f_in.readlines(): if line.strip() == '': continue video_name, time_txt = line.strip().split(',') ...
15a9ea922c60d018ffde0e407db097027c034057
651,544
from typing import Any def is_iterate(value: Any) -> bool: """Return `True` if `value` is an "iterate" directive.""" return type(value) is dict and "iterate" in value
3d436eb22c6e8bcb3a2429b91cf274c07c000873
651,545
def judgeWhetherNULL(param, lastOne=False): """ 判断前台传过来的数据,如果是null则将SQL字串改为NULL,否则插入对应类型的数据 :param param: SQL参数 :param lastOne: 是否是最后一个参数 :return: """ if not lastOne: if param is None: return 'NULL, ' else: if isinstance(param, int): return '%d, ' % param else: return "'%s', " % param else:...
f77f2a21a6b81295a3cd196944672333b050c67f
651,547
import re def add_datepart(df, fieldname): """ Adds date related features to dataframe df inplace df: dataframe fieldname: name of the date field in df """ new_df = df.copy() field = df[fieldname] target_prefix = re.sub('[Dd]atetime$', '', fieldname) date_features = ( ...
7774056dd856553501f288c9c97dbc04d359ae59
651,549
def _apply_signed_threshold(value, min_thr=None, max_thr=None): """ Apply threshold on signed value. usage examples : >>> _apply_signed_threshold(0.678, min_thr=0.5) 0.5 >>> _apply_signed_threshold(-0.678, min_thr=0.5) -0.5 >>> _apply_signed_threshold(0.678, max_thr=2.0) 0.678 >>> _apply_signed_thres...
098a37ec49930634475868c12ffe8bf28b252a48
651,550
def list_sorted(words): """ Check if a Tuple of words are Anagrams using Sorted :param words: Tuple :return: bool """ word_one, word_two = words return sorted(word_one) == sorted(word_two)
e6449769d51571a8faaab0cbcf51aa7800d766e8
651,551
def select_hannover_from_metadata(metadata): """Select entries from Hannover""" return metadata.query('doi == "10.6084/m9.figshare.12275009"')
0400073dcd9a752df4352f4d3e1195fe23fae6d5
651,552
import hashlib def get_fd_hash(fd): """ Compute the sha256 hash of the bytes in a file-like """ BLOCKSIZE = 1 << 16 hasher = hashlib.sha256() old_pos = fd.tell() fd.seek(0) buf = fd.read(BLOCKSIZE) while buf: hasher.update(buf) buf = fd.read(BLOCKSIZE) fd.seek(o...
2607d44feeeabe38e3ea240f800e8e42add3ff7a
651,553
def decline_weak_neuter_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak neuter nouns. >>> decline_weak_neuter_noun("auga", "auga", "augu") [['auga', 'auga', 'auga', 'auga'], ['augu', 'augu', 'augum', 'augna']] >>> decline_weak_neuter_noun("hjarta", "hjarta", "hjörtu") [[...
2589aa79afa240c65b3bd6b4334f52fc2c9f66db
651,554
def crop(img, left=None, right=None, top=None, bottom=None): """Crop image. Automatically limits the crop if bounds are outside the image. :param numpy.ndarray img: Input image. :param int left: Left crop. :param int right: Right crop. :param int top: Top crop. :param int bottom: Bottom cr...
e4d18b959c9f0f55f9c6d24a41658922e34b53c0
651,556
import yaml def open_yaml(path): """Open yaml file and return as a dictionary""" data = {} with open(path) as open_file: data = yaml.safe_load(open_file) return data
81cc6a046566ec4a9d365ed14d26036e5b6c1005
651,557
import logging def getLogger(name): """ Returns a logger. Wrapper of logging.getLogger """ logger = logging.getLogger(name) return logger
85ea7245ff87a26d127b54a20b5e852d6d09d7d6
651,558
def isPerfectSquare(num: int) -> bool: """Okay. Solution is O(1).""" r = int(num ** 0.5) return r * r == num
9531efd2433711803d35fa6ddce4cd34e691ec8a
651,559
import numpy def isempty(s): """ checks that a string is empty, returns also True if s is ``NaN`` @param s ``str`` or ``numpy.NaN`` @return boolean The function imports :epkg:`numpy` (delayed import). """ if s is None: return True if isinstance(s, str):...
a615538a1e5aa0ec27e51a7f768d77277f57fd18
651,560
def find_missing_keywords(keywords, text): """ Return the subset of keywords which are missing from the given text """ found = set() for key in keywords: if key in text: found.add(key) return list(set(keywords) - found)
4612511654aae93104c6a1edc98b1b4927619539
651,561
def build_complement(dna): """ This function find A to T, T to A, C to G, Gto C. """ ans = '' for base in dna: if base == 'A': ans += 'T' elif base == 'T': ans += 'A' elif base == 'C': ans += 'G' elif base == 'G': ans +=...
e08d7331b8390057faba470ce1e7c7283a0ff378
651,562
def remove_readonly_fields(patron): """ remove readonly fields from patron dict must run patron records through this fn before PUTting to Koha """ read_only_patron_fields = ("anonymized", "restricted", "updated_on") for field in read_only_patron_fields: patron.pop(field, None) return patron
980d936278726ed17567c543f22130cba117c009
651,563
import subprocess def get_db2_inst_fmp_user(): """ Retrieve the db2 instance and fmp user names """ instusr = subprocess.Popen( ["ps", "-o", "user", "-C", "db2sysc"], stdout=subprocess.PIPE ).communicate()[0].strip().splitlines()[1].strip() fmpusr = [x for x in subprocess.Popen...
6ed6ed6189939b3d49474a58e02584544c66b108
651,565
import configparser def readConfig(file="config.ini"): """Extract IP addresses and CMDS from config file and returns tuple""" ips = [] cmds = [] Config = configparser.ConfigParser() Config.read(file) machines = Config.items("MACHINES") commands = Config.items("COMMANDS") for ip in mach...
e22d5f85a0f4dfbbcf76cc5de269bee5a7a863de
651,567
import re def file_path(f_name): """ find path of file """ list_path = re.findall("(.*/).*", f_name) file_path = list_path[0] if not list_path == [] else f_name return file_path
5687921b573bcaad1f760945cb57dc41f142310e
651,568
def samplesheet_headers_to_dict(samplesheet_headers: list) -> dict: """ Given a list of headers extracted with extract_samplesheet_header_fields, will parse them into a dictionary :param samplesheet_headers: List of header lines :return: Dictionary containing data that can be fed directly into the RunSa...
2df9d99d0971ce182e8e62453c5b7006918806d0
651,569
from typing import Dict from typing import Any from typing import List import yaml def insert_worker(worker: Dict[str, Any], workers: List[Dict[str, Any]]) -> None: """Inserts client or server into a list, without inserting duplicates.""" def dump(...
35d9e908dbc2f706034ab70ca78e890ea79736e7
651,571
def spin_forward(time, co, particles=[], **kwargs): """A function that continues to simulate the galaxy without graphing, so we can check long term behaviour more frugally""" for i in range(0, int(time / co.tstep)): for j in range(0, len(particles)): particles[j].sim(particles, co) ...
d36d29e8f97c310959062b0956d8872dfb27d8f6
651,572
from typing import Any import requests import json def stateful_json_request(page_url: str, api_url: str) -> Any: """Query SEPAQ API. SEPAQ API requires to get a cookie from a main page to disambiguate the API (park, cabin, ...). """ # Aquire cookies on main page page_response = requests.get(...
e0234447d60b4b9be807c205b9dfcb5285972869
651,575
def solve_5bd6f4ac(x): """ - Problem : 5bd6f4ac \n *General Description* (Problem and solving it visually - intuition): I get the zoomed in grid, only containing the top right third of the original input grid.\n *Algorithm* (to guide understandiing of the code) - Fi...
07e9de65e2284fa3a3c6a6dc5165af44440cda17
651,576
def calc_score(res): """ #res --> array formato così #0: [true_razza1, true_razza2, Cane] #--> Cane è il cane predetto dalla rete! #1: [true_razza1, true_razza2, Cane] #--> Cane è il cane predetto dalla rete! # ... #Se true_razza2 = None --> cane puro altrimenti incrocio -- Punteggio alla ...
30b9870e41be825207cf4752c869dd7e2ed2cf89
651,577
def set_windows_slashes(directory): """ Set all the slashes in a name so they use Windows slashes (\) :param directory: str :return: str """ return directory.replace('/', '\\').replace('//', '\\')
dcca256d71133d1d394df30177bd151ae059a065
651,578
def parse_google_events_for_nav_apt(event_objects, rqst_apt_datetime): """ This function takes a list of Google event objects from the navigator's 'Navigator-Consumer Appointments (DO NOT CHANGE)' calendar and returns the appointment id whose start time matches the given datetime. :param event_objects:...
a1bcb4ba8e39279273274976f62b52e210b4b683
651,579
def to_str(s): """Parse a string and strip the extra characters.""" return str(s).strip()
1e978481b926e82e1f72c16ca15c3bf2a6db1b53
651,580
def remove_prefix(text: str, prefix: str) -> str: """ Removes the prefix if it is present, otherwise returns the original string. """ if text.startswith(prefix): return text[len(prefix):] return text
acd31410ef982adba2eb69d2553a0eaa0df9b5f9
651,581
def classesByCredits (theDictionary, credits): """Lists the courses worth a specific credit value. :param dict[str, int] theDictionary: The student's class information with the class as the key and the number or credits as the value :param int credits: The credit value by which classes are queried ...
1169d8d52977d808d73993b135beef2daa64e89b
651,582
import math def _score_flops(tree): """Score by flops but split ties with size. """ return math.log2(tree.total_flops()) + math.log2(tree.max_size()) / 1000
c24323d4f270eb0886091fead65660e9509175c2
651,583
import pandas import logging def convert_to_floats(datalist): """ Converts a list of data into floats, if possible. Returns the indices of all values that cannot be casted as float. :param datalist: The list of data (either time or voltage) :return: Lists containing float values and indices of non-f...
74cdc0fcf0b7ccbb696dd06f0e827ad1ec2b66a8
651,584
def revise_ksize(ksize, moltype, input_is_protein): """If input is protein, then divide the ksize by three""" if moltype == "DNA": return ksize elif input_is_protein: # Ksize includes codons return int(ksize / 3) else: return ksize
42877f3a00d5bf95066c7482552a74f873faf145
651,585
import base64 def _decode_string(text): """Decode value of the given string. :param text: Encoded string :return: Decoded value """ base64_bytes = text.encode('ascii') message_bytes = base64.b64decode(base64_bytes) return message_bytes.decode('ascii')
b7ab66e032ac9560a6b0c55add022f26840e2a18
651,587
def svg_line_join_style(obj): """Returns an SVG style string describing the linejoin for the passed in Faint object. """ join = obj.get_settings().join return "stroke-linejoin:%s;" % join
e7f11caf0020af29d7c899df9f0443cc040163c0
651,588
import os def in_path(name): """ Check whether a command line tool exists in the system path. """ for dirname in os.environ['PATH'].split(os.pathsep): if os.path.exists(os.path.join(dirname, name)): return True return False
323d3455ea8289354e5e3b412165a2fb4ad222c7
651,589
def _gc_commands_to_rmfiles(hsize, files): """Return the history files to remove to get under the command limit.""" rmfiles = [] n = 0 ncmds = 0 for ts, fcmds, f in files[::-1]: if fcmds == 0: # we need to make sure that 'empty' history files don't hang around rmfiles...
77fc0b6d279ceb907d004ddcd5d07752a7379613
651,590
def highlight_series(s): """ Highlight a series or datafragme with background color light gray. An apply function for pandas styler. Maps Series/DataFrame -> Series/Dataframe of identical Parameters ---------- s : pandas Series or Dataframe Returns ------- str css text...
6bb27c2a6186c05b68134fca84c97418432d9e99
651,591
def create_occurence_dict(text): """Create the occurence dict of characters for a given text. :text: str, ascii text :returns: Dict[char:int], occurence dict """ result = {} for c in text: if c in result: result[c] += 1 else: result[c] = 1 return resu...
827edad4ea226ddebdab1e8ec4a72895fef8497d
651,592
import numpy as np from copy import deepcopy def make_4dshape(predictor_1d, predictor_raw, degree=4, neighbors_only=False): """This function makes a 2~4D polynoimal transformed version of the nucleotide predictor.""" pred_wide = np.shape(predictor_1d)[1] predictor_out = deepcopy(predictor_1d) Labels_...
b6023a65ba189fdb1067815f2a985e968e06457e
651,593
def data_init(): """ 初始化数据和属性集。 Returns: train_set (list): 训练集 test_set (list): 测试集 attributes (list): 属性集 is_discrete (list): 属性是否离散 """ train_set = [['青绿', '蜷缩', '浊响', '清晰', '凹陷', '硬滑', 0.697, 0.460, '好瓜'], ['乌黑', '蜷缩', '沉闷', '清晰', '凹陷', '硬滑', 0.77...
876dbd78ea0a480e3cc68da13aae7bfe3c9cb9db
651,594
import torch def gaussian_smearing(distances, offset, widths, centered=False): """ Perform gaussian smearing on interatomic distances. Args: distances (torch.Tensor): Variable holding the interatomic distances (B x N_at x N_nbh) offset (torch.Tensor): torch tensor of offsets cente...
5efd0093bd9705ea6752517a06de5392db6f7476
651,595
def search_roles_by_name(api, configuration, api_version, api_exception, role_name): """ Searches for a role by name and returns the ID. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The version of the API to use. ...
e5ea95316f56a3fe742a5c71b50428c58bcf459c
651,596
def get_relevant_features(features, diff_threshold = 0.05, active_threshold = 0.1, inactive_threshold = 0.1): """ -- DESCRIPTION -- Extract "relevant" features from a set of given features. Relevant in this case means that th...
2ae3a49786f8d4e5e80c158add6fb2fdc85f412e
651,598
def group_weights(weights): """ Group each layer weights together, initially all weights are dict of 'layer_name/layer_var': np.array Example: input: { ...: ... 'conv2d/kernel': <np.array>, 'conv2d/bias': <np.array>, ....
357b9eacda4fad058ffb5b1bec96ed4f030486b1
651,599
def _merging_small_segments(segment_list: list, threshold: float): """ merging the small voice segments that may from an utterance :param segment_list: a list of segments :param threshold: threshold to do the merge :return: a merged segment list """ merged_list = [] merging_buffer_pos = ...
9b60c6729d5d9c698680dfa2b6ea753830509db2
651,600
def get_leaf_certificate(chain): """ :param chain: certificate chain :return: leaf certificate """ leaf_cert = chain[0] for cert in chain: for cert2 in chain: if leaf_cert.get_subject() == cert2.get_issuer(): leaf_cert = cert2 return leaf_cert
5962cd03ef6db9ba3d5581c8af5713752329384b
651,601
def from_local_name(acs, attr, name_format): """ :param acs: List of AttributeConverter instances :param attr: attribute name as string :param name_format: Which name-format it should be translated to :return: An Attribute instance """ for aconv in acs: #print(ac.format, name_format)...
1ffeba9bfae41f4c863a83c9854743a0a954ab32
651,602
def get_knapsack_0_1_solution(w, wt, vt, n): """ Print solution of 0-1 knapsack problem :param w: total capacity :type w: int :param wt: weight of each element :type wt: list[int] :param vt: value of each element :type vt: list[int] :param n: number of elements :type n: int ...
47e3b0d5916ce6249f0c9751f6523fe710e53376
651,603
from typing import Dict from typing import List def dict2args(data: Dict) -> List[str]: """Convert a dictionary of options to command like arguments.""" result = [] # keep sorting in order to achieve a predictable behavior for k, v in sorted(data.items()): if v is not False: prefix...
ef2d30a1ceeb95929b5a8e5ed2ef2af750aaaa44
651,604
def merge_np_arrays(arr1, arr2): """ Merges two numpy arrays containing boolean values using the logical OR operator. :param arr1: :param arr2: :return: """ arr1[arr2] = True return arr1
ae022ef6f81ad8d702457ef1217b455339bf6a09
651,605
import hashlib def _hash(example_with_id) -> str: """Hashes a single example.""" key = example_with_id[0], example_with_id[1]["text"] key_bytes = str(key).encode("utf8") return hashlib.sha256(key_bytes).hexdigest()
112736cec9566633cabd6cfe74b8fe4780b5c861
651,606
import pickle def reference(infile): """ Load the given reference profile file. :params infile: The input filename or file object :returns: The reference list """ # If the input is a string then open and read from that file if isinstance(infile, str): with open(infile, "rb") as i...
550a8fdc1295e249c23a0ae3c21fb2e9c7570573
651,607
def add_element_wise(list1, list2): """Adds the two lists interleaved by eachother""" return [a + b for a, b in zip(list1, list2)]
cfd3964cb12ea35b04d7252ed1666ece37c6431e
651,608
import os def get_version(): """ Read the version.txt file to get the new version string Generate it if version.txt is not available. Generation is required for pip installs """ try: f = open('version.txt') except IOError: os.system("./version.sh > version.txt")...
64216905221b8b8874951584939b17e32d08d40e
651,609
from typing import Optional def _text_compare(t1: Optional[str], t2: Optional[str]) -> bool: """Compare two text strings, ignoring wrapping whitespaces. Args: t1: First text. t2: Second text. Returns: True if they are equal, False otherwise. """ ...
965c61e565aa2608742bcd291fcdf04b26d3ff38
651,610
def load_categories(): """Loads a csv containing all the unique categories for restaurants in the database""" with open('data/categories.csv') as f: categories = [cat.strip() for cat in f.readlines()] return categories
e7c71eb524c7df69c1780091bdcc4ff9ae23a074
651,611
def invert_y_and_z_axis(input_matrix_or_vector): """ This Function inverts the y and the z coordinates in the corresponding matrix and vector entries (invert y and z axis <==> rotation by 180 degree around the x axis) For the matrix multiplication holds: |m11 m12 m13| |x| |m11 x + m12 y + ...
76e71af3c4ed8bae98c69ccf8fd52d383ddb0ce3
651,612
import ast def binop(x, op, y, lineno=None, col=None): """Creates the AST node for a binary operation.""" lineno = x.lineno if lineno is None else lineno col = x.col_offset if col is None else col return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
cf8f0320b71ffee0f3e4916c73e7feccf8ec0160
651,613
import math def quadratic_limb_darkening(impact, l1, l2): """Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1""" impact = math.cos(impact) return 1 - l1 * (1 - impact) - l2 * (1 - impact) ** 2
e5305ede25a31e5e26f6138b3f35688c505857af
651,614
import argparse def parse_arguments(args): """ Parse the arguments from the user """ parser = argparse.ArgumentParser( description= "HUMAnN2 Test\n", formatter_class=argparse.RawTextHelpFormatter, prog="humann2_test") parser.add_argument( "--run-functional-tests-to...
3751aaae3846b348910f46384442f92c5d99fe4c
651,616
def cargar_matriz_puestos(ruta_archivo: str) -> list: """ Esta funcion carga la informacion de la matriz de puestos estudiante a partir de un archivo CSV. ruta_archivo (str): la ruta del archivo que se quiere cargar Retorno: list La matriz con los puestos estudiante de cada facultad ...
aab3c9aadeef42983c2ebd539a0f64f64e337f5e
651,618
import torch.__config__ from torch.utils.collect_env import get_pretty_env_info def collect_torch_env(): """ If torch is available, print the torch config. """ try: return torch.__config__.show() except ImportError: # compatible with older versions of pytorch return get_p...
bfc74c433c49b58cef0b3c335cc65b341ca5f775
651,619
def strtobool(value): """ This method convert string to bool. Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0. Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1. Or, othres return None. Args: value : string value Return: Return False for va...
a56d1317aa7b5767875841499c88f498f5dd7989
651,620
def no_of_replicates_per_cpd(df, df_lvl4): """This function computes the numbers of replicates for each compound""" dose_list = list(set(df_lvl4['Metadata_dose_recode'].unique().tolist()))[1:7] cpds_no_of_reps = {} for cpd in df.index: num_of_reps = 0 df_cpd = df_lvl4[df_lvl4['pert_...
ba6ba79e8315ba2d4dbd06ace443d4b57f5d6d27
651,621
import numpy def ts_zeros(sz, d=1): """Returns a time series made of zero values. Parameters ---------- sz : int Time series size. d : int (optional, default: 1) Time series dimensionality. Returns ------- numpy.ndarray A time series made of zeros. Exampl...
ed733b3b34a13ff4f7e13560c270da16fee57ee6
651,622
import os import subprocess def in_repository(path, ignore=True): """Return True if path is inside a repository, False if not. If <in_ignore> is set to False, will also return False if the path is inside a repository but is ignored by a .gitignore. """ cwd = os.getcwd() try: ...
eed974d98714db73fb51001c8c3afae496676fe7
651,624
from datetime import datetime def extract_date_place(date_born_place): """ extract date born and place born """ start_date = date_born_place.find(": ") + 2 end_date = start_date + 10 date_born_scraped = date_born_place[start_date:end_date] date_born = datetime.strptime(date_born_scraped, "%d/%m/%Y...
852ebbd7a8fab152346377c21aa8d316d8783f6f
651,625
import re import os def build_submission_list(dir,SUBMISSIION_PATTERN): """SCan the directory dir and find all submission description files.""" pattern=re.compile(SUBMISSIION_PATTERN) files=list() for f in sorted(os.listdir(dir)): if pattern.match(f) is not None: print("{} Matched ...
59ccf4413a5293d3009437c88320d3533068684d
651,626
def _fetch_ignorable_policy_topics(client, googleads_exception): """Collects all ignorable policy topics to be sent for exemption request. Args: client: The GoogleAds client instance. googleads_exception: The exception that contains the policy violation(s). Returns: A l...
4bfb539e468af02d81e0cfc2bac8aead42d67ccf
651,627
def toStringVer(version): """Converts a semantic version string to a string with leading zeros""" split = version.split(".") fullversion = "" for i, v in enumerate(split, start=0): fullversion += v.rjust(2, "0") return fullversion
5e5b4b395cc0d9539f066c0ec68fb257572576af
651,628
def ranges_overlap(x1, x2, y1, y2): """Returns true if the ranges `[x1, x2]` and `[y1, y2]` overlap, where `x1 <= x2` and `y1 <= y2`. Raises: AssertionError : If `x1 > x2` or `y1 > y2`. """ assert x1 <= x2 assert y1 <= y2 return x1 <= y2 and y1 <= x2
b83699379e9036f5e7981bf2c541cf3931a54638
651,629
def and_between_sentence(sentence): """ separate sentences if between them there is 'and' Input=sentence Output=sentence """ # init i = 0 while i < len(sentence): j = 0 while j < len(sentence[i]): if sentence[i][j] == 'and' and sentenc...
a97ed987924a1e63153050a1d79a31ad6e03833d
651,630
from sys import stdin def ReadAllLines(): """Read all non-empty lines from stdin. Returns: A list of strings. """ lines = [] for line in stdin: if len(line.strip()) == 0: break lines.append(line.strip()) return lines
3ade97a40038b7a21affdd93caaf99a4cbf70031
651,631
def cursors_of_view(view): """Locates points of all cursors of the view. Args: view - an instance of sublime.View where to look for cursors Returns: [point] - a list of cursor points, sorted """ return [region.begin() for region in view.sel() if region.empty()]
8c0c1f8e271bb3f3f251df797db5695184364234
651,633
def compute_offset(name): """Return byte array with offsets of component separators Parameters ---------- name : str The content name Returns ------- offsets : str String of offsets """ offsets = [i for i, ch in enumerate(name) if ch == '/'] return "".join(chr(i...
7afe25976e1f3146d5d56a950436873bf94c488d
651,635
import re def initialize_record(fields, shape_record): """Initializes a dictionary that stores a shapefile record. Args: fields: List that stores the shapefile record names shape_record: Object that contains a shapefile record and associated shape Returns: ...
4343c4622069afdac34a3939e90bb089d322cf00
651,636
def get_default_feepoints(sim, numpoints=20): """Returns a list of sensible default feepoints. This is basically equispaced feerates from stablefeerate to 0.05 utilization. """ minfeepoint = sim.stablefeerate maxfeepoint = sim.cap.inv_util(0.05) assert maxfeepoint >= minfeepoint spacing...
beb393cf5fc7402ee301cce8f4dc83e3dd0b2716
651,638
def pull_answers(surveys, all_questions): """ Runs through questions and pull out answers, append them to the lists in the container constructed by compile_question_data. """ for survey in surveys: for question in survey: question_id = question['question id'] answer = questio...
ea458fb27b01a0fae57c53374dbbe40a6d656e7b
651,639
from pathlib import Path def collect_filepaths(main_path, format="png"): """ Collect a set of files using a determined location on disk and a known list of file formats. This is useful to get the full path of files encountered on a disk folder. Parameters ---------- main_path : str ...
171cffe20611924acf3c6879433550a97f10622e
651,640
import sys import os def get_editable_dallinger_path(): """In case dallinger was installed as editable package (for instance with `pip install -e`) it returns its location. Otherwise returns None. """ for path_item in sys.path: egg_link = os.path.join(path_item, "dallinger.egg-link") ...
63b14d155903f52d58b4996801c3a29a0e7e526c
651,642
import re def natural_sort(values, case_sensitive=False): """ Returns a human readable list with integers accounted for in the sort. items = ['xyz.1001.exr', 'xyz.1000.exr', 'abc11.txt', 'xyz.0999.exr', 'abc10.txt', 'abc9.txt'] natural_sort(items) = ['abc9.txt', 'abc10.txt', 'abc11.txt', 'xyz.0999.exr...
9ed1ef665912e0b820f9cb001909bd95fd23ee26
651,643
def python_name(cmd_name): """Convert ``-`` to ``_`` in command name, to make a valid identifier.""" return cmd_name.replace("-", "_")
f79dfec66310b19d667f0799a0fc3eedbe771152
651,644
def _preprocess_segmentation_dict(segmentation_dict): """help to preprocess the indexs to list.""" final_dict = {} for k in segmentation_dict: final_dict[k] = [[]] final_part_indexs = final_dict[k] part_indexs = segmentation_dict[k] part_indexs.sort() for index in ran...
d8cf1bc146fa1288f344972c7e93c162533d9af1
651,645
def name(name): """Give a command a alternate name.""" def _decorator(func): func.__dict__['_cmd_name'] = name return func return _decorator
f03f80f1022b87380ba2a15b2ff783885b722556
651,646
def get_words(filename): """Сегментация текста на слова""" with open(filename, encoding="utf8") as file: text = file.read() text = text.replace("\n", " ") text = text.replace(",", "").replace(".", "").replace("?", "".replace("!", "")) text = text.lower() words = text.split() words.so...
e97284f23484fa9f36b6cb48124498647f719155
651,647
def do_stuff3(): """This is not right.""" first, second = range(100) return first + second
cce6e4ba8b56f1f42f70275c9d4b739e49b9aa70
651,648
import inspect def params(func): """Shorthand to get the parameter spec for a function.""" return list(inspect.signature(func).parameters.values())
f1666b0d5cc27fb9d0612bb84b0f18e449a6a836
651,650
import random def random_class_ids(lower, upper): """ Get two random integers that are not equal. Note: In some cases (such as there being only one sample of a class) there may be an endless loop here. This will only happen on fairly exotic datasets though. May have to address in future. :param lo...
dcb351efbf772f2408213b362b9a5af4bfabc8cb
651,651
import torch def blur_with_zeros(image, blur): """Blur an image ignoring zeros. """ # Create binary weight image with 1s where valid data exists. mask = torch.ones(image.shape, device=image.device) mask[image <= 0] = 0 # Compute blurred image that ignores zeros using ratio of blurred images. ...
d747f5bf8c8b53f37d735963990b935a02604535
651,652
import re def cleanhtml(raw_html): """ This function is for creating filenames from the HTML returned from the API call. It takes in a string containing HTML tags as an argument, and returns a string without HTML tags or any characters that can't be used in a filename. """ # Created a regular...
51a0bd1ce37e3bc59d0b457b398acbcd518b2fdd
651,653
from typing import List from typing import Optional import os import functools def concatenate_files(fname_l: List[str], out_fname: Optional[str] = None, chunk_size: int = 128 * 1024) -> str: """Concatenate multiple files into a single file. This is used to recover a la...
8a0fb940217c1f3705cefbf4d6d8b40508f3e452
651,654
def endfSENDLineNumber( ) : """Indicates the end of an ENDF data section for one (MF, MT) pair.""" return( 99999 )
bd910343d6800bbb608774cdf6a62585d32dc54f
651,655
def partition_at_level(dendrogram, level) : """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher the level...
fd8e12fd60e2f8c399a87aaf62d24864e5380f9c
651,656
def _extract_data(spark, input_fname, app_config): """ Read the input data in the form of csv file. :param spark : Active spark session :param input_fname : Input filename as in the storage directory :param app_config : loaded json object with app configuration :returns : spark dataframe of inp...
1103bdcad1fa9d8b5b018882cc43b9c5917b3937
651,657
def venv(virtualenv): """Create a virtualenv for each test""" return virtualenv
123fe15e38bca6954f51949213e18d9a9c4a0819
651,658
def adjust_fg_positions(fg_id, positions): """ Adjusts a prospect's position given their fangraphs player_id (fg_id). Not heavily necessary unless a player has been mis-classified as a pitcher when they should be a hitter or vice versa. """ positions_dict = { } if fg_id in positions_dict: ...
60ca9571106b4664658671ae4a5c055c83af7182
651,660
def admin_persona(personas, posted_personas): """ This fixture is intended to be an arbitrary choice among persona users that IS a group administrator. """ for key, persona in personas.items(): groups = persona.get("groups", []) if "admin" in groups: return posted_personas[ke...
1d597b00bc7e0d96a09f1b9f63bffff9c8b0e6b9
651,661
def inc_key(text): """ increment the last letter of text by one. Used to replace key in SQL LIKE case with less than """ return text[0:-1] + chr(ord(text[-1]) + 1)
e8753ef1cd5018a73427ec3cca7778a9034939bf
651,662