content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import List def build_location_line(split_ids: List[str], keys: List[str], delimiter: str) -> str: """ Builds the locations and lines based on the configuration. :param split_ids: The split IDs :param keys: The locations or lines keys position to join from IDs :return: The joined locations or lines """ temp_list = [] for key in keys: if len(split_ids) - 1 >= int(key): temp_list.append(split_ids[int(key)]) return delimiter.join(temp_list)
fbcace1da1e0bd737531f8dcfbda5644958d5d6e
19,330
def get_view_model(cls): """ Get the model to use in the filter_class by inspecting the queryset or by using a declared auto_filters_model """ msg = 'When using get_queryset you must set a auto_filters_model field in the viewset' if cls.queryset is not None: return cls.queryset.model else: assert hasattr(cls, 'auto_filters_model'), msg return cls.auto_filters_model
7f0d3141eba794778679d0c30bfdcddbc145f63d
19,334
def strategy_largest_first(G, colors): """ Largest first (lf) ordering. Ordering the nodes by largest degree first. """ nodes = G.nodes() nodes.sort(key=lambda node: -G.degree(node)) return nodes
0ef116896b8e43712887888dcc79af197f7a9d17
19,336
import math def prime_pi_upper_bound(n): """ Return an upper bound of the number of primes below n. """ ln = math.log(n) return int(n / (ln - 1 - (154/125) / ln))
1a7330f50bc14e4ba20f6efedad48d55a4ccbd01
19,340
def find_animals_groups(df): """given a dataframe, return animals and groups dataframes based on population of each row (> 1 == group)""" pop_sums = df[ ["Population _Male", "Population _Female", "Population _Unknown"] ].sum(axis=1) groups = df[pop_sums > 1] animals = df[pop_sums == 1] return animals, groups
02a8376dcdb7abf2e3df39672650bfac8adc7c64
19,343
def word_capital(text): """ Capitalizes the first character of each word, it converts a string into titlecase by making words start with an uppercase character and keep the remaining characters. """ if text and len(text) > 0: return ' '.join([s[0].upper() + s[1:] for s in text.split(' ') if len(s) > 0]) else: return text
fbb20324204f62344af5b76f74fad98810f6fee0
19,346
def yields_from_leung_nomoto_2018_table10(feh): """ Supernova data source: Leung & Nomoto, 2018, ApJ, Volume 861, Issue 2, Id 143, Table 10/11 The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5. Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4771 and 0.69897. We use seven intervals delimited by midpoints of those values. """ if feh <= -1.65: return [0.0, 5.48e-4, 1.3e-11, 2.15e-9, 3.46e-2, 1.63e-4, 2.50e-3, 1.72e-1, 1.14e-1, 2.55e-2, 7.57e-1] elif -1.65 < feh <= -0.65: return [0.0, 5.44e-4, 1.54e-12, 4.34e-10, 3.81e-2, 1.63e-4, 1.84e-3, 1.79e-1, 1.12e-1, 2.24e-2, 7.60e-1] elif -0.65 < feh <= -0.15: return [0.0, 5.88e-4, 3.24e-12, 2.94e-10, 4.85e-2, 6.58e-4, 1.69e-3, 2.30e-1, 1.14e-1, 1.84e-2, 7.20e-1] elif -0.15 < feh <= 0.15: return [0.0, 5.82e-4, 6.45e-12, 3.69e-10, 4.90e-2, 6.56e-4, 1.22e-3, 2.8e-1, 1.9e-1, 1.59e-2, 6.81e-1] elif 0.15 < feh <= 0.39: return [0.0, 5.71e-4, 1.62e-11, 5.52e-10, 4.94e-2, 6.46e-4, 8.41e-4, 2.13e-1, 9.81e-2, 1.26e-2, 6.44e-1] elif 0.39 < feh <= 0.59: return [0.0, 5.47e-4, 5.54e-11, 9.20e-10, 6.23e-2, 6.82e-4, 7.57e-4, 2.21e-1, 9.27e-2, 1.11e-2, 5.87e-1] elif 0.59 <= feh: return [0.0, 5.36e-4, 8.29e-11, 7.60e-10, 7.54e-2, 2.81e-4, 8.39e-4, 2.25e-1, 8.00e-2, 8.93e-3, 4.99e-1]
4a03971e14c80d013259afefdbece6e2c67ccdf8
19,349
def describe(path): """ Returns a human-readable representation of path. """ return "/" + "/".join(str(p) for p in path)
7b6ba2f17379bfca88d79eb15db35a3bff183720
19,354
def _get_transform_y(element): """ Extracts the translateY for an element from its transform or assumes it to be 0 :return: an int representing the translateY value from the transform or 0 if there is no transform present """ return element.get('transform').get('translateY') or 0
5c1c00843148ae384604d71c46aceaa2904a6497
19,358
def _p_r_log_helper(x, a, b, alpha, beta, n, p): """ Step function used with the pollard rho discrete log algorithm """ if x % 3 == 1: f = ((beta * x) % p, a, (b + 1) % n) elif x % 3 == 0: f = ((x * x) % p, (2 * a) % n, (2 * b) % n) else: f = ((alpha * x) % p, (a + 1) % n, b) return f
092f7111d3b7fb8ce8a4ba27775bdf89cb99308f
19,362
def _isascii(string): """Tests if a given string is pure ASCII; works for both Python 2 and 3""" try: return len(string) == len(string.encode()) except UnicodeDecodeError: return False except UnicodeEncodeError: return False
1ef5c22b15b4953b8b9bba8ad9f5d2da0c68ee03
19,368
def get_high_cardinality_features(X, threshold=50): """Get features with more unique values than the specified threshold.""" high_cardinality_features = [] for c in X.columns: if X[c].nunique() > threshold: high_cardinality_features.append(c) return high_cardinality_features
4ab222c12a68c2ce259b9de41998d649d80b30ef
19,370
from typing import Dict import base64 import json def encoded_to_json(encoded_string: str) -> Dict: """ Transform your encoded string to dict. Parameters ---------- encoded_string: str your string base64 encoded. Returns ------- Dict your string cast to a dict. """ decode = base64.b64decode( encoded_string + "=" * (-len(encoded_string) % 4), ) return json.loads(decode)
37ab5fe52db9f25926f30d0e763177c8f399ff4b
19,374
def createBatchSystem(config, batchSystemClass, kwargs): """ Returns an instance of the given batch system class, or if a big batch system is configured, a batch system instance that combines the given class with the configured big batch system. :param config: the current configuration :param batchSystemClass: the class to be instantiated :param kwargs: a list of keyword arguments to be passed to the given class' constructor """ batchSystem = batchSystemClass(**kwargs) return batchSystem
afff2df95a353c3138b137ccbfe5e16f22843589
19,379
def sort_in_wave(array): """ Given an unsorted array of integers, sort the array into a wave like array. An array arr[0..n-1] is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= """ n = len(array) for i in range(n - 1): if i % 2 == 0 and array[i] < array[i+1]: array[i], array[i+1] = array[i+1], array[i] return array
1904a8715d2b6a8b8cbd29ed7a129ca45b1d57d0
19,380
import re def any_match(expressions, value): """ Return true if any expression matches the value """ for exp in expressions: if re.match(exp, str(value)): return True return False
34e7aac238be92769965390a702f9a61741f9289
19,385
def subtract(a, b): """Subtraction applied to two numbers Args: a (numeric): number to be subtracted b (numeric): subtractor Raises: ValueError: Raised when inputs are not numeric """ try: return a - b except: raise ValueError("inputs should be numeric")
7cfa9607145fb1713309fcb2e543a3a528aa26f1
19,389
def retr_smaxkepl(peri, masstotl): """ Get the semi-major axis of a Keplerian orbit (in AU) from the orbital period (in days) and total mass (in Solar masses). Arguments peri: orbital period [days] masstotl: total mass of the system [Solar Masses] Returns smax: the semi-major axis of a Keplerian orbit [AU] """ smax = (7.496e-6 * masstotl * peri**2)**(1. / 3.) # [AU] return smax
3b5833151888490cd632b8d9a76d5bfcb268a42c
19,390
def title_case(sentence): """ Convert a string ti title case. Title case means that the first character of every ward is capitalize.. Parameters sentence: string string to be converted to tile case Returns ------- ret: string Input string in title case Examples -------- >>>> title_case("ThIs iS a STring to be ConverteD") >>>> This Is A String To Be Converted. """ # Check that input is string if not isinstance(sentence, str): raise TypeError("Invalid input must be type string.") if len(sentence) == 0: raise ValueError("Cannot apply title function to empty string") return sentence.title()
b4e2b58c2270af6022aaa82bbae5099ed7d07ea8
19,394
def is_duckument_type(obj): """Internal mapping type checker Instead of using `isinstance(obj, MutableMapping)`, duck type checking is much cheaper and work on most common use cases. If an object has these attritubes, is a document: `__len__`, `keys`, `values` """ doc_attrs = ("__len__", "keys", "values") return all(hasattr(obj, attr) for attr in doc_attrs)
31aa4066d5810bb088720f96c889b36e6015583e
19,400
import re def getPrefix(name): """ Get common prefix from source image file name. """ result = re.search(r'([0-9]{2}[A-Z]{3}[0-9]{8})[-_]', name) return None if not result else result.group(1)
633223a5ff29005f815a29dfcaed5900c8449b83
19,401
def field_to_attr(field_name): """Convert a field name to an attribute name Make the field all lowercase and replace ' ' with '_' (replace space with underscore) """ result = field_name.lower() if result[0:1].isdigit(): result = "n_" + result result = result.replace(' ', '_') result = result.replace('/', '_') result = result.replace('-', '_') result = result.replace('.', '_') result = result.replace('+', '_plus') return result
b6aa8a55f660648e3d259a6b6df0f560550c7d8a
19,406
def get_words_list() -> list[str]: """Returns a list of words from the file wordle-answers-alphabetical.txt.""" with open("wordle-answers-alphabetical.txt", "r", encoding="utf-8") as file: words = file.read().splitlines() return words
fa14e3ac576f93d92e6453df36010f1b51b2082b
19,414
def find_idx(words, idx): """ Looks for the named index in the list. Test for the index name surrounded by quotes first, if it is not present then the error will return the index name without quotes """ try: return words.index('"' + idx + '"') except ValueError: return words.index(idx)
4c76fcd752de0545cea77def672d1555c071815f
19,415
def is_unicode_list(value): """Checks if a value's type is a list of Unicode strings.""" if value and isinstance(value, list): return isinstance(value[0], str) return False
c6c88770be2d1e75f800b3c22ec52a9a17384d73
19,416
import binascii def hexarray_to_str(hexa): """Convert hex array into byte string.""" hstr = ''.join(["{:02x}".format(h) for h in hexa]) return binascii.unhexlify(hstr)
59af9dad6833bb417cb9c29f60c498b8452951d7
19,418
def filter_resources(resource, filter_name, filter_value): """Filter AWS resources Args: resource (object): EC2 resource filter_name (string): Filter name filter_value (string/list): Filter value(s) Returns: List: Filtered AWS resources """ values = [filter_value] if type(filter_value) is list: values = filter_value filters = [{ "Name": filter_name, "Values": values }] return list(resource.filter(Filters=filters))
d72f091af78ec73a81a50dc02cbeefde94de58d9
19,419
def toggle_manual_match_form(method): """ Hide/show field based on other values """ # This one is for manually picking years. # 1=override (manual match). 0= auto match # Test if method == 1: return "visible" return "hidden"
9ba3b63898f4a3c4a0bba19abe77ae218ae23275
19,424
def calculate_stimulation_freq(flash_time: float) -> float: """Calculate Stimulation Frequency. In an RSVP paradigm, the inquiry itself will produce an SSVEP response to the stimulation. Here we calculate what that frequency should be based in the presentation time. PARAMETERS ---------- :param: flash_time: time in seconds to present RSVP inquiry letters :returns: frequency: stimulation frequency of the inquiry """ # We want to know how many stimuli will present in a second return 1 / flash_time
069165f62416a79a0ba59893c9a61d8c99d3c903
19,431
def parse_ants(antstr): """Split apart command-line antennas into a list of baselines.""" rv = [s.split('_') for s in antstr.split(',')] rv = [(int(i[:-1]), int(j[:-1]), i[-1]+j[-1]) for i,j in rv] return rv
438abdf11acaebdc471d6d9e6f007e4d27b3f293
19,434
def clean_text(x): """Helper function to clean a string.""" x = str(x) x = x.lower() x = x.strip() x = " ".join(x.split()) # removes extra whitespace between words return x
74dbb5e07c42c668cdbe380670e87e81f4678407
19,439
def getIncomparable(rs1, rs2): """ Return the set of problem IDs which are only solved by rs1 :param rs1: result set of the 1st approach :param rs2: result set of the 2nd approach :return: a set {pid, stim} """ inc = set() for pid in rs1.keys(): r2 = rs2[pid] if r2 is None: inc.add(pid) return inc
a8b4baa5fc43b2d9f136c63f5aabe624149a9d47
19,441
def get_n_overlapping_chunks(data_size, chunk_size, chunk_overlap): """Compute the number of overlapping chunks Args: data_size (int) chunk_size (int) chunk_overlap (int) Returns: The number of chunks. """ hop_size = chunk_size * (1 - chunk_overlap) return int((data_size - chunk_size) / hop_size + 1)
8ada086145d136638e5ba7703cc2095ee696fbd0
19,443
def maybe_map(apply_fn, maybe_list): """ Applies `apply_fn` to all elements of `maybe_list` if it is a list, else applies `apply_fn` to `maybe_list`. Result is always list. Empty list if `maybe_list` is None. """ if maybe_list is None: return [] elif isinstance(maybe_list, list): return [apply_fn(item) for item in maybe_list] else: return [apply_fn(maybe_list)]
13f61f0d7c6592dc4ea3cce091635f5119f1a70c
19,448
from datetime import datetime def format_timestamp(dt_object): """Formats a datetime object into a Joplin timestamp.""" return(int(datetime.timestamp(dt_object))*1000)
e728a4da2c5148a4e815af1485fc77029ef03fd0
19,450
from typing import List def _find_index(distance_along_lane: float, lengths: List[float]) -> int: """ Helper function for finding of path along lane corresponding to the distance_along_lane. :param distance_along_lane: Distance along the lane (in meters). :param lengths: Cumulative distance at each end point along the paths in the lane. :return: Index of path. """ if len(lengths) == 1: return 0 else: return min(index for index, length in enumerate(lengths) if distance_along_lane <= length)
7a36cd603d266653155e089eb0e72099210601f5
19,452
def find_submission_body_end(submission_body: str) -> int: """Finds the end of the story's body by stripping edits and links at the bottom. Returns: the index at which the story's body ends. """ markers = [ '-Secrets', 'EDIT:', 'Edit:', 'Continued in [part', 'Concluded in [Part', '[Part' ] # only match the bottom half of the story so we don't # match things at the start of the story offset = int(len(submission_body) / 2) # find the end of the story, marked by one of the markers, # or none, and then we don't cut off anything at the end story_end_offset = None for end_marker in markers: try: story_end_offset = submission_body.index(end_marker, offset) except Exception as excp: continue break # no marker has been found, take the entire story if story_end_offset is None: story_end_offset = len(submission_body) return story_end_offset
d4c533ebf322956304e38eced409a9a1c043e37c
19,468
def valuefy(strings, type_cast=None): """ return a list of value, type casted by type_cast list return type: list if values By default, type cast is int """ vals_string = strings.split('_') if type_cast is None: type_cast = [int]*len(vals_string) return [t(e) for e, t in zip(vals_string, type_cast)]
36bc5a6ff64826877bd4f434a0e540f72c4aeb9e
19,469
import pickle def read_pickle(file): """Read a pickle file""" with open(file, "rb") as handle: return pickle.load(handle)
d074df20a4b035137efb8c1fc52f6e9fcdda7add
19,474
import re def remove_tags(sent: str) -> str: """ Replace every tag with "_". Parameters ---------- sent: str Input string on CoNLL-U format. Returns ------- str: Processed string. """ return re.sub( r"(^\d+(?:\-\d+)?\t*(?:[^\t]*)\t(?:[^\t]*)\t)(\w+)", r"\1_", sent, flags=re.MULTILINE, )
9966ab60bcf1b9db19da23f48e7cc52b6dfdf580
19,480
def non_negative_int(argument): """ Converts the argument into an integer. Raises ValueError for negative or non-integer values. """ value = int(argument) if value >= 0: return value else: raise ValueError('negative value defined; must be non-negative')
b5c447055305141144934a484efc28ee07a7c6fe
19,482
def _reverse_input_einsum_eq(equation): """ Reverse the input order of the einsum eqaution e.g.: input : "nchw,nwhu->nchu" returns : "nwhu,nchw->nchu" """ input_output_strings = equation.split('->') assert len(input_output_strings) == 2, "invalid equation" input_strings = input_output_strings[0].split(',') assert len(input_strings) == 2, "invalid equation" equation = input_strings[1] + ',' + input_strings[0] + '->' + input_output_strings[1] return equation
f8c2900b6592f04fdc72b85c5ffdaba4b3b34952
19,493
def select_regions(localqc_table, genomeinfo, resolution, elongation=150, maxdisp=2.5): """ Select regions to display based on their dispersion and their read count intensity :param localqc_table: LocalQC regions file :param genomeinfo: Dictionary of chromosomes' size :param resolution: Total size of the desired regions (bp) :param elongation: Length (bp) to stretch the region in both directions :param maxdisp: Dispersion filtering (the lower the better) :return: A list of regions and the total number of reads in all selected regions """ regions = {} total_reads = [] with open(localqc_table) as f: for line in f: cols = line.rstrip().split('\t') chrm = cols[0] # Dispersion 10% for 50% sampling # Use the new localqc table format (10 columns instead of 13)! disp = abs(float(cols[9])) if disp <= maxdisp and not chrm.lower().startswith(('chrx', 'chry', 'chrm')): total_reads.append(int(cols[3])) bin_start = int(cols[1]) start = bin_start - resolution / 2 - elongation end = int(cols[2]) + resolution / 2 + elongation # Shift region start/end if it's outside of the chromosome if 0 <= start < end <= genomeinfo[chrm]: # Region entirely in the chromosome if chrm not in regions: regions[chrm] = [] # Store chrm, start, end, reads, bin_start regions[chrm].append([start, end, int(cols[3]), bin_start]) return regions, total_reads
adc1fd762165fd7d6170605ac11be92f370baeb1
19,496
def halosInMassRange(massColumn, minMass, maxMass, VERBOSE=True): """ Returns the selection array which has 'True' values for halos with masses in the range 'minMass' to 'maxMass'. The masses are given by the argument 'massColumn'. """ if VERBOSE: print( "Selecting the halos with masses in the interval [%e,%e] ... " % (minMass, maxMass) ) return (massColumn >= minMass) * (massColumn <= maxMass)
361e7faffaf2133e222859fdbb8431704af52099
19,498
def get_P_Elc_audio_microsystem_with_md_listening(P_Elc_audio_microsystem_with_md_rtd): """聴取時の消費電力を計算する Parameters ---------- P_Elc_audio_microsystem_with_md_rtd : float 定格消費電力, W Returns ---------- P_Elc_audio_microsystem_with_md_listening : float 聴取時消費電力, W """ P_Elc_audio_microsystem_with_md_listening = \ 0.4 * P_Elc_audio_microsystem_with_md_rtd return P_Elc_audio_microsystem_with_md_listening
20e2c58ef3c019236e131d637e19f0a50acc55de
19,505
def lerp(a, b, i): """Linearly interpolates from a to b Args: a: (float) The value to interpolate from b: (float) The value to interpolate to i: (float) Interpolation factor Returns: float: Interpolation result """ return a + (b-a)*i
8422222416668a70feb2a75790a25d7ab1f0af14
19,512
def strip_datetime_for_db_operations(dt): """ Some of our queries get very slow unless we remove the timezone info before we put them into sql. """ return dt.replace(tzinfo=None)
4cf19578afdb213f2f57a845f711ebbb96b869f6
19,513
def response(update=None): """ Emulates JSON response from ulogin serivce for test purposes """ data = { 'network': 'vkontakte', 'identity': 'http://vk.com/id12345', 'uid': '12345', 'email': '[email protected]', 'first_name': 'John', 'last_name': 'Doe', 'bdate': '01.01.1970', 'sex': '2', 'photo': 'http://www.google.ru/images/srpr/logo3w.png', 'photo_big': 'http://www.google.ru/images/srpr/logo3w.png', 'city': 'Washington', 'country': 'United States', } if update: data.update(update) return data
8a29ba65c38d5833e1474486135a9648f860a9a6
19,519
from pipes import quote def make_input_json_cmd(bam_fn, json_fn, sample): """CMD which creates a json file with content [['path_to_bam', 'sample']], which will later be used as pbsv call input. """ c0 = 'echo [[\\\"{}\\\", \\\"{}\\\"]] > {}'.format(quote(bam_fn), quote(sample), quote(json_fn)) return c0
5d50ea49027f6b7110193fed22a2990cc978c545
19,523
def iter_first_value(iterable, default=None): """ Get first 'random' value of an iterable or default value. """ for x in iterable: if hasattr(iterable, "values"): return iterable[x] else: return x return default
7fac2cbbe1a6923a1f737b0a86b208a62cfe6d50
19,524
import requests def download_tigrfam_info(tigrfam, api_endpoint): """ Download TIGRFAM from API endpoint. """ return requests.get(api_endpoint+tigrfam).text
4573fed797c3f3e6b16330fb7dd41aa57b156db1
19,525
def is_palindrome_permutation(input_string): """Checks to see if input_string is a permutation of a palindrome Using bool (is even?) instead of int value reduces space usage. Parameters ---------- input_string : str String to check Returns ------- bool True if input_string is a palindrome permutation, False otherwise """ # Generate is even counts hash table char_counts_is_even = {} for char in input_string: if char not in char_counts_is_even: char_counts_is_even[char] = False else: # if True (even count), swithc it to False (odd count) if char_counts_is_even[char]: char_counts_is_even[char] = False # if False switch to True else: char_counts_is_even[char] = True # Check is even counts are mostly even (allow up to 1 odd count) num_odd_counts = 0 # keep track of how many counts are odd for key, is_char_count_even in char_counts_is_even.items(): # Check to see if count is odd if not is_char_count_even: num_odd_counts += 1 # Check not too many odds if num_odd_counts > 1: return False return True
4867a94bd9051f07b04e60288739b3e98333fbda
19,529
def convert_box_xy(x1, y1, width, height): """ Convert from x1, y1, representing the center of the box to the top left coordinate (corner). :param x1: the x coordinate for the center of the bounding box :param y1: the y coordinate for the center of the bounding box :param width: with of the bounding box :param height: height of the bounding box :param img_width: the width of the image :param img_height: the height of the image :return: the top left coordinate (corner) of the bounding box """ left = (x1 - width // 2) top = (y1 - height // 2) if left < 0: left = 0 if top < 0: top = 0; return left, top
7524dd86f8c8ebff84cd9da0e75abd0b580547a0
19,531
def _get_tuple_state_names(num_states, base_name): """Returns state names for use with LSTM tuple state.""" state_names = [ ("{}_{}_c".format(i, base_name), "{}_{}_h".format(i, base_name)) for i in range(num_states) ] return state_names
8d96508174ec4893e9a9812d75471303ff972248
19,535
def _position_is_valid(position): """ Checks if given position is a valid. To consider a position as valid, it must be a two-elements tuple, containing values from 0 to 2. Examples of valid positions: (0,0), (1,0) Examples of invalid positions: (0,0,1), (9,8), False :param position: Two-elements tuple representing a position in the board. Example: (0, 1) Returns True if given position is valid, False otherwise. """ if type(position) != tuple or len(position) != 2: return False return 0 <= position[0] < 3 and 0 <= position[1] < 3
f7f277a472ea7046b6029a657215fa7006a4d808
19,542
def getInv(wmap): """ Get the inverse map of a dictionary. :param wmap: Dictionary :returns: Dictionary which is an inverse of the input dictionary """ inv_map = {} for k, v in wmap.items(): inv_map[v] = inv_map.get(v, []) inv_map[v].append(k) return inv_map
441bfa8e543a3aa24494d290e1e3cf6baa81437e
19,553
def optimal_noverlap(win_name,win_len): """ This function is intended to support scipy.signal.stft calls with noverlap parameter. :param win_name: (str) name of the window (has to follow scipy.signal.windows naming) :param win_len: (int) lenght of the FFT window :return : (int) optimal overlap in points for the given window type """ window_to_overlap_coef = {'hann': 0.5, 'hamming': 0.75, 'blackmanharris': 0.75, 'blackman': 2/3, 'flattop': 0.75, 'boxcar': 0} try: noverlap = int(win_len*window_to_overlap_coef[win_name]) except KeyError as exc: print(exc) print('The window you have selected is not recognized or does not have optimal overlap. Setting window overlap to default 75%.') noverlap = int(win_len*0.75) return noverlap
d98db08a9e08b6639a38a324799d1141e65b1eb4
19,554
def _prefix_range(target, ge, le): """Verify if target prefix length is within ge/le threshold. Arguments: target {IPv4Network|IPv6Network} -- Valid IPv4/IPv6 Network ge {int} -- Greater than le {int} -- Less than Returns: {bool} -- True if target in range; False if not """ matched = False if target.prefixlen <= le and target.prefixlen >= ge: matched = True return matched
536eea3be670e21065f5cd81b5f0e268d564c559
19,559
def _get_nodes_perms_key(user, parent_id=None) -> str: """ Returns key (as string) used to cache a list of nodes permissions. Key is based on (user_id, parent_id) pair i.e we cache all nodes' permissions dictionary of folder. If parent_id == None - we will cache all root documents of given user. """ uid = user.id pid = parent_id or '' nodes_perms_key = f"user_{uid}_parent_id_{pid}_readable_nodes" return nodes_perms_key
fb3875a53c17b6a818f9bb97738a47222733af70
19,561
from typing import OrderedDict def train(model, dataloader, criterion, optimizer, device='cpu', t=None, best_acc=None): """One iteration of model training. Intentionally kept generic to increase versatility. :param model: The model to train. :param dataloader: Dataloader object of training dataset. :param criterion: The loss function for measuring model loss. :param device: 'cuda' if running on gpu, 'cpu' otherwise :param t: Optional tqdm object for showing progress in terminal. :param best_acc: Optional parameter to keep track of best accuracy in case code is run in multiple iterations. :return: Training accuracy """ # Initialize variables model.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(dataloader): inputs, targets = inputs.to(device), targets.to(device) # Forwards pass optimizer.zero_grad() outputs = model(inputs) # Backpropagation loss = criterion(outputs, targets) loss.backward() optimizer.step() # Keep track of loss train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() # Print results to terminal if t is not None and dataloader.num_workers == 0: od = OrderedDict() od['type'] = 'train' od['loss'] = train_loss / (batch_idx + 1) od['acc'] = 100. * correct / total od['test_acc'] = best_acc if best_acc is not None else None od['iter'] = '%d/%d' % (correct, total) t.set_postfix(ordered_dict=od) t.update(inputs.shape[0]) else: print('Loss: %.3f | Acc: %.3f%% (%d/%d)' % (train_loss/(batch_idx+1), 100.*correct/total, correct, total)) return 100. * correct / total
f65899cd5d769cef628c15e35835bcd7a93bde60
19,562
def frequency(string, word): """ Find the frequency of occurrences of word in string as percentage """ word_l = word.lower() string_l = string.lower() # Words in string count = string_l.count(word_l) # Return frequency as percentage return 100.0*count/len(string_l)
dd2183dcec04bdf835ab22a8a351d53571f6e5e9
19,566
def get_func_names(job_content): """ Get function names from job content json :param job_content: job content info :return: function names """ func_names = [] for op in job_content["op_list"]: if "func_name" in op: func_names.append(op["func_name"]) return func_names
58d32e48f308758a2d6028f3312c2b376e04c9f5
19,568
def filter_out_dict_keys(adict, deny): """Return a similar dict, but not containing the explicitly denied keys Arguments: adict (dict): Simple python dict data struct deny (list): Explicits denied keys """ return {k: v for k, v in adict.items() if k not in deny}
a377c35f4eaedf0ed3b85eeaedbd45f7af0e8ec7
19,580
def loadraw(path, static=False): """Loads raw file data from given path with unescaped HTML. Arguments: path (str): Path to the file to read. static (bool): If True, all the `{` and `}` will be replaced with `{{` and `}}` respectively. Example: >>> # $ cat path/to/file.html >>> # <p>{foo}</p> >>> >>> loadtxt("path/to/file.html") >>> b'<p>{foo}</p>' >>> >>> loadtxt("path/to/file.html", static=True) >>> b'<p>{{foo}}</p>' """ with open(path) as f: data = f.read().strip() if static: data = data.replace("{", "{{").replace("}", "}}") return data.encode()
438d4128bd72a81f46e581984d1cf53b3d11254a
19,581
def get(obj, path): """ Looks up and returns a path in the object. Returns None if the path isn't there. """ for part in path: try: obj = obj[part] except(KeyError, IndexError): return None return obj
f7d936174f1171c42cd7ec2fa4237a887e78bb0e
19,584
import pickle def load_pickle_object(filename: str): """Load/Unpickle a python object binary file into a python object. Args: filename (string): pickle filename to be loaded. (<filename>.pkl) Returns: python object: returns the loaded file as python object of any type """ obj = None with open(filename, 'rb') as fp: obj = pickle.load(fp) return obj
d079728fce59420cba6d17da8743d6dba8d4d37d
19,592
def nonzero_reference_product_exchanges(dataset): """Return generator of all nonzero reference product exchanges""" return (exc for exc in dataset['exchanges'] if exc['type'] == 'reference product' and exc['amount'])
77796243c4f07b0877c997a9103a4d14ab48f2c7
19,596
def __update_agent_state(current_agent_state, transition_probability, rng): """ Get agent state for next time step Parameters ---------- current_agent_state : int Current agent state. transition_probability : ndarray Transition probability vector corresponding to current state. rng : numpy random number generator Returns ------- agent_state : int Agent state at next time step. """ choice = rng.uniform() agent_state = current_agent_state for i in range(len(transition_probability)): if choice < sum(transition_probability[0: i + 1]): agent_state = i break return agent_state
4d447f196ac6a326720cdf69c67286fe5053e5fc
19,597
def is_leap_year(year): """ Indicates whether the specified year is a leap year. Every year divisible by 4 is a leap year -- 1912, 1996, 2016, 2032, etc., are leap years -- UNLESS the year is divisible by 100 AND NOT by 400. Thus, 1200, 1600, 2000, 2400, etc., are leap years, while 1800, 1900, 2100, etc., are not. Why do we have this logic? This is because the earth orbits the sun in approximately 365.2425 days. Over 400 orbits, that comes out to 146,097 days (365.2425 * 400). Ignoring the century rule (making every fourth year a leap year, including 1800, 1900, etc.), gives us 146,100 days, overcounting by 3 days every 400 years. Thus, making 3 out of every 4 century boundaries non-leap years fixes this overcounting. """ return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
7e56255a4d3d969f56bb27b9b4474b56b047b022
19,601
def hotel_name(hotel): """Returns a human-readable name for a hotel.""" if hotel == "sheraton_fisherman_s_wharf_hotel": return "Sheraton Fisherman's Wharf Hotel" if hotel == "the_westin_st_francis": return "The Westin St. Francis San Francisco on Union Square" if hotel == "best_western_tuscan_inn_fisherman_s_wharf_a_kimpton_hotel": return "Best Western Fishermans Wharf" return hotel
d7e6118f25caa59174480c44fc4be63198d0c2c0
19,615
def always_true(*args, **kwargs): # pylint: disable=unused-argument """ Returns ``True`` whatever the arguments are. """ return True
6f755e48a482dba4a3cccc8dad92cb6fbb610a1b
19,616
def undocumented(func): """Prevents an API function from being documented""" func._undocumented_ = True return func
135de1a166927dda811c6a9f7b6d5f826a13e42d
19,621
def get_mask_bool(mask, threshold=1e-3): """ Return a boolean version of the input mask. Parameters ---------- mask : enmap Input sky mask. threshold : float, optional Consider values below this number as unobserved (False). Returns ------- mask_bool : bool enmap Boolean version of input mask. """ # Makes a copy even if mask is already boolean, which is good. mask_bool = mask.astype(bool) if mask.dtype != bool: mask_bool[mask < threshold] = False return mask_bool
f7950e1b332c5b6de6b963578e510a3e4fe65799
19,622
import torch def activate_gpu(gpu='GPU'): """Use GPU if available and requested by user. Defaults to use GPU if available.""" if torch.cuda.is_available() and gpu.lower() == 'gpu': print('Running on GPU') device = torch.device('cuda:0') else: print('Running on CPU') device = torch.device('cpu') return device
3d5fbda4709a1307373156d8fab269445d24aeda
19,623
def round_if_near(value: float, target: float) -> float: """If value is very close to target, round to target.""" return value if abs(value - target) > 2.0e-6 else target
005a7d7110265bbb1abd5f5aef6092fb67186a62
19,626
def get_authors() -> str: """Ask for an author until nothing is entered.""" authors = [] while True: author = input("Author: ") if not author: break authors.append(author.title()) return ' and '.join(authors)
2332f9ff2680d2d5612fc2f0a32e1020f0c674a0
19,628
import re def tokenize_per_cluster_args(args, nclusters): """ Seperate per cluster arguments so that parsing becomes easy Params: args: Combined arguments nclusters(int): total number of clusters Returns: list of lists: Each cluster conf per list ex: [[cluster1_conf], [cluster2_conf]...] """ per_cluster_argv = list() multi_cluster_argv = list() common_argv = list() cluster_ctx = False regexp = re.compile(r"--cluster[0-9]+") index = 0 for i in range(1, nclusters + 1): while index < len(args): if args[index] == f"--cluster{i}": cluster_ctx = True elif regexp.search(args[index]): cluster_ctx = False break if cluster_ctx: per_cluster_argv.append(args[index]) else: common_argv.append(args[index]) index = index + 1 multi_cluster_argv.append(per_cluster_argv) per_cluster_argv = [] return multi_cluster_argv, common_argv
be4c8d0ef01a2d2431f46434bd1ca88127b75cb6
19,640
def _from_quoted_string(quoted): """Strip quotes""" return quoted.strip('"').replace('""', '"')
febde29bb30d54675b1ff5eebf5276d0ef9efdc2
19,642
def get_parent_build(build): """Returns the parent build for a triggered build.""" parent_buildername = build.properties_as_dict['parent_buildername'] parent_builder = build.builders[parent_buildername] return parent_builder.builds[build.properties_as_dict['parent_buildnumber']]
ef4b1041bfd54b7aa2ac1469e6b58bfcf6acd724
19,643
def format_app_name(appname): """ Convert long reverse DNS name to short name. :param appname: Application name (ex. sys.pim.calendar -> "calendar") :type appname: str """ final = appname.split(".")[-1] return final
aceb4f58506fa7fae0358f9fcf3dd0ea6fbab352
19,645
import re def parse_show_vlan_internal(raw_result): """ Parse the 'show vlan internal' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show vlan internal command in a \ dictionary of the form. Returns None if no internal vlan found or \ empty dictionary: :: { '1024': { 'interface': '1', 'vlan_id': '1024' }, '1025': { 'interface': '10', 'vlan_id': '1025' } } """ show_re = ( r'\s+(?P<vlan_id>\d+)\s+(?P<interface>\S+)' ) result = {} for line in raw_result.splitlines(): re_result = re.search(show_re, line) if re_result: partial = re_result.groupdict() result[partial['vlan_id']] = partial if result == {}: return None else: return result
f3f7bec8d4afc8d1d65e5eef0f60f772128e8530
19,649
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ high = number low = 0 while low <= high: mid = (low + high) // 2 midsquare = mid * mid next_midsquare = (mid+1) * (mid+1) if midsquare == number or midsquare < number < next_midsquare: return mid elif midsquare > number: high = mid - 1 else: low = mid + 1
1dca451d1b96ec88a36753d9d07edd9ba2f34de8
19,652
def do_work(func, args, kwargs=None): """ Wrap a function with arguments and return the result for multiprocessing routines. Parameters ---------- func Function to be called in multiprocessing args : tuple Positional arguments to 'func' kwargs : dict Keyword arguments to 'func' Returns ------- result Output of 'func(args, kwargs)' """ # needed for use in the Python parallelization functions (e.g. apply_async) # ¯\_(ツ)_/¯ if kwargs: result = func(*args, **kwargs) else: result = func(*args) return result
0f14dddccc40afdeeb18c3cd16322f85a2008112
19,653
import itertools def make_call_summary_report(calls_list, users, for_graphviz=False): """ Makes a graphical or textual report of who has been on a call with who. Only considers calls initiated by one of the tracked users. Parameters ---------- calls_list: list Calls to look through (perhaps representing a section of history) users: list List of users to consider. for_graphviz: boolean A flag indicating this report should be for graphviz dot tool. If false, prepares a human-readable text report section. """ lines = [ "", "Section C - Calls Summary - Who talks to whom? (group-initiated calls only)", ""] summary_of_each_call = [ (users[call['user']]['real_name'], call['duration_m'], [users[participant]['real_name'] for participant in call['participants'] if participant in users] ) for call in calls_list if call['user'] in users] # call['user'] is participant if for_graphviz: # list each user as node # list each call as a list of edges between its participants lines = ["graph CallNetwork {"] for uid in users: lines.append("%s;" % users[uid]['real_name']) for (_, _, participants) in summary_of_each_call: for (f, t) in itertools.combinations(participants, 2): lines.append("%s -- %s;" % (f, t)) lines.append("}") else: for (starter, duration, participants) in summary_of_each_call: lines.append("Call of duration %dm started by %s, \n\twith participants %s" % (duration, starter, ", ".join(participants))) return "\n".join(lines)
607c590e51194100e3fbc0f1f5aa09c4fe94a4ca
19,656
def get_dataset(dataloaders: dict) -> dict: """ From dictionary of dataloaders to dictionary of datasets """ datasets = {split: dataloader.dataset for split, dataloader in dataloaders} return datasets
b21b266f377a2edb910bde163ff656988512f964
19,664
import cmath def twiddle_factor(turns): """ Calculates the FFT twiddle factor of an angle measured in turns (not radian). """ return cmath.exp(-2.0j*cmath.pi*turns)
4521143dc42d2e70c2215a36977d69e7cc519418
19,670
def wrap_deprecated(func, name): """Return a check function for a deprecated assert method call. If the `assertive-deprecated` option has been enabled and the wrapped check function doesn't yield any errors of its own, this function will yield an A503 error that includes the new name of the deprecated method. """ def wrapper(self, node): for error in func(self, node): yield error else: yield self.error(node, 'A503', func=name, name=node.func.attr) return wrapper
a94e0308ad4271ec669f4c5392a54193754c6b3f
19,672
def _get_error_message(check, threshold, importance, series_name, value): """ Construct a check's error message, which will differ based on the number of consecutive failed points. For a single failed point: Format: <importance> <series_name>: <value> not <comparator> <threshold> Example: WARNING foo.service.errors: 100 not < 50 For N consecutive failed points: Format: <importance> <series_name>: <N> consecutive points not <comparator> <threshold> Example: CRITICAL foo.service.errors: 10 consecutive points not < 50 """ if check.consecutive_failures == 1: fmt = u'{} {}: {:0.1f} not {} {:0.1f}' return fmt.format(importance, series_name, value, check.check_type, threshold) else: fmt = u'{} {}: {} consecutive points not {} {:0.1f}' return fmt.format(importance, series_name, check.consecutive_failures, check.check_type, threshold)
a91a761fc5bfb59c8ac8bdc3ea71b0e457d40bc1
19,674
def make_subj(common_name, encrypted=False): """ Make a subject string :param common_name: Common name used in certificate :param encrypted: Add the encrypted flag to the organisation :return: A subject string """ return "/C=FR/ST=Auvergne-Rhone-Alpes/L=Grenoble/O=iPOPO Tests ({0})" \ "/CN={1}".format("encrypted" if encrypted else "plain", common_name)
def68ad50d44003c27b2ac0dfa4f67faa8bf9ed9
19,676
def string_contains_surrogates(ustring): """ Check if the unicode string contains surrogate code points on a CPython platform with wide (UCS-4) or narrow (UTF-16) Unicode, i.e. characters that would be spelled as two separate code units on a narrow platform. """ for c in map(ord, ustring): if c > 65535: # can only happen on wide platforms return True if 0xD800 <= c <= 0xDFFF: return True return False
f459cfd562cf40e8e5705fa58009fcde6c9b1a0c
19,678
def finalize(cur_aggregate): """Retrieve the mean and variance from an aggregate.""" (count, mean, m_2) = cur_aggregate mean, variance = mean, m_2 / (count - 1) if count < 2: return float('nan') else: return mean, variance
50190036de4eee6b3a5fac3ee0488fc9f21fb734
19,680
def can_be_index(obj): """Determine if an object can be used as the index of a sequence. :param any obj: The object to test :returns bool: Whether it can be an index or not """ try: [][obj] except TypeError: return False except IndexError: return True
899b36096a1aaf3fc559f3f0e6eb08251c36277c
19,681
def scale(coord_paths, scale_factor): """ Take an array of paths, and scale them all away from (0,0) cartesian using a scalar factor, return the resultinv paths. """ new_paths = [] for path in coord_paths: new_path = [] for point in path: new_path.append( (point[0]*scale_factor, point[1]*scale_factor)) new_paths.append(new_path) return new_paths
e38dc71c0e2361628e428804e41b5314907641d5
19,692
def get_documentation_str(node): """ Retrieve the documentation information from a cwl formatted dictionary. If there is no doc tag return the id value. :param node: dict: cwl dictionary :return: str: documentation description or id """ documentation = node.get("doc") if not documentation: documentation = node.get("id") return documentation
6fce12b94d6000aee862c7dc8f105f4420357370
19,695
import json def generateKoldieQueryCampaignIDJSONpayload(koldie_query_campaign_id): """ Input: Takes in Kolide query campaign ID Output: Returns JSON payload for querying result(s) of query """ koldie_query_campaign_id_payload = { "type":"select_campaign", "data":{ "campaign_id": koldie_query_campaign_id } } return json.dumps(koldie_query_campaign_id_payload)
bd71b1d1f0d6eb57169e5fe93e6a8184b3149bb7
19,698
def get_shape_xyzct(shape_wh, n_channels): """Get image shape in XYZCT format Parameters ---------- shape_wh : tuple of int Width and heigth of image n_channels : int Number of channels in the image Returns ------- xyzct : tuple of int XYZCT shape of the image """ xyzct = (*shape_wh, 1, n_channels, 1) return xyzct
7b8ec67ccbfd33811904393dfe0905a169900513
19,699
def rescale(num, old_min, old_max, new_min, new_max): """ Rescale num from range [old_min, old_max] to range [new_min, new_max] """ old_range = old_max - old_min new_range = new_max - new_min new_val = new_min + (((num - old_min) * new_range)/old_range) return new_val
f823f46267d3b666ae0921957c2c3a3ca8c0a393
19,701
def find_fired_conditions(conditions, guard=None, *args, **kwargs): """ For an iterable (e.g. list) of boolean functions, find a list of functions returning ``True``. If ``guard`` is given, it is applied to a function to get the predicate - a function ``() -> bool``. If this predicate is not ``None``, it is checked and the condition is then evaluated if and only if the predicate returns ``True``. If ``guard`` is not provided, or the predicate is ``None``, condition is tested without additional check. Normally the predicate should be a very short function allowing to test whether a complex condition need to be evaluated. Args: conditions: an iterable of boolean functions guard: a ``(condition) -> predicate`` function, where ``predicate`` is ``() -> bool``. *args: positional arguments passed to each condition **kwargs: keyword arguments passed to each condition Returns: a list of conditions evaluated to ``True`` """ fired = [] if guard is not None: for condition in conditions: g = guard(condition) if g is not None and g(): if condition(*args, **kwargs): fired.append(condition) else: if condition(*args, **kwargs): fired.append(condition) return fired
0ae88df1df36667c7d771380c12d413437ebed11
19,702
def get_month(date): """ Extract month from date """ return int(date.split('-')[1])
eabf8f51554f537bbf12148eb9a9151fabe1cfad
19,704
def lollipop_compare(old_epoch: int, new_epoch: int) -> int: """ Compares two 8-bit lollipop sequences :returns: a value indicating if the given new_epoch is in fact newer than old_epoch 1 if the new_epoch is newer than old_epoch 0 if the new_epoch is newer and the sequence has been reset -1 if new_epoch is not newer than old_epoch """ if old_epoch == new_epoch: return -1 if new_epoch > old_epoch: # Case 1: new epoch is greater, 43 > 42 return 1 elif new_epoch < 0 <= old_epoch: # Case 2: new epoch is lesser, but is negative, -127 < 0 <= 10 return 0 elif new_epoch < old_epoch < 0: # Case 3: both negative, this is either a reset or a delayed packet # from another neighbor. Let's assume it's a reset. -126 < -120 < 0 return 0 elif new_epoch < old_epoch and (old_epoch - new_epoch > 32): # Case 3: wrap around, 10 < 128, (128 - 10 > 32) return 1 else: return -1
b925a333324c905ee89f368b218ffe584501fc9b
19,705