content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def parseSec(name): """ Results as in miliseconds """ if name == "nsec": return 1e-6 elif name == "msec": return 1 elif name == "sec": return 1e3
d7c906df7169ba96e7ebbc159f5c1b488e28f190
640,834
def must_replace_suffix(str, suffix, replacement): """ Replaces the given suffix in the string. If the string does not have the suffix, a runtime error will be raised. """ splits = str.rsplit(suffix, maxsplit=1) if len(splits) != 2 or splits[1]: raise RuntimeError(str + " does not contai...
d4577bfe05c95866553a776fd65493dec858d524
640,835
import re def strip_whitespace(uni): """Strips all whitespace from a unicode string. Args: uni (unicode) Returns: unicode """ return re.sub(r"\s+", "", uni)
b68ab2de6c8f37ed6bf9b04281ce9878a3b8d094
640,837
from typing import Optional def reverse_mac(mac_bytes: bytes) -> Optional[str]: """Change Little Endian order to Big Endian.""" if len(mac_bytes) != 6: return None octets = [format(c, "02x") for c in list(reversed(mac_bytes))] return (":".join(octets)).upper()
493abcad87a5df39ab31616bd388a06f3e2076f7
640,838
import os import requests import json def upload_report(report_id, generated_report_id, output_file): """ upload a report file to the server Parameters ---------- report_id The id of the report definition that was originally created for this report. generated_report_id Id ret...
1a310a9ed7ea277e0df42970a39fe6cba5a520aa
640,839
def prepare_params_yaml(param_dic): """This function takes a single parameter dictionary and transforms it for the standard use in the network model. Parameters: ---------- param_dic: dict, dictionary with params. """ new_params = {} # init dictionaries in the main dictioarny for i...
cd8a11e09071f53e4d94d09663c5a75018c3aa2b
640,841
import os def get_path(): """ Return path to dictionary. """ return os.path.join(os.path.dirname(__file__), 'data')
57ba9a30b1e11f834800ff628a035ff091db516b
640,842
from typing import Tuple def get_ports(line: str) -> Tuple[str, str]: """Returns 2 port labels strings from interconnect file.""" line = line.replace('"', "") line = line.replace("(", "") line_fields = line.split(",") port1 = line_fields[0] port2 = line_fields[3] return port1, port2
20720b5a64ccc30cceaa767156808e055d159951
640,843
import sys import platform import os def get_configs_dir(): """ Generate configs dir path on install, moved from utils due to import error :return: str """ # detect virtualenv or pyenv usage if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix): ...
f2b614f02513f59b51eb50f3d65b8e79d3ea707c
640,844
def get_run_info_nextseq500( instrument_model, application_version, tree ): """ Helper function to get some info about the sequencing runs. Args: tree: xml tree Returns: dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc. """ ...
e2ff69ef20282692c43cc08047c971e1a0106b98
640,845
def simplificado(fracoes): """ Parâmetro: Uma lista contendo frações (em formato de string) Return: Uma lista que pode conter números inteiros ou frações irredutíveis, ambos em formato de string. """ simplificados = list() for fracao in fracoes: if 'sqrt' not in fracao and '/' in fracao...
772645fcaa229fc3d20394f291fdd965b60023a7
640,846
import os import codecs def random_bytes(length): """Return random bytes in hex""" bytes = os.urandom(length) b_string = codecs.encode(bytes, 'hex') return b_string.decode('utf-8').upper()
20fca43dd4e0597b3e6b6224de6667ccaa783a8a
640,847
def is_empty(obj): """ These conditions are considered empty s = [], s = None, s = '', s = ' ', s = 'None' """ if isinstance(obj, str): obj = obj.replace('None','').strip() if obj: return False return True
8102089bfc35d960402377d6cf7060cfba0c37db
640,848
def read_htree(bit_seq): """Generate a Huffman tree from a bit sequence.""" if bit_seq.next(): val = 0 bits = [1 << i for i in reversed(range(8))] for bit in bits: if bit_seq.next(): val |= bit return val t0 = read_htree(bit_seq) bit_seq.next()...
58dc92a8cc105be1e0f5cca2c50cd8d493105111
640,849
import json def load_config(): """ Function for loading necessary credentials such as \ Docusign client_id, Docusing client_secret and arcgis key input :: output :: json object of all the credentials """ with open('config.json') as f: return json.load(f)
c3bd3a8d32acb63107fb439b6745dce1891655a8
640,850
import codecs def getNotations(filepath): """ :param filepath: ann标注文件路径 :return: 返回标注文件中每个标注信息的三元组【实体类别,起始位置,终止位置】,返回值为这些三元组构成的列表 """ pairs=[] for line in codecs.open(filepath, 'r', 'utf8'): parts=line.split('\t')[1].split(' ') # print(filepath,parts) pair=[] ...
0bde562fd1977e8d790db149060b651e5706e394
640,851
import math def AltitudeOffset(Altitude): """Calculate the pressure offset, based upon current altitude.""" # p = 101325 (1 - 2.25577 10-5 h)5.25588 # Pressure at Altitude p2 = 2.25577 * math.pow(10, -5) p1 = 1 - (p2 * Altitude) p = 101325 * math.pow(p1, 5.25588) # Pressure at Sea Level ...
a2c4f793a7b0d79047dbde5b12af27e1ceda905e
640,852
def is_external(label): """Determines whether a label corresponds to an external artifact.""" return label.workspace_root.startswith("external")
5378b4ab313bfe286d00bf4deaba7de84580724f
640,853
def listMountpoint(rc,output,outerr,parseParamList,Logger): """ Return target volume of a mount point """ mountpoint="" return mountpoint
41e0d5c83d054231a900b1bac1e26a1d826a5fb8
640,854
def flip_intervals(a,b): """flip intervals, to ensure a < b """ return(b,a)
d5cb29bb18d8c38dd1eef3abcc60ef5c73c5b986
640,855
def unroll(piano_roll): """ Unrolls a piano roll into a list of notes. Args: piano_roll (list of lists of lists): the piano roll list """ temp = [] for song in piano_roll: for notes in song: temp += notes return temp
464f5a1707f4c8abe6290e9fe044666038902fc2
640,856
import pkg_resources def return_save_json_button_style_sheet(): """ Return the Qt style sheet for the button that saves JSON configuration files. Returns ------- style_sheet_save_json_button : str Qt style sheet """ save_json_icon = pkg_resources.resource_filename( 'ne...
e3218dedfd633a55886ce94dd551738d5f0a6957
640,857
import MySQLdb as mysql def createDBonServer(prj, settings={}, callback=None, access=None): """Create a project on the mysql server""" db = mysql.connect(**settings) c = db.cursor() cmd = "create database " + prj + ";" try: c.execute(cmd) except: pass if access != None: ...
57f252029f750408a29c175eca9868eb5f1818e6
640,858
import numpy def log_uniform(low, high): """ Generates a number that's uniformly distributed in the log-space between `low` and `high` Parameters ---------- low : float Lower bound of the randomly generated number high : float Upper bound of the randomly generated number ...
bf14726b4c5459e23dc93f36a70bf97931cf8799
640,859
import math def sin(number): """ function to find sin value of number """ return math.sin(number)
e7a5a92d9d86538891cdcc4b54d0f0a775763173
640,860
def checkRecord(s: str) -> bool: """ given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. The st...
e294ab577d930c38d8c603f3a8b357b22cb1f3e4
640,861
def junos_topo(): """topology fixture """ return { 'devices': { 'junos1': { 'driver': 'junos', 'hostname': 'labhost', 'username': 'vrnetlab', 'password': 'vrnetlab9', 'optional_args': { '...
79e772a7e735529dbe4927bba67d58b364327418
640,862
def calc_start(page, paginate_by, count): """Calculate the first number in a section of a list of objects to be displayed as a numbered list""" if page is not None: if page == 'last': return paginate_by * (count / paginate_by) + 1 else: return paginate_by * (int(page) - 1...
2038c2784d66bc72a947e08aea7168c9ec9a3eaf
640,863
def is_child_recursive(window, possible_child): """ :type window: Window :type possible_child: Window :rtype: bool """ children = window.query_tree().children for child in children: if child == possible_child: return True else: return is_child_recursiv...
6269a9642a39af4ffcb4fa7d45d11d9e9a0d9472
640,864
from typing import Counter def allele_freq(all_alleles, n=None): """Given all alleles at a locus, return a frequency-sorted list of their counts Args: all_indels: an iterator representing all alleles at a locus n (int): return the most frequent n alleles Returns: list of ...
399676b08488473d0c841f49b02c94c96ce15261
640,865
def point_str(x,y=0,z=0): """ Returns a string repr of a point. Example: point_str(1,2,3) returns '(1.0,2.0,3.0)' Parameter x: the x coordinate Precondition: x is a number Parameter y: the y coordinate Precondition: y is a number Parameter z: the x coordinate Precondition: z...
1586e0b789449cb56690d631aca921ca501b4dcb
640,866
import re def especial_split(string_to_split): """Convert a string with + and - to a list with element, which conservates the sign + or -.""" separador = "," string_with_plus = string_to_split.replace("+",",+") string_final = string_with_plus.replace("-",",-") regular_exp = '|'.join(map(re.esc...
b506ca220ed10d6930f163024b9cf607b58e6de7
640,867
from typing import Callable def set_value( record: dict, column_name: str, setter: Callable) -> dict: """ Sets the value of a column to either a fixed value or as the result of a function which recieves the row as a parameter """ if callable(setter): record[column_n...
be2c617b2c530754df01ce55aa2cf091fdecf3a5
640,869
def displayHits(hits): """ Handles the I/O of the song-searching functionality Parameters ---------- hits : list Holds json dictionaries with information of the songs that the search turned up Returns ------- integer Either -1 if no song was chosen or the index in hits with the appropriate song's...
d7fd517245a4f56ca87d73f866cea9fbd66ed327
640,872
def prime_sieve(n: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a certain number https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] ""...
fa1a12cd3b7e4aa50c3e87c5e14fe9e838fcb57f
640,873
def version_check(version): """Checks if OpenFlow version is compatible and returns the version if it is Parameters ---------- version: hex The OpenFlow version taken from the SDN switch 'hello' message Returns ------- The OpenFlow version if match, else 0 for unknown version ...
a0edb7f70dca6f9be64b020c13a9a02f1d65572c
640,875
def generate_schema_obj(content_type, parameters, requestbody): """ Generate schema object for validation """ required = list() schema_obj = { "type": "object", "properties": dict(), "additionalProperties": False } p...
6a9692e117df40864f3359d9f80b2b20c82ae844
640,879
import os def create_native_path(path): """ All nysa paths are stored in a *nix style, but Nysa may be run on a different OS, so Take any path that is pulled in and send it out as a native path for this OS Args: path (string): path to change Return: (string): native path ...
aa6046c5305dbd77a255f5508236a99b368a30e7
640,880
def is_outpatient(med): """Return true if the medication record belong to a valid outpatient order.""" return med.ordering_mode_name == 'Outpatient' and med.order_status_name == 'Sent'
cbac59b5257134f9bc59de69c67fdf39bc9dc2a8
640,881
from typing import Tuple from typing import Optional import re def decode_mention(mention: str) -> Tuple[Optional[str], Optional[int]]: """returns whether mention is a member mention or a channel mention (or neither) as well as the id of the mentioned object""" match = re.search(r"<(#|@)!?(\d+)>", mention) if matc...
7981010aaac8289ebda6d12f923c5e7e5f5c2544
640,882
import itertools def jumble(jumble_dict, word): """Jumble solver Args: jumble_dict (dict[list[str]]): Dictionary contained hashed words word (str): Input word Returns list[str]: Jumble solutions """ words = {} for i in range(2, len(word)+1): # Getting combinations of ...
37865512554000015490579031d7f1e353811163
640,883
def get_binary(values, threshold, target): """ Transforms continuous or multiclass values into binary values (0/1) Args: values (list): vector of the target values threshold (int or float): threshold used to assign a binary value 0 is assigned to 'bad' values...
4c065990948d7ff65d4a0ca915e450663f378abf
640,884
def _convert_keyword(keywords): """Convert keywords collection.""" if isinstance(keywords, (list, tuple)): return keywords if isinstance(keywords, dict): return keywords.keys()
b5c8e6f16879a22c4e117d2d614941e125e668b2
640,885
def L(V): """Gamma 2.4""" return V ** 2.4
dcc2acc6c0b2620b9349bfc0adfe125f78ff867a
640,886
def example(t): """ Label a test as an example. Parameters ---------- t : callable The test to label as slow. Returns ------- t : callable The decorated test `t`. Examples -------- The `statsmodels.compat.testing` module includes ``example``. A test can...
6f245f189b8142d213813c8891ac042e671ca4b6
640,887
def calc_gamma_FeO_silicate(silicate_comp): """ Returns a value for gammaFeO in the silicate. Parameterization is based on Holdzheid, where gammaFeO is taken as a constant value from 1.7-3, dependent only upon MgO content. Parameters ---------- silicate_comp: dict Dictionary of the composition of the silicate...
336627053f9595a8d2848315db560a95710cd276
640,888
def flatten(l: list): """ Accepts a list containing one or more nested lists and returns a flattened copy. Parameters ---------- l: list A list containing one or more lists. Can contain zero lists but there's no point Returns ------- list A flattened version of the orig...
31393053cc6e4c7fe8191cc1fa2890faa8ec3277
640,889
import pathlib def print_markdown(data, **kwargs): """Print listed data in GitHub-flavoured Markdown format so it can be copy-pasted into issues. Can either take a list of tuples or a dictionary, which will be converted to a list of tuples.""" def excl_value(value): # don't print value if it ...
347ea4d28846d34076ab1ad846a0aa3d32165af5
640,891
def get_headings(self, saa_dict): """ Table headings for output Notes: This is awful but it works. """ cont = True keys = list(saa_dict.keys()) count = 0 headings = [] # find the first spectral averaging area where there is a fit # and get the parameter names while co...
bcaa8f24ae81a4abc428cb90cd0a1cb6ed74c9db
640,892
def generate_fasta_dict(sec_record_list): """ Creates a dictionary containing FASTA formatted strings from a list of sequence record objects. This dictionary is keyed by the sequence ID. :param sec_record_list: List of Biopython sequence record objects. :return: Dictionary containing FASTA formatted strings. """...
045dd447fecd772dbef4cac6529dd8f2e7d27263
640,893
def chop_at(s, sub, inclusive=False): """Truncate string ``s`` at the first occurrence of ``sub``. If ``inclusive`` is true, truncate just after ``sub`` rather than at it. >>> chop_at("plutocratic brats", "rat") 'plutoc' >>> chop_at("plutocratic brats", "rat", True) 'plutocrat' """ pos...
66401f4a8e36d299bb882269cd49cdbe089ca8f2
640,894
def format_percent(num): """ Format a percentage """ return int(round(num))
d41680f4fd537ca70130fa0aff544c5865d0f066
640,895
def _is_namedtuple(obj): """Returns `True` if `obj` is a `collections.namedtuple`.""" return isinstance(obj, tuple) and hasattr(obj, "_fields")
f1928c1361774363c6dfb1ede91c8a3d65c93e13
640,896
def _reachable(graph): """Return a dictionary with all reachable nodes from the graph nodes. Args: graph: dict: dictionary representing a graph. Keys are the nodes and values is a set containing the linked nodes. Returns: a new dictionary with the same keys, but whose values are al...
0c122d43ac28384bc9763dda9ffdf808563b2b5e
640,897
def add(n1, n2): """Return the sum of two numbers.""" return n1 + n2
d4bb851d5ddddffe3bb10e25dc0ec00296ee8fd1
640,898
import sys def check_relative_path(path): """ It adds './' to the begining of the path if it is linux or '.\' when the OS is windows. If the paths starts with '.', '\' or '/', it returns the path as provided. Args: path: Path to check (String) Returns: ...
e41e9fae2efa36fbea8bc48997bd18722d349b55
640,899
def moyenne_ponderee(a : float, b : float, c : float, pa : float, pb : float, pc : float) -> float: """Hypothèse : pa + pb + pc != 0 Retourne la moyenne des trois nombres a, b, c, pondérés respectivement par pa (pondération pour a), pb et pc. """ return ((a * pa) + (b * pb) + (c...
2931cb3289bf9c241f7e64c8210fca8b836c96c6
640,900
import torch def update_D(X, Z, net_D, net_G, loss, trainer_D): """Update discriminator.""" batch_size = X.shape[0] ones = torch.ones((batch_size,), device=X.device) zeros = torch.zeros((batch_size,), device=X.device) trainer_D.zero_grad() real_Y = net_D(X) fake_X = net_G(Z) # Do not n...
714807370d74114a2f5755c8e7235979bdaf35a6
640,901
def format_as_string(string: str): """ Formats a given string in a different color using ANSI escape sequences (see https://stackoverflow.com/a/287944/5299750) and adds double quotes :param string: to be printed """ ansi_start = '\033[32m' ansi_end = '\033[0m' return f"{ansi_start}\"{str...
4ba55f4b35bf55e91085c49724d7dce81a8ed12a
640,902
import os def readMotionFile(filename): """Reads OpenSim .sto files. Parameters ---------- filename: str absolute path to the .sto file Returns ------- header: list of str the header of the .sto labels: list of str the labels of the columns data: list of l...
c167da9715172136dabafccbfc6710dc1f2d8670
640,904
import os def get_readme(): """ Returns README.md content. :return str long_description: README.md content """ long_description = "" this_directory = os.path.abspath(os.path.dirname(__file__)) if os.path.isfile(os.path.join(this_directory, 'README.md')): with open(os.path.join(thi...
8f86a1c4330a7850a8ff5213a63d5958e1f48e6f
640,905
def track_prop_dict_length(track_prop_dict): """Returns the number of tracks in a track properties dictionary. Raises an exception if the value lists in the input dictionary are not all of the same length. Returns zero if the track properties dict is empty.""" # A fancy way of checking if all value...
76572405b8c2498dd9660651785b71ce2aa55490
640,906
def base_n(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """base_n""" return ((num == 0) and numerals[0]) or (base_n(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
d46f3cc8634a5dee5a9a307c5550dc282ec1db90
640,907
def get_embedding_info(name, x, n_wires, n_layers): """ get information about the number of weights, entangling gates, number of gates with input/non-trainable parameters and number of non-parametrized gates (hadamards) in an embedding :param name: name of embedding used :param x: input, len(x) is <= len(wi...
9a467e6ea1497ee0589c5bb05b12c7391d739938
640,908
from math import log as ln def _rh_to_dewpoint_magnus(rh, tc, b=18.678, c=257.14): """ See https://en.wikipedia.org/wiki/Dew_point#Calculating_the_dew_point b = 18.678, c = 257.14 °C """ gam = ln(rh/100.) + b*tc / (c + tc) return c*gam / (b - gam)
05106c83d80d4e4b7e732cf9e74114abb2f0499f
640,909
def count_lines(abspath): """Count how many lines in a pure text file. """ with open(abspath, "rb") as f: i = 0 for line in f: i += 1 pass return i
c892cefca6ec16b8d2b96b4b9bae3be6e22366d7
640,910
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return Tr...
c0602a1b28d787d93897f8380e34ee683cc95ad0
640,911
def _get_error_threshold_function(error_threshold, simulator): """ Returns a boolean-valued function that indicates whether a particular (x,y) pair is outside a specified threshold :param error_threshold: can be None or a string; if this is a string, the first character MAY be '+' or '-', to indica...
7dc15face5fd9f565494d194ec9fec5417e11a49
640,912
def hide_example_page(file_handler): """Heuristic that determines whether example file contains python code.""" example_content = file_handler.read().strip() no_percent_comments = True no_imports = True for line in example_content.split("\n"): if line.startswith(r"# %%"): no_pe...
31df65a143d24743b8a4b6337d68b9273bc5cfa7
640,914
def latest_consent(user, org_id=None, include_suspended=False): """Lookup latest consent for user :param user: subject of query :param org_id: define to restrict to given org :param include_suspended: set true to stop looking back, even if the consent is marked suspended (aka withdrawn). By de...
701dacb7b1269630060c9ea3e71a879836008244
640,915
def get_node_components_from_abstraction_graph(graph): """Extract the set of node ids from each node label in the input graph. Parameters ---------- graph : Networkx undirected graphs Abstract graph with set of node ids as labels. Returns ------- node_components : list[set(node ids...
d7b62f223d460043e7aa90ce53bb47c6fb15a40e
640,916
def melt_cluster_rep_matrix(df, name="count"): """Helper function to melt a cluster rep matrix for saving as feather""" return df.T.reset_index().melt(id_vars=["cluster", "rep"], var_name="FBgn", value_name=name)
9fad9f1126d7dee6f38ac4e72a76b0d5d6244d96
640,917
def wheel(pos): """b->g->r color wheel from 0 to 1020, neopixels use grb format""" if pos < 255: return [0 , pos , 255] elif pos < 510: pos -= 255 return [0 , 255, 255 - pos] elif pos < 765: pos -= 510 return [ pos, 255, 0] elif pos<=1020: pos -= ...
613d7233d6cb081336ebadcc5a5682fd5c9eb281
640,918
def impc_pipeline(spark_context): """ :param spark_context: :return: """ return spark_context
92a421fdbdb56f328f5b97e95ce012923809cebb
640,920
def _opacity_from_bin(bin, n_bins): """ Return opacity for bin.""" if n_bins <= 0: return 0.35 ratio = bin/float(n_bins) if ratio < 0.2: return 0.6 elif ratio < 0.3: return 0.85 elif ratio < 0.5: return 1.0 return 1.0
c7ef062be3046ae845cf8ba09b221b34d22558a4
640,922
def make_pseudonumber_sortable(pseudonumber): """For a quantity that may or may not be numeric, return something that is partially numeric. The method must always return a tuple containing a number, then zero or more strings. Other parts of the program assume that the first number is the numeric representa...
7cf49e42ec87cd2b24f9bdf17800294c3407b42b
640,923
import torch def db(complex, complex_real_axis=-1, keepdim=False): """Compute the amplitude in decibeis of a complex number for a Torch tensor.""" ampl_sq = torch.sum(complex * complex, dim=complex_real_axis, keepdim=keepdim) return 10*torch.log10(ampl_sq)
89b2daa98883dd6dfaac876dc15d2ef1bcca99a7
640,924
import os def path_is_in_directories(path, directories): """Is the given path within the given directories? :param str path: The path to test. :param list directories: The directories to test if the path is in. :returns bool: """ path = os.path.abspath(path) + os.path.sep for dir_ in dir...
b110d8b318a9f3b6271fa803af80ab7272ff6612
640,925
def fib(n, i=0, a=0, b=1): """Return the nth fibonacci number. >>> fib(6) 8 >>> [fib(n) for n in range(6)] [0, 1, 1, 2, 3, 5] >>> fib(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 """ if not n >= 0: raise ValueError("n must be >= 0") ...
64e5822f9e148dbd949cfa822424212facad3fe2
640,926
import subprocess def execute(cmd, cwd, env=None) -> subprocess.Popen: """ Executes a command in a directory with a certain environment :returns Popen """ kwargs = {"encoding": "utf-8", "stdout": subprocess.PIPE} process = subprocess.Popen(cmd, cwd=cwd, env=env, **kwargs) try: pro...
a461add675372e20ca4a1fb1993f36fd13dc0e9c
640,927
def purchase_intention(people_who_declared_interest, total_people): """Returns the purchase intention rate for a product. This can be used for cart-to-detail, buy-to-detail, and similar calculations. Args: people_who_declared_interest (int): Number of people who declared interest in a product. ...
fa5e4c16fa3a796c2297d9b39b1e5ccc9f3459ce
640,928
def file_get_contents(path : str) -> bytes: """ Returns contents of file located at 'path' """ with open(path, 'rb') as f: return f.read()
d8785080cc6e2a234ce44d8cc6961524f20de03c
640,929
def fill(s, length=45): """ """ while len(s) < length: s += ' ' return s
fe1fa830e28c89f61622046868ebee59f29413bf
640,930
def name_adder_stop(a_list): """assumes a_list is a list of strings (possibly including empty strings) returns a list of the non-empty strings in a_list up to the first empty string""" i = 0 new_list = [] while i < len(a_list): if a_list[i]: new_list.append(a_list[i]) els...
77dceceda4d1ec7c7c9fe80e3707276e214dbdde
640,931
def part1(data): """ >>> part1([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 7 >>> part1(read_input()) 1581 """ previous = data[0] count = 0 for value in data[1:]: if value > previous: count += 1 previous = value return count
1de5b26fe9d3392709fbfc004e30417ac15e75b3
640,932
def parse_instruction(puzzle_input, current): """parses the instructions stored in the current position of the input """ instruction = str(puzzle_input[current]).zfill(5) opcode = instruction[-2:] modes = [int(instruction[2]), int(instruction[1]), int(instruction[0])] current += 1 return opc...
633323271c58ee55e262ab10eecb8b3f697679ba
640,933
def unit_uniform(df): """Make units in *df* uniform.""" column = [x for x in df.columns if x in ['commodity', 'emission']] if column: com_list = set(df[column[0]]) for com in com_list: df.loc[df[column[0]] == com, 'unit'] = df.loc[ df[column[0]] == com, 'unit'].mo...
ea7f29dd7398fc358329e28f28824376687b6834
640,934
import random def split_list_equal_sized_groups(lst: list, n: int, seed: int = 123) -> list: """This function splits a list in n approximately equal-sized subgroups Args: lst (list): input list that we want to split n (int): number of splits seed (int): random seed to use; defaults to ...
68d1fc7a50895401eace475ed10bcc3fcf216dcf
640,935
import base64 def encode(data, chunklen=6, linelen=78): """ Encode data with base64 and format it. Arguments: data: String to be encoded. chunklen: Number of bytes in a chunk, defaults to 6. linelen: Length of a line, defaults to 78 characters. Returns: The base64 enc...
cfb5a5c246682b2f2b7210c9dd7bc9fa37f08e81
640,936
import re def __check_reg_str_contain(file_reader, reg_str): """ check if any line matches the reg_str :param file_reader: FileReade Object :return: return True if found """ file_content = file_reader.read() lines = file_content.splitlines() for line in lines: ...
e7ce5612023ddf5a64fc2af92b27764b99567c1e
640,937
import time def epoch2timefmt(epoch): """Converts epoch time to YYYYMMDDHHMMSS for ssh-keygen ssh-keygen accepts YYYYMMDDHHMMSS in the current TZ but doesn't understand DST so it will add an hour for you. :-/ """ struct_time = time.localtime(epoch) if struct_time.tm_isdst == 1: struct...
2ef3f9f2882bb5e4b72266aef582adf4ef80e14d
640,938
def get_chart_url(country_code, interval, date1, date2): """Gets a url with the specified parameters""" chart_url = f'https://spotifycharts.com/regional/{country_code}/{interval}/{date1}--{date2}' return chart_url
a77688a863582e6e30114222eda24e588827995a
640,939
def get_pdb_atom_info(line): """Split and read pdb-file line (QPREP-OUT). Extract and return: atomnumber, atomname, resname, resid) """ # UNIT: check if the correct numbers are extracted atomnum = int(line[6:11]) atmname = line[13:17].strip() resname = line[17:20].strip() resin...
e0c05d1d543c7b08be3c404427c19b42a1b93a15
640,940
def get_rot_mat(T): """ Takes a homogeneous transformation matrix and returns the corresponding rotation matrix and position vector :param T: 4 x 4 transformation matrix :return: rot_mat: 3 x 3 rotation matrix pos_vec: 3 x 1 position vector """ rot_mat = T[0:3, 0:3] ...
764ba2b00be138a7f750a7d154c1ff0eb5b4ce05
640,941
def get_ddfNames(opsimdb): """Given an opsim database object, return the DDF field names.""" propInfo = opsimdb.fetchPropInfo() DD_Ids = propInfo[1]['DD'] DD_names = [propInfo[0][x].split(':')[1] for x in DD_Ids] return DD_names
ec6c22d9aac55da708ba42647835fa14e752bf40
640,942
def db_headings(dict1: dict): """This program returns all the keys in the dictionary of dictionaries >>> db_headings(dict1) {'died', 'notes', 'surname', 'author', 'born', 'jgoodall', 'rfranklin', 'rcarson', 'forename'} """ headings = set() for i in dict1.keys(): headings.add(i) for j...
e9f2d04a11bafe82a6cc682b05a08a160c559028
640,943
def append_correct_whitespace(token, pronoun): """ If the original pronoun was followed by whitespace, append whitespace to new pronoun. """ if token.text_with_ws != token.text: whitespace = token.text_with_ws[-1] pronoun = pronoun + whitespace return pronoun
8e2aa839b2b457f118a2b015605c2bfe0461f971
640,945
import os def _env_int(key: str, default: int = 0) -> int: """ Retrieve an int from the named environment variable. Args: key (str): Environment variable to look for. default (int): Default value if variable not found or on type errors. Returns: (int): Int value of environmen...
df506c8d7a71b1f1fac5fc43a92806441bbd3005
640,946
def social_networks(context, user): """ Return user's social network connections """ association_facebook = user.social_auth.filter(provider='facebook').first() association_twitter = user.social_auth.filter(provider='twitter').first() association_googleplus = user.social_auth.filter(provider='go...
2406c6fec354ac4cb8824688e0f6289fceb549c1
640,947
import re def preprocess_ents(label, text): """ Preprocess an entity Parameters ---------- label: str: The named entity label text: str: The name entity text Returns ------- tuple: returns a tuple of strings containing the label and text """ pattern = ':...
17d99929266a630733faa101d227a318db561990
640,948