content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def drf_datetime(dt): """ Returns a datetime formatted as a DRF DateTimeField formats it Args: dt(datetime): datetime to format Returns: str: ISO 8601 formatted datetime """ return dt.isoformat().replace("+00:00", "Z")
fe7803f9cd3ef8702eeb028645e43622b5154b46
97,317
def first_n_primes(n): """Compute the first n prime numbers. Parameters ---------- n : int Number of prime numbers to compute. Returns ------- primes : list of int The first n prime numbers. Examples -------- >>> first_n_primes(4) [1, 2, 3, 5] >>> first_n_primes(10) [1, 2, 3, 5, 7, 11, 13, 17, 19, 23] """ primes = [] # Prime numbers found so far candidate = 1 # Number to try for primeness while len(primes) < n: # See if the candidate number is prime for prime in primes: if candidate % prime == 0 and prime != 1: break # Candidate is not prime! else: # No previous prime number was an equal divider of the candidate # number. This means the candidate is prime! primes.append(candidate) # Next iteration, try this candidate number: candidate += 1 return primes
8ea23d43a9e8d4d7a7d114da49f3a9f9ba0b1013
97,325
def forward_prop_affine_transform(a_prev, weight, bias): """ Apply affine transformation for forward prop Parameters ---------- a_prev: ndarray Previous layer's activation weight: ndarray Weight bias: ndarray Bias Returns ------- z: ndarray Affine transform """ return a_prev.dot(weight) + bias
201b9883ba34bf2f1b5abe15338a8de49bd68a5f
97,328
def _round_coord(coord): """ Round a number to the nearest arc-minute """ dm = 1.0 / 60 mm = coord / dm imm = int(mm + 0.5) return imm * dm
31055302fca788e460a7a6c066de492b31836750
97,329
import math def next_smaller_multiple(value, multiple): """The largest multiple of `multiple` <= `value`. Parameters ---------- value: float multiple: int Returns ------- float The largest integer multiple of `multiple` less than or equal to `value` """ return multiple * math.floor(value / multiple)
6385e60b8bca9991536a48d45b064131aedec43c
97,331
def _TransformNumInstances(resource): """Sums up number of instances in a patch job.""" if 'instanceDetailsSummary' not in resource: return None instance_details_summary = resource['instanceDetailsSummary'] num_instances = 0 for status in instance_details_summary: num_instances += int(instance_details_summary.get(status, 0)) return num_instances
ea4eabc03a6a926f51b154839582c81a3f398526
97,334
def wake_after_sleep_onset(predictions): """ Calculates number of minutes awake after first sleep period on an array of sleep/wake predictions in one minute epochs. Value is exclusive of the last wake period after sleep. Parameters ---------- predictions : array-like Binary sleep/wake predictions. Awake encoded as 1 and sleep as 0. Returns ------- waso : int Total number of minutes spent awake after the first sleep period. """ first_sleep_epoch = predictions.argmin() last_sleep_epoch = predictions[::-1].argmin() waso = predictions[first_sleep_epoch : -1 - last_sleep_epoch] waso = waso.sum() return int(waso)
56968800ed7b703e05dedc9665dd53ceb7dfb560
97,335
def getSyndrome(H, v): """ Calculates the syndrome string given a matrix and codeword :param H: :param v: :return: """ s = (H*v) % 2 return s.reshape(1, 11)
f3f44ce537f3d740a48b9565cfa3e4fc48067236
97,336
def bdev_ftl_create(client, name, base_bdev, **kwargs): """Construct FTL bdev Args: name: name of the bdev base_bdev: name of the base bdev kwargs: optional parameters """ params = {'name': name, 'base_bdev': base_bdev} for key, value in kwargs.items(): if value is not None: params[key] = value return client.call('bdev_ftl_create', params)
a32a9ce4e9f695cd5d6877d0c88bc3cd1eccdab6
97,339
def max_yngve_depth(yngve_tree_root): """Returns the max depth of the ynvge tree of the sentence Args: yngve_tree_root (obj): The root node Returns: int: The max depth of the yngve tree """ return max([leaf.score for leaf in yngve_tree_root.leaves])
09b31e14ac66f07dd21b041740301a1e8355e71f
97,342
def _read_marker_mapping_from_ini(string: str) -> dict: """Read marker descriptions from configuration file.""" # Split by newlines and remove empty strings. lines = filter(lambda x: bool(x), string.split("\n")) mapping = {} for line in lines: try: key, value = line.split(":") except ValueError as e: key = line value = "" if not key.isidentifier(): raise ValueError( f"{key} is not a valid Python name and cannot be used as a marker." ) from e mapping[key] = value return mapping
7d8d1114480bec0cd571380c2369b72da1e91021
97,343
import string def _sanitize_module_name(module_name): """Sanitize the given module name, by replacing dashes and points with underscores and prefixing it with a letter if it doesn't start with one """ module_name = module_name.replace('-', '_').replace('.', '_') if module_name[0] not in string.ascii_letters: module_name = "a" + module_name return module_name
163d1b99548fa652587c78b71adcfc5c2169c01f
97,345
def get_output_shape(kernel_size, stride, padding, H_prev, W_prev): """Get the output shape given kernal size, stride, padding, input size.""" k_H, k_W = kernel_size stride_H, stride_W = stride pad_H, pad_W = padding H = int((H_prev - k_H + 2 * pad_H) / stride_H) + 1 W = int((W_prev - k_W + 2 * pad_W) / stride_W) + 1 return H, W
2215b038f662ad97445d3c8221aeaf8912ebeeee
97,348
def swap_element(list1, list2, index): """ Swaps element between list1 and list2 at given index Parameters: list1 -- First list list2 -- Second list index -- Index the swap operation will be applied Returns: list1 -- First list with swapped element list2 -- Second list with swapped element """ temp = list1[index] list1[index] = list2[index] list2[index] = temp return list1, list2
ed3333b548a4bcd27e889655055f805ff477a76e
97,352
def readint(bs, count): """Read an integer `count` bits long from `bs`.""" n = 0 while count: n <<= 1 n |= next(bs) count -= 1 return n
b9f53dc7a6bb7f13b6b5bedfa47910ced116bf5a
97,354
def A11_2_R11(A11): """ Convert Abundance to Ratio notation. """ return A11 / (1 - A11)
48000e429fafc12cccc3f2b2205d04b54257dc24
97,357
import random def getRandomWord (wordDict): """ Returns a random string from the passed dictionary of lists of strings, and the key also. """ # Randomly select a key from the dictionary wordKey = random.choice(list(wordDict.keys())) # Randomly select a word from the key's list in the dictionary wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) return [wordDict[wordKey][wordIndex], wordKey]
015be984a5173954ac071a676a1d17912e88d550
97,364
import re def split_string(s): """Docstring for split_string. Take space-delimited string and split into list using re. :s: space-delimited string :returns: list """ return re.split('\s+', s)
6ef0f50394fc70d93917b86a022087a94a5d44f4
97,365
import collections def list_of_flat_dict_to_dict_of_list(list_of_dict): """ Helper function to go from a list of flat dictionaries to a dictionary of lists. By "flat" we mean that none of the values are dictionaries, but are numpy arrays, floats, etc. Args: list_of_dict (list): list of flat dictionaries Returns: dict_of_list (dict): dictionary of lists """ assert isinstance(list_of_dict, list) dic = collections.OrderedDict() for i in range(len(list_of_dict)): for k in list_of_dict[i]: if k not in dic: dic[k] = [] dic[k].append(list_of_dict[i][k]) return dic
ce665c4f82475851eaa3b8f105cb623fc4f702c7
97,370
def select_answer(list_of_answers): """The player select *one* char out of a list""" answer = "" while not answer in list_of_answers: answer = input(">>>") return answer
03320e5d677d9dc07ea564b60294e098d38763bc
97,371
def is_visible(attr): """ This function checks whether an HTML element attribute is visible or hidden based on the style of that HTML element. The purpose of this function in this package is to avoid including data that is useless, such as inner code markers, non-sense data, etc. So this function will ensure that we just retrieve useful data. Args: attr (:obj:`lxml.html.HtmlElement`): HTML element Returns: :obj:`bool` - flag This function returns either `True` or `False` depending on the style of the HTML element received from parameter, whether if it is visible or not, respectively. """ if 'style' in attr.attrib: style = attr.get('style') if style.__contains__("display:none") or style.__contains__("display: none"): return False return True
0e1eb59f7c53b0329c1ad4e61e4fe100d63ee112
97,377
def cw(i): """Get index (0, 1 or 2) decreased with one (cw)""" return (i - 1) % 3
40dd4cbfa2d54ee4a9d197bcf606d72fae2c3228
97,383
import re def parse_show_snmp_agent_port(raw_result): """ Parse the 'show snmp agent-port' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show snmp agent-port :: { 'SNMP agent port': '677' } """ snmp_agent_port_re = ( r'\s*SNMP\s*agent\sport\s*:\s*(?P<agent_port>.+)' ) re_result = re.match(snmp_agent_port_re, raw_result) if re_result is None: return re_result result = re_result.groupdict() return result
01e0efbe2a0934f15afe72d0529edd86d988e2c9
97,384
def split_chunk_for_display(raw_bytes): """ Given some raw bytes, return a display string Only show the beginning and end of largish (2xMAGIC_SIZE) arrays. :param raw_bytes: :return: display string """ MAGIC_SIZE = 50 # Content repeats after chunks this big - used by echo client, too if len(raw_bytes) > 2 * MAGIC_SIZE: result = repr(raw_bytes[:MAGIC_SIZE]) + " ... " + repr(raw_bytes[-MAGIC_SIZE:]) else: result = repr(raw_bytes) return result
4e7d8584f628d75791533ea50fcf1f3b974471cc
97,385
import hashlib def hash_one(n): """A somewhat CPU-intensive task.""" for i in range(1, n): hashlib.pbkdf2_hmac("sha256", b"password", b"salt", i * 1000) return "done"
521eea5576935cb024880f316653ac89634552b1
97,386
import types def type_details(example, avk_name, description=None): """Collection of details about a Python type.""" return types.SimpleNamespace(example=example, avk_name=avk_name, description=description or avk_name.lower())
6ed2ef66b216f2059df82836c16e46e01235ccd5
97,389
def opcode_exa1(self, x) -> int: """ EXA1 Skip the following instruction if the key corresponding to the hex value currently stored in register VX is not pressed """ return self.pc + (2 if self.keypad.is_this_key_pressed(x) else 4)
b2a7afac5bff0f3c5b6e150b4185ffab761a9ebc
97,390
def _Pbar(Z): """ ASHRAE Fundamentals Handbook pag 1.1 eq. 3 input: Z: altitude, m return standard atmosphere barometric pressure, Pa """ return 101325. * (1 - 2.25577e-5 * Z)**5.256
6a4677099c5d7b80d643afe4d5d00fa17bc0734c
97,394
def is_list_of_ints(intlist): """ Return True if list is a list of ints. """ if not isinstance(intlist, list): return False for i in intlist: if not isinstance(i, int): return False return True
1288dc2ac4f8efb9f089b2c3ea8511eab3c3297b
97,399
def get_record_if_exists(dh_records, params): """Checks to see if record specified in config.json exists in current Dreamhost records.""" for record in dh_records: if record["record"] == params["record"] and record["type"] == params["type"]: # Return Dreamhost record if record does currently exist. return record # Return empty dictionary if record does not currently exist on Dreamhost. return {}
425f28694b8b8b1da2aa8d3ff8d8a8b53c68f88b
97,402
def cubeUsingMap(myList: list) -> list: """ Simple map function for cube of numbers in the list using map and lambda. """ odd = list(map(lambda x: x**3, myList)) return odd
c9e56788972120935b9bf47d5d8daf686661ccd9
97,404
def bool_formatter(bool_value): """ convert Python boolean to json/xml format of boolean Parameters ---------- bool_value: bool the boolean value that needs to be converted Returns ------- str either "true" or "false" """ if isinstance(bool_value, bool): if bool_value: return("true") else: return("false") else: msg = "bool_value must be a boolean" raise ValueError(msg)
406ff05b8ce05c6d6ce567581612f07da5b97e47
97,406
def flatten_dict(to_flatten): """Flattens nested dictionaries, removing keys of the nested elements. Useful for flattening API responses for prefilling forms on the dashboard. """ flattened = {} for key, value in to_flatten.items(): if isinstance(value, dict): flattened.update(flatten_dict(value)) else: flattened[key] = value return flattened
a70c888fae129c92e93e02bbcea2aedfa3e5e5cb
97,412
def get_skewness(m1: float, m2: float, m3: float) -> float: """Compute skewness. """ var = m2 - m1**2 std = var**0.5 return (m3 - 3*m1*var - m1**3) / (var * std)
f74eefa43d56c4f350d17caa21790b92eebb9ffd
97,413
def getGenderForMember(member): """ Returns the member's gender as a string: 'F' or 'M'. """ return member['Gender']
3b4997ac54ec71af12ab8c0aa43009f2bc449ae1
97,417
def part_filename(num): """Return a string conforming to the output filename convention. EXAMPLE >>> part_filename(3) 'part-00003' """ return f"part-{num:05d}"
05bb5ecb3c58dcaa5911ad8c1ebb598dce56f607
97,419
from typing import AnyStr def write_file(filepath: str, content: AnyStr, *args, **kwargs) -> AnyStr: """Writes to a file and returns the content Parameters ---------- filepath : str The path to the file to write to content: AnyStr The content to write to the file Returns ------- AnyStr The thing that was written to the file """ with open(filepath, "w" if content is str else "wb", *args, **kwargs) as f: f.write(content) return content
ee0237e6664a1fa454027392edd0d3081f64abbf
97,421
def map_compat_facility_state(facility_state: str) -> str: """ Maps a current v1 version opennem facility_registry.json state to a v3 state """ state = facility_state.lower().strip() if state == "commissioned": return "operating" if state == "decommissioned": return "retired" return state
20a483ab92e8bde5476c870dcd771d4f68ddcefa
97,425
import re def get_lang(hocr, default_lang="fra"): """ Retrieves the most represented language, returns `default_lang` if language is undefined in hocr Parameters ---------- hocr : str, required an hOCR Document default_lang: str, optional (default='fra') The default language if the language is undefined """ langs = re.findall(r'lang="([a-z]{3})"', hocr) if len(langs) == 0: return default_lang return max(set(langs), key=langs.count)
eb3e7a5a7d57e9258a72b922413651e8525c15b0
97,429
def find_types_with_decorator(class_type, decorator_type): """ A method to collect all attributes marked by a specified decorator type (e.g. InputProperty). Parameters ---------- class_type: type The class to pull attributes from. decorator_type: type The type of decorator to search for. Returns ---------- The names of the attributes decorated with the specified decorator. """ inputs = [] def get_bases(current_base_type): bases = [current_base_type] for base_type in current_base_type.__bases__: bases.extend(get_bases(base_type)) return bases all_bases = get_bases(class_type) for base in all_bases: inputs.extend([attribute_name for attribute_name in base.__dict__ if isinstance(base.__dict__[attribute_name], decorator_type)]) return inputs
4965e9f3be50da680486c088ac1554dafc30c2e5
97,431
def _safe_issubclass(derived, parent): """Like issubclass, but swallows TypeErrors. This is useful for when either parameter might not actually be a class, e.g. typing.Union isn't actually a class. Args: derived: As in issubclass. parent: As in issubclass. Returns: issubclass(derived, parent), or False if a TypeError was raised. """ try: return issubclass(derived, parent) except TypeError: return False
23ce954fcb133cdf81ff498352e6644dd8b1c224
97,437
def expand_loop(start, step, length): """A convenience function. Given a loop's start, step size, and length, returns the loop values. The opposite of deconstruct_loop().""" return [start + (step * i) for i in range(length)]
37607199a6a4fd706bacf9657a31331a63100121
97,438
def field_add(field, vector): """ Add the vector to the field. Parameters ---------- field: array (x, y, z, 3) an image of vectors. vector: array (3, ) the vector that will be added to the field. Returns ------- field: array (x, y, z, 3) the incremented image of vectors. """ field[..., 0] += vector[0] field[..., 1] += vector[1] field[..., 2] += vector[2] return field
06387b1c72b97a926c3e72a83f3c033921d013d7
97,439
import time def timeit(func, *args, **kwargs): """ Time execution of function. Returns (res, seconds). >>> res, timing = timeit(time.sleep, 1) """ start_time = time.time() res = func(*args, **kwargs) timing = time.time() - start_time return res, timing
5b3d01055ee06ff8a77a90514cb12070ac22cda1
97,440
def zip_len_check(*iters): """Zip iterables with a check that they are all the same length""" if len(iters) < 2: raise ValueError(f"Expected at least 2 iterables to combine. Got {len(iters)} iterables") n = len(iters[0]) for i in iters: n_ = len(i) if n_ != n: raise ValueError(f"Expected all iterations to have len {n} but found {n_}") return zip(*iters)
3ac39de6ca43265b188d73dc3240b2b435aec18b
97,441
def yes_no_to_bool(s): """Converts yes or y to True. false or f to False. Case-insensitive.""" return {"yes": True, "y": True, "no": False, "n": False}[s.casefold()]
fc7c580736209f650c6b1651affde7e3ab33148f
97,444
def count_jailed(model): """Count number of jailed agents.""" count = 0 for agent in model.schedule.agents: if agent.breed == "citizen" and agent.jail_sentence: count += 1 return count
d6f7aca961917eebf40db11ab859511cf7c2606a
97,445
import re import string def sanitize_name(name): """ Sanitize a given name such that it conforms to unix policy. Args: name: the name to sanitize. Returns: The sanitized form of name. """ if len(name) == 0: raise Exception("Can not sanitize an empty field.") sanitized_name = re.sub(r"[^a-z0-9\+-]", "-", name.lower()) if sanitized_name[0] in string.digits: sanitized_name = "p" + sanitized_name return sanitized_name
fa62863082a37e9825b213049f9010d4d05aeea4
97,446
def trial_success(boutlist): """Takes list of times of bouts in seconds, returns bool of whether the mouse managed to get the tape off in time. """ if boutlist[-1] == 300: success = False else: success = True return success
c159a42e7f16ba6c91bca065df14807ea6d7ddfc
97,447
def hex_to_rgb(hex): """ Convert hex color code to RGB """ code = hex.lstrip("#") return [int(code[i : i + 2], 16) for i in (0, 2, 4)]
58fb775aa90fe83f6678435a6dbe2a5a347ed679
97,448
def get_genea_id(binfile): """ Get serial number of GENEActiv device """ assert binfile.lower().endswith(".bin"), f"Cannot get device id for {binfile}" with open(binfile, 'r') as f: # 'Universal' newline mode next(f) # Device Identity device_id = next(f).split(':')[1].rstrip() # Device Unique Serial Code:011710 return device_id
ab3a2b65d2e00afcd7ceb7c9f7ad0adf23976dd8
97,451
import collections def _make_shuffle_pcols(n, grid): """ Generates a list of integers instructing `pshuffle` to have each processor n units downward. Returns e.g. (4, 5, 6, 7, 0, 1, 2, 3) For n=1, grid=(2, 2, 2), "shift hor" """ Ncore, Nrow, Ncol = grid chips_per_pcol = Ncore * Nrow out = collections.deque() for i in range(Ncol): col = tuple(list(range(i * chips_per_pcol, (i + 1) * chips_per_pcol))) out.append(col) out.rotate(n) out = list(out) to_return = [] for tup in out: to_return += list(tup) return tuple(to_return)
22197a10fa68f926a7400baf919eef345218adac
97,452
def pow(x, n): """ Power. """ return x**n
e00a4969ff00dea6dbddaaef002283d2283840f9
97,454
def get_all_streams(client): """ Get all current Zulip streams. :param client: A Zulip client object :return: Dictionary containing all current streams. """ result = client.get_streams() return result
eb13000b5ede6ff5eeb0ed0224817b99077f2824
97,455
import math def get_angle_between_yaw_and_point(a, p, yaw): """ Gets the angle between the point p and the vector starting from a's centroid with the given yaw angle. """ p_yaw = [math.cos(math.radians(yaw)), math.sin(math.radians(yaw))] p_self = [p[0] - a.centroid.x, p[1] - a.centroid.y] angle = math.degrees(math.atan2(*p_yaw) - math.atan2(*p_self)) % 360 return angle
f6ff0d1affec482a2324209e452d7e24439466b4
97,457
def complete_leaf_value(return_type, result): """ Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible. """ # serialize = getattr(return_type, 'serialize', None) # assert serialize, 'Missing serialize method on type' return return_type.serialize(result)
68a62cc6359283b3528571e01b94a899cb500486
97,462
def git_line(*items): """Formats items into a space separated line.""" return b" ".join(items) + b"\n"
750a207ef0b93fec633a6b08c5e7703893032f3e
97,465
def sub_point(p1, p2, factor=0.5): """ Returns a point on the line between p1 and p2 according to factor. """ x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] x = x1 + factor * (x2 - x1) y = y1 + factor * (y2 - y1) return (int(x), int(y))
87e94b96c5eabf278d323e308ea4f8b88c55ea10
97,468
import json def loadJsonFile(filePath: str) -> dict: """ Load json file. :param filePath: File path. :type filePath: str :returns: Json data. :rtype: dict """ with open(filePath) as fp: data = json.load(fp) return data
1cb95ce6b904e69edd88704fedcf963d93b3c1f1
97,471
import re def remove_number_of_hits_from_autocomplete(user_entry): """ removes number of hits from entry string that has been added by autocomplete :param user_entry: user entry string with number of hits in parenthesis :return: user_entry without number of hits """ user_entry = re.sub("\([0-9]*\)$", "", user_entry).strip() return user_entry
e6e356cce3048988a48b03ba7c26da07a03ee8bc
97,474
import re def max_match(sentence, dictionary): """ MaxMatch algorithm for segmenting a sentence into a list of words/tokens. """ # We first remove whitespace from sentence. sentence = re.sub('\W', '', sentence) # For now, we're not really concerned with efficiency. words, pos = [], 0 while pos < len(sentence): # Pick the longest prefix from position pos that's present in # the dictionary. If no prefix is in dictionary, pick single # letter as the next word. for j in range(len(sentence), pos + 1, -1): word = sentence[pos : j] if word in dictionary: pos = j words.append(word) break else: words.append(sentence[pos]) pos += 1 return words
415700d44e529be8e24dc1e2a943530655a4dfb5
97,476
def list_access(service_listing, service_name): """ For a given USEF service name (API endpoint) in a service listing, return the list of USEF roles that are allowed to access the service. """ return next( service["access"] for service in service_listing["services"] if service["name"] == service_name )
a7bae132c63ef79e8a0085bffb3161dba5e53c2a
97,480
def ask(question: str) -> bool: """ ask to user the question until given an answer then return the answer :param question: the question to ask the user :return: the users answer """ while True: answer: str = input("Do you want to " + question + "? [Y/n]") # check if one viable answers if answer.lower() == "y"\ or answer == ""\ or answer.lower() == "n": # return True if y or empty or False if n return answer.lower() == "y" or answer == ""
91522baf56bd2aa024b55bf90394b618c5c3c24e
97,486
from typing import List from typing import Optional def calculate_increases(depths: List[int]) -> int: """Calculate the number of depth increases.""" previous: Optional[int] = None depth_increase: int = 0 for depth in depths: if previous is not None and depth > previous: depth_increase += 1 previous = depth return depth_increase
b7e16b121e6bf24b8d9c4b2bb1e9e9d6d38fbce5
97,487
def csv2list(csv_str): """csv2list Converts a string of comma-separated values into a Python list of strs, stripping whitespace and disallowing empty strings from appearing in the final list. :param csv_str: String of comma-separated values """ return list(filter(lambda s: s != '', map(str.strip, csv_str.split(','))))
d95f324bbf838c8c65398a5e31a724f50ddf1586
97,491
def getSortOnName(prefix=None): """convert the table prefix to the 'sort on' name used in forms""" # useful for code that wants to get the sort on values themselves sort_on_name = 'sort_on' if prefix is not None: if not prefix.endswith('.'): prefix += '.' sort_on_name = prefix + sort_on_name return sort_on_name
e8a68d283cb189abab2784a1cc198255133e4c1d
97,496
import string def iterable(obj): """ Return True if C{obj} is a collection or iterator, but not string. This is guaranteed to work in both python 2 and 3. @rtype: bool """ if hasattr(obj, '__iter__'): if not isinstance(obj, string): return True return False
2b2023330f3bb0da5ef4d400646a770a9dd1815a
97,500
def _res_to_dpi(num, denom, exp): """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution, calculated as (num / denom) * 10^exp and stored in dots per meter, to floating-point dots per inch.""" if denom != 0: return (254 * num * (10**exp)) / (10000 * denom)
b7eee7894df52d195bf62e3c395ad08e165ccb8a
97,501
def pairs2dict(s): """convert comma-delimited name,value pairs to a dictionary""" items = s.split(',') m = dict() for k, v in zip(items[::2], items[1::2]): m[k] = v return m
aef36335a48347ad3ab55d7f78b948cfc673066a
97,504
def update(im, *args, **kw): """Update an immutable object. This is a helper method for ``IImmutable.__im_update__(*args, **kw)``. """ return im.__im_update__(*args, **kw)
cb385ea27ec5a008e4fe23e688a646a4d18b498f
97,509
def upper(s): """ Number of upper case letters in a string. Solution for day 4. >>> upper("UpPer") 2 >>> upper("alllower") 0 """ # Current number of upper case letters found upper = 0 # Loop through all the letters in the string and if it is upper, increase for x in s: if x.isupper(): upper += 1 # Return upper return upper
4a3e7798641c6366fadb248368f40c5f919b2513
97,510
def pentagonal(nth): """ Providing n'th pentagonal number. :param nth: index for n'th pentagonal :returns: n'th pentagonal number see http://en.wikipedia.org/wiki/Pentagonal_number >>> pentagonal(3) 12 >>> pentagonal(4) 22 """ return (nth * (3 * nth - 1)) // 2
681be998d916935d966c1ad082afd0e0fc79aa07
97,513
def get_converter_name(conv): """Get the name of a converter""" return { bool: 'boolean', int: 'integer', float: 'float' }.get(conv, 'string')
a20c4f74110c5c616960dcdfc0f26d0b57eb7797
97,516
import typing def is_union_type(type_): """Check if a type is :data:`typing.Union` or a parameterized version of it. param type_: Type object to check. :type: bool >>> from typing import Union >>> is_union_type(Union) True >>> is_union_type(Union[int, str]) True >>> is_union_type(Union[int]) # just returns int False >>> is_union_type(int) False """ return isinstance(type_, type(typing.Union))
8881d4d3592d73bcdcd68396489a83f540346f0a
97,517
def assert_pure(s): """ raise an Exception if the given string is not :func:`ispure`. """ #~ assert ispure(s), "%r: not pure" % s if s is None: return if isinstance(s, str): return True try: s.decode('ascii') except UnicodeDecodeError as e: raise Exception("%r is not pure : %s" % (s, e))
42d17bea17a224c62784dc8d1bc131a47df4f0d2
97,518
import functools import operator def _topmost_artist( artists, _cached_max=functools.partial(max, key=operator.attrgetter("zorder"))): """Get the topmost artist of a list. In case of a tie, return the *last* of the tied artists, as it will be drawn on top of the others. `max` returns the first maximum in case of ties, so we need to iterate over the list in reverse order. """ return _cached_max(reversed(artists))
fad00274a87614f12d8b1cdb35b25413f8d6763c
97,519
def mean(x): """Finds mean value of data set x""" return sum(x) / len(x)
7de8f72fea4b5ad67ed369d7f2583f7998d63362
97,522
def select_sample_df(list_of_groups:list, df): """Selects specific groups from df Args: list_of_groups: group numbers in a list, if just one group, specify as a list anyway df: pandas DataFrame Returns: small dataframe with the selected groups and reindexed """ small_df = df[df["group_id"].isin(list_of_groups)].reset_index(drop=True) return small_df
7102a6a2f8c65f5beebd049b8c9ac5c918bf7275
97,529
def smf_bindmap(bones): """Construct the SMF bindmap from the given list of Blender bones""" # Create the bindmap (i.e. which bones get sent to the shader in SMF) # See smf_rig.update_bindmap (we only need the bindmap part here!) # Only consider Blender bones that map to SMF bones # Every SMF node that has a parent and is attached to it, represents a bone # (the detached nodes represent the heads of bones) smf_bones = [b for b in bones if b and b.parent] bindmap = {} sample_bone_ind = 0 for node in smf_bones: bindmap[node.name] = sample_bone_ind sample_bone_ind = sample_bone_ind + 1 return bindmap
4b5f108bc28501521c59aa66d3a99fb7523af49f
97,534
from datetime import datetime import pytz def time_to_string_if_valid(t): """ Validate event_time according to EventAPI Specification.""" if t is None: return datetime.now(pytz.utc).isoformat() if type(t) != datetime: raise AttributeError("event_time must be datetime.datetime") if t.tzinfo is None: raise AttributeError("event_time must have tzinfo") # EventServer uses milliseconds, but python datetime class uses micro. Hence # need to skip the last three digits. # pat: from PIO return t.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + t.strftime("%z") return t.isoformat()
4c8338d5d9015fd5aa394c571648a4e0a08bd53f
97,535
def check_vulnerable_package(version, version_string): """Check if the request version available in vulnerable_versions.""" if(version in version_string.split(",")): return True return False
0215df375898e0fca2b5447c62aaa6d02ba5b19e
97,537
def extent(lst): """Get extent (dimensions object given by lst).""" vecs = zip(*lst) return [max(v) - min(v) for v in vecs]
498ad04049d7993c098b7cfdc6ef8555b657103e
97,540
import calendar def ts_to_unix(t): """Convert a datetime object to an integer representing the current UNIX time.""" return calendar.timegm(t.utctimetuple())
b0d7186b59eef73ad32af4407752a270e5c0fe7e
97,546
def ask_for_confirmation(message, default="y"): """ Use this function to request a confirmation from the user. Parameters: - message: str, the message to display - default: str, either "y" or "n" to tell "Yes by default" or "No, by default". Returns: a boolean, True or False to reply to the request. Note: this function will append a " (y/N): " or " (Y/n): " to the message. """ cache = "Y/n" if default == "y" else "y/N" user_input = None try: user_input = input("{} ({}): ".format(message, cache)) except EOFError as e: pass if not user_input: user_input = default if user_input.lower() == "y": return True return False
807228fe558a8dcb0121d85c9f6016dc129ece1e
97,547
def fold_spaces(low_spaces, high_spaces): """ Creates all possible combinations of hyperspaces. Parameters ---------- * `low_spaces` [list, shape=(n_spaces,)]: lower spaces defined by hyperspace classes. * `high_spaces` [list, shape=(n_spaces,)]: lower spaces defined by hyperspace classes. Returns ------- * `hyperspace` [`list of lists`, shape=(2**n_spaces, n_spaces)]: - All combinations of hyperspaces. Each list within hyperspace is a search space to be distributed across 2**n_spaces nodes. """ if len(low_spaces) != len(high_spaces): raise ValueError(("low_spaces and high_spaces must have the same length. " "Got {} and {} respectively.".format(len(low_spaces), len(high_spaces)))) indices = len(low_spaces) num_hyperspaces = 2**indices hyperspace = [[] for i in range(num_hyperspaces)] for space in range(num_hyperspaces): for index in range(indices): bit_tester = 1 << index if space & bit_tester: hyperspace[space].insert(index, low_spaces[index]) else: hyperspace[space].insert(index, high_spaces[index]) return hyperspace
4e541bbd6893e5803a66b764b13833ef11877f2a
97,554
import requests def GetVTIresults(VTI_API_KEY, sha256_file_hash): """ Input: Take in API key and SHA256 file hash Output: Return VTI report for the SHA256 file hash provided """ auth_header = { "x-apikey": VTI_API_KEY } url = f"https://www.virustotal.com/api/v3/files/{sha256_file_hash}" r = requests.get(url=url, headers=auth_header) return r.json()
3556d679e737ec8631dfd85f93310a97fa261110
97,557
def normalize_option_name(name): """Use '-' as default instead of '_' for option as it is easier to type.""" if name.startswith("--"): name = name.replace("_", "-") return name
5f971b9c925486843ce4b050be048f0fb3efbdf1
97,558
def get_total_config_size(config): """ Given a config file, determine the total size of assets, zipped assets, and the total of both. :param config: The config file to parse :type config: `dict` :rtype: `int`, `int`, `int` """ total_base_size = total_zipped_size = 0 for asset_details in config['files']: total_base_size += asset_details['size'] if 'zsize' in asset_details: total_zipped_size += asset_details['zsize'] return total_base_size, total_zipped_size, total_base_size + total_zipped_size
23de238e33132e1ff6f73e54142099ae649bebc0
97,561
def _window_match(match, window=100): """Take incoming match and highlight in context. :rtype : str :param match: Regex match. :param window: Characters on each side of match to return. :type window: int """ window = int(window) start = match.start() end = match.end() snippet_left = match.string[start - window:start] snippet_match = match.string[match.start():match.end()] snippet_right = match.string[end:end + window] snippet = snippet_left + '*' + snippet_match + '*' + snippet_right return snippet
4d315b975b1fc638ea85a46799760424d8005791
97,563
def stcubic_eval(coeffs, t): """ Input: iterable coeffs = (p0,p1,p2,p3) Output: p3*t**3 + p2*t**2 + p1*t + p0 """ p0, p1, p2, p3 = coeffs return p3 * t ** 3 + p2 * t ** 2 + p1 * t + p0
a8e9aaa2804ea4559fb3198114b5a0688cc04da2
97,568
import torch def unsqueeze(x: torch.Tensor, factor: int = 2) -> torch.Tensor: """ Args: x: Tensor input tensor [batch, length, features] factor: int unsqueeze factor (default 2) Returns: Tensor squeezed tensor [batch, length * 2, features // 2] """ assert factor >= 1 if factor == 1: return x batch, length, features = x.size() assert features % factor == 0 # [batch, length * factor, features // factor] x = x.view(batch, length * factor, features // factor) return x
5ad1def67f49a670943b2b190c78244b84813f45
97,580
def get_item(dictionary, key): """ Given a dictionary and a key, return the key's value """ return dictionary.get(key)
97bf041cb8afe160a5c1610e088dadb91d023e8f
97,582
from typing import List from typing import Dict def get_annotation(annotations: List[Dict[str, str]], filename: str): """ Get annotation for an audio file by looking up filename match in the spreadsheet json :param annotations: data from input spreadsheet in JSON format :param filename: name of WAV file to get annotation for :return: annotation retrieved from the spreadsheet data matching the WAV filename """ annotation = '' for record in annotations: if record["File name"] == filename: annotation = record["Transcription"] break return annotation
748d6f0d8e2928f38c89716a4710e7d741b3b81a
97,583
import re def meta_graph_filename(checkpoint_filename, meta_graph_suffix="meta"): """Returns the meta graph filename. Args: checkpoint_filename: Name of the checkpoint file. meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. Returns: MetaGraph file name. """ # If the checkpoint_filename is sharded, the checkpoint_filename could # be of format model.ckpt-step#-?????-of-shard#. For example, # model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002. basename = re.sub(r"-[\d\?]+-of-\d+$", "", checkpoint_filename) suffixed_filename = ".".join([basename, meta_graph_suffix]) return suffixed_filename
eb07edadb778526625d679b507bac82eb6ba39e8
97,589
import math def create_icosagon_dict(radius): """ create_icosagon_dict Generates a dictionary with coordinates for each amino acid position. Input : radius, assumed to be the central pixel of the image Output: icosagon_dict, a mapping of amino acid to pixel coordinates (as 2-tuple) """ icosagon_dict = {} # Counterclockwise ordering of amino acids, sstarting at degree 0 (Eastwards) aa_order = ['A', 'P', 'V', 'L', 'I', 'M', 'F', 'W', 'D', 'E', 'S', 'T', 'C', 'N', 'Q', 'Y', 'K', 'H', 'R', 'G'] degree = 0 for aa in aa_order: # Must ensure to add radius to each to translate the origin x_pixel = int(radius * math.cos(degree)) + radius y_pixel = int(radius * math.sin(degree)) + radius icosagon_dict[aa] = (x_pixel, y_pixel) degree += 18 return icosagon_dict
26ab9ff84f4105cc19c4b11694cbf3097c7f4f69
97,593
def list_to_cpp_vec_list_initialiser(labels: list, indentation: int) -> str: """ Converts a list of strings to a C++ styled list initialiser Parameters: labels (list): List of strings indentation (int): number of spaces for indentation for all lines Returns: string formatted as a C++ styled initaliser list. """ space_indent = " " * indentation initaliser_list = "{\n" for label in labels: initaliser_list += space_indent + f'"{label.strip()}",\n' initaliser_list += space_indent + "};" return initaliser_list
c6dded1e8c63e9587acaecf6e8999f080729d8ed
97,594
import six from typing import MutableMapping def _is_tuple_str_mapping(obj): """Predicate that returns True if object is a tuple of length 2, composed of a string and a mapping. Args: obj (object): object to be inspected Returns: True or False """ return ( isinstance(obj, tuple) and len(obj) == 2 and isinstance(obj[0], six.string_types) and isinstance(obj[1], MutableMapping) )
d5dc32492f71bff6edaf85f9aacfcb877b04aa44
97,598
def parse_optimizer_scope(update_op_name): """ Given the name of an update_op, return its optimizer name scope. Args: update_op_name: the name of an update_op (usually ResourceApply). Returns: str: The outermost name scope of the optimizer """ first_pos = update_op_name.find('/') second_pos = update_op_name.find('/', first_pos + 1) return update_op_name[:second_pos + 1]
ad708c7b89391a3657a55e4efaf084d9d5bb3b20
97,601
def get_character_weight(char: str, options: dict) -> int: """ Return an integer weight corresponding to `char`. The weight is determined by the Unicode code point of `char` and ranges specified by `options`. >>> char = '日' >>> options = { ... 'default_weight': 200, ... 'ranges': [ ... { 'start': 0, 'end': 4351, 'weight': 100 }, ... { 'start': 8192, 'end': 8205, 'weight': 100 } ... ] >>> get_character_weight(char, options) 200 """ ranges = options['ranges'] char_code_point = ord(char[0]) match = [range['weight'] for range in ranges if range['start'] <= char_code_point <= range['end']] weight = match[0] if match != [] else options['default_weight'] return weight
23c734d4aac5852ea3420ef8e36247db69d5db58
97,602
from typing import Dict from typing import Any from typing import Optional def get_dict_value( profile: Dict[str, Any], *keys: str, default: Optional[Any] = None ) -> Any: """Save function to get an item from a nested dict Arguments: profile: the dict to start with *keys: a list the keys to descent to the wanted item of the profile default: the value to return if a key does not exist. Defaults to None. Returns: the item """ if not profile: return default for key in keys: if key in profile: profile = profile[key] else: return default return profile
0c758b7bc785bd8be00d848654c68b9007f4cd2b
97,603