content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_indeces(a, b): """ Extracts the indices multiple items in a list. Parameters: a: list. where we want to get the index of the items. b: list. the items we want to get index of. #example: x = ['SBS1', 'SBS2', 'SBS3', 'SBS5', 'SBS8', 'SBS13', 'SBS40'] y = ['SBS1...
a4010d30dcf107983e9169f8adeb1e608c4e8bb2
641,517
import os import re def get_proc_names(out_dir): """ Retrieves a mapping of process names to their PID as well as the raw output of b2g-procrank. """ with open(os.path.join(out_dir, 'b2g-procrank'), 'r') as f: procrank = f.read().split('\n') proc_names = {} for line in procrank: ...
4772d97e81e33d92a6daa3dfefe8ce2576fb734f
641,518
def nl_strip(string: str) -> str: """ Strip blanks and punctuation symbols :param string: :return: """ return string.strip().strip('.,:!?').strip()
b85e45cd9855e2811b32b70af9bbcb01944a5d3c
641,520
import hashlib def sha256(x): """ Simple wrapper of hashlib sha256. """ return hashlib.sha256(x).digest()
19f0d01d024058f8a35d9c4cf2faa4bf7ac5ea10
641,522
import yaml def load(filename): """Load a dictionary from a yaml file. Expects the file at filename to be a yaml file. Returns the parsed configuration as a dictionary. :param filename: Name of the file :type filename: String :return: Loaded configuration :rtype: Dict """ with open...
6df97f1d2554dde578298e35fd9c548fbf4382f4
641,523
def is_valid_img(image) -> bool: """Checks if an image is valid or not. Args: image (numpy array): [description] Returns: bool: [description] """ return image is None or not (len(image.shape) != 3 or image.shape[-1] != 3)
f18c50dfe80db24decfadd80950e48c480db34dc
641,524
def getJointConstraint(joint, ctype): """Returns the constraints of a given joint. Args: joint(bpy_types.Object): the joint in question ctype: constraint type to retrieve Returns: """ con = None for c in joint.pose.bones[0].constraints: if c.type == ctype: con ...
43b325ca5da2e836be063c475687228ecd3fecde
641,525
def unique_family(data): """A list of unique families in the USDA data provided Iterates through the DictReader for the family names, and returns a list of names Args: A DictReader instance of the usda plant checklist Returns: A list of strings containing all the unique family...
3040e4ce089a438aa6be6ea8ee55a9ba73ef1541
641,526
def raw(s): """ Coverts ScholarOne MS_ID into its base form (i.e. removes revision number if present) """ if '.R' in s: s = s.split('.R')[0] return s
499d2a7c4d5056ccc0a61a01d31bb3c952b500f8
641,528
def is_inverted(c): """Returns True if the ordering of the candidates in the sentence is inverted.""" if len(c) != 2: raise ValueError("Only applicable to binary Candidates") return c[0].get_word_start() > c[1].get_word_start()
a09c50b9e19d4dc43cb5276a12ab616302d93bcd
641,529
def hypot(x, y): """Return the Euclidean norm, ``sqrt(x*x + y*y)``. This is the length of the vector from the origin to point ``(x, y)``.""" return 0.0
67675d437576149a72e1d1c67aad58e73acfc73d
641,530
def input(): """ Return input records. """ return [{"str": "abc"}, {"str": "def"}, {"str": "ghi"}]
b48b310d4806e399274c7cc22ac63d305daf8132
641,531
import unicodedata def remove_non_ascii(words): """Remove non-ASCII characters from list of tokenized words""" # replaces non-ascii tokens with "" # example £ § new_words = [] for word in words: new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignor...
dd21eea6ec340bbfc6984d11424778ebe2725c1a
641,532
import os import sqlite3 def connect_db(dbname="results.db"): """Attempt a database connection, exiting with 1 if dbname does not exist, else return with db connection""" if not os.path.isfile(dbname): print("{} does not exist".format(dbname)) raise IOError(dbname) db = sqlite3.connect(dbn...
81324b4bd7c024a79e3191c0f5d44c4d669e6c9a
641,533
import yaml def read_items(file_path: str): """ Read transcription specs for testing """ with open(file_path) as fp: return yaml.safe_load(fp)
910a5a507d5f4acc03002c3a48a5642ec5166b6e
641,535
def get_figsize(image, max_size=10): """Helper to scale figures""" scale = max_size / max(image.shape) return (scale * image.shape[1], scale * image.shape[0])
64706aec53677b0914a91fc153c6b35bab32fc36
641,536
def allsame(xs): """ Returns whether all elements of sequence are the same """ assert len(xs) > 0 return all(x == xs[0] for x in xs[1:])
74f4830345b152dedf6b269943a15308f223b5fa
641,537
def get_min_sec_stocks(nr_of_stocks, sectors): """ Returns the Number of minimum stocks per sector requiered to get to the nr_of_stocks with the selected sectors Args: nr_of_stocks (ind): Readout of the 'nr_of_stocks' input in the interface. sectors (list): List that is returned from the 's...
0448b27d6c40531a1e4e206aacbfacdcafd18a95
641,538
def bytes_to_gb(bytes_val): """ Convert bytes to GB, rounded to 2 decimal places """ BYTES_IN_GB = 1024 * 1024 * 1024 gbytes = bytes_val / BYTES_IN_GB return round(gbytes, 2)
97837c3060aac2ac75af6e20a9589d3ad02a4d22
641,539
def MockToken(): """Mock token generator that returns empty.""" return ''
c5cbecef7990fb9e3fbfbec3962c9ad91a9a360b
641,540
def bytes_to_encoded_string(bstr): """Perform the opposite of encoded_string_to_bytes.""" return "".join('\\x%02x' % b for b in bstr)
eaeb5c1336c39f16e3157b88d5524d516f04c566
641,541
import hashlib def generate_object_key(lookup_key, resolution, time_sample, morton_id): """ Generates an object key assumes iso=False. Based on spdb.spatialdb.object.AWSObject.generate_object_key() Args: lookup_key (str): lookup key collection_id&experiment_id&channel_id resolution (int ...
e4d80f8a0b7fdb258dd5d121fcc30f6672827e0a
641,543
def gen_options(d:dict) -> str: """ :param d:dict: """ opt_list = [] for key,value in d.items(): opt_list.append(f'-{key} {value} ') return ''.join(opt_list)
3f49f3d625c501be946967b9cf420a4834d8a89d
641,544
from typing import Optional from typing import Dict def prepare_ids_str(ids: Optional[Dict]) -> Optional[str]: """Prepare string with EntitySet IDs.""" if isinstance(ids, dict): # Generate ID string (id1='value',id2='value') ids_str = ','.join("{}='{}'".format(k, v) for k, v in ids.items()) ...
6e1150f9596b4eb52ca210ceb1a65327783b4724
641,545
def _to_xml(number): """ convert Python number to XML String representation Keyword Parameters: number -- Python numeric variable >>> _to_xml(0) '0' >>> _to_xml(0.09834894752) '0.09834894752' >>> _to_xml(None) '' """ if number is None: return '' return str(...
e41dc380cb2f9237b4946a2b7f008b0efdb907c5
641,546
from typing import Union def check_outliers(lower_bound: float, upper_bound: float, current_value: Union[int, float]) -> bool: """ Check if a value is an outliers by comparing it with interquartile range :param lower_bound: lower bound of interquartile range :param upper_bound: upper bound of interqu...
68468f67ca3ad0aacac95a524366afecf9dd02b2
641,547
def convert_cost_units(items): """To convert cost_unit choice type to it's value. For example, for each item's cost_unit tuple (type="per-packet", value="Per Packet") will be converted to a `str` "Per Packet". """ for item in items: item.cost_unit = item.cost_unit.value return items
8fd736ab68cd6008f33a944efcc4a8b5238af5e7
641,548
def ap(docs, n=10): """Average Precision""" precision_values = [ len([ doc for doc in docs[:idx] if doc["relevant"] == "true" ]) / idx for idx in range(1, n + 1) ] return sum(precision_values) / len(precision_values)
96542a81a4698ed7a97a9739328babeb7d73169f
641,549
import os def read_text_file(file_path): """ Gets the contents of a text file """ if not os.path.isfile(file_path): return False, "" file_pointer = open(file_path) contents = file_pointer.read() file_pointer.close() return True, contents
4448acbb7d370979f7bf45fe96cd2d105cec2209
641,551
import os def make_url(env, filename, expire=True): """Return a output url, modified for expire header handling. Set ``expire`` to ``False`` if you do not want the URL to be modified for cache busting. """ if expire: path = env.abspath(filename) if env.expire == 'querystring': ...
3e152f172c0102c2596317e0aa7c6c3f8f12b5b5
641,552
def shinglelize(text, shingle_size=3): """ Transform an input string to a list of shingles (or n-grams) with a given size. Parameters ---------- text : string Text to shinglelize shingle_size: int, optional, default 3 Size of a shingle Returns ------- shingles : li...
5bb6a6a7b6f886f509b1ef5c86bca30ab7e411ae
641,553
def format_fold_run(rep=None, fold=None, run=None, mode="concise"): """Construct a string to display the repetition, fold, and run currently being executed Parameters ---------- rep: Int, or None, default=None The repetition number currently being executed fold: Int, or None, default=None ...
ce14f51a97552d1292cf4fd1e3431ba36929d445
641,554
def get_y_max_list(alt_dropdown_options, topology_df): """Generate list of max y-values for additinal data""" y_maxes = [] for i in alt_dropdown_options: try: data_type = type(topology_df[i][0]) except KeyError: data_type = str if data_type == str: ...
ed4fe80fbb27872a077bd21e1495d1c400dc7e33
641,555
from typing import List def reconstruct_queue(people: List[List[int]]) -> List[List[int]]: """ h为身高,k为排在这个人前面且身高大于或等于h的人数 身高矮的插入身高高的前面,不影响身高高的k值 :param people: :return: >>> reconstruct_queue([[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]) [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]] >>...
950f02ef7d8d60a7bb307635892e0ace9b80b00c
641,556
def read_tles(tle_path): """ Convert TLE text files in a given directory to a list of TLEs. Parameters ---------- tle_dir : str Path to the directory containing TLE .txt files. Returns ------- sats : List of lists. Each internal list has the 3 lines of a TLE as its elem...
aa8aae9ec1eb286abf5fd5b4eb1474e807d3f34d
641,557
import hashlib def file_md5(file_path, buffer_size=1024 * 16): """ Calculate the md5 checksum for the provided file path :param str file_path: path of the file to read :param int buffer_size: read buffer size, default 16k :return str: Hexadecimal md5 string """ md5 = hashlib.md5() wit...
9ab399e07f43c56801c41e266199a488d393f2f6
641,559
def get_formatted_tag(tag): """Format a tag to correct case.""" words = tag.split(' ') for i, word in enumerate(words): if len(word) < 3: words[i] = word.upper() else: words[i] = word.title() return ' '.join(words)
b32e7cf8a64c8ab6bbcba0795852094c7c4ad464
641,560
def get_object_provenance(obj): """returns string of complete object provenance""" # algorithm inspired by Greg Baacon's answer to # https://stackoverflow.com/questions/2020014/get-fully-qualified-class # -name-of-an-object-in-python if isinstance(obj, type): mod = obj.__module__ nam...
221bdc8c33f77b5d0caaa81e01f5870be82cdfcf
641,561
def compare_sequences(ref, seq, cdna_coding_start, cdna_coding_end): """Compare transcript sequence with reference""" if len(ref) != len(seq): while seq[-1] == 'A': seq = seq[:-1] while ref[-1] == 'A': ref = ref[:-1] if ref == seq: return '.' if len(ref) != len...
13043428187357297ed84f65bdd647cc7742e5d1
641,563
def unify_equivalent_indels(df): """Unify equivalent indels with highest somatic probability Args: df (pandas.DataFrame): df after left-alignment -> all equivalent indels have same 'chr', 'pos', 'ref', 'alt' Returns: df (pand...
de4ca7bf81df6edf093d40739efe07dc85f2af89
641,564
import pkg_resources import re def get_version_id(): """ OFX seems to like version ids that look like NNNN, so generate something like that from our version. """ ver = pkg_resources.require('jaraco.financial')[0].version ver_id = ''.join(re.findall(r'\d+', ver)) # first pad right to three ...
e7e80466361c7a473aa1b3827f1384dfd8c140a5
641,565
import os def abspath(pname): """Return the absolute path of the directory. This function expands the user home directory as well as any shell variables found in the path provided and returns an absolute path. Args: pname (path): Pathname to be expanded Returns: path: Absolute pa...
5ff1d2482928b7afda792c92a51037323abf4e39
641,566
import socket def getFQDN(default=None): """Return the FQDN.""" fqdn = socket.gethostname() if not '.' in fqdn: return default return fqdn
33157712a5e4ec7bf198005389d2718d7895463c
641,568
def validate_heart_rate_timestamp(in_heart_rate, heart_rate_expected_keys): """Validate inputted json data This function tests 3 criteria for the inputted json file. 1. It must be a dictionary 2. It must contain all of the expected_keys: "patient_id" and "heart_rate" 3. It must contain the corr...
11fe174f7ab503b0c040be8f9c2dd7ab4a207a5f
641,569
def fibonacci_memoized(n): """ Memoization refers to remembering results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. time: O(n) space O(n) """ if n < 2: return n return fibonacci_memoized(n - 1) ...
49629e99008672f553a5b1ab19ca50cb68bf5bfb
641,570
def _get_function(line, cur_func): """ >>> _get_function('foo', None) >>> _get_function('def hello():', None) 'hello' """ if 'def ' in line: start = line.find('def ') + len('def ') end = line.find('(') return line[start:end] return cur_func
85027f722095e2be20785174e3d9cca9252013f9
641,571
def check_for_reqd_cols(data, reqd_cols): """ Check data (PmagPy list of dicts) for required columns """ missing = [] for col in reqd_cols: if col not in data[0]: missing.append(col) return missing
3712046e59047e3c365279935fd93ee00c78237c
641,572
def sanitize_html(text): """Prevent parsing errors by converting <, >, & to their HTML codes.""" return text\ .replace('<', '&lt;')\ .replace('>', '&gt;')\ .replace('&', '&amp;')
b14e4836be1cda20c7b2ae5eb185234dc8b1d112
641,573
import os def pytest_configure(config): """Configure before running tests.""" os.environ['TOM_CONFIG'] = os.path.join(config.rootdir, 'config-test.yml') os.environ['TOM_DATA'] = os.path.join(config.rootdir, 'tests/data') return config
083b4c0d1881db235101e865d4e325c0bc8de44e
641,574
def get_overridable_template_name(name, plugin, core_prefix='', plugin_prefix=''): """Return template names for templates that may be overridden in a plugin. :param name: the name of the template :param plugin: the :class:`IndicoPlugin` that may override it (can be none) :param core_prefix: the path pr...
d92d63483ef8953a58d198505b64f90277ece27e
641,575
def _copy(a:bytes) -> bytes: """Ugly copy that works everywhere incl micropython""" if len(a) == 0: return b"" return a[:1] + a[1:]
765bda44c499dd4ac5b64a6fad10b11034066069
641,576
import argparse def make_parser(): """Makes an argument p object for this program Returns: Argument p """ p = argparse.ArgumentParser(description="Acquire (from cache or Firebase) graphs, run optimization, and plot") p.add_argument( "-p", type=str, help="Pattern to...
22c61b589b2a81c5b73225d23bbd6fa1a73e38de
641,577
import os def repopath(): """ Returns: str: path to the repos/win7/deleted-instance repository """ cd = os.path.dirname(os.path.abspath(__file__)) return os.path.join(cd, 'repos', 'win7', 'deleted-instance')
6a7f61715764e158a56edfa968a3019a36755771
641,578
def optParameterDomain(longName, shortName): """ Returns a list that you can use in your L{usage.Options}'s C{optParameters} list. """ # Automatically setting document.document based on a GET # parameter or by looking at parent's URL is insecure (because # some browsers will allow setting document.domain to 'com...
cacdc397c7019db2c8330c6067ac80e89197fe1f
641,579
def config_get(from_,what_): """ Returns value what_ from_ """ from_=from_.replace(' ','') d = from_[from_.index(what_+'=')+1+len(what_):].split('\n')[0] return d
6e4ace1a0f4d220aa9f3397890a289db88b45ce3
641,580
def process_record_assistant1(col_start_time,col_end_time,col_summary,record): """ Check if the txhash exists or not in the end_time table if yes, send streaming data to query tx details and remove related record in the end_time db else, save data in the start_time db """ if('txhash' in record):...
b89a4184eea1d1a08039806908bc5d3ea936d7c8
641,581
def sort_96_well_plate(wells): """Sort 96 well plate wells in vertical order. Arguments: wells -- unordered list of wells: ['A1', 'C1', 'E1', 'B1', 'D1'] """ order = [ 'A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'A3', 'B3', 'C3', 'D3', 'E...
b74f2e6f56a38d76b41580363c74dc8e1d3586da
641,582
def ndre(nm790, nm720): """function returning a NDRE map. NDRE is calculated as: NDRE = (790nm - 720nm) / (790nm + 720nm) which corresponds to: NDRE = (NIR - RE) / (NIR + RE) Parameters ---------- nm790 : numpy.ndarray 2d-numpy array of the target response at 790nm (NIR) n...
2989a9d9a2eb6dfd43584495890d4868f42090e1
641,583
import os def get_rel_path(fn, base_dir): """ Will return the relative path of fn as seen from base_dir. If fn is None, will return None. """ if fn is None: return None return os.path.relpath(fn, base_dir)
6b294473385c5b4d070d75b7a11c7b03498c49f2
641,584
import torch def rho_test( cost: torch.Tensor, new_cost: torch.Tensor, total_cost: torch.Tensor, new_total_cost: torch.Tensor, ): """Modified gain ratio test.""" improved_maps = new_cost < cost psi_inf = (cost[improved_maps]).sum() psi_sup = (cost[~improved_maps]).sum() psi_new_inf...
5a235c479aa4d6ff3252e4a8940919088a5e80e7
641,585
import os def truncate_filepath(filepath, max_len=50, basename_only=False): """ Truncate a long filepath --> '.../long/path.txt' Args: :filepath: filepath to truncate :max_len: (int) maximum string lenght to return :basename_only: (bool) if True, only use the basename of 'filepath...
abdb320c40f324910b1c150fa526842f76e8c4ef
641,586
from typing import Dict def prettify_wildfire_rule(rule: Dict) -> Dict: """ Args: rule: The profile security rule to prettify. Returns: The rule dict compatible with our standard. """ pretty_rule = { 'Name': rule['@name'], } if isinstance(rule.get('application'), dict) an...
1bf153d81a611c1cb275ed1025cd0680ebbf0267
641,587
import os def exec_cmd(cmd): """ 执行Shell指令 """ r = os.popen(cmd) text = r.read().strip() r.close() return text
b2d3ad9c5ec9039c413a593add8989e62ee45723
641,588
def convert_v4_address_string_to_bits(ip_address): """ return v4 address string to bits for example: '255.255.0.0' -> '11111111111111110000000000000000' """ return ''.join([bin(int(octet))[2:].zfill(8) for octet in ip_address.split('.')])
a0d1fb710e600c47b41ee80e5aa5a5a40c73401b
641,589
def is_closed(instance, *args, **kwargs): """ Helper function to test if some instance is closed (to be used with ``raise_if`` decorator) :param instance: some instance with ``is_closed`` property accessible :returns: value of ``instance.is_closed`` or False """ return getattr(insta...
307178eacc07a39743243fd693af414b40619c74
641,590
def find_sublist_containing(el, lst, index=False): """ Parameters ---------- el : The element to search for in the sublists of `lst`. lst : collections.Sequence A sequence of sequences or sets. index : bool, default: False If False (default), the subsequence or subset co...
6c9edb33091a1eca96cb77f239abc365bd10d22a
641,591
def check_single_string(inp): """inspect single (doc)string """ test = inp[0] while test in ('"', "'"): try: ix = inp.index(test, 1) except IndexError: return False inp = inp[ix + 1:].strip() if not inp: return True test = inp[0...
57ce3e2714dc875cfc4f4a48ddd9f67d6860b455
641,592
def round_coordinates(cell_poly): """ Rounds the coords of the polygon Only implemented to pass tests. :param cell_poly: polygon feature :returns: polygon feature """ coords = cell_poly["geometry"]["coordinates"] coords = [ [[round(coord, 6) for coord in point] for point in l...
cd6d2de31670b166a1577f4bcb67a3effa655f57
641,593
def user_is_mentor(user): """Check if a user belongs to Mentor group.""" return user.groups.filter(name='Mentor').exists()
34de16d61b79b189b591c43dbb67f62d164978d2
641,594
import logging def confirm_account_match(account_name, connect_str): """ Ensure that the account name provided matches the account name stored in the connection string :param connect_str: type str: Connection string for the Azure storage account :param account_name: type str: Name of the Azure storage...
872f2a746e637a703199458ab61cdc4788eb6de7
641,597
def dynamic_import(name): """ Dynamically import a class from an absolute path string """ components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod
7467cf8050b0b700a14d72e39ef8d8a7c1652ad7
641,598
import os import logging import fcntl def get_cdrom_status(devpath): """get the status of the cdrom drive\n devpath = path to cdrom\n returns int CDS_NO_INFO 0\n CDS_NO_DISC 1\n CDS_TRAY_OPEN 2\n CDS_DRIVE_NOT_READY 3\n CDS_DISC_OK 4\n see linux/cdrom.h for specifics\n ""...
7cad9147c88cb54327b3042fa8f15d861fd232d3
641,599
def _get_node_value(nod): """XML parsing helper for extracting text value from an ElementTree Element. No error checking performed. Parameters ---------- nod : ElementTree.Element the xml dom element Returns ------- str the string value of the node. """ if nod.text...
0c01311eb347b52c4e9971c864f93a7a904cd245
641,601
def n_eff(dlnsdlnm): """ Return the power spectral slope at the scale of the halo radius, Parameters ---------- dlnsdlnm : array The derivative of log sigma with log M Returns ------- n_eff : float Notes ----- Uses eq. 42 in Lukic et. al 2007. """ ...
33b433b18591afa0b12cf9adcd5f62f5db3e12d9
641,602
from datetime import datetime import os def modification_date(filename): """Get the modification date of a file""" return datetime.fromtimestamp(os.path.getmtime(str(filename)))
33086ecb0d40670d5ecb27c0f5255ed1b691ce49
641,603
def apply_weight_decay_data_parameters(args, loss, class_parameter_minibatch, inst_parameter_minibatch): """Applies weight decay on class and instance level data parameters. We apply weight decay on only those data parameters which participate in a mini-batch. To apply weight-decay on a subset of data para...
8d979f01e62091bd81c66bdc283e3986638f4e34
641,604
import re def match_patterns(patterns, name, default=True): """ Retur True if Match Patterns """ if not patterns: return default for pattern in patterns: res = re.search(pattern, name) if res: return True return False
7ca5039a9a19b190ebf6df067525977c30509a32
641,605
def compute_hash(*args): """Compute a hash vlaue from all given arguments.""" return hash(args)
1632f22c3127cfa1ad50144674a1a8cd26e7e480
641,606
def decode_responses(response): """ :code-block 'responses': { 'items': { 'type': 'object', '$ref': '#/definitions/wallpaper' }, 'required': True, 'type': 'array', 'allowEmptyValue': False }, """ ...
fb776f20ae5373d1d280c7c7a662bb8446005b39
641,607
def get_ospf(engine): """ Get OSPF settings for the engine :return: dict of entries only if OSPF is enabled """ ospf = engine.dynamic_routing.ospf data = dict( enabled=ospf.status, router_id=ospf.router_id) if ospf.status: data.update(ospf_profile=ospf.profile.na...
d6a5a0e08dcc75705bd6c4a692027c91f924676d
641,608
import re def str_visible_len(s): """ :param str s: :return: len without escape chars :rtype: int """ # via: https://github.com/chalk/ansi-regex/blob/master/index.js s = re.sub("[\x1b\x9b][\\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]", "", s) return len(s)
5f5d0bd14c0805cd13c3ba22f3cefdee7485d33e
641,611
def clean_name(name): """Replace dashes and spaces with underscores""" return '_'.join(name.split()).replace('-', '_')
5de49ec064b3e6b4359d29d822fd732d080f8a43
641,612
def flatten_dictionary(dictionary): """Get a list of tuples with the key value pairs of the dictionary. """ result = [] for k, s in dictionary.items(): for v in s: result.append((k, v)) return result
7da8eeb1716cbd1664b921943cb70774ced2cbe7
641,613
def flake8(ctx, noerror=False): """check the project files for correctness with flake8""" return ctx.run(f'python -m flake8 w3modmanager{" --exit-zero" if noerror else ""}').exited
2bb91c621d877c388daa28aabbe7b513184cac9a
641,614
import shutil def create_make_command(keyboard, keymap, target=None): """Create a make compile command Args: keyboard The path of the keyboard, for example 'plank' keymap The name of the keymap, for example 'algernon' target Usually a bootloader....
dccd741fec64799afa9fcabc18a7e458d60c2b4f
641,615
import string def _react( polymer : str ) -> str: """ Reacts the polymer by repeatedly looping over it and removing 'aA', 'bB', 'Cc', etc.. pairs until none exist Arguments: polymer {str} -- The original string representing the polymer Returns: str -- The new string representing the reacted polymer """ p...
1e553806642b11384c86c9f3a72e79a9ae0ad064
641,616
def bytesToInt(bytes): """Converts a basestring to its integral equivalent.""" return int(bytes.encode('hex'), 16)
2ea8a3b644e7a8eae9a883efb695bce8f75e0abb
641,617
import binascii def gotenna_to_intelhex(firmware_data): """ Convert raw bytes in goTenna firmware to the hex encoded INTELHEX """ firmware_bytes = bytearray(firmware_data) output_bytes = bytearray() while firmware_bytes: header_byte = firmware_bytes.pop(0) assert header_byte =...
32274ee02574098795f23741d09a9f798c7c240d
641,618
import re def load_mem_file(filename, pack_bytes = 4): """ Load a mem file and return it as list. Pack pack_bytes into one word. The list contains integers packed from pack_bytes bytes. One byte is what the file stores in one string, where strings are separated by spaces and newlines. """ rv = [] f = open(f...
ce21c916b9a97bc1c9d4e775cdd202f079e25332
641,619
def optimize_parallel_run(num_samples, num_threads, num_cores): """ Optimizes the pool_size and the number of threads for any parallel operation """ print("Optimizing parallel jobs for number ot threads and samples run at a time") print("Parameters passed : no. samples {0} , no. threads {1} , no. c...
a1bca3b1f2028917ea80cd0ca4c9ccf9d3a88025
641,620
def arg_list(items, prefix=''): """Process a list or string of arguments into a string containing them Used so users can pass arguments as a string or list in the configuration file. :param items: :param prefix: :return: """ if not items: return '' list_of_items = items.split(...
2374d9504190452d0a9e17e5b3330c57fe988fc5
641,621
def crop_at_center(img, output_size): """" Crop image to a desired output size.""" x = img.shape[0] y = img.shape[1] startx = x // 2 - (output_size[0] // 2) starty = y // 2 - (output_size[1] // 2) return img[startx:startx + output_size[0], starty:starty + output_size[1]]
34018aa8a2f51b496957a19f0d00314667944119
641,622
def is_number(s): """ Args: s: A string Returns: True iff the string represents a number """ try: float(s) return True except (ValueError, TypeError): return False
00da2e9d30d4a37a5f4ec97c34aa261c06da08d8
641,623
def validate_ipv4(ip_str): """ function: check whether is or not validate ipv4 input : NA output : NA """ sep = ip_str.split('.') if len(sep) != 4: return False for i, x in enumerate(sep): try: int_x = int(x) if int_x < 0 or int_x > 255: ...
7f1ab5a4a2b9b0c13589dedded5094f82b1ea965
641,624
def remove_non_name_matches(entries, query_obj): """Filter out Person entries if there is no overlap between names_prefixes and query_obj.query_words.""" filtered_entries = [] for entry in entries: for word in query_obj.query_words: if word in entry.names_prefixes: fi...
06df0c35891528003ce15c083c4d0d0cf3152be9
641,625
import os def get_source_relative_path(source_path: str, config_path: str) -> str: """Return path of a source file relative to config file path :param source_path: Path of the Python source code file :param config_path: Path of the valohai.yaml config file :return: Path of the source code file relativ...
db9aa13e97a81e0ba634015267d09c25ba3319e3
641,626
def rotate_matrix(matrix): """ Rotate the n x n matrix 90 degrees clockwise. Given the original matrix. initial_matrix = [ [1, 2], [3, 4] ] The rotated matrix should look like this. rotated_matrix = [ [3, 1], [4, 2] ] ...
a3f77f4dcc96fa519af561c4e9c5b351a48dc549
641,627
def color2rgba(colorstring): """ convert #RRGGBB[AA] to an (R, G, B, [A]) tuple """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) != 8: raise ValueError( "input #%s is not in #RRGGBBAA format" % colorstring) r, g, b, a = colorst...
3f6f80cc2411b9a643b53cc968131ac8caa32e59
641,628
def variable_set_up_computer(num): """Return the computer's choice""" if num == 1: return 'The computer chose rock.' elif num == 2: return 'The computer chose paper.' elif num == 3: return 'The computer chose scissors.'
e3ddee976af9b04718deaad1bea1abdd7e35e113
641,629
def commonprefix(m): """Return the longest prefix of all list elements.""" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break ...
4bac90c54def505cf3fc3573c079030f33cddc7f
641,632