content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _temp_analyze_files_prime(tmpdir): """Generate temporary analyze file pair.""" orig_img = tmpdir.join("orig_prime.img") orig_hdr = tmpdir.join("orig_prime.hdr") orig_img.open('w+').close() orig_hdr.open('w+').close() return orig_img.strpath, orig_hdr.strpath
4d1b390936c2c92e90c2fe82d44097683262be2c
659,278
from xdg.DesktopEntry import DesktopEntry def parse_linux_desktop_entry(fpath): """Load data from desktop entry with xdg specification.""" try: entry = DesktopEntry(fpath) entry_data = {} entry_data['name'] = entry.getName() entry_data['icon_path'] = entry.getIcon() en...
e3b43c3c1331bfee7f4dd244b8f8ba5344cefc09
659,279
import ssl def build_ssl_context(local_certs_file: str, ca_certs_file: str, key_file: str, ): """ :param local_certs_file: The filename of the certificate to present for authentication. :param ca_certs_file: The filename of the CA certificates as passed to ssl.SSLContext.load_verify_locations :param k...
1643fb82319e421ce87054f00d0a18a288e08dfa
659,280
import math import sys def make_image_square(samples=16, flipy=False): """ Creates a list containing the image data in a square format. :param samples: The number of samples, should be 16, 64 or 256 :type samples: int :param flipy: Flip the image vertically :type flipy: bool :return: List...
d1f23767e351b98c9666e8a6710da22813cd0061
659,281
import textwrap def to_curvedskip(of, to, angle=60, xoffset=0): """ Curved skip connection arrow. Optionally, set the angle (default=60) for out-going and in-coming arrow, and an x offset for where the arrow starts and ends. """ text = rf""" \draw [copyconnection] ([xshift=...
6e7ff9430d53690f327dec2da6da24be10a7c656
659,282
from typing import List def subarraySum1(nums: List[int], k: int) -> int: """前缀和优化""" length = len(nums) if length <= 0: return -1 #前缀和n+1项 sum = [0] * (len(nums) + 1) sum[0] = 0 for i in range(0, length): sum[i+1] = sum[i] + nums[i] count = 0 for i in range(0, length): ...
a38353b052179e1f9580b8e61858119270a1692f
659,283
def file_loader(filepath): """Extract the text data from the paragraph file""" with open(filepath, "r") as paragraph_file_handler: return paragraph_file_handler.read().lower().split()
405dca98d5b6b16e64dbd0e4e245220b34c330aa
659,284
import os def get_int_env(envname): """ Gets the int value of a environmental variable. Args: envname (str): name of the environmental variable Returns: os.environ.get(envname , 0): the value of the environmental variable...
ca186026e05ad7b434fcf3436bf9d49435907cdc
659,285
import dataclasses def abstract_variable(): """Marks a variable as abstract such that a child class needs to override it with a non-abstract variable. See :py:func:`variable` for the non-abstract counterpart. Examples: >>> @dataclasses.dataclass >>> class CustomTask(Task): >>>...
8ce4f53d63d07fb2071a00b338cbf966e600ca2d
659,286
from typing import List def parse_key_name(keyname) -> List[str]: """keyname => resource, username""" # Relies on resource name not containing -, validated in # validate_resource_name toks = keyname.split('-') if len(toks) != 2: return [] # some other keyname not launched by nexus else: return to...
3a7fd94ee7e41fb3ba8459277856d35c52650f09
659,287
def extract_video_id_from_yturl(href): """ Extract a Youtube video id from a given URL Returns None on error or failure. """ video_id = None try: start = -1 if href.find('youtube.com/watch') != -1: start = href.find('v=') + 2 elif href.find('youtu.be/') != -1...
f5b31e11300abef58c1a3588c471f906c207a21f
659,288
import pickle def get_label_dict(train_dir, val_dir): """ Return the dictionnary ID - (labels, confidences) """ link = train_dir + '/pickle/combined.pickle' with open(link, 'rb') as f: dict_train = pickle.load(f) if val_dir != None: link = val_dir + '/pickle/combined.pickle' wi...
0389078eb4852bf8375a89e1e8ede5537cc4d745
659,289
def zone_bc_type_english(raw_table, base_index): """ Convert zone b/c type to English """ value = raw_table[base_index] if value == 0: return "NA" if value == 1: return "Direct" if value == 2: return "3WV" if value == 3: return "NA" if value == 4: ret...
d6fef02dd92ec1604b2bb892e6ad6dc00d5f889f
659,290
import subprocess import sys def exec_command(command, **kwargs): """ Executes a command and exit if it fails """ comp = subprocess.run(command, capture_output=True, **kwargs) if comp.returncode != 0: sys.exit(1) return comp
d7fa8cb3da5defc3b47487353df36c50ad6eeead
659,291
import uuid import hashlib def _create_token(user): """Create a unique token for a user. The token is created from the user id and a unique id generated from UUIDv4. Then both are hashed using MD5 digest algorithm. """ _id = f"{user.id}-{str(uuid.uuid4())}" _hash = hashlib.md5(_id.encode('as...
ea2458c45043ed9c0902b0a88d20c9c13ede00d0
659,292
def git_clone(repo, branch=None): """ Return the git command to clone a specified repository. Args: repo: string representing a git repo. branch: string representing a branch name. Returns: cmd: list containing the command line arguments to clone a git repo. """ cmd = [...
1f96df641285a98ad18e0de766c76f1ecc51c98c
659,293
def test_extras(): """ A valid dict of extras as would be returned by 'get_setup_deps' or 'get_pipfile_deps' """ return { 'pyhive': ['hive', 'presto'], 'testpackage': ['extra0', 'extra1'] }
39accc1cc9a79d32ab8f192ca6877764edff04f3
659,294
def _extract_version(version_string, pattern): """ Extract the version from `version_string` using `pattern`. """ if version_string: match = pattern.match(version_string.strip()) if match: return match.group(1) return ""
5fcb5b60a7a3ae70ba2ad2c2bb7e9c92bf0db6d7
659,297
def prepend_dict_key(orig, prep_text, camel_case=False): """ Return a new dictionary for which every key is prepended with prep_text. """ if camel_case: return dict( (prep_text + str(k).title(), v) for k, v in orig.items() ) else: return dict((prep_text + str(k), ...
1c5ed248c24fe2b849451ef0f45bd88fa8d4556d
659,298
def int_check(input_value, warning_box): """Checks if input is a positive integer.""" try: int_value = int(input_value) if int_value > 0: warning_box.config(text="") return True else: warning_box.config(text="Please type a positive integer.") return False except ValueError: warning_box.config(tex...
bbd606380625b6ba8bd7195680feac49aa4e33d5
659,299
def generate_connector_name(storage_type, rt_id): """ 构造任务名 :param storage_type: :param rt_id: rt id :return: connector name """ return storage_type + "-table_" + rt_id
4d6a8bbdb15d9c48a1ac8af08464b380ce1a735d
659,300
import os import requests def check_number(link, number, plain_key): """Checks if number and plain key match.""" payload = { "key": os.getenv("KEY"), "plain_key": plain_key } return requests.post(f'{link}/number/{number}', json=payload).json()
765eaeb356efb3239ce054e9449230f57fe81ffb
659,301
import os import re def is_interest_call(call_command): """ A predicate to decide the entry is a compiler call or not. """ basename = os.path.basename(call_command).lower() patterns = [ re.compile(r'^g(cc|\+\+)(-\d+(\.\d+){0,2})?'), re.compile(r'^([^-]*-)*g(cc|\+\+)(-\d+(\.\d+){0,2})?'), ...
d5d94f7153791b08fe5475b505bb9c0be0c06005
659,302
def is_win(matrix): """ is game win? return bool """ for item_list in matrix: if 2048 in item_list: return True return False
c5a77933037064f8330963ce8fe4cc49db8c909c
659,303
import sqlite3 def get_twinkles_visits(opsim_db_file, fieldID=1427): """ Return a sorted list of visits for a given fieldID from an OpSim db file. Parameters ---------- obsim_db_file : str Filename of the OpSim db sqlite file fieldID : int, optional ID number of the field ...
791f779cfba6125eaf7efea1930c6373f71e3efe
659,305
import string import random def random_string(string_length=20, punctuation=True): """ Create a random string that is quotable. Usable for basic passwords. Args: string_length - (optional) The number of characters to generate punctuation - (optional) True if the generated characters shoul...
09224f0dd520832eda6538d865e22f7446b92f5a
659,307
from pathlib import Path import json def read_authors(filename): """Read the list of authors from .zenodo.json file.""" with Path(filename).open() as file: info = json.load(file) authors = [] for author in info['creators']: name = ' '.join(author['name'].split(',')[::-1]).s...
b79602070a27495aa7bed3b5f004aece2e1ead29
659,309
import torch def get_center_block_mask(samples: torch.Tensor, mask_size: int, overlap: int): """ Mask out the center square region of samples provided as input. Parameters ---------- samples: torch.Tensor Batch of samples, e.g. images, which are passed through the network and for which sp...
9f020a5ce4f1128b3112e8106a9facd82e1af124
659,310
import re def hex2rgb(hex_code: str) -> tuple: """ Convert color given in hex code to RGB in ints. Result is returned inside 3-element tuple. :param hex_code: :return: tuple (R, G, B) """ pattern = re.compile(r'^#?[a-fA-F0-9]{6}$') if not re.match(pattern, hex_code): raise ValueEr...
ae855676d25c320a47ad6ee64e4669ea23e50a1d
659,311
def eh_posicao(pos): # universal -> booleano """ Indica se certo argumento e uma posicao ou nao. :param pos: posicao :return: True se o argumento for uma posicao, False caso contrario """ # uma posicao e um tuplo com dois elementos em que ambos variam de 0 a 2 if type(pos) != tuple or len(p...
036e6ce48b8c96dd2732d828225e84ceceb73a95
659,312
def _choose_num_bootstraps(sample_size, mean_size, fuel): """Choose how many bootstraps to do. The fuel is the total number floats we get to draw from `np.random.choice`, which is a proxy for the amount of time we're allowed to spend bootstrapping. We choose how many bootstraps to do to make sure we fit in ...
69f18667c5df7c2d3017a3ca8d573eb2e631731c
659,313
def add_totals_to_dataframe(df, row_name="Row total", col_name="Column total"): """Add row and column totals to dataframe""" df.loc[row_name]= df.sum(numeric_only=True, axis=0) df.loc[:,col_name] = df.sum(numeric_only=True, axis=1) return df
8babbf24ff436be9b0b1c36461c86961118f3478
659,315
import uuid def get_unique_suffix(): """ Get unique suffix by using first 4 chars from uuid.uuid4 to make unique identity name. :return: Unique suffix string. """ return str(uuid.uuid4())[:4]
cab78e0ed0e1302d65cad427d1e825d2c8d4b39f
659,316
import torch def segment2distance(points, segment, max_dis=None, eps=0.1): """Encode segment based on distances. Args: points (Tensor): Shape (n,), [center]. segment (Tensor): Shape (n, 2), "start, end" format max_dis (float): Upper bound of the distance. eps (float): a small ...
2d6c499b3eaa80a369724281382a1c36f73c5e61
659,317
def CreateOnHostMaintenanceMessage(messages, maintenance_policy): """Create on-host-maintenance message for VM.""" if maintenance_policy: on_host_maintenance = messages.Scheduling.OnHostMaintenanceValueValuesEnum( maintenance_policy) else: on_host_maintenance = None return on_host_maintenance
5daaf3baf6e2b33066e8febebd15a54402e1f081
659,318
import posixpath def ls(session, path): # pylint: disable=invalid-name """ List files on an iRODS server. Args: session (iRODS.session.iRODSSession): iRODS session path (String): path on iRODS server to list. Must be absolute. """ coll = session.collections.get(po...
4228d65551b9206b619c92cccd56a3d406327d9a
659,319
from typing import Mapping from typing import Optional from typing import Any from functools import reduce def get_value_by_dot_notation(dict_obj: Mapping, key: str, default: Optional[Any] = ...) -> Any: """ Return the value of a key in dot notation in a arbitrarily nested Mapping. dict_obj: Mapping k...
541438295d03ac7d987584c6a219158b12062bc3
659,320
import hashlib def get_md5_checksum_of_file(file_path): """ Get the md5 checksum of the local file. """ return hashlib.md5(open(file_path, 'rb').read()).hexdigest()
49dee23ed967c9c6b9a35260b9096a757ff9cc1f
659,321
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
063710899786bc7e5872a2980647f0b14a186183
659,322
def topological_sort(graph): """Conducts a topological sort of a directed acyclic graph and returns the sorted nodes as a ``list``. :param dict graph: The graph to sort, which must be a ``dict`` mapping each node to a ``set`` containing that node's edges (which are other nodes present in t...
852e89b6b9103309f07abd5b49810a9158571ce5
659,323
def clamp(a, x, b): """ Ensures x lies in the closed interval [a, b] :param a: :param x: :param b: :return: """ if x > a: if x < b: return x else: return b else: return a
3c36572de64e4ecdaca0b9bd73a49ac04b088437
659,325
def calc_sidak_correction(alpha_value, num_total_tests): """ Calculates the Sidak correction for multiple hypothesis testing for a given alpha-value. See http://en.wikipedia.org/wiki/Bonferroni_correction#.C5.A0id.C3.A1k_correction for more detail. Returns the Sidak corrected p-value upon ...
5b9eb37930167ba01f441fc240add2f8035ed22d
659,326
def fuel_requirement(mass: int) -> int: """Base fuel requirements for a single module.""" return (mass // 3) - 2
fec5f5ca44a2b3f26f0f6578338bfbe07308c495
659,327
def generate_field_mapping(field_groups): """ Returns mapping for collapse_field_mapping made from field groups: list [ dict { 'from': dict { 'client_id': int, 'object_id': int }, 'to': dict {...
e075c5e1f25c4bf74dc2f6c577094c469d7bb1e2
659,328
import random def generate(alignment): """Return a character based on alignment""" characters = {'good': [{'first': 'Jack', 'last': 'Goodguy', 'pronouns': ['he', 'him', 'his']}, {'first': 'Wanda', 'last': 'Smart', 'pronouns': [...
c4b22a30dadb221d2b537ed84b855c665c635d9e
659,329
import pkg_resources import inspect def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point( "ipython", "c...
fc9edd10a67ca93dcb53945d66f8a3a5be32d94f
659,330
def notify_hello(*args): """ Sample with a list of optional arguments (returns the list), meant to be called as a notification """ return args
80d4af0d190c1210aa0ef4a0715a122bb3807669
659,332
def text2short(text, max_length=20): """ long text to short text """ if text is None: return '' text = str(text) return text[:max_length] + '...' if len(text) > max_length else text
10432dff6e36336af72ff813f0eebd792988bd39
659,333
import os def relpath(path): """Returns the relative path to the script's location Arguments: path -- a string representation of a path. """ return os.path.join(os.path.dirname(__file__), path)
734427227013b737ac13fd0770a4d5f4f76c6360
659,334
def kph2ms(v): """ This function converts velocity from kph to m/s. """ return v / 3.6
85e8f03030ee80ed5cb531ec8d142761edd9a72e
659,335
import importlib def _import_func(dotted_str): """ Imports function using dot-notation string. :param dotted_str: Dotted path to function like `module.submodule.func` :return: func """ module_name, factory = dotted_str.rsplit('.', 1) module = importlib.import_module(module_name) try: ...
5c09ff9e81fe91f98b8376bc3d6d8eebbddeb0aa
659,336
import decimal def enforce_decimals(obj: object): """Enforce required (Decimal) formatting of the object's attributes by replace (float) and (int) types. Args: obj (object): Returns: object: obj """ if isinstance(obj, list): for i in range(len(obj)): obj[i] = enforce_decimals(obj[i]) return obj elif ...
b815b6dfb43ce4d5a8d5200b7aee09a387337a50
659,337
def StrJoin(delim, data): """String-ize & join data.""" return delim.join(str(x) for x in data)
10e54ba84f686b0f48c9ab6766515db37a16b88f
659,338
import random def weighted_choice(weight): """ Parameters ---------- weight: float Weight of choosing a chromosome Returns ------- Bool random (not uniform) choice """ # This help to don't generate individuals of the same size on average p = random.uniform(0, weig...
7a5a39f726ddef22110aa9a4c8821a0c6b5e278a
659,339
import yaml def encrypted_constructor(loader: yaml.SafeLoader, node: yaml.nodes.MappingNode): """ Construct an ecrypted token. """ return ""
435f5479f84ef9ba80c0a320bbcba5f399d9d193
659,340
from typing import Any import os def readFile(path: str, fd: int) -> Any: """ Read File Contents located at a specified path. Parameters ---------- path : str File path to locate file to read. fd : int Associated file descriptor Returns ------- content : Any ...
c6ee7b6ddb09653db120a168504be78b386a7435
659,341
import os def separate_by_length(input_stream, length_max, length_min, file_prefix = ""): """ Given a bed file handle and a length range [min length, max length] it partitions the file into bed files for each length in the given range file_prefix is pre_appended to each file ...
edbbc63880e174c5c6e21b489d685a10e06204e7
659,342
def dominant_sign(elements): """ A function to calculate the dominant sign of a set of numbers :param elements: a list of numbers :return: the dominant sign """ return sum(elements) / abs(sum(elements))
732b23ab87a8ade41f8aac5b84e44a2a7ad2931e
659,343
import argparse def parse_args(): """parse arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--script-file', help='execute script file') parser.add_argument('--script-args', help='args of script') parser.add_argument('--expect-output', help='expect output') parser.add_argum...
00ba011ecbeaa136e7a151964d4de67a2f9888b5
659,344
def load_kernel_code(filename): """return the cuda source code""" with open(filename, 'r') as f: kernel_code = f.read() return kernel_code
cc8dd4429df8d8dfd9d418ab979454be3a01bb52
659,345
def generate_managed_policy(resource_name: str, permissions): """Generate an IAM Managed Policy resource""" return { resource_name: { "Type": "AWS::IAM::ManagedPolicy", "Properties": { "PolicyDocument": {"Version": "2012-10-17", "Statement": permissions} ...
c0a8e6c4856753ac7aa3ada4c0c33d4059ec1767
659,347
def allow_all(*args, **kwargs): """Return dummy permission that always allow an access. :returns: A object instance with a ``can()`` method. """ return type("AllowAll", (), {"can": lambda self: True})()
4b6d4f722b0dedcf0f7c8059b27bdc4388abe0db
659,348
def print_break(text): """Helper function to print clean sections to console.""" print("") print("#" * 64) print("# " + text) print("#" * 64) return None
6c2ab4a964ca6f08a3668a8c2031382603065bcc
659,349
import os import time import subprocess def check_path_validity(pfi, interval=1, timeout=100): """ Workaround function to cope with delayed operations in the cluster. Boringly asking if something exists, until timeout or appearance of the sought file happen. :param pfi: path to file to assess :par...
7c059983705df4788745c4dbcbf4da7e7e725fca
659,350
def get_skills_v3(): """ READING THE THIRD SKILLSET """ skills_v3 = [] f = open('skills_v3.json', 'rb') for a in f: skills_v3.append(a) f.close() return skills_v3
6c05a5a9c2c246e917a129f9cb6a39e32e0aaf4c
659,351
import math def multiply(int1, int2): """ An implementation of the Karatsuba algorithm for integer multiplication. Returns product of int1 and int2. """ # Base case if (int1 < 10 and int1 > -10) or (int2 < 10 and int2 > -10): return int1 * int2 # Set up strInt1 = str(int1) ...
da4ca6d0e96420283542d335f37762c35f1c397a
659,352
import re def trim_alphanum(name, length=100): """Replace non alphanum charss with '-', remove leading, trailing and double '-' chars, trim length""" return re.sub( '^-|-$', '', re.sub('[-]+', '-', re.sub('[^-a-zA-Z0-9]', '-', name[0:length])) )
33804f7af1f4e6d764ac408924e4cfedb76515b5
659,353
import math def F13(x): """Schaffer F2 function""" s = 0.5 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/(1+0.001*(x[0]**2+x[1]**2)) return s
ff23d90f4de6807ec6756625ac2664ec32d7855e
659,354
def normalize(np_array, x_max=255, x_min=0): """ Normalize data to a scale of: [0,1] Default: normalizing pixel values [0,255]. """ return (np_array - x_min) / (x_max - x_min)
88140a4519b451d4b5dce381e1d8f75acef00a6a
659,355
def generate_normalized_name(name_tuple): """ Generates a normalized name (without whitespaces and lowercase) """ name_arr = list(name_tuple) name_arr.sort() name_str = ''.join(name_arr) return name_str.lower()
598ef66ad8fe71cf5a1fba8719be184aa7bd4d9a
659,356
def name_equality_check(setup_deps, pipfile_deps): """ Checks that all names present in either dependency file are present in both dependency files Args: setup_deps (dict<str, list<tuple<str, str>>>): Dictionary from setup.py dependency name keys to a list of tuples as a...
c46a99b09c58916af53f2abf535e001f6ef0e810
659,357
import os def get_prefix(filename: str) -> str: """A convenient function for getting the filename without extension. Parameters ---------- filename: str Name of file to get the prefix. Returns ------- str prefix of file. """ # strip filename extension name, ex...
256d840418136b245e4d9dc5ceb760b3b77da0cb
659,358
import pkg_resources def _registered_commands(group='mupub.registered_commands'): """ Get our registered commands. Iterates the entry points and returns the registered commands as a dictionary. :param str group: The group in setup.py to iterate. :return: A table containing command-name:command p...
b7bab437273fad534b08ab48833257a82ee7bb86
659,359
import os def get_modules(projectpath): """ Get all the modules of the project. """ modules = [] for i in os.listdir(projectpath): path = os.path.join(projectpath, i) if not os.path.isdir(path): continue if i[0] == ".": continue modules.append(i) ...
76182e7835942b7c2a7c55db8bc91627cf27e9b8
659,360
def _EscapeArgText(text): """Escape annotation argument text. Args: text: String to escape. """ return text.replace('@', '-AT-')
762c2a6de2147886723deeb40cd3ddd5625cd16f
659,361
import requests def is_reachable(url: str, redirects: bool) -> bool: """ Test if a web site is reachable. This test has two different uses in the certmgr container: 1. Test if the NGINX server is up; and 2. Test if the device, e.g. the NUC, is connected to the internet. Args: url...
b73f903b68971bb398564e7fbdc344c5fcbd9a83
659,362
def output_formatter(value): """ Output formatter for environment variable values. Parameters ------------ value Value to format. Returns -------- :class:`str` Formatted value. """ if value is not None and not isinstance(value, bool): return str(value) ...
e0bd03f9580ee17d9464178a43b1406e763d1d73
659,363
import six import json def load_config(config): """Load configuration. """ if isinstance(config, six.string_types): with open(config, "r") as f: return json.load(f) elif isinstance(config, dict): return config else: raise NotImplementedError("Config must be a js...
34d51056170709aa236a43d713c77f511caeb479
659,364
import numpy def ihat(scale=1.0): """Get an x unit vector Arguments: scale: scale the vector by this value Returns: ihat: i vector scaled by the specified value """ return numpy.array([1.0, 0.0, 0.0]) * scale
6fd5e9b73297aecba7797f6cda7f7dfc7f622b96
659,365
import inspect def caller_locals(): """This will return the locals of the *parent* of the caller. This allows a function to insert variables into its caller's scope. Yes, this is some black magic, and yes it's useful for implementing things like depends_on and provides. """ # Passing...
b2d2c67a5e8e554ba3ba8d9d87c658978209cfc6
659,366
def cyclic_index_i_plus_1(i, length): """A helper function for cyclic indexing rotor scans""" return i + 1 if i + 1 < length else 0
72067d2e1f89363d7b284ce2b69c1cccebda4162
659,367
def max_pyr_path_sum(p): """returns max adjacent path sum top->down through pyramid p""" f = [[0 for j in range(i)] for i in range(1,len(p)+1)] for i in range(len(p)): for j in range(len(p[i])): sigma = [] if i == 0: f[i][j] = p[i][j] ...
3453d0c2b1ea9bd8a0dcf3257ffc9094999ce607
659,368
import os def get_number_files(extensions, directory=None, ignore_folders=False): """Return number of file of a certain type in cwd. Parameters ---------- extensions : dict Contains the lists of extensions for each type of file. directory : string Target directory. If None, return...
2e7f6ca5612b16174e3c800368138ed304c2efba
659,369
def Read(filename): """A dummy worker that reads input from a file.""" with open(filename, 'rb') as infile: return infile.read()
bca68ee8b50bccb64396a575cbb41043898486d2
659,371
def url(): """ url() :return: """ url = "https://www.google.com" return url
c46305fa1e60cf0427b4b5631a0275334e04cc96
659,372
from typing import List from typing import Dict from typing import Any def type_match(object_: List[Dict[str, Any]], obj_type: str) -> bool: """ Checks if the object type matches for every object in list. :param object_: List of objects :param obj_type: The required object type :return: True if al...
8e9e4eefc8e90b9e4932e983c5b1055d25baf8b7
659,373
def obs_filter_step(distance, view): """ Perfectly observe the agent if it is within the observing agent's view. If it is not within the view, then don't observe it at all. """ return 0 if distance > view else 1
3760fb8444ee5c83cf42266a64c7cf980a9d4451
659,374
def from_hex(string): """This function is the inverse of `to_hex`.""" return bytes.fromhex(string.replace(":", ""))
368873082a09bad38c98f357162afea64c0e8075
659,375
def flatten(seq): """Transforms tree lists like ['a', ['b', 'c'], 'd'] to strings like '(a, (b, c), d)', enclosing each tree level in parens.""" ret = [] for one in seq: if type(one) is list: ret.append(flatten(one)) else: ret.append(one) return "(" + ", ".join(re...
38275adcd1aea4872b6cf74293e1adf7ee5c4478
659,376
import platform def is_macos(): """ :return: True if system is MacOS, False otherwise """ return platform.system() == 'Darwin'
12a095beac734bb965ca35faaab7482d545ae2d9
659,378
def dupTest(object): """Checks objects for duplicates enabled (any type) object: Blender Object. Returns: Boolean - True if object has any kind of duplicates enabled.""" if (object.is_duplicator): return True else: return False
bd57bab0cd87fbdd22e90bd1d0fafdb4dca3a653
659,379
def m_shape(A): """ Determines the shape of matrix A. """ rows = len(A) columns = len(A[0]) if A else 0 return rows, columns
85e9346d6432f2cb544e48ea8225b93791f16ad4
659,380
def get_loco_connlines(track, loco): """ Returns a dict of lines representing each locos base connections. """ # Build loco to base connection lines loco_connlines = [] for conn in [c for c in loco.conns.values() if c.connected()]: linepath = [] linepath.append({'lat': conn.conn_to.c...
68b762ae7e60076f29b829f4fb019ea814726929
659,381
import re def clean(text, newline=True, quote=True, bullet_point=True, link=True, strikethrough=True, spoiler=True, code=True, superscript=True, table=True, heading=True): """ Cleans text (string). Removes common Reddit special characters/symbols: * \n (newlines) * &gt; (>...
42e317731c43e3cafe270fa1a40734f09606d333
659,382
import json def objEncode(obj): """ obj,返回binary对象 """ return json.dumps(obj,indent=4, sort_keys=True,separators=(',',':')).encode('utf-8')
4b5436e92de2e6dda5bb89567c143d1dba3d3b74
659,383
def _spec_arg(k, kwargs, v): """ Specify a default argument for constructors of classes created from .mat files. Used in autogenerated classes like ModelParameters. Parameters ---------- k : string Name of variable whose value will be assigned kwargs : dict Dictionary of ke...
36dd882105299ec297972ec35c651ea108f691d5
659,385
def evaluate_error(z1, z2): """ # cette methode ne marche pas car le numero de cluster pourra changer :param z1: actual clustering :param z2: clustering done by CEM algorithm :return: error in percentage """ err = 0 n = len(z1) for i in range(n): if z2[i] != z1[i]: ...
35f0714bab82b9161db672a11e658074491e6c13
659,386
import jinja2 def load_template(filename, **kwargs): """Wrapper for loading a jinja2 template from file""" templateLoader = jinja2.FileSystemLoader( searchpath="./powerhub/templates/payloads/" ) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = filename template =...
d30e104d618581f8b24ad54e1eafa9a0c85191a0
659,387
def sort_by_length(arr): """Sort list of strings by length of each string.""" return sorted(arr, key=len)
29b0b73456af386d4cf8a9380558b5780060abde
659,388
import os def get_log_path(log_dir): """from a folder, load all log paths in that folder""" ret = [] log_paths = os.listdir(log_dir) for runs in log_paths: run_dir = log_dir + '/' + runs for run in os.listdir(run_dir): run_path = log_dir + '/' + runs + '/' + run ...
7ade1db206ec170fa5df990ffa8cfa0c5b7da204
659,389