content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _CanReportAnalysis(analysis): """Returns True if the analysis can be reported, False otherwise.""" return analysis.start_time and analysis.end_time
3bea955a3965004cb2e08a2022e8dfdf0bb76b96
669,607
import ast def unwrap_unary_node(node: ast.AST) -> ast.AST: """ Returns a real unwrapped node from the unary wrapper. It recursively unwraps any level of unary operators. Returns the node itself if it is not wrapped in unary operator. """ if not isinstance(node, ast.UnaryOp): return n...
c704115985580f16e21be83c7e6c97921e3f1ea3
669,609
import random def load_word_set(filename): """loads the words used as bingo labels, first line is the center""" lines = open(filename).readlines() if len(lines) < 25: raise Exception("Not enough labels in %s" % filename) total_word_list = [x.strip() for x in lines] center_word = total_wor...
8f3de270b41c1ea50a18711f19a2e73c3dc8f03b
669,614
def _get_editable_repo_dir(script, package_name): """ Return the repository directory for an editable install. """ return script.venv_path / 'src' / package_name
baf3cd8346eabb73bdc20929ed0e40a5fd543414
669,615
def scaling_model_auto_rules(experiment): """Use dials.scale rules for determining suitable parameters.""" osc_range = experiment.scan.get_oscillation_range() scan_width = osc_range[1] - osc_range[0] if scan_width < 5.0: scale_interval, decay_interval = (1.0, 1.5) elif scan_width < 10.0: ...
77d5dd097a1ed1634e9947dce3cdc47a9f247841
669,616
def sign(value): """Returns the sign of the given value as either 1 or -1""" return value / abs(value)
28daa4de89c4ae8c09745b36c00de468875fb7cd
669,621
from typing import Union from datetime import datetime def time_from_timestamp(timestamp_in: Union[int, float]) -> datetime: """ Convert timestamp to :py:class:`datetime <datetime.datetime>` object. :param timestamp_in: Number representing the epoch. :return: :py:class:`datetime <datetime.datetime>` ...
6abeaced426b4b22e772d7bfa9ec9f5eef182d1d
669,622
def format_html(html): """ Helper function that formats HTML in order for easier comparison :param html: raw HTML text to be formatted :return: Cleaned HTML with no newlines or spaces """ return html.replace('\n', '').replace(' ', '')
6f06f074b0546ed1ca0d0365c250a40f6ddb58e2
669,623
def _transform_array(data, is_array, is_scalar): """Transform an array into a scalar, single value array or return in unmodified.""" if not is_array: return data[0] if is_scalar: return [data[0]] return data
64c47ffe45bc3e2c58ea2ec17e84600d638fd0d7
669,626
def check_bounds(bounds): """ Check a bounds array is correct, raise ValueError if not Parameters: bounds - the bounds array to check. Of form (minx, miny, maxx, maxy) or (left, bottom, right, top). Returns: the bounds array, if valid """ if not ((bounds[0] <= bound...
99c9ebc3a780831470dc95965e700f1aa5cc612e
669,627
def curtail_string(s, length=20): """Trim a string nicely to length.""" if len(s) > length: return s[:length] + "..." else: return s
48b6624983b810517651d89185761210ba95ad27
669,629
def sort_summoner_name(name, name2, name3): """Adds spacebar formatting for names """ if name2 == "": return name else: concat_name = name + "%20" + name2 if name3 != "": concat_name += "%20" + name3 return concat_name
c6b8e4f8914a20f718bbe781d8af22fc41eb8ad6
669,631
def icingByteFcnSEV(c): """Return severity value of icing pixel. Args: c (unicode): Unicode icing pixel. Returns: int: Value of severity portion of icing pixel. """ return (ord(c) >> 3) & 0x07
8eab1513b0431e89f9b56c4c2e1fe68f77466409
669,633
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(di...
0410eacc3f02f1cfb14a90cbd550fb9f503ea319
669,634
def extract_test_prefix(raw_fullname): """Returns a (prefix, fullname) tuple corresponding to raw_fullname.""" fullname = raw_fullname.replace('FLAKY_', '').replace('FAILS_', '') test_prefix = '' if 'FLAKY_' in raw_fullname: test_prefix = 'FLAKY' elif 'FAILS_' in raw_fullname: # pragma: no cover te...
45e12753a6dd24a25577827ac11f6cdcf297da8f
669,635
def verify_entry_compatibility(e1, e2): """ Verify that the two entries @e1 and @e2 are compatible. If the entries are compatible, returns (True, diff). Otherwise, returns (False, diff). Here diff is a list of differences between @e1 and @e2. Each list element is a tuple of (name, e1, e2). In ...
59e4df5944993a54844ad4e27a9e28629bf6ae4d
669,639
from typing import Dict def make_combo_header_text( preposition: str, combo_dict: Dict[str, str], pop_names: Dict[str, str], ) -> str: """ Programmatically generate text to populate the VCF header description for a given variant annotation with specific groupings and subset. For example, if prepositi...
5126a2cd20922668eaa5fa3834e681a8188012b1
669,641
import torch def get_all_predictions(model, loader, device): """Get All predictions for model Args: model (Net): Trained Model loader (Dataloader): instance of dataloader device (str): Which device to use cuda/cpu Returns: tuple: all predicted values and their targets ...
aca84ffaa16408bc691d60c8207318c7e214a509
669,643
def format_path(template, name, delimiter): """Fills the placeholders to get the path. Args: template (str): A string that contains blanks to be filled. name (str): An option name of section defined in settings.txt. delimiter (str): The signal of a blank's beginning position. Retur...
d5841d7b3bea208a473758d8fc7ca64c0ec6a044
669,647
def m_p_s_to_km_p_hr(m_p_s): """Convert to km/hr.""" return m_p_s * 3.6
478e3931dcab3301079b0fbc692124c3c3c93557
669,651
def get_utc_time(cur): """Get current time in UTC timezone from Central Server database""" cur.execute("""select current_timestamp at time zone 'UTC'""") return cur.fetchone()[0]
bd80981e5d81dff44f348aab0064cd0f3a2c9ef3
669,656
import re def validate_ip(ip): """ Validates an IPv4 or IPv6 IP address """ regex = re.compile('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)' '{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|' '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ' ...
ffdafcf172620133a947f5898365b6063707be47
669,657
def extract_name_from_job_arn(arn): """Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job. Args: arn: """ slash_pos = arn.find("/") if slash_pos == -1: raise ValueError("Cannot parse invalid ARN: %s" % arn) return arn[(slash_pos...
8c95295866b876bdcf0088823b805a499d45a126
669,659
def convert_to_binary(fb_id_list): """Change the fb ids column in to a minary list. If an id is present represent the value as 1. If none represent as 0. """ final_list = [] for item in fb_id_list: if item == None: final_list.append(0) else: final...
12c22d4274fd2f93a7520fb3b80c54162606f610
669,661
def kmers(s, k): """create an array with kmers from one string""" if len(s) <= k: return [s] return [s[i:(i+k)] for i in range(len(s)-k+1)]
890a9bd8f4fe9fc2911c7fef4fbb804ffc8e7562
669,665
import pickle def read_file(filename='bins.prdb'): """ Read binner from file :param filename: Path to file :return: Binner instance """ with open(filename, 'rb') as inp: binner = pickle.load(inp) return binner # бининг в файл
a8f7ad3e499d433a0948ec766f0791551df1a51e
669,671
def _add_dicts(*dicts): """ Creates a new dict with a union of the elements of the arguments """ result = {} for d in dicts: result.update(d) return result
073f70d718b2ee8d5a55c9ee6854510766754354
669,672
def cleaned_code(arg): """ Strip discord code blocks """ arg = arg.strip('`') if arg.startswith('py'): arg = arg[2:] return arg.strip()
06271be1adc55d289598ee8fd600346f56faf015
669,673
def edge_index_set_equiv(a, b): """Compare edge_index arrays in an unordered way.""" # [[0, 1], [1, 0]] -> {(0, 1), (1, 0)} a = a.numpy() # numpy gives ints when iterated, tensor gives non-identical scalar tensors. b = b.numpy() return set(zip(a[0], a[1])) == set(zip(b[0], b[1]))
4b214b7061739a77f77240c9f957c2a802dde4ff
669,677
def reverse_geometric_key(string): """Reverse a geometric key string into xyz coordinates.""" xyz = string.split(',') return [float(i) for i in xyz]
4ca34a6c5f3607f3c1ea38642309e0ef988a61d9
669,685
def chooseSize(string): """ Determines appropriate latex size to use so that the string fits in RAVEN-standard lstlisting examples without flowing over to newline. Could be improved to consider the overall number of lines in the string as well, so that we don't have multi-page examples very often. ...
4b1eee8ce1a768ee320f4b78fac16df42db19eca
669,686
import binascii def shinglify(clean_text): """ Generates list of 'shingles': crc sums of word subsequences of default length :param clean_text: cleaned text to calculate shingles sequence. :return: shingles sequence """ shingle_length = 3 result = [] for idx in range(len(clean_text) - ...
aedd17f3eed48aaf1cbeb0bbe34103d594d6428b
669,687
def plot_arrow(ax, x1, y1, x2, y2, shrink_a=1, shrink_b=1, connectionstyle="arc3,rad=0", arrow_style="<-"): """ This function plots arrows of the task schematic :param ax: Axis object :param x1: x-position of starting point :param y1: y-position of starting point :param x2: x-position of end point ...
f731a96dc253db03eeeb16ee2594a96969b01219
669,688
def writeResults(Patterns, df): """ utility function to write patterns in a pandas dataframe Parameters ---------- Patterns : list list of patterns df : pandas dadaframe input dataframe Returns ------- pandas dadaframe updated dataframe """ for pat i...
a079e9614c1000e22af5b4a1050adc303bae7c9d
669,689
def is_ip_per_task(app): """ Return whether the application is using IP-per-task. :param app: The application to check. :return: True if using IP per task, False otherwise. """ return app.get('ipAddress') is not None
7de05a7db5eb886bea2687492585b554f898fc41
669,691
def map_atoms(indices, nres_atoms=1): """ Map the indices of a sub-system to indices of the full system :param indices: indices of atoms to map with respect to full system :param nres_atoms: number of atoms per residue :type indices: list :type nres_atoms: int :return: dictionary of mapped in...
b49487cb2926b9529330a01b11164ba871af85e2
669,692
def match_token(token, tok_type, tok_str=None): """Returns true if token is of the given type and, if a string is given, has that string.""" return token.type == tok_type and (tok_str is None or token.string == tok_str)
5486eb439c15a15116f417c641c936e981c43c71
669,693
import time def wait_until(somepredicate, timeout, period=0.1, *args, **kwargs): """Waits until some predicate is true or timeout is over.""" must_end = time.time() + timeout while time.time() < must_end: if somepredicate(*args, **kwargs): return True time.sleep(period) ret...
b8744afdd052146a01c0280550974ace83718063
669,694
def crop_to_subarray(data, bounds): """ Crop the given full frame array down to the appropriate subarray size and location based on the requested subarray name. Parameters ---------- data : numpy.ndarray Full frame image or ramp. (x,y) = (2048, 2048) May be 2D, 3D, or 4D ...
0327e996c96664c6a40be03ee1c9f121c10d656f
669,698
def get_rpath_deps(pkg): """Return immediate or transitive RPATHs depending on the package.""" if pkg.transitive_rpaths: return [d for d in pkg.spec.traverse(root=False, deptype=('link'))] else: return pkg.spec.dependencies(deptype='link')
1664fd2e54b2b29cf615a365131c057d7eb261b7
669,704
def double_factorial(n: int) -> int: """ Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> import math >>> all(double_factorial(i) == math.prod(rang...
085ba77f7fc27d2e7438b44f9e815d760527ff8b
669,708
def is_even(value: int) -> str: """Return 'even' or 'odd' depending on if the value is divisible by 2.""" if value % 2 == 0 or value == 0: return 'even' else: return 'odd'
2fd9b0bcbfa75852de61371d88b27e6e6e522864
669,712
def dtool_lookup_config(dtool_config): """Provide default dtool lookup config.""" dtool_config.update({ "DTOOL_LOOKUP_SERVER_URL": "https://localhost:5000", "DTOOL_LOOKUP_SERVER_TOKEN_GENERATOR_URL": "http://localhost:5001/token", "DTOOL_LOOKUP_SERVER_USERNAME": "testuser", "DTOO...
d9c81e9e04b709ec5d3c5ea0f27d1198317673b5
669,713
def update_minmax(array, val_min, val_max, matrix, il, xl, ilines_offset, xlines_offset): """ Get both min and max values in just one pass through array. Simultaneously updates (inplace) matrix if the trace is filled with zeros. """ maximum = array[0] minimum = array[0] for i in array[1:]: ...
fea1b825ba15342f6d3d15ff8d0c9f12e1f06534
669,715
import math def circunference(rad) -> float: """Returns the surface length of a circle with given radius.""" return 2 * math.pi * rad
1051c9f5f0fa4b80d1bbc3395c871de3fa7ce010
669,716
def known_words(word_list, lm_vocab): """ Filters out from a list of words the subset of words that appear in the vocabulary of KNOWN_WORDS. :param word_list: list of word-strings :return: set of unique words that appear in vocabulary """ return set(filter(lambda word: word in lm_vocab, word_lis...
adbd120072ec1b75b89e091a2f7897a2fba4f479
669,719
def minSize(split, mined): """ Called by combineCheck() to ensure that a given cleavage or peptide is larger than a given minSize. :param split: the cleavage or peptide that is to have its size checked against max size. :param mined: the min size that the cleavage or peptide is allowed to be. :re...
d89c330bc69c9e39a6887e5d8e114a87a072e12c
669,720
def simple_substitute(text, alphabet, code): """ Used to encode or decode the given text based on the provided alphabet. PARAMS: plaintext (string): The message you want to encode alphabet (dictionairy[char] = char): Key is plaintext char, value is the substitute. Enter the same alphabet for...
e34643ef45eb6ceb493c35c43a302e661e0933a9
669,721
def func_ideal_length(target_position, no_probe_sites): """Finds the optimum length between insertion sites, based on the nucleotide length""" length = target_position[-1] - target_position[0] #length of sequence available for probe sites no_intervals = no_probe_sites - 1 #number of intervals between probe ...
efc51c0cb2572c521dc141daf632bd5e0152fef3
669,724
def var_replace(eq, var, new): """ Replace all instances of string var with string new. This function differs from the default string replace method in that it only makes the replace if var is not contained inside a word. Example: eq = "-1j*kx*v*drho -drhodz*dvz -1.0*dz(dvz) - drho" var...
892bef29250fd57aa304f7ce099a684ac9df61d6
669,725
from typing import Tuple def xgcd(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm. Finds :code:`gcd(a,b)` along with coefficients :code:`x`, :code:`y` such that :code:`ax + by = gcd(a,b)`. Args: a: first number b: second number Returns: gcd(a,b),...
6d8764e21511b473b968b24d6783ac97ead0a180
669,732
def get_line_starts(s): """Return a list containing the start index of each line in s. The list also contains a sentinel index for the end of the string, so there will be one more element in the list than there are lines in the string """ starts = [0] for line in s.split('\n'): sta...
3f88d8bfb5ab63662c7c4dbc0ef3fe4253be3291
669,734
def find_ns_subelements(element, subelement_name, ns_dict): """ retuns list of subelements with given name in any given namespace Arguments: - element (ElementTee.Element): main element to search in - subelement_name (string): searched name of element - ns_dict: dict of ...
1bbd87025ba9cac503b4ceb7523485a9b33d5637
669,739
def all_params(params, funcs): """ Combined list of params + funcs, used in the test """ return params + funcs
d5f93e52201f57c31b16e10c5f45a16ebaee0813
669,744
from operator import mul def text_color(bg): """ Determine text color based off background color. Parameters ---------- bg : tuple[int] Background RGB color. Returns ------- tuple[int] Foreground RGB color. """ luminance = sum(map(mul, (0.299, 0.587, 0.114), b...
4e99e9c06ab5a8574f735d98db0b0b12c69a35a5
669,745
import re def is_valid_input(service_name): """ Validate the input. Args: service_name (str): the name of the service. given as an argument to the module Returns: bool: True if the input is valid, else False. """ if re.match("^[A-Za-z0_]*$", service_name): return True...
f42e37e6e26bd0b64c1cc45a295d47b49cd8e9c4
669,750
def min_reconstruction_scale(ls_min, ls_max): """ Calculate the smallest scale in phi that can be reconstructed successfully. The calculation is given by Eq. (9) in Cooray et al. 2020b. Parameters ---------- ls_min : float Lower limit of lamdba squared in the observed spectrum...
d13fc138b7f3c1bd02bda03f1add307d5e0b1733
669,752
def nogil(request): """nogil keyword argument for numba.jit""" return request.param
9d5f53c0636f8af6d5196c71f8f5e40bbab99769
669,758
def applies_to_product(file_name, product): """ A OVAL or fix is filtered by product iff product is Falsy, file_name is "shared", or file_name is product. Note that this does not filter by contents of the fix or check, only by the name of the file. """ if not product: return True r...
3b816fec99a6353b69dc61629aaa91adbc949488
669,759
def drop_cols(data_frame, columns): """ Remove columns from data frame """ for col in columns: data_frame = data_frame.drop([col], axis=1) return data_frame
244f7910e960de51a5b585fbb891b5a94f5eba3f
669,766
def help_flag_present(argv: list[str], flag_name: str = 'help') -> bool: """ Checks if a help flag is present in argv. :param argv: sys.argv :param flag_name: the name, which will be prefixed with '-', that is a help flag. The default value is 'help' :return: if the help flag is present """ ...
a804ec64702e6173d94c50f024373f67d9893344
669,769
def get_fraction(lsnp1, lsnp2): """Return the fraction of reads supporting region1.""" reg1_fraction = [] for index in range(len(lsnp1)): sumdepth = lsnp1[index] + lsnp2[index] if sumdepth == 0: reg1_fraction.append(0) else: reg1_fraction.append(float(lsnp1[in...
27f7740ea214dc438b22e730110f770c3e3a061a
669,770
def bool_eval(token_lst): """token_lst has length 3 and format: [left_arg, operator, right_arg] operator(left_arg, right_arg) is returned""" return token_lst[1](token_lst[0], token_lst[2])
990588c9ea1ebb0ef743bcd31c43b80332238df8
669,773
import logging def basic_logger(name, level): """ Returns a basic logger, with no special string formatting. Parameters ---------- name : str The name of the logger. level : int An integer, such as `logging.INFO`, indicating the desired severity level. As in the `loggi...
c1440c1dc1a4ee68eede0975b9cb6f6e19f13fd5
669,774
def get_headers(data, extra_headers=None): """ Takes the response data as well as any additional headers and returns a tuple of tuples of headers suitable for passing to start_response() """ response_headers = { "Content-Length": str(len(data)), } if extra_headers: response_...
d00c8315b21dd697b3a7ba1689b4b858af616fc6
669,777
def unfold(vc: set, folded_verts: list): """ Compute final vc given the partial vc and list of folded vertices (unreversed) :param vc: partial vc as a set :param folded_verts: list of folded vertices as 3-tuples :return: final vertex cover as a set """ final_vc = set(vc) for u, v, w in f...
89fd6852548bb5e133b7a9d07accfdb51fbf74c5
669,780
def find_shops(index: dict, products: list) -> set: """ Find all the shops that contain all the products :param index: Index of products :param products: Products to match :return: Set of all shops that sell all mentioned products """ try: final_set = index[products[0]] # Initial in...
04716a4178392075767632d2f1762215fdaec601
669,783
import re def sanitize_filename(filename: str) -> str: """ Make the given string into a filename by removing non-descriptive characters. :param filename: :return: """ return re.sub(r'(?u)[^-\w.]', '', filename)
859249f3d2a70c7413e92c5df7cee9b7bccb7ecc
669,787
def df_variant_id(row): """Get variant ID from pyvcf in DataFrame""" if row['ID'] != '.': return row['ID'] else: return row['CHROM'] + ':' + str(row['POS'])
460868e501b5e4683fc88d80cee363b5778d7623
669,788
def get_hd_domain(username, default_domain='default'): """Returns the domain associated with an email address. Intended for use with the OAuth hd parameter for Google. Args: username: Username to parse. default_domain: Domain to set if '@suchandsuch.huh' is not part of the username. Defaults to ...
adae35610ef1452de0dfac3980cccd91a7f7e41f
669,789
def generate_term(n): """Generates nth term in the Fibonacci sequence""" assert n >= 1 if n == 1: return 1 elif n == 2: return 2 else: return generate_term(n-1) + generate_term(n-2)
92073b38f74c70099eb64671ecaf4e9ad6307470
669,791
def abbr(name): """ Return abbreviation of a given name. Example: fixed-effect -> f10t per-member -> p8r """ return name if len(name) <= 2 else f"{name[0]}{len(name) - 2}{name[-1]}"
3bbddbad6372f0dfa17b3e5e1b0c30fcf3c401d7
669,792
def is_isogram(string): """Checks whether a given string is isogram or not. Returns a boolean.""" string = string.lower().replace(' ', '').replace('-', '') return len(string) == len(set(string))
33202ce21f0e333471dab3453d1b0cd6d000ec26
669,793
def parse_one_column_table(data_table): """Parse tables with only one column""" output_list = [] data_rows = data_table.find_all("tr")[1:] for data_row in data_rows: data_cells = data_row.find_all("td") for data_cell in data_cells: try: output_list.append(data...
53d703050a89fd8f3fb12575405c332eecb4dd19
669,794
import shelve def read_net_cp(namefile): """Read pre-computed network cp assignation.""" db = shelve.open(namefile) cps = db['cps'] net = db['net'] methodvalues = db['methodvalues'] db.close() return cps, net, methodvalues
bbf5f2c798af398b85e5f949ab8e45325d768755
669,795
def dh_number_digest(g_val: int, p_val: bytes) -> int: """Determine hash value for given DH parameters. Arguments: g_val: the value g p_val: the value p Returns: a hash value for the given DH parameters. """ return hash((g_val, p_val))
9a107af56a82a57cd6c91758194102675f8bc528
669,797
def time_to_str(delta_t, mode="min"): """Convert elapsed time to string representation Parameters -------- delta_t: time difference Elapsed time mode: str Time representation manner, by "minitues" or "seconds". Returns -------- delta_str: str Elapsed time string...
f1cba8a07fd75e82a0a9009739ab6e9e23c371ac
669,804
def find_squeezenet_layer(arch, target_layer_name): """Find squeezenet layer to calculate GradCAM and GradCAM++ Args: arch: default torchvision densenet models target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below. target_layer_na...
0294e443804fc28ee69e9cfae9280e101151d08a
669,805
def is_word_guessed(secret_word, letters_guessed): """ secret_word: string, the word the user is guessing; assumes all letters are lowercase letters_guessed: list (of letters), which letters have been guessed so far; assumes that all letters are lowercase returns: boolean, True if all the le...
14377e1638e271b8d24207dcb56871a6a336d492
669,809
import math def sinh(x): """Get sinh(x)""" return math.sinh(x)
8adf2afd4858ed6e0e73cd4237bec5197b7393ad
669,810
def norm_to_max(vals): """Normalizes items in vals relative to max val: returns copy.""" best = max(vals) return [i/best for i in vals]
874b54fde9386a197d80b80e8632f0826796eb90
669,811
def prefix_string() -> str: """Use string as prefix.""" return "test"
6e3d89079b67f8d7cb4eaac28cfdebaead01d733
669,816
def _abs(arg): """Returns the absolute value.""" return abs(arg)
d42359d5307701df2593c4b605f478fc9b4f516b
669,818
from typing import List from typing import Any def node_values_for_tests() -> List[Any]: """[summary] Returns: List[Any]: list of potential node values """ return [1, 2, 3, 4, 5, 6, 7, "spam", "sausage"]
b77fd6d0e5788737d2e1935ceb076d1a8afafdbb
669,825
def add_chars() -> bytes: """Returns list of all possible bytes for testing bad characters""" # bad_chars: \x00 chars = b"" chars += b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" chars += b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" chars += b"\x20\x21\x2...
cce8008085e6480642dad23b8e3a11728912d9ae
669,826
import math def xy_yaw_from_quaternion(quat): """Calculate the yaw angle in the xy plane from a rotation quaternion. :param quat: A unit quaternion representing the :type quat: Any container that has numerical values in index 0, 1, 2 and 3 :return: The yaw angle in radians projected on the xy plane ...
255225c80bba64f0d347871584db8a4138c199b8
669,832
from typing import Any def option_selected(variable: Any, testvalue: Any) -> str: """ Returns ``' selected="selected"'`` if ``variable == testvalue`` else ``''``; for use with HTML select options. """ return ' selected="selected"' if variable == testvalue else ''
aedf22cbf5b5078835cd32656e4d0b789c48e54f
669,839
def handle_args(pwb_py, *args): """Handle args and get filename. @return: filename, script args, local args for pwb.py @rtype: tuple """ fname = None index = 0 for arg in args: if arg.startswith('-'): index += 1 else: fname = arg if not fn...
acd7ec2d05e719a73f329469a0c3569312ea9781
669,843
from typing import Dict def is_active_user(user: Dict) -> bool: """ Returns true if the user is active and not the bot :param user: the user to check :return: boolean if user is active """ return (user is not None and not user['deleted'] and not user['is_restricted'] ...
0ce709a32eef92dd12493c7e8877b7ebed643437
669,845
import types def copy_func(f, name=None): """ Return a function with same code, globals, closure, and name (or provided name). """ fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, f.__defaults__, f.__closure__) # If f has been given attributes fn.__dict__.upda...
65be84ec7e46c7f6726248fa627bfd9b800a24af
669,850
def __eq__(self, other): """Common `__eq__` implementation for classes which has `__slots__`.""" if self.__class__ is not other.__class__: return False return all(getattr(self, attr) == getattr(other, attr) for attr in self.__slots__)
bcc9f70e3b27b0a19fe7ed99858a616cac05ffac
669,851
def compute_delta(num_levels): """Computes the delta value from number of levels Arguments --------- num_levels : int The number of levels Returns ------- float """ return num_levels / (2.0 * (num_levels - 1))
ad97e2041453863e82fc259780f1a125b9e81776
669,852
def _replace_slash(s, replace_with="__"): """Conda doesn't suppport slashes. Hence we have to replace it with another character. """ return s.replace("/", replace_with)
277a03faf4a87294fdd702082de68ef20d6fe895
669,854
def _set_object_from_model(obj, model, **extra): """Update a DesignateObject with the values from a SQLA Model""" for fieldname in obj.FIELDS: if hasattr(model, fieldname): if fieldname in extra.keys(): obj[fieldname] = extra[fieldname] else: obj[...
7920a759a40a67c04ca4a8712aa77d83c8f85ae5
669,856
def str_to_class(cls_name: str) -> type: """ Converts a string into the class that it represents NB: Code based on https://stackoverflow.com/questions/452969/does-python -have-an-equivalent-to-java-class-forname :param cls_name: The string representation of the desired class :return: A pointer ...
5fe2b06697fed364c3cd6c1a4574e27e44a00a40
669,857
def rescol(rescol): """ Comfirms that a give value is a valid results column and returns the corresponding units column and results column. """ if rescol.lower() == 'concentration': unitscol = 'units' elif rescol.lower() == 'load_outflow': unitscol = 'load_units' else: ra...
8d007227b2a19b071d32776d37b43774a6e83134
669,858
def ContentTypeTranslation(content_type): """Translate content type from gcloud format to API format. Args: content_type: the gcloud format of content_type Returns: cloudasset API format of content_type. """ if content_type == 'resource': return 'RESOURCE' if content_type == 'iam-policy': ...
3676261db84286e5e410a5cceb7423bfdec47dce
669,862
def get_fk_model(model, fieldname): """returns None if not foreignkey, otherswise the relevant model""" field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname) if direct and field_object.get_internal_type() in [ "ForeignKey", "OneToOneField", "ManyToManyField", ...
2bed2f0f8018ada2416573bcfbd00f3d5e23c115
669,863
import json def load_circuit_ordering(file): """Loads a circuit ordering (e.g. mapping from spin-orbitals to qubits) to a file. Args: file (str or file-like object): the name of the file, or a file-like object. Returns: ordering (list) """ if isinstance(file, str): wi...
05977ce119db9f5a737a455dfc04c25c6f154828
669,866
def when_did_it_die(P0, days): """ Given a P0 and an array of days in which it was alive, censored or dead, figure out its lifespan and the number of days it was alive' Note, the lifespan is considered to last up to the last observation. I.e., a worm that was observed to live 3 days, and died o...
1f7a92ed04a69f006753777eaa2c56d17aa209e3
669,868