content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def linear_y(t0, t_step, slope, y0): """ A function to generate y values that satisfied to linear relationship with independent value t_list, slope, and start point of y Parameters: ----------- t0: t0, with dependent variable as startpoint_y t_step: step of t slope: slope y0: startpoint...
bbaf3e86c2bd040cafacc600f19b4ab7449e2778
631,030
def build_profile(first, last, **user_info): """Cria um perfil de usuário Args: first (str): Primeiro nome last (str): Sobrenome **Kwargs: user_info (key, value), optional: Campo => Valor Returns: dict: {first_name: first, last_name: last, key: value...} """ pr...
a28a2aae91ebec90408cc9cda261ab57eb9406f3
631,031
from argparse import ArgumentParser from argparse import RawTextHelpFormatter import os def get_parser(): """Build parser object.""" parser = ArgumentParser( description="""NiWorkflows Utilities""", formatter_class=RawTextHelpFormatter ) parser.add_argument("fmriprep_dir", action="store", hel...
073ec0312a257f478749f808cd9db2adc4ee6b14
631,032
def complexAdd(complex1, complex2): """This method is used to add 2 complex numbers Arguments: complex1 {tuple} -- tuple of 2 representing the real and imaginary part complex2 {tuple} -- tuple of 2 representing the real and imaginary part Returns: tuple -- tuple...
01653bd5d05baaadca8f3a9b452d199421c237ee
631,034
import torch def collect(input, index, padding_idx=0): """ Perform a batched index select where index is given for each example Args: input: tensor of shape (B, T_1, dim_2, dim_3, ...) index: tensor of shape (B, T_2) Return: tensor of shape (B, T_2, dim_2, dim_3, ...) """ ...
6121fc76b99e2f23b307d72da3ea3c2e752b72c0
631,035
def select_link_function(self, tag): """Only customize if trying to leverage "attachments" in *GitHub* releases A way to select from one or multiple attached donwloadable files from the server, instead of downloading the default release/tag source code """ # -- Default, universal case (and is the only option for...
6d38b0d09632661290a43834ee10703e7b7baa71
631,036
def merge_bytes(*args): """Returns a single list of bytes from given bytes and list of bytes. Arguments: *args -- bytes and list of bytes to merge """ result = [] for arg in args: if type(arg) in [list, tuple]: result.extend(arg) else: result.append(arg) ...
46563fe704609f1e1857feb94e3064fca17e67c0
631,037
def task_8_count_customers_by_city(cur): """ List the number of customers in each city Args: cur: psycopg cursor Returns: 69 records in descending order """ cur.execute("""SELECT COUNT(customerid), city FROM customers GROUP BY city ORDER BY count DESC""") return cur.fetchall()
647d1710dc6c47005c169b9398cffab5e9897ba0
631,038
import torch def ndc_to_camera_space(Xn, P): """Transform point(s) from normalised device coordinates to camera space. Args: Xn (torch.Tensor): homogeneous point(s) in normalised device coordinates. P (torch.Tensor): projection matrix. Returns: Xc (torch.Tensor): homogeneous poin...
40e731bb349ed5248bf22993107c76245e4e0767
631,039
import time def should_refresh(tok): """Returns True if the token must be refreshed because it expires soon.""" return time.time() > tok.expiry - 60
83e506cb7236813927fd8b5c29715e7f8a681ed3
631,040
def p_r(logits, targets, th=0.5): """ :param logits: Tensor of shape (B, num_class) :param targets: Tensor of shape (B, num_class) :param th: Float threshold :return: (Float, Float) """ assert len(logits) == len(targets) sample_num = len(targets) pred = (logits.sigmoid() > th).int() ...
78e47a53bb9269090e572b69139a7314ecf47893
631,041
import argparse import sys def get_args(): """ get args """ parser = argparse.ArgumentParser() parser.add_argument("filename", help="the csv file containing the fake pypi packages", type=str) if len(sys.argv) == 1: parser.print_help() ...
f2ba3642b1b96a93994a38fabff1b6d92221e5c1
631,042
def strip_quotes(s): """Trim white space and, if necessary, quote characters from s.""" s = s.strip() # Strip quotation mark characters from quoted strings. if len(s) >= 3 and s[0] == '"' and s[-1] == '"': s = s[1:-1] return s
03effc4939b405f84b21feb2e67c5077cb46eee9
631,043
def move_loop(arr, range_from, range_to, move_value=2): """ Perform array moving :param arr: array to move :param range_from: range() from param :param range_to: range() to param :param move_value: class to move :return: moved array """ for i in range(range_from, range_to, -1): ...
873cb3394b7ba26862cb0f5faad345c4dbe2d1b2
631,044
def set_lifecycle_events_enabled(enabled: bool) -> dict: """Controls whether page will emit lifecycle events. Parameters ---------- enabled: bool If true, starts emitting lifecycle events. **Experimental** """ return {"method": "Page.setLifecycleEventsEnabled", "params": {"enab...
f9e2ca6972be192a0348c8b8c6b8ce395bf5f17f
631,045
def adjustLearningRate(learning_rate, decay_rate, epoch_num): """ Adjust Learning rate to get better performance :param learning_rate: :param decay_rate: :param epoch_num: :return: """ return learning_rate / (1 + decay_rate * epoch_num)
ac09c7ddadfce6c0fcc427046e095073e97e9629
631,046
def default_weight_func(distance): """ A linear or exponential decay function used for getting an association score between two words based on their distance. """ return 10/2**distance
c542c7c659ca8d32390ffbdbccafd2194d11de1e
631,047
from typing import Tuple import re def parse_dice_string(dice_string: str) -> Tuple[int, int]: """parses formatted string to a dice roll, e.g. "2D6" for rolling two six-sided dice. Args: dice_string: formatted string for roll. Returns: tuple of the count and sides for the roll. ...
dd594325ac3fdd60bff7e700ce7c723b7048373c
631,048
def calculate_allocation_from_cash( last_cash_after_trade: float, last_securities_after_transaction: float, spot_price: float ) -> float: """Calculates the current allocation.""" security_bankrupt = spot_price <= 0.0 cash_and_securities_zero = last_cash_after_trade == 0.0 and last_securities_after_trans...
2a8c6c129ee0e2017a4a9bba51f8e89b498baca2
631,049
def _count_words(s): """count the number of words in a paragraph Args: [String] s Return: [INT] number of words in the string """ return len(s.split(" "))
e5659fc173092d139149368a8c9424040ff52568
631,051
def count_ed_mgs(db): """ Just return how many times Ed answered. """ try: count = db.get('ed_info')['qty_answed_message'] except: count = 1 return count
58b81537fe378128c250a6685ad4a5ebed02e859
631,052
def _get_county_variants(county: str) -> list: """ Given a county, returns a list of the possible variants of the county name. Args: county: A string literal that represents the county name. Returns: A list of the possible variants of the county name. """ county = county.replac...
b61356fc1845907c3b761dbdaed607ba965f531a
631,054
def sanity_check(data, folds): """ check if num samples from class is less than num of folds :param folds: k, num of folds in k-fold :param data: DataFrame, last column is target :return: dropped- dropped class , drop_file - need to drop file, cls_count """ data_count_target = data[data.colu...
b24b0a5831b882b280d3c4c5f423f5baee3e086d
631,055
def rotate_box(pre_box, axis, rot_num = 0, box_size = 9): #box size is the number of bins """ rotates box along one axis rot_num times """ box_size -= 1 # with 9 bins, indices are 0-8 dict = {"x":[1, 2], "y":[0, 2], "z":[0, 1]} # lists the axes to be changed if rotated around key new_pre_box = [] for ind_...
c482e147826a0075d529c8b5b28582355f275ede
631,056
def sniff_appendix_id_type(paragraphs): """ Detect whether an appendix follows the section paragraph indentation scheme (a-1-i-A-1-i) or the appendix scheme (1-a) The sniffer should return 'section', 'appendix', or None. """ for graph in paragraphs[:10]: if graph.text.startswith('(a)'):...
99fe8ec3b8c007fb5228060c92721a8b35e0fd9d
631,057
def obj_func(xl, arg): """Wraps a spreadsheet computation as a Python function.""" # Copy argument values to input range xl.Range('Inputs').Value = [(float(x), ) for x in arg] # Calculate after changing the inputs xl.Calculate() # Return the value of the output cell result = xl.Range("Outp...
a1d8b2f3384449fcef0b0f88b21946692c7270f7
631,058
def is_tree(character): """ A tree character is defined as "#" """ return character == "#"
fc84c97bb77a8d1f2211e400abdf910c0761152d
631,059
def testset_single(paths, rgen): """ Returns a test set where each test corresponds to a single probing path. This function is reproducible: iteration proceeds through the probing-path dictionary in sorted order, and a random shuffle is applied before returning. """ testset = list() for src...
a61e9dd7153863162980f6390ee3183c5e0b4568
631,061
import getpass def input_api_key() -> str: """Get the Meaki dashboard API key from the user's input. -> Return the API key (string) with the leading & trailing whitespace removed if the key is not a blank value. """ input_message = "Enter your Meraki's dashboard API Key: " api_key = getpass....
69bbe71fac22ed3628adb12344a06c865a5a8340
631,062
import pkg_resources def dump_env() -> list[str]: """ Get all packages and versions from the current environment. conda list is slow, use pkg_resources instead this might miss dev overrides """ return sorted(str(pkg) for pkg in pkg_resources.working_set)
793ecbc3de6a0dbefb591a9376f22a644d60866c
631,063
def body(expr): """Gets the body of a parsed lambda (represented as 2-tuples)""" assert type(expr) == tuple return expr[1]
40f51184c9d48be56c91291f645113d3b3485b7f
631,064
def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" Args: key: string, the method key name. Returns: A safe method name based on the key name. """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') f...
064c2800c94767da7a499d3a842808fac9641947
631,065
import os def read_txts(): """ using all the txts in results generates a dict with test accuracy as % :return: dict with results per model per data :rtype: dict """ RNN_results = {} GRU_results = {} LSTM_results = {} for file in os.listdir("results"): file_as_list = fi...
07de14776a5442c7c28933a13938a5a3b150a161
631,066
from typing import Sequence def timestamp_to_ms(groups: Sequence[str]): """ Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds. Example: >>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups()) 420 """ h, m, s, frac = map(int, groups) ms = fra...
2928a0b14876e3b14ad8056bafbab5d540ead686
631,067
def expand_args_to_list(args,type_=int): """ it generates a list of args from a sequence like 1,3,5 or 3-7 """ result = [] for arg in args.split(',' in args and ',' or ' '): if type_ is int and '-' in arg: vals = [type_(v) for v in arg.split('-',1)] result.extend(range(*(vals[0],vals[1]+1))) e...
be84f03133fd5d10e645917954b8e2d504889bb2
631,068
def box_sz(b): """ Returns the box size""" return ((b[:, 2]-b[:, 0]) * (b[:, 3]-b[:, 1]))
5a38db0bcf11b5b31b42bf261e2cd09a07c4188c
631,069
def min(raw_metric): """ .. note:: Deprecated use `longMin`, `doubleMin' instead """ return {"type": "min", "fieldName": raw_metric}
75bff81e6ce181f61867f830ecdc53f1b60f3b8b
631,070
from typing import Dict from typing import List from typing import Any def get_value(dictionary: Dict) -> List[Any]: """Return a list of values in a given dictionary.""" return list(dictionary.values())
956b2e23055657c2dda1a54c840ea548acdebdfd
631,071
import random def split_test_from_training_data(network, ratio=0.1): """ Splits a given network into two networks with disjoint edges randomly. """ test_edges = random.sample(list(network.edges()), int(len(network.edges()) * ratio)) training_network = network.copy() training_network.remove_edg...
589c2b4f8c56941bca70a7342e5a47a41e23ce86
631,072
def invert_dictionary(aDict): """Transforms a dict so that keys become values and values become keys""" return {v: k for k, v in aDict.items()}
a4ec169b2f8d0857d4b22191c8823b17a03fc954
631,073
def expectation_value(state, operator): """ Calculates the expectation value of a superoperator for a quantum state. Parameters ---------- state: np.ndarray Vectorised density matrix of a quantum state. operator: list of np.array Quantum superoperator. """ return sum((s...
e9b8d89a47649209c1263956facd3bb043a052ad
631,074
import numpy def get_global_accuracy(data, target, classifier): """ returns the global accuracy of the classifier on data and target""" return numpy.sum(numpy.equal(classifier.predict(data), target)) / float(len(target))
9e37f58f19fb19b876422bcee4e7133835a28dbb
631,075
def find_block_from_timestamp( w3, timestamp: int, low: int = 0, high: int = 0, search_range: int = 150_000, accuracy_range_seconds: int = 180): """ A basic algorithm to find a block number from a timestamp. Args: w3: web3 instance timestamp: Target block timestamp ...
1d819e1494afa6b4d45d8864c576461f5dda6deb
631,078
import re def shorten_url(args, head, shortenapi): """Shorten a url.""" if args.bitly: try: link = shortenapi.shorten(head.link)["url"] link = re.sub("http://", "https://", link) except Exception: # pylint: disable=broad-except link = head.link else: ...
275aff2ed7e30b253aa9b507826bd80f101ad1df
631,079
def _clean_page_wheel(text): """ remove unexpected characters @param text string @return string """ text = text.replace("&quot;", "'") text = text.replace("&#8209;", "-") text = text.replace("&#46;", ".") text = text.replace(" &middot; ", "-") text = ...
57c04acd001d0dc827d84b407f3ab00c0e033199
631,080
def get_output_dataframe(timeseries, preprocessed_data, topmodel_data): """Get the output data of interest. Returns a Pandas Dataframe of all output data of interest. """ output_data = {} if preprocessed_data["snowprecip"] is not None: output_data["snowprecip"] = preprocessed_data["snowprec...
b8694bda313b6651977f0aa150d0a2ee1c6e6bd4
631,081
def percentile(N, P): """ Find the percentile of a list of values @parameter N - A list of values. N must be sorted. @parameter P - A float value from 0.0 to 1.0 @return - The percentile of the values. """ if len(N)==0: return 0.0 n = int(round(P * len(N) + 0.5)) return N[n-...
4ef0e9baad1f008e28b821ee7c65177d50e5b8fd
631,082
def problem1(individual): """ Implements the first test problem ("bi-objetive Sphere Model"). Variables = 2 Objetives = 2 f(x) = (x'x, (x - a)'(x - a))' with a = (0, 1)' and a, x element of R^2. Bounds [0, 1] @author Cesar Revelo """ a = [0,1] f1 = (individual[0] ** 2) + (...
8a0683de94051a752b4168da90fa63aca6c5493a
631,083
def get_team(teams, team_input): """ Returns desired Team from Teams :type teams: Teams :type team_input: string :rtype: Team """ for team in teams: if team_input.lower() in team.name.lower(): return team
2e3affdd9bd555f4f49939913f0287a3971672e5
631,085
from typing import List def _parse_online_cpus_string(raw_string) -> List[int]: """ Parses string returned by /sys/devices/system/cpu/online and returns a list of online cores """ parsed_cpus_info = [] for nr in raw_string.split(','): if '-' not in nr: parsed_cpus_info.appe...
d0932b855a6211cab6ef032d4ade8661fd23e3ee
631,086
def mimebundle_to_html(bundle): """ Converts a MIME bundle into HTML. """ if isinstance(bundle, tuple): data, metadata = bundle else: data = bundle html = data.get('text/html', '') if 'application/javascript' in data: js = data['application/javascript'] html +...
4d32f50a241d2b64952bb4849ddbe52cb55d94a5
631,087
import collections import copy def HeadToSelect(head): """Converting a rule head to a SELECT representation.""" select = collections.OrderedDict() aggregated_vars = [] for field_value in head['record']['field_value']: k = field_value['field'] v = field_value['value'] if 'aggregation' in v: s...
4857ccaa0e5afadec14bad9be80b7f33c827e15b
631,089
import hashlib def id_from_email(email): """ Just generates a predictable user ID from the email entered """ md5 = hashlib.md5() md5.update(email.encode("utf-8")) # Truncate to 32-bit return int(md5.hexdigest(), 16) & 0xFFFFFFFF
e8c15b8225aef10d511fe4bd297946a74b271f9b
631,090
def fsescape(s): """Escape string to be safely used in path names @param s: some string @type s: basestring @returns: escaped string @rtype: str """ res = [] for x in s: c = ord(x) if c > 127 or c == 47 or c == 92: # 47==slash, 92==backslash res.append("~%...
f0c8d9d1500f2711e0ea966c51a32df8479e3d6d
631,091
def wrapM(monad): """ Takes a monad and wraps it so that any attribute that is not in the monad is automaticall forwarded to the monad value. Complexity: O(1) params: monad: the monad to wrap returns: the proxy object """ class Proxy(): """The monad proxy object""" ...
f97fc22a43ab588c0ae9519a9baaee6ce5406a5a
631,092
import math def GetRealignIters(realign_times, num_iters, num_jobs_initial, num_jobs_final): """ Takes the realign_times string and identifies the approximate iterations at which realignments have to be done.""" # realign_times is a space seperated string of values between 0 and 1 ...
eba0aae87302e058dc06347e1532e35cbbab0e28
631,093
import importlib def get_runner_constructor(suite_tag): """ Returns the function to run for the test runner. Args: suite_tag: A str, locates the test runner for an API. Returns: A function to run the tests. """ module_name = "api_tests." + suite_tag.lower() module = importlib.import_module(modul...
d9295bc5a19c3031941e7865fc285a33b2c1ec4a
631,094
import argparse def parse_args(): """ Can set prefix and enable develop mode. """ parser = argparse.ArgumentParser() parser.add_argument("-p", "--prefix", help="Set a prefix for the bot.") parser.add_argument("-d", "--dev", help="Enable develop mode.", action="store_true") return parser.p...
fda7e39cc0874880a7998cb4e5f205819b740dd8
631,095
import subprocess def get_module_collection(): """Return user Lmod module collection. Lmod collection can be retrieved using command: ``module -t savelist`` :return: list of Lmod module collection :rtype: list """ return subprocess.getoutput("module -t savelist").split("\n")
85131c1b10221e72c2bae91329e848d2e32204c9
631,096
def set_or_check_min(x, min_x, var_name): """ If x is None, set its value to min_x; also check that it is at least min_x. :param int|float x: the value to check :param int|float min_x: minimum required value for x :param str var_name: name of the variable (for error logging) :return: set/checked val...
aac0290c50a8e4b5145222c415e4a18289101070
631,097
from pathlib import Path def batch(action, card_dir: Path, max_backup: int = 1): """Performs an `action` repeatedly across a given `region` and `card_slot`. Before using this function, ensure all parameters are valid. Args: action (function): the function to run in batch card_dir (Pa...
0b933da7ca35361c491ee2a24faca214dc74e863
631,098
def statistics_cases(self): """Get a list of all statistics cases in the Grid Case Group Returns: List of :class:`rips.generated.generated_classes.EclipseCase` """ stat_case_collection = self.children("StatisticsCaseCollection")[0] return stat_case_collection.children("Reservoirs")
3be8b4d1f4ebdf0936b2e795675bf3ac6675c0e1
631,100
import math def seqDistance(sq1,sq2): """Computes the pairwise distance between seq1 & seq2""" count = 0 denom = 0 for a,b in zip(sq1,sq2): #to exclude all empty spaces if a == '-' or b == '-': pass elif a != b: count += 1 denom += 1 ...
801637bf9153399bb483ea357bb8ec582d7aadfc
631,101
def is_subsequence_of(iterable1, iterable2): """Tests if :iterable1: is a subsequence of :iterable2:.""" if (len(iterable1) > len(iterable2)): return False for i in range(len(iterable1)): if (iterable1[i] != iterable2[i]): return False return True
4df4a91a340094ed7d944b000c57821598f5fef5
631,102
def parse_error_hash(self): """Define missing ParseError.__hash__().""" return hash((self.position, self.formatReason()))
c61ad3e05e40669ac2729df9bb389cb0edda54d9
631,103
def numberOfUniqueTranscripts(transcripts): """ Given a list of transcripts, return the number of unique names. """ names = set() for t in transcripts: if t not in names: names.add(t) return len(names)
fddde42abaf87dd684ccf17c4a3a9f3326ed8bd8
631,104
def eval_string(s): """evaluate python statement (String)""" if s.startswith("eval("): try: return eval(s[5:-1]) except: return s else: return s
a3ff7582d16b9253c1634636e626bacbb5a8c299
631,105
def _break(bitstring,groupsize): """ Break a binary string into groups of groupsize digits. For example, _break('1100001111',4) returns '11 0000 1111' :param bitstring: The ASCII binary string to break into groups :param groupsize: The number of bits to group together in each group :return: A st...
1cf511e6ef8b33dc24c3f577b6a73267bf7fb76a
631,106
def _build_path_query(path): """ converts path in url to path required in query. :param path: like 'a/b/c/d' :return: ('a', ('a','b','c','d'), '{a,b,c,d}') """ if not path: return None sp = path.split('/') if len(sp) == 1: return sp[0], sp[0], '{' + ','.join(sp) + '}' ...
2f063ba7ed33782195d96cf9e5af2683ee1196c1
631,107
from typing import Deque def build_dequeue_three_nodes(): """Build three-node dequeue.""" q = Deque() q.append('apple') q.append('peaches') q.append('bananas') return q
aa73c9f9707d81c71fdea09615117da9ba733a8b
631,108
from pathlib import Path def _is_file_exists(path: str) -> bool: """Whether the path is a file. Args: path: The file path. Returns: True if the path is a file, otherwise returns False. """ return Path(path).is_file()
1b10c9c5f6b08367d20906ed82c924ed12df6587
631,109
def is_connected(result_graph): """Determines, whether all vertices that contain an edge are connected. Vertices without an edge are not considered. Parameters ---------- result_graph : dict A graph as returned by edges_to_graph. Returns ------- bool True, i...
2c4219e305219152ba2438a638f6afe311470b07
631,110
import numpy def angle_difference(angle_1, angle_2): """ compute the difference between two angles this takes care of the wraparound at -pi/pi in angles and delivers the minimum angular distance between two angles Arguments: angle_1: the first angle angle_2: the second angle whic...
e838b88401909fa7b3b874338f41a411219d8d2d
631,111
import os def get_nproc(): """Get the number of processes for QM calculation.""" if "OMP_NUM_THREADS" in os.environ: nproc = int(os.environ["OMP_NUM_THREADS"]) elif "SLURM_NTASKS" in os.environ: nproc = int(os.environ["SLURM_NTASKS"]) else: nproc = 1 return nproc
fc4a2326f9a12de8e3831bf54f6f0e70037c34b1
631,112
def some_args(num: int, s: str, b: bool) -> None: """Some arguments require descriptive names >>> some_args(1, "a", True) None """ return None
f075b932a989d73e3b8b4e98068d05494b473fe9
631,114
def get_alternated_ys(ys_count, low, high): """ A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the x axis are too crowded. :param ys_count: integer from 1 to 3. :param low: lower bound of the area designated for annotations :param h...
e606ef555ff29285d4b7b77076939e66b8997856
631,116
def height2rate(height_of_rainfall, duration): """ calculate the specific rain flow rate in [l/(s*ha)] if 2 array-like parameters are give, a element-wise calculation will be made. So the length of the array must be the same. Args: height_of_rainfall (float | np.ndarray | pd.Series): height...
6a5b8c0eca91abdbed7d85cc031b3d3ff61aae9a
631,117
import math def round_up(number, precision=10.0): """Round a number up to the given precision. Precision = 1.0 means 12345.6 gets rounded to 12346, precision = 10.0 means 12345.6 gets rounded to 12350, precision = 100.0 means 12345.6 gets rounded to 12400, and so on. """ return math.ceil(number / precision...
bdb4151fdd1db5b3f64d5623770ed531ef36a9ac
631,118
import math def is_NaN(value): """ check value is nan or not :param value: :return: bool """ if isinstance(value, float): return math.isnan(value) else: return value != value
03eb4876ba9aabc7150a5d7f57f2d59c1b8aa879
631,119
def wordCount(wordListDF): """Creates a DataFrame with word counts. Args: wordListDF (DataFrame of str): A DataFrame consisting of one string column called 'word'. Returns: DataFrame of (str, int): A DataFrame containing 'word' and 'count' columns. """ return (wordListDF.group...
8f4e546588a4a0c66955eebe0fab619acdf71a7e
631,120
from typing import Pattern from typing import Tuple import re def parse_vector(s: str, *, num_re: Pattern = re.compile(r"[\d.-]+")) -> Tuple[float, ...]: """Convert a vector string into a tuple.""" return tuple(map(float, num_re.findall(s)))
9221798ef280f9d82f3282071ea16affa441f3d6
631,121
from typing import Union from pathlib import Path import re def get_dois_from_bib_re(bib_file: Union[str, Path]) -> list: """Retrieve DOIs by parsing bib file line by line.""" with open(bib_file, "r") as bibtex_file: data = bibtex_file.readlines() re_doi = re.compile(r"^doi\s=\s\{(?P<doi>.+)\}")...
b57526a1f28a0810017b1be5638d4b72519a46c3
631,122
def filter(function_or_none, sequence): """Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. :type function_or_none: collections.Callable | None :type sequ...
3b065ab30d2819ac91e9d6f566839e63c5f3ffe6
631,123
import os def _all_files(root, filter_function=None): """Returns the set of all files at the given root. Filtered optionally by the filter_function. """ all_files = set() for dirpath, _, filenames in os.walk(root): for filename in filenames: if filter_function is not None and...
eebb45f520cfa57e1dba6583c7340af1423818a1
631,125
def param_name(p): """Extract parameter name from attributes. Examples -------- - ``fix_x`` -> ``x`` - ``error_x`` -> ``x`` - ``limit_x`` -> ``x`` """ prefix = ["limit_", "error_", "fix_"] for prf in prefix: if p.startswith(prf): i = len(prf) return ...
4d012bfec5412c6fef06146ae9c56b2cf860f7b9
631,126
def get_datafile_save_path(direc): """ get_datafile_save_path(direc) Returns directory path amended with data file subdirectory. Required args: - direc (Path): directory path Returns: - direc (Path): amended directory path """ direc = direc.joinpath("data_files") ...
46e55a22791c9894d0dd5ceabb29ec34e8f5e117
631,127
def format_header_break(): """Returns a header break of 39 '#' glyphs. Examples: >>> format_header_break()\n '#######################################' """ return "{0:#<39}".format("")
b41def782deb5ecb245f077289f4422fe06b1420
631,128
import re def is_sale(this_line): """Determine whether a given line describes a sale of cattle.""" sale = False while True: has_price = re.search(r'\$[,0-9]+\.[0-9]{2}', this_line) if not has_price: break has_another_price = re.search(r'\$[,0-9]+\.[0-9]{2}\s*-\s*\$...
f747d19c85b5979334f0d71415c7dd369ee6f8a0
631,129
def get_pod(module, array): """Get ActiveCluster Pod""" pod_name = module.params["pgroup"].split("::")[0] try: return array.get_pod(pod=pod_name) except Exception: return None
f9373b0597549bdb4f36e28a71dc4d065e7a8dca
631,130
from typing import List def is_valid_rule_one(character_count_range: List[int], character: str, password: str) -> bool: """ Return True if a password is abides to its asscoiated policy else return False The policy is represented as follows: [1-3] a --> the character a should occur at least 1 time and at m...
f58ae7040d757f1cefd26cfef2d39977f33d6c10
631,131
def defangIPaddr(self, address): """ :type address: str :rtype: str 82% faster 50% less mem """ output = "" for char in address: if(char == '.'): output = output + '[.]' else: output += char return output
6d82e3926a0800d90f4de9434c8c099d821cdb95
631,132
def writeable_property(default_fun): """ function decorator that allows overwriting default properties """ pname = '_' + default_fun.__name__ @property def pfun(self): attr = getattr(self, pname, None) if attr is None: return default_fun(self) if callable(attr): ...
104352b3860ea1710f373b8365afd290f15edb3c
631,133
def sanitize_name(name: str) -> str: """Make a name safe for use as a keyspace name.""" # For now just change dashes to underscores. Fix this more in the future return name.replace("-", "_")
70f373141f04d861e9dbe106f83951ada96f1c09
631,134
import os import re def get_distro(): """Get the distro as defined in /etc/os-release[ID].""" distro = None os_release_file = '/etc/os-release' if os.path.isfile(os_release_file): with open(os_release_file) as release_file: for line in release_file.readlines(): matc...
3954409233f27fa0a8f7e6ba6bd1ac2f1e29ac06
631,135
def dna_to_rna(seq): """ Converts DNA sequences to RNA sequences. """ rs = [] for s in seq: if s == 'T': rs.append('U') else: rs.append(s) return "".join(rs)
8d51dc102e7c7b5693a8f3d3daccef89ce65d2ba
631,137
def problem_5_5(a, b): """ Write a function to determine the number of bits required to convert integer A to integer B. Input: 31, 14 Output: 2 Solution: compute (a XOR b) and produce the number of 1 bits in the result. """ def num_set_bits(n): count = 0 while n != 0: ...
09c6c63af7d69f868867d43783a96f28676ce452
631,138
def check_nrow(d_f): """check if row >= 1""" if d_f.shape[0] >= 1: print('Pass check_nrow') else: print('This dataframe has less than one row.') return False return True
1b8533223bca541773362cb4b550ad7099c29f3e
631,139
def read_file(file_path): """ Outputs the content of a text file (> string) """ reading_file = open(file_path) result = reading_file.read() reading_file.close() return result
4565c546736b9aeb82a41e4089e5a30b87f073f6
631,140
def is_aa_by_target_atoms(res): """Tell if a Residue object is AA Args: res: a Bio.PDB.Residue object representing the residue. Return: Bool. Wheather or not the residue is AA. """ target_atoms = ["N", "CA", "C", "O"] for atom in target_atoms: try: res[atom] ...
f108e464e08ad82420fbef605d2f0135cfbd271b
631,141
def at_index(string, element_index): """ Get the string at the specified index of a list seperated by ',' """ len_string = len(string) current_index = 0 current_ptr = 0 is_in_quote = False is_escaped = False while current_ptr < len_string and current_index < element_index: if not ...
d3c1c2b9381b7a55ed6b3fdb483154b5819a1dd8
631,142