content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _bool(raw_bool): """ Parse WPS boolean string.""" return raw_bool == "true"
52ea61e35844395f54fae0757c2e27f28fedb76c
636,054
import tempfile import os import json def create_tmp_datastore(): """ Rather than mocking the file system, this actually creates some temporary files that emulate the file store system in Sacred. Unfortunately, Sacred and Sacredboard are completely decoupled, which makes it impossible to ensure that t...
d3c71316565b92e4b767b36934b3d0e0c995e841
636,055
import re def search_last_letter(input_string): """ Returns the last letter in a string :param input_string: str, string to search for a letter :return: str, last letter in the string """ match = re.findall('[_a-zA-Z]+', input_string) if match: return match[-1][-1]
d8b1566ed5c0c9777a90664c47d1fd379838bb0d
636,056
import os def fort_type(filePath): """ Extract the integer type of a fort.X file, where X is the type. """ fullpath = os.path.abspath(filePath) p, f = os.path.split(fullpath) s = f.split('.') if s[0] != 'fort': print('Error: not a fort file:', filePath) else: return int...
e043642adafffa21cf9eac86b91d5cd6be14ca82
636,057
def img2rgb(img): """ Convert the image into rgb mode for displaying :param img: input img :return: output img """ img_rgb = (img / 255)[:, :, [2, 1, 0]] return img_rgb
80c231e4e0d395ed6b5f90d8a9e39b81d0e2c87b
636,058
def get_bbox_from_shapely(shapely_object): """ Accepts shapely box/poly object and returns its bounding box in coco and voc formats """ minx, miny, maxx, maxy = shapely_object.bounds width = maxx - minx height = maxy - miny coco_bbox = [minx, miny, width, height] coco_bbox = [round(point...
18ba6f37de016817c8218a042b3dc1248ab64b35
636,059
import argparse def arg_parse(): """ Parse arguments """ parser = argparse.ArgumentParser( description='This script is for calling the HTTP REST API for Azure ML cloud service') parser.add_argument("--image", dest='image', help="Image file", type=str) return parser.parse_args(...
8014a9f41a38d3d02d88628298b7017362479a57
636,060
import subprocess def paired_devices(): """ paired_devices Return a list of paired devices """ return subprocess.check_output("bluetoothctl paired-devices", shell=True).decode()
ac17cf061a4f9b6e0ffe9bf7ab61afdef26da9a7
636,061
def pb_config(pb2): """Returns an instance of config of *_pb2 package""" return pb2.PrefixConfig()
72fa5d45ca3b77fa538c9491bcb77a4a02904ee8
636,062
def word_counter(text): """ Given a list of words as `text`, count the occurrence of each group of characters in any order that they might appear. Example: foo, ofo, oof are all counting towards foo = 3 """ counter = {} delimiters = ['.', ',', '\n'] for d in delimiters: text = te...
696cb1a44942e17d1d38ddaa7cad9c53c6ce6847
636,063
def _remove_proper_feature(human_readable: str) -> str: """Removes proper feature from human-readable analysis.""" human_readable = human_readable.replace("+[Proper=False]", "") human_readable = human_readable.replace("+[Proper=True]", "") return human_readable
37a07a16a022e380c9f7cdedf8b1d9fb88d25f0c
636,064
def get_data(string: str) -> list[list[int]]: """Take char string of numbers and convert to integer list of lists.""" new_list = list(string.split("\n")) final_list = [] for i in new_list: lst = list(i.split(" ")) ints = [] for j in lst: ints.append(int(j)) fi...
d48c78f1a3983e714ffdb92e09a51bbd7b640ef3
636,065
def _initialize_session(par_harness, protocol_name, hints=()): """ Private function to initialize session. Args: par_harness (ParHarness): An instance of ParHarness protocol_name (str): Name of the protocol hints (list[str]): Hints used in session request Return: sessio...
b3309e279b8de2e4da95f5805c60e8a66f58c5f7
636,066
def flatten_lists(list_of_lists): """ This function flattens a list of lists into a single list. Args: list_of_lists (list): the list to flatten Returns: list: the flattened list """ return [item for sublist in list_of_lists for item in sublist]
d87a55be373f47081e2d60fcfaf75021e579209c
636,067
import subprocess def run_cmd(cmd, shell=False): """ Runs a shell command. :param cmd: Command to run :param shell: Whether to run raw shell commands with '|' and redirections :type cmd: str :type shell: boolean :return: Command output :rtype: str :raises: subprocess.CalledProces...
02dfe94de1ab25f396f57bca1420d374ef290a53
636,068
def get_deadends(lab): """ Return a list of all the dead-ends in a given lab """ deadends = [] for cell in lab.keys(): if type(cell) != type("a"): if len(lab[cell]) == 1 and cell != (0, 0): deadends.append(cell) return deadends
b8ff2e3fab02e06b0d7c6af1c65d0a4abb1fb199
636,069
def cable_type(request): """Dualtor cable type.""" return request.param
f706c51b2003fc73a76c91c6ccd261ae52498a76
636,071
def get_raw_hist_file_path(data_dir: str, data_type: str, split: str = '1.0', concat: bool = False, ext: str = 'pkl') -> str: """ Call as get_raw_hist_file_path(data_dir=data_dir, data_type=data_type...
b840f0fe539e7d4136bdd2cf5f67dc1aac3a07d1
636,072
from typing import List from typing import Tuple from pathlib import Path def parse_benchfile(f) -> List[Tuple[Path, Path]]: """Parse the given file into benchmark cases. On each line in the file, there should be a path to a map, a colon and a space-separated list of scenarios which should be benchma...
5b673c663e19093c7cf9d6b3fb93f8fd5d247087
636,073
def is_in_list(list_one, list_two): """Check if any element of list_one is in list_two.""" for element in list_one: if element in list_two: return True return False
5cb3569b552557909c58e9892f29261d60a20271
636,074
def letters_to_py(_letters): """ return list of letters e.g. uyir_letters as a Python list """ return u"[u'" + u"',u'".join(_letters) + u"']"
0653d3812000da550a4457414b628f6c7b84317c
636,076
import copy def datasets_from_solr_search(solr_search_result): """Convert a Solr search result on files to a Dataset search result. Parameters ---------- solr_search_result : string the json structure from a Solr query Returns ------- out : string restructured json respon...
b653a1696bb40653ba7ad7ea8910d666a5ba4914
636,079
def SortClassAdsByElement(classads, element_name): """ Sort the classads (or any dictionary really) by an attribute @param classads: list of classad objects @param element_name: string of element name """ sorted_ads = sorted(classads, key=lambda ad: int(ad[element_name])) return sorted_...
dcf43f0fb0f4839752664f0e0e2fcd368734395a
636,080
def get_process_command(cmd_args): """Get command-line text for task process.""" # Join arguments into command string, escaping any with spaces. cmd = '' for arg_index, arg in enumerate(cmd_args): if arg_index > 0: cmd += ' ' if ' ' in arg: cmd += '"' + arg + '"' else: cmd += arg ...
a2fb1041155145c1c80057bbb404852593e94cb9
636,081
def bitflip(case, caselen): """Flip 1 to 0 and 0 to 1""" mask = "1" * caselen flip = str(bin(int(case, 2) ^ int(mask, 2)))[2:] return flip.zfill(caselen)
df7da502358324a569784f709cbc8adb38503b5f
636,082
def correct_german_spellings(spelling): """Correcting the exceptions in German spellings. Aeseses -> Aseses Eeseses -> Eseses Heseses -> Beses Aeses -> Ases Eeses -> Eses Heses -> Bes Hes -> B Aes -> As Ees -> Es ---------- H♭♭♭ -> B𝄫 H𝄫 -> B♭ H♭ -> B """ ...
60142a64965615a45f6ea654aeeb57658cbe1067
636,083
def lambda_handler(event, context): """Lambda function to generate the Map input state for LQP Run Base Parameters ---------- event: dict, required Input event to the Lambda function context: object, required Lambda Context runtime methods and attributes Returns ------ ...
7c17c28432ed87123dbedbae22efb7070324a7e3
636,084
def back_to_last_left(path): """ find where is the last step where choice is 1: reverse the index of choices, grab index of first 1, add 1, add minus sign, gives you index of the last 1 """ return path[:-([n.choice for n in path][::-1].index(1))]
7da4a37dca32841761272268be6dce1ae908b38a
636,085
def generate_frapp_broadcastinfos(schedule): """ Generate broadcast infos according to FRAPP datamodel Returns a string """ # Don't translate! weekdays = ('Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag') broadcasttime = schedule.tstart.strftime('%H:%M') + ' ...
c4b20a3103e324761295e7e6a594ac8e3466efdb
636,086
import os import re def get_comparable_filenames(files: list)-> dict: """Returns a dictionary with the conference's files without prefixes and extensions Parameters ---------- files: list List of files to assign to corresponding metadata Returns ------- names_to_compare: dict ...
b09882b1b226c04aa9b8c5198433ec46a724316c
636,087
def text_block(text, margin=0): """ Pad block of text with whitespace to form a regular block, optionally adding a margin. """ # add vertical margin vertical_margin = margin // 2 text = "{}{}{}".format( "\n" * vertical_margin, text, "\n" * vertical_margin ) ...
b045b82bf3d3b2c215d862ef0894b30d72b73d29
636,089
import shlex def convert_arg_line_to_args(arg_line): """argparse helper for splitting input from config Allows comment lines in configfiles and allows both argument and value on the same line """ return shlex.split(arg_line, comments=True)
e0391ed18c2849d5201c36db7264e7c73e98c27d
636,090
def update_key(args_dict, key_to_update, replace_value): """ Searches and replaces text in keys from received dictionary """ for key, value in args_dict.items(): if isinstance(value, dict): args_dict[key] = update_key(value, key_to_update, replace_value) if key_to_update in arg...
e55cc70e2c89faf82b0c1832299fcda511a22aea
636,091
import torch def load_ckpt(modules_optims, ckpt_file, load_to_cpu=True, verbose=True): """ load state_dict of module & optimizer from file Args: modules_optims: A two-element list which contains module and optimizer ckpt_file: the check point file load_to_cpu: Boolean, whether to t...
29a3131e41236d19c556c955f7f319c19747b7d8
636,092
def slice_detections(all_ground_truth_bboxes, slice_mode): """ Find indices of detections of interest and modify the ground truth detections based on slice mode. Params: all_ground_truth_boxes (List of xml.etree.ElementTree.Element): List of all ground truth bounding boxe...
f3da6f6a5c84c973c92add16dd65afb4c0763f18
636,093
def get_attr_value(attrs, key): """Read attr value from terncy attributes.""" for att in attrs: if "attr" in att and att["attr"] == key: return att["value"] return None
73ec422f8a0a48890fa9faf5e0f8d8044dd156f2
636,094
import os def find_huc12s(scenario): """yield a listing of huc12s with output!""" res = [] for huc8 in os.listdir("/i/%s/yld" % (scenario,)): for huc12 in os.listdir("/i/%s/yld/%s" % (scenario, huc8)): res.append("/i/%s/yld/%s/%s" % (scenario, huc8, huc12)) return res
55474daaee01ff76752a85babc761794cd7af1e6
636,095
from functools import reduce import operator def findTheDifference(self, s, t): # ! 68ms 采用异或 """ :type s: str :type t: str :rtype: str """ return chr(reduce(operator.xor, map(ord, s + t)))
23fdfd75725db189829f31ad776afedeb6fcb50e
636,097
def ec2_entities(job_name): """ Returns the name of basic ec2_entities. * Keypair name * Security group for slaves * Security group for master @param job_name: User given name of the Job. @type job_name: string """ keypair_name = "multistack-" + job_name sec_slave = "multistack...
95ebdc4bd4a3ffb875df77e89dac0b762e188e8c
636,098
def contar_caracteres_repetidos(cadena: str) -> int: """ Caracteres Repetidos Parámetros: cadena (str): La cadena que se debe revisar. Retorno: int: La cantidad de caracteres diferentes que aparecen repetidos en la cadena. """ caracteres_cadena = {} diferentes_repetidos = 0 for c...
e107df83fc5f6525f3aba76c920c38669318ce3f
636,099
import math def resize_bytes(input_bytes: bytes, length: int): """Takes in a byte string and an integer. Outputs the byte string repeated till it is of length integer""" multiplier = math.ceil(length / len(input_bytes)) raw_output = input_bytes * multiplier return raw_output[:length]
8a056dc8b7fed2054049ab3b7d4671a62a7a3939
636,101
def numbase(n, dim): """Calculates the number of basis in a complete degree 'n' polynomial basis in 'dim' dimensions @param n The degree of the polynomial @param dim The dimension of the basis @retval nb The number of basis in a complete degree 'n' polynomial basis ...
a707488daa2088f6d9b066080a6e2439713519aa
636,102
def lmap(v, x, y) -> float: """Linear map of value v with range x to desired range y.""" return y[0] + (v - x[0]) * (y[1] - y[0]) / (x[1] - x[0])
0e8b272fab0e4f1397c2e21631dd7b88b6eb8d31
636,103
def get_folder_id(path, c): """Query the folder id of the directory.""" sql = ''' SELECT folder_id FROM folders WHERE path = ? ''' c.execute(sql, (path, )) return c.fetchone()[0]
4f958498007e618ca23f0cbe386f1ed1d4a2e7bd
636,104
import fnmatch import os import re def glob_to_re(pattern): """Translate a shell-like glob pattern to a regular expression; return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = ...
c6c63d3645ec6fa2bd35a07cc498a04a4b047f4d
636,105
def getmeminfo(): """ try to return some memory info input: none output: dict with memory info """ data = open("/proc/meminfo", 'rt').readlines() memdict = {} # let's start with the free memory: for line in data: if line.startswith("MemFree"): ...
802c14930d0618c9b1b9513247edffc6ea48666f
636,107
def node_restore_all(self, flag=0) : """ Restores a all device from the configuration in ISY args : flag 0 or 1 Flag : 0 = All shall be restored from the configuration files in ISY 1 = Does not regenerate groups/scenes - good for testing ...
ef7f63ee26b9e08e23e3ac26971729e008322858
636,108
import torch def FloattoRGB(images): """Converts a 0-1 float image with an alpha channel into RGB""" if len(images.size()) < 4: images = torch.unsqueeze(images, 0) return torch.clip(images[:,:3,:,:] * images[:,3,:,:] * 255 + (1-images[:,3,:,:])*255, 0, 255).type(torch.uint8)
9ae3e06d6168c8100fda6f35f1074fbcd53a1794
636,109
def get_tf_config(worker_num, index, ports, machine_list=None): """Generate tf config.""" hosts = [] if machine_list is not None: hosts = machine_list.split(",") hosts = [host if host.startswith('"') else '"{}"'.format(host) for host in hosts] else: ip = '127.0.0.1' for i in range(worker_num): ...
9b95f72e141cdf908c115d37d4ab7c8e3a736951
636,110
def extract_from_config(config): """ When parsing, config can be wraped at dictionary where 'config' contains given config """ if isinstance(config, dict) and 'config' in config: return config['config'] return config
ed2a13eee68da28b323973b176ba9aef5661eb5c
636,111
def get_zipcode(): """read zipcodes from file.""" with open('./data/zipcodes.csv', 'r+') as file: zipcodes = [ (zipcode.strip()) for zipcode in file.read().split('\n') if zipcode.strip() ] return zipcodes
3e0192ccc1c259db36fa8ea42707966b93bda5a4
636,112
import inspect def get_argument_spec(provisioner_method): """ Provides the argument list and types of methods which have a default value; :param provisioner_method: the method of an instance :return: the method arguments and default values as a dictionary, with method parameters as key and default val...
bec2d409bebdf19bc3209c0a1a66911d0242577f
636,113
def launch_piece_letter_to_number(letters): """Convert 24 upper case letter 3-letter code to integer, omitting I (eye) and O (oh) from the alphabet. The TLE standard is 24 upper case letter 3-letter code, omitting I (eye) and O (oh) from the alphabet, with no representation for zero. The 1st p...
ddcb3177ebf32f19551673f3413e62643c3e3b4a
636,114
def _uuencode_int6(n): """uuencode a 6-bit element into a char""" if n == 0: return '`' else: return chr(0x20 + n)
2b2dd55fb3440e3ec56c4cdb6650c32380e31f4f
636,115
import six def _MergeDicts(a, b): """Shallow merge two dicts. If both dicts have values for a same key and both are lists, it concats them. Args: a: a dict object. This will be updated with merged items. b: a dict object. Returns: a merged dict object. """ for key, value in six.iteritems(b)...
4bf7a5ba20806003e7cd92fc6f9aa415301d8bc6
636,116
def _time_hms(datetime_obj): """ Return datetime_obj formatted as mm/dd HH:MM:SS. """ return '{time:%m/%d %H:%M:%S}'.format(time=datetime_obj)
a08bafac2c9d40ef2b08d5eba5475972cc12adc1
636,117
import collections def get_gene2go_info(genes_w_pval, go_fname): """ Parse gene2GO annotation file """ gene2go=collections.defaultdict(list) go_fh=open(go_fname, 'rU') for line in go_fh: parts=line.strip('\n\r').split('\t') if parts[0] in genes_w_pval: gene2go[p...
02ceaa104bc72424b8847fe6e190cc5cf84d3c18
636,118
def rgb(r, g, b, divide_by=255.0): """Convenience function: return colour in [0, 1].""" return (r/divide_by, g/divide_by, b/divide_by)
afff50abe9e0d8184008002af954a24072dd4649
636,119
def get_travels_url(root): """从页面中获取景点对应的游记展示页面的地址,以进一步爬取游记""" try: travels_url = root.find_element_by_link_text("查看相关游记").get_attribute('href') return travels_url except: return None
d2d6f7f0ee83cd56bb11522dfa1b391f0ab5da81
636,120
def _get_set_name(test_data): """Get the set_name from test_data Return the value of 'set_name' key if present in the data If set_name it is not present in data, return the value of the first key. If there's no data, leave set_name as '' """ set_name = '' if 'set_name' in test_data: ...
8b02fe1c6bb53afba312fe228966b58bc083d63a
636,121
def _phi(speciation_initiation_rate, speciation_completion_rate, incipient_species_extinction_rate): """ Returns value of $\varphi$, as given in eq. 6 in Etienne et al. (2014). Parameters ---------- speciation_initiation_rate : float The birth rate, b (the incipient speci...
dcd56555661f565d5a6648734125fb3f2e997aad
636,122
def create_cmd(parts): """Join together a command line represented as list""" sane_parts = [] for part in parts: if not isinstance(part, str): # note: python subprocess module raises a TypeError instead # of converting everything to string part = str(part) ...
c7fe6e58d32c96fe4d70a3cc1290638170351b88
636,123
def write_names_to_file(): """ 106 Create a new file called “Names.txt”. Add five names to the document, which are stored on separate lines. Once you have run the program, look in the location where your program is tored and check that the file has been created properly. :return: """ wit...
7b11242c2767798222b1c84b78c16e2ab2bbf6fa
636,124
from typing import Tuple from pathlib import Path import argparse def parse_arguments() -> Tuple[str, Path, Path, float]: """Parse command line arguments Returns: Tuple[str, Path, Path, float]: (identifier, path to save log, path to store video, record_time) """ parser = argparse.ArgumentPars...
8c87e316d5eef737361ba8b1b5b99d22624fc882
636,125
import os import subprocess def get_current_branch(srcdir): """Return current Git branch name checked out in the given directory. :param srcdir: source code directory :type srcdir: str :return: checkout out branch in the component source code directory :rtype: str """ os.chdir(srcdir) ...
2e45945820749f7c16a089db3ffc6b0161d231c2
636,126
def trim_pv(pv): """ Strip anything after +git from the PV """ return "".join(pv.partition("+git")[:2])
8061a761de8c18a1465c6c9274de43ce99a2ad15
636,127
import subprocess def check_slurm(): """Check if this script is run on a frontal with slurm installed.""" try: subprocess.check_call(["sbatch", "--version"], stdout=subprocess.PIPE) return True except OSError: return False
e9075638c2a1267c9417021043953858d2b5aa18
636,129
def APs2mAP(aps): """ Take a mean of APs over all classes to compute mAP """ num_classes = 0. sum_ap = 0. for _, v in aps.items(): sum_ap += v num_classes += 1 if num_classes == 0: return 0 return sum_ap/num_classes
807df1ff7b64824855cec16cc8ce39b55d03ca17
636,131
import argparse def create_parser(args): """ Function which add the command line arguments required for the command line input of text similarity index processor""" # Create the parser cos_parser = argparse.ArgumentParser(description='Text Similarity') # Add the arguments cos_parser.add_argum...
1cfa03030d4fc6d84ae014df380c3d5de1458307
636,132
def calc_stress_drop(magnitude): """Stress drop using Atkinson & Boore (2011, :cite:`atkinson11`) model. Parameters ---------- magnitude : float Moment magnitude of the stress drop. Returns ------- stress_drop : float Stress drop (bars). """ return 10 ** (3.45 - 0...
22e137b215368293e7926b21d8734150b54acfd3
636,133
import hashlib def generate_empty_template(page): """Generate an empty template(sample) page""" return { 'extractors': {}, 'url': page.url, 'original_body': page.body, 'scrapes': 'aile-item-0', 'page_type': 'item', 'page_id': hashlib.md5(page.url).hexdigest(), ...
be1c2a270e43fcd807188fbf4f779550d2c4ed13
636,135
def _clean_dt_data(anno, current_cls_name, difficulty): """clean dt data""" min_height = [40, 25, 25] num = len(anno['name']) ignored = [] for i in range(num): if anno["name"][i].lower() == current_cls_name: valid_class = 1 else: valid_class = -1 heigh...
5f542f63ffcb4ac3570c81941e4645ba83466da0
636,136
def search_mergedcell_value(xl_sheet, merged_range): """ Search for a value in merged_range cells. """ for search_row_idx in range(merged_range[0], merged_range[1]): for search_col_idx in range(merged_range[2], merged_range[3]): if xl_sheet.cell(search_row_idx, search_col_idx).value:...
7fa60dadf60f9be95686fade14466b05e7f030bd
636,137
def _(obj, **kwargs): """ Used for dict & json serialization """ fields = { 'days':'d', 'hours':'h', 'minutes':'m' } fmts = [] for field, abbr in fields.items(): val = getattr(obj.components,field) if val > 0: fmts.append(f"{val}{abbr}") ...
15b125ae18e5a8d1be86c0a1315c6c9dd2738766
636,138
def add_route(routes, start, finish, number): """ Добавить данные о маршруте """ routes.append( { 'start': start, 'finish': finish, 'number': number } ) return routes
ec5c57bed636b393149b823e817b70a1a3fd2a72
636,139
def _theta_deg_to_alpha(theta): """ Non implémenté de manière définitive Formule : alpha = (2 sin(θ))/(sqrt(3 - 3 sin(θ)^2) + 3 sin(θ)) Utilisée avec succ pour la représation d'échantillons de microstructures. """ # sin_ = np.sin(np.deg2rad(theta)) # alpha = (2 * sin_) / (np.sqrt(3 - 3 * sin_ **...
ea735dc35265866a647afdaa346f9405efbb6998
636,140
def biggest(aDict): """Returns the key corresponding to the entry with the largest number of values associated with it. If there is more than one such entry, return any of the matching keys :aDict: {string: [string]} :returns: string """ result = ('', 0) for (k, v) in aDict.items(): ...
1db89a37f53393b09d69cf6a1f30c8924d87ed20
636,141
def guesstype(s, makeintfloats=False): """ guess the datatype (between ints, floats, str) of the object printed as a string and return a tuple of (dtype, data in appropriate dtype) Parameters ---------- s : mandatory, string elemental python data type whose type we want to obtain ...
6a17e6b46feafbf09a3838542d34add53456a2c1
636,142
def bounding_box(points): """ The function calculates bounding_box from the coordinates. XY - Min , XY - Max :param points: coordinates list :return: List of bounding box. """ x_coordinates, y_coordinates = zip(*points) return [(min(x_coordinates), min(y_coordinates)), (max(x_coordinates), m...
1bc25ef347284cecf167b9067e9d20fd9ec273ad
636,143
def image_data_to_dict(image_data): """ Converts a desktop notification image data array into a dict. """ result = {} result['width'] = image_data[0] result['height'] = image_data[1] result['rowstride'] = image_data[2] result['has_alpha'] = image_data[3] result['bits_per_sample'] = image_data[4] result['chan...
26363d8cb183133c975cc9d2612d0731a5a86e3b
636,144
import numpy def GenerateMixedGraph(num_samples, block_size): """ Generates a (consistent) mixed graph. """ N = num_samples num_blocks = N // block_size if N % block_size != 0: err = "num_samples(%d) must be a multiple of block_size (%d)" % (num_samples, block_size) raise Exception(er...
872d5e8309240bf1dd83c22fc082b73d66c5093b
636,145
import re import pathlib def get_library_folders(steam_path, library_index_path): """ Reads the library index file `libraryfolders.vdf` to get a list of all Steam library locations on your system. Because of the lazy way in which the RegEx is written, it only supports up to 100 Steam librarie...
c53004126426c5ab37c211c365f0d1ce40a3a29d
636,146
import os def soft_link(src, dst): """ create a link if filesystem supports it otherwise copy """ return os.symlink(src, dst)
06129ed147c1bf895033d867c8751466d4da4f70
636,147
def c(sr=False, sy=False, e=False): """ -> Cores vermelha e amarela :param sr: start red(começo vermelho) :param sy: start yellow(começo amarelo) :param e: end(fim) :return: codigo de começo e fim de cor """ if sr: return '\033[0;31m' if sy: return '\033[0;33m' if...
c6f4acd2c61316b7ee403389385d8b649ffe217b
636,148
def filter_str(check_str): """ 过滤无用字符 :param str check_str:待过滤的字符串 :return str temp:过滤后的字符串 """ temp = '' for i in check_str: if i != '\n' and i != '\x00': temp = temp + i return temp
2787d1455beb491b85ce3db17232503565b76693
636,149
import torch def cosine_cont(repr_context, relevancy, norm=False): """ cosine siminlarity betwen context and relevancy Args: repr_context - [batch_size, other_len, context_lstm_dim] relevancy - [batch_size, this_len, other_len] Return: size - [batch_size, this_len, context_lstm...
990b1fa659ce7d00b951b4bf1a6e389c7333adcc
636,150
import requests def obtener_pais(codigo: str) -> str: """Obtiene el nombre del país a partir del código. :param codigo: Código del país. :codigo type: str :return: Nombre del país. :rtype: str """ url = f"https://restcountries.com/v3/alpha/{codigo}" response = requests.get(url) ...
399e08b7bfd9546c6a4d122e9bca451fe6f00840
636,151
def merge_proteins(proteins): """ Merge all isozymes that catalyze a given reaction. Automatically removes all isozymes with missing score. Args: proteins (pandas.Series): list of proteins Returns: str: boolean rule """ proteins = set(proteins.dropna()) if not proteins: ...
b22b798f9aa66549181dea6020bbaeff5d03888b
636,152
def extract_stats_from_uartlog(uartlogpath): """ read a uartlog and get sim perf results """ elapsed_time = -1 sim_speed = -1 cycles = -1 with open(uartlogpath, 'r') as f: readlines = f.readlines() for line in readlines: if "time elapsed:" in line and "simulation speed" in line: ...
c37dd9b850ed6045a5c2eb4628a3341301a1b23b
636,153
def to_float(seq): """ Takes an arguement seq, tries to convert each value to a float and returns the result. If a value cannot be converted to a float, it is replaced by 'nan'. Parameters ---------- seq : array-like The input object. Returns ------- subseq : array_like ...
f54d58df236d9a196369cc3153c8a472da632161
636,154
import time def time_now_str(format_str='%Y-%m-%d'): """ 获取当天时间 :param format_str: :return: """ return time.strftime(format_str, time.localtime())
9898e11abd35cdd74b9432da84d6961adcaab277
636,155
def c(x, y): """Returns 1 if x < y and -1 if x > y.""" return (y - x) // abs(y - x)
f8cb7afafefaf9ba4bd4813f5c5f730a08734aa3
636,156
def ghost_api_update_bluegreen_app(apps_db, blue_app, green_app_id): """ Update the current app blue_green object """ # Generate the BlueScreen object for the green app blue_green = blue_app.get('blue_green') color = blue_green.get('color', 'blue') if blue_green else 'blue' blue_green = { ...
a9d28569fc849546845a040666f065baeb2bcfe2
636,157
def col_length(headline, content, dict_key=None): """ calculate the max needed length for a output col by getting the headline, the content of the rows (different data types) and in some cases a specific key :param headline: Column headline :param content: A list of column contents :param dict_k...
57d95b80f16a047bbf085be00786fe85cd1907ac
636,158
import sys def site_packages(modules_tmpdir, monkeypatch): """Create a fake site-packages.""" rv = modules_tmpdir \ .mkdir('lib') \ .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \ .mkdir('site-packages') monkeypatch.syspath_prepend(str(rv)) return rv
62247eb119c9e812171a7ac9f603dc668a71e036
636,159
def private_key(): """Server side private key.""" return "Lehma take over Cancuu tacos"
c4fb7bdd4f990e0c9a90de2737be3217cba28e95
636,160
import csv def read_limericks(): """ :return: List of poems """ with open(f'data/raw/limericks.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter='"') return [r[0] for r in csv_reader]
422b7d1b23bacaf36beb7e24f4596dc71f8ccd21
636,161
import requests def _connect_to_attivio(target_address, auth): """ Connecto to attivio and return session id """ url = '{attivio}/rest/ingestApi/connect'.format(attivio=target_address) response = requests.get(url=url, auth=auth) response.raise_for_status() return response.json()
e11a1ae58e60b13cff3b5f7f1a41078e99d77a49
636,162
def get_theme_color(html): """Scrape brand color.""" if html.find("meta", property="theme-color"): color = html.find("meta", property="theme-color").get('content') return color return None
6b908a4d18f79e5f09acbaf2343849e4917a53d2
636,164
import os import pwd def my_user_name(): """ Returns the name of the user running this process. """ uid = os.getuid() return pwd.getpwuid( uid )[0]
c887fe5628fcdfd93cff75eb0a67e19882061b9f
636,165