content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import hashlib def hashstring(s: str) ->str: """ Generating an "unique" user id from the sha224 algorithm. """ return hashlib.sha224(s.encode('ascii')).hexdigest()
d56e45b2f60bcd5ab096cce539bab49a7a6c96ef
680,748
import re def deNumerize(text:str) -> str: """Removes numbers from strings""" regex_pattern = re.compile(pattern = r'[0-9]', flags=re.UNICODE) return regex_pattern.sub(r'', text)
6983cb6de3cd52fee797cd9559402d83d514a100
680,750
from typing import Dict from typing import Any def get_schema_type(arg_schema: Dict[str, Any]) -> str: """Returns the schema type for an argument. Args: arg_schema: dict(str, *). Schema for an argument. Returns: str. Returns schema type by extracting it from schema. """ return ar...
4f62bb591640ca2bccb0a111e7528b3ef582366e
680,752
def extractScopeLFN(scope_lfn): """ Extract the scope and LFN from the scope_lfn string """ # scope_lfn = scope:lfn -> scope, lfn _dummy = scope_lfn.split(':') return _dummy[0], _dummy[1]
91d4672624b2b6f5df4f132f4da6d9016747cce5
680,754
def set_style(style, text_color='white', highlight_hover=True, mini_zoom=False, th_mini_font_size=6, enforce_size=False, td_width=15, td_height=15): """Imposes some styling options on a DataFrame.style object.""" prope...
d6b8ba059b001a0f53cc08311525b048a17f8c74
680,756
def _hasfield(model_fields, field_name): """ Check if field name exists in list of model fields :param list model_fields: List of Django Model object fields :param string field_name: attribute string, dotted or dunderscored. example: 'user.first_name' or 'user__first_name' :returns: Field obje...
701099a73d2e46f686c7c353172dfe83573c72ec
680,757
def enum_solutions(node): """ >>> node = {'entry': {'lemma': u'EOS'}} >>> enum_solutions(node) [[u'EOS']] >>> node = { ... 'entry': {'lemma': u'ใ“ใ‚Œ'}, ... 'next': [ ... { ... 'entry': {'lemma': u'ใฏ'}, ... 'next': [ ... {...
5f1a6a7b9ed2c0667720fda7e65231fbe30915df
680,761
def postprocess(var_list): """์ˆ˜์ง‘ํ•œ ํ™˜์ž์ˆ˜ ํ›„์ฒ˜๋ฆฌ Args: var_list: ํ›„์ฒ˜๋ฆฌ ํ•  ๋ฌธ์ž์—ด list Returns: (list) var_list ์ˆœ์„œ๋Œ€๋กœ ํ›„์ฒ˜๋ฆฌ๋œ ๊ฒฐ๊ณผ """ result = [] for var in var_list: var = var.replace(',', '').strip() if '.' in var: var = float(var) elif var == '-': ...
791ad52fdf9b532766aea7e6b92a2cb5b18abae3
680,768
def edit_distance(left_word: str, right_word: str) -> int: """ The difference between same-length words in number of edits The result is the edit distance of the two words (number of substitutions required to tranform left_word into right_word). Args: left_word: One word to compare rig...
0db7798a95ac5934c75ab623b895e56bfba40035
680,769
def convert_to_undirected(G): """Return a new undirected representation of the graph G.""" return G.to_undirected()
018e1a1a5773a025729560ad03a9eec85dd1e198
680,770
def make_tuple(input): """ returns the input as a tuple. if a string is passed, returns (input, ). if a tupple is passed, returns the tupple unmodified """ if not isinstance(input, (tuple, list)): input = (input,) return input
d5b6c69898c583c42dea70ecac56943dee97db92
680,773
def rawformat(x, pos): """ Generic number formatter to help log plot look nice """ if (x < 1000): return '%1.0f' % x if (x < 10000): return '%1.1fK' % (x/1000.0) if (x < 1000000): return '%1.0fK' % (x/1000.0) if (x < 1e9): return '%1.1fM' % (x/1.0e6) if (x < 1e12): return '%1.1fB' % (x/...
f7f91e32b614f910fb2b120df1e74c69e3de5270
680,774
def get_nested_attr(obj, attr, default=None): """Get nested attributes of an object.""" attrs = attr.split(".") for a in attrs: try: obj = getattr(obj, a) except AttributeError: if default: return default else: raise ret...
7f8dc82f6d08a763a0a083967ef524acbba8e983
680,775
import hashlib def validate_proof(previous_proof, proof): """ Validates the new proof. :param int previous_proof: Proof of the previous block :param int proof: Potential proof of the next block :return bool: True if the new proof is valid, False if not """ attempt = f'{previous_proof}{pr...
1c02d5a07bc6476dd2c3a65ff2c4693d3e89d0cf
680,776
def split_barcode(barcode, return_gg=False): """Splits a barcode sequence into part A, part C, and part B sequences.""" split = barcode.split("-") if len(split) == 2: # Remove the gem group from the barcode barcode, gem_group = split else: gem_group = None assert len(barcode)...
44451b5d4f181bc7c0d9e065c9c0d21c3e26854d
680,777
import math def compute_idfs(documents): """ Given a dictionary of `documents` that maps names of documents to a list of words, return a dictionary that maps words to their IDF values. Any word that appears in at least one of the documents should be in the resulting dictionary. """ # Slig...
ea62ca6d00c68c5b1ab7529445ea49952cdefde0
680,780
import csv def _readcsv(file): """Read a CSV file into a multidimensional array of rows and columns.""" rows = [] with open(file, newline='') as csvfile: reader = csv .reader(csvfile, delimiter=',', quotechar='"') headers = next(reader, None) # headers for row in reader: ...
f9248635d9b380e6862715bdde5d2345ecf31e42
680,781
def format_txt_desc(node): """ Formats a XML node into a plain text format. """ desc_buf = '' for desc in node.childNodes: if desc.nodeName == "#text": desc_buf += desc.data + "\n" elif desc.nodeName == "p": desc_buf += desc.firstChild.data + "\n" for chld in desc.childNodes: if chld.nodeName ==...
b5f6050167f9b3df0e7f5aac47b3579fe35192ba
680,785
def sum_attributes(triplet): """ return the sum of the attributes of a triplet ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1))) returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1] """ return [sum(a) for a in zip(*triplet)]
5998240254da5fdeb169e7e9d18f106b13495f4a
680,788
from typing import Union from typing import Iterable from typing import Any def flatten_to_list(obj: Union[Iterable[Any], Any]) -> Union[list[Any], Any]: """ Flattens iterable to a non-nested list Function ignores strings and treats as non-iterable :param obj: iterable of nested iterables :retur...
4240b0399347f4c757301be106b2afdd7237acd0
680,790
def clean_team_name(team_names): """Take a list of team_names, modify the names to match the format specified in br_references, and return a new list Args: team_names: a list of team_names to be checked for validity, and if needed, modified """ new_team_names = [] for team in team_names: ...
792c06197c999e4480f64560500245d4c3b5639c
680,793
from typing import Iterable from typing import Callable def any_matches(iterable: Iterable, cond_fn: Callable = bool) -> bool: """ Returns `True` if `cond_fn` is `True` for one or more elements in `iterable`. Parameters ---------- iterable : Iterable The iterable to be checked con...
902a90388a34330a2c39af35025f8e2c41426deb
680,801
from typing import Set def get_valid_name_permutations(param_name: str) -> Set[str]: """Get all underscore permutations for provided arg name""" return { "_", param_name, f"_{param_name}", f"{param_name}_", }
0cbf5e751307ec24665ec8f0cb9657c6e17b1b75
680,802
def add_arguments(parser, create_group=True): """A helper function to add standard command-line options to make an API instance. This adds the following command-line options: --btn_cache_path: The path to the BTN cache. Args: parser: An argparse.ArgumentParser. create_group: Wh...
a6fb6e5a2b2e4ac9a5d1313da9876722fa026014
680,804
def import_object(module_name, attribute_name): """Import an object from its absolute path. Example: >>> import_object('datetime', 'datetime') <type 'datetime.datetime'> """ module = __import__(module_name, {}, {}, [attribute_name], 0) return getattr(module, attribute_name)
daa127b60089a815f1ac887662755a88e8f54f23
680,805
import re def get_prefix(curie): """Get prefix from CURIE.""" match = re.fullmatch(r'([a-zA-Z.]+):\w+', curie) if match is None: raise ValueError(f'{curie} is not a valid CURIE') return match[1]
84e295bcb764a83cc2fb0432caef220589ab94c9
680,806
def cross(v1, v2): """ Returns the cross product of the given two vectors using the formulaic definition """ i = v1[1] * v2[2] - v2[1] * v1[2] j = v1[0] * v2[2] - v2[0] * v1[2] k = v1[0] * v2[1] - v2[0] * v1[1] return [i, -j, k]
dc74c72b7a36716721b427a08d57d0927a761bc6
680,808
def iterable(item): """If item is iterable, returns item. Otherwise, returns [item]. Useful for guaranteeing a result that can be iterated over. """ try: iter(item) return item except TypeError: return [item]
e9ba90fa3b5818e72d40cb7486ae8c8863e6bd16
680,810
def xy_to_uv76(x, y): # CIE1931 to CIE1976 """ convert CIE1931 xy to CIE1976 u'v' coordinates :param x: x value (CIE1931) :param y: y value (CIE1931) :return: CIE1976 u', v' """ denominator = ((-2 * x) + (12 * y) + 3) if denominator == 0.0: u76, v76 = 0.0, 0.0 else: ...
9aed4b49adc2e6379489009454a642f2a2fdbd92
680,811
def parent(n: int) -> int: """Return the index of the parent of the node with a positive index n.""" return (n - 1) // 2
b2b9451d00124665fd7443b6fe663f24ba6d7fc7
680,812
import collections import itertools def find_repeat(data): """You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice. >>> find_repeat([+1, -1]) 0 >>> find_repeat([+3, +3, +4, -2, -4]) ...
65f46e40d434994f49ab7520ae852de1ca209da6
680,814
def _next_power_of_two(value): """Return the first power of 2 greater than or equal to the input.""" power = 1 while power < value: power *= 2 return power
3b3574e8c5fb5c051dec9d722d02e0e0e5506d09
680,815
import math def Tan(num): """Return the tangent of a value""" return math.tan(float(num))
0c7854800d144d68009ffd7ad7fc51d4b513186d
680,817
def _read_file(path): """Default read() function for use with hash_files().""" with open(path,"rb") as f: return f.read()
c65dfdccdb011d4871e6d2bfaf02164e14d0e828
680,820
def string_is_comment(a_string): """Is it a comment starting with a #.""" return a_string[0] == "#"
b605c73f12d6791fc3d78177805e2bed02aabe20
680,824
def wrap(item): """Wrap a string with `` characters for SQL queries.""" return '`' + str(item) + '`'
bd25264ad8c3ffda41b57ba6b263105e31343b9b
680,826
def recvn(sock, n): """ Read n bytes from a socket Parameters ---------- sock - socket.socket The socket to read from n - int The number of bytes to read """ ret = b'' read_length = 0 while read_length < n: tmp = sock.recv(n - read_length) ...
07e854ea13d2bf0c74dbbea0348bf6ee15ac1a0c
680,830
def is_palindrome(n): """Returns True if integer n is a palindrome, otherwise False""" if str(n) == str(n)[::-1]: return True else: return False
c297288e0af7d458b8c7c4917b1feaa558d760ab
680,832
import textwrap def prepare_description(report): """Constructs a description from a test report.""" raw = report['description'] # Wrap to at most 80 characters. wrapped = textwrap.wrap(raw, 80) description = wrapped[0] if len(wrapped) > 1: # If the text is longer than one line, add a...
999fd532dfc08aa5e9cc0ef240cb47cc0fbc817e
680,833
import torch def select_nms_index(scores: torch.Tensor, boxes: torch.Tensor, nms_index: torch.Tensor, batch_size: int, keep_top_k: int = -1): """Transform NMS output. Args: scores (Tensor): The detection scores of sha...
e7c34d757216f863f0b28fdada43f8f4ef096075
680,836
def dict_from_cursor(cursor): """ Convert all rows from a cursor of results as a list of dicts :param cursor: database results cursor :return: list of dicts containing field_name:value """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for r...
88d640d78c761be8474965f1a6cce8151a2217ef
680,839
def parse_rmc_status(output, lpar_id): """ Parses the output from the get_rmc_status() command to return the RMC state for the given lpar_id. :param output: Output from IVM command from get_rmc_status() :param lpar_id: LPAR ID to find the RMC status of. :returns status: RMC status for the given...
bcb47653045ce6f08e60f70eed02477b4ff27cdc
680,840
def miles_to_kilometers(miles): """Convert miles to kilometers PARAMETERS ---------- miles : float A distance in miles RETURNS ------- distance : float """ # apply formula return miles*1.609344
65700f378a65161266a5229596765a89e6556367
680,841
from pathlib import Path def _get_timestamped_path( parent_path: Path, middle_path, child_path='', timestamp='', create=True, ): """ Creates a path to a directory by the following pattern: parent_path / middle_path / [child_path] / [timestamp] :param parent_pat...
59f39cb79cfc815aaff44db734d9cb0018e12f23
680,845
def node2code(nodes, with_first_prefix=False): """ convert a node or a list of nodes to code str, e.g. " import paddle" -> return "import paddle" " import paddle" -> return "import paddle" """ if not isinstance(nodes, list): nodes = [nodes] code = '' is_first_leaf =...
331570be3a57f0cd3a37a6c68c515a50e9e33c74
680,847
def is_int(int_string: str): """ Checks if string is convertible to int. """ try: int(int_string) return True except ValueError: return False
4d40ee83e4c5869e569226b842188aa152154472
680,848
def _get_course_marketing_url(config, course): """ Get the url for a course if any Args: config (OpenEdxConfiguration): configuration for the openedx backend course (dict): the data for the course Returns: str: The url for the course if any """ for course_run in course....
5a45d320b3805535e3cd6018a987df6d255827b8
680,849
def try_get_value(obj, name, default): """ Try to get a value that may not exist. If `obj.name` doesn't have a value, `default` is returned. """ try: return getattr(obj, name) except LookupError: return default
694180b8aad2bff8288838e1cdab784c0df23864
680,851
def count_null_urls(conn): """ Queries the sqlite3 table unpaywall and finds the number of Nones in pdf_url""" cur = conn.cursor() query = """ SELECT count(*) FROM unpaywall WHERE pdf_url IS NOT NULL """ cur.execute(query) return cur.fetchone()[0]
14d88993e1310eaf0e3a5dc234f48e8f62f41cf3
680,854
def check_win(secret_word, old_letters_guessed): """ this function checks whether the player was able to guess the secret word and thus won the game :param secret_word: the word the player has to guess :param old_letters_guessed: all the characters the player has already guessed :type secret_word:...
007cb0fdfc47011943f4b9cd9bdf69ba785ab51e
680,857
def Axes_Set_Breakaxis(bottom_ax,top_ax,h,v,direction='v'): """ Remove the spines for between the two break axes (either in vertical or horizontal direction) and draw the "small break lines" between them. Parameters: ----------- direction: the direction of the two break axes, could ...
04eab5126aa35a85ead516979738578d8257d24e
680,860
def islistoflists(arg): """Return True if item is a list of lists. """ claim = False if isinstance(arg, list): if isinstance(arg[0], list): claim = True return claim
753162d40c52fb15494c1f097e85d326f30497e3
680,863
def date_to_str(ts): """ Convert timestamps into strings with format '%Y-%m-%d %H:%M:%S'. Parameters ---------- ts : pd.timestamp Timestamp. Returns ------- str Strings with format '%Y-%m-%d %H:%M:%S'. """ return ts.strftime('%Y-%m-%d %H:%M:%S')
95d3ff658068394530790ae6df23759729d2596a
680,867
def list_to_tuple(x): """ Make tuples out of lists and sets to allow hashing """ if isinstance(x, list) or isinstance(x, set): return tuple(x) else: return x
044f94e94fa0220a278bffc0d1a4975fe75be8d5
680,868
import gzip import pickle import logging def load_obj(filename): """ Load saved object from file :param filename: The file to load :return: the loaded object """ try: with gzip.GzipFile(filename, 'rb') as f: return pickle.load(f) except OSError: logging.getLogge...
e7317cde84c88f4e39a57a04ce26c5d04185a33a
680,871
import base64 def b64urlencode(message): """ This function performs url safe base64 encoding. :param message: Message to encode, :return: Encoded string. """ return base64.urlsafe_b64encode(message)
a46a946b18041f6c9d76cb741a7b12bb0ef1b390
680,877
def lesser(tup,value): """ Returns the number of elements in tup strictly less than value Examples: lesser((5, 9, 1, 7), 6) returns 2 lesser((1, 2, 3), -1) returns 0 Parameter tup: the tuple to check Precondition: tup is a non-empty tuple of ints Parameter value: the value to...
199895708250e993b80c63669c3b68806a5aaec1
680,878
def problem_19_1(x, y): """ Write a function to swap a number in place without temporary variables. """ # Bit-wise operations. #x = x ^ y #y = x ^ y #x = x ^ y #return (x, y) # Arithmetic operations. x = x - y y = y + x x = y - x return (x, y)
89902c1210f1b79869eef826cecd89bbba204c69
680,880
def generate_bs_pointers(bs_lengths, bs_size): """ It generates the pointers (i.e. time indexes) of each modified sax word into the original time-series data :param bs_lengths: list of modified sax words :type bs_lengths: list of str :param bs_size: window size (in the original time-series) of a si...
8d4c6b3369d2fcb7bb59ab73b2e75aed8c7f87db
680,884
def upper_first(text: str) -> str: """ Capitalizes the first letter of the text. >>> upper_first(text='some text') 'Some text' >>> upper_first(text='Some text') 'Some text' >>> upper_first(text='') '' >>> upper_first(text='_some text') '_some text' :param text: to be cap...
62670f7348c1384b939f25eec7df5846b0e866f1
680,885
def parse(line): """Parses HH:MM:SS text -> (time,text)""" parts = line.strip().split(" ") return (parts[0], " ".join(parts[1:]) )
c57e1d06a702e5933610d321c13681343fe05d85
680,888
def last(mention): """ Compute the last token of a mention. Args: mention (Mention): A mention. Returns: The tuple ('last', TOKEN), where TOKEN is the (lowercased) last token of the mention. """ return "last", mention.attributes["tokens"][-1].lower()
0b252eb5a9b84806828e1866eb52b7a3381bf0ad
680,890
from typing import Any from typing import Iterable def elem(n: Any, it: Iterable[Any]) -> bool: """ Determine if iterable object contains the given element Args: n: Value to validate it: Iterable object Examples: >>> fpsm.elem(2, range(10)) True >>> fpsm.elem(...
595ce3e21bf5a6cf2c77d1417404950de6fc845f
680,891
def to_camel(string): """Convert a snake_case string to CamelCase""" return "".join(word.capitalize() for word in string.split("_"))
2962e613dbe018148126fa69649d8a9a18150081
680,892
def get_temperature_number(temp_str): """ Given a temperature string of the form "48.8 ยฐC", return the first number (in this example, 48). Also handles strings of the form "48,8 ร‚ยฐC" that apparently can exist (at least when reading the response from a file) :param temp_str: Temperature string ...
30b9985a1d2ff4471ad4286903b035f2d1c6d589
680,895
import re def squish(text): """Turn any run of whitespace into one space.""" return re.sub(r"\s+", " ", text)
631cdf496e95cab9062156de4fcd7bf353844a50
680,900
def compute_union_of_regions( regions ): """Compute a non-overlapping set of regions covering the same position as the input regions. Input is a list of lists or tuples [ [a1,b1], ... ] Output is a similar list. All regions are assumed to be closed i.e. to contain their endpoints""" result = [] reg...
6a5efa05a29bc9455eef8e3062c1f242262c55bc
680,902
def get_grid_coupling_list(width, height, directed=True): """Returns a coupling list for nearest neighbor (rectilinear grid) architecture. Qubits are numbered in row-major order with 0 at the top left and (width*height - 1) at the bottom right. If directed is True, the coupling list includes both [a, b...
1a34f1ea643561126073992f583fc0aee6dc902e
680,903
from datetime import datetime def get_month_number(month): """ Get the month in numeric format or 'all' Parameters ---------- month : int or str Returns ------- n_month : int or 'all' Month in numeric format, or string 'all' """ if isinstance(month, str): if ...
f3741dc80914609666da7b123109900e1ed0f11a
680,904
def name_matches(texnode, names): """ Returns True if `texnode`'s name is on one of the names in `names`. """ if hasattr(texnode, 'name') and texnode.name in names: return True else: return False
554a24d05cc6ef93645ef6877bcae2e671cd1bed
680,906
async def absent( hub, ctx, name, zone_name, resource_group, record_type, connection_auth=None, **kwargs, ): """ .. versionadded:: 1.0.0 Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name ...
3aa18778b0fa46a393d31bedae89a1ff3f2b16c2
680,908
import socket import errno def check_port_is_available(host, port): """Check if a given port it's available Parameters ---------- host : str port : int Returns ------- available : bool """ available = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: ...
14e120a38d70f9b7471c94f46743400b93eda8f8
680,909
def get_list_index(str_list, selection): """ Gets the index of the string in a list of strings. This is case case insensitive and returns the index of the default string. It removes any EOL in the strings. Parameters: str_list(list of (:term:`String`)) selection (:term:`String`):...
5b2974efb0bed3c43251b7fa727fe48d39146115
680,912
import re def _clean_maxspeed(value, convert_mph=True): """ Clean a maxspeed string and convert mph to kph if necessary. Parameters ---------- value : string an OSM way maxspeed value convert_mph : bool if True, convert mph to kph Returns ------- value_clean : str...
49cf4a46d1be664c51c6eaa6734b919f649dad93
680,916
def equalContents(arr1, arr2) -> bool: """ Checks if the set of unique elements of arr1 and arr2 are equivalent. """ return frozenset(arr1) == frozenset(arr2)
cb27f12e8a16f47f78b754bf797e247b604d5990
680,917
def colorbar_extension(colour_min, colour_max, data_min, data_max): """ For the range specified by `colour_min' to `colour_max', return whether the data range specified by `data_min' and `data_max' is inside, outside or partially overlapping. This allows you to automatically set the `extend' keyword on ...
517c71e7d0cd1792e48d87e2275a82f129d51fca
680,918
def publish_changes(isamAppliance, check_mode=False, force=False): """ Publish configuration changes """ if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_put("Publishing configuration changes", "/docker/publish", {})
6d7d5efcd1930ad365617bed36d64e4e2aa2b326
680,921
def toposort(graph, start): """Standard topological sort of graph from start nodes. Vertices are represented by integer ids. Args: graph: graph represented by dictionary keyed by vertex id, each value being a list of the connected vertex ids. start: list of starting vertices' ids for initializing ...
97c0c8fab6ad5c2c5a8f71f41bf756fe02093021
680,929
from typing import Tuple from typing import List import csv import json def load_tsv_data(path: str) -> Tuple[List[str], List[List[str]], List[str]]: """Load arbitrary tsv file of formed like (id, dialogue, summary) with header each `dialogue` should be dumped json string from a list of utterances. ex) '[...
81cbd1d150311d832bea0d498faf1b339cb564f6
680,933
def search(lst: list, target: int): """search the element in list and return index of all the occurances Args: lst (list): List of elements target (int): Element to find Returns: list: list of index. """ left = 0 right = len(lst) - 1 mid = 0 index = [] whi...
9b01c88d55eebcd0dc77581365a8794b498cc511
680,937
def make_reverse_dict(in_dict, warn=True): """ Build a reverse dictionary from a cluster dictionary Parameters ---------- in_dict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. Returns ------- ou...
7126107779524026f3bf04ec37235413984ea583
680,941
def sum_total_emissions(emissions, areas, mask): """ Function to sum total emissions across the region of interest. Arguments: emissions : xarray data array for emissions across inversion domain areas : xarray data array for grid-cell areas across inversion domain mask : xa...
e4c0d1b75216ffe8efab275b780268863e6cdd76
680,942
def upper_power_of_two(value) -> int: """Returns the value of 2 raised to some power which is the smallest such value that is just >= *value*.""" result = 1 while result < value: result <<= 1 return result
592bf0c6dbdf87916dfb1abc9b0a84c1bb27a79b
680,944
from datetime import datetime def log(message, when=None): """ Log a message with a timestamp. :param message: Message to print. :param when: datetime of when the message occured. Defaults to the present time. :return: """ when = datetime.now() if when is None else when ...
81cd215cc94673bd4669026ebe160a9c12e33fa1
680,946
def tkeo(x): """Calculate the TKEO of a given recording by using 2 samples. github.com/lvanderlinden/OnsetDetective/blob/master/OnsetDetective/tkeo.py Parameters ---------- x : array_like Row vector of data. Returns ------- a_tkeo : array_like Row vector containing the...
b32e4f6e004f144fd70ffecc4b424360f5f20492
680,951
def _get_winner(sgf_game): """Reads the games winner from an sgf. Args: sgf_game: from bytes parsed sgf Returns: 1 if BLACK won -1 if WHITE won 0 if it was a DRAW """ sgf_winner = sgf_game.get_winner() if sgf_winner == 'b': winner = 1 elif sgf_winner =...
5597e3ac26eb6bd4b8fdf3e2a1fb080f5f8b9ae0
680,952
def GetPlatformArchiveName(platform): """Get the basename of an archive given a platform string. Args: platform: One of ('win', 'mac', 'linux'). Returns: The basename of the sdk archive for that platform. """ return 'naclsdk_%s.tar.bz2' % platform
a5da4972c532dac98486cee6e29400858127f6db
680,955
def featurewise_norm(x, mean=None, std=None, epsilon=1e-7): """Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value ...
d1fe5e58efc60bf0dd755e402ddf0368c0743b4c
680,959
def shapestring(array): """Returns a compact string describing shape of an array.""" shape = array.shape s = str(shape[0]) for i in range(1, len(shape)): s += 'x' + str(shape[i]) return s
21572d955b1520239c4b6d4a236a56578f42f426
680,962
def waypoint_menu(waypoints_exist): """asks what to do with waypoints""" print("\nWas moechtest du als naechstes tun?") print("1: Wegpunkte hinzufuegen") if waypoints_exist: print("2: Wegpunkte zu Geocaches zuordnen oder loeschen") print("3: nichts") else: print("2: nichts")...
775650c4039c04b92b46d47d13b88302fa609a3d
680,963
import copy def clone_processor(p): """ Create a new processor with the same properties as the original Recursive copy child processors :param p: :return: """ return copy.deepcopy(p)
5b1178584d2e64a57d84035d4de67173bdc2aa60
680,964
def binary_search(sorted_list, target): """Find where a number lies in a sorted list. Return lowest item that is greater than or equal to target, or None if no item in list greater than or equal to target """ if sorted_list==[]: return None if len(sorted_list)==1: if target <= so...
c90302825dcb5b2e6989b261357e7362ccd175be
680,966
def findpeptide(pep, seq, returnEnd = False): """Find pep in seq ignoring gaps but returning a start position that counts gaps pep must match seq exactly (otherwise you should be using pairwise alignment) Parameters ---------- pep : str Peptide to be found in seq. seq : str Sequ...
3af5afa60fd29f28fd5d3d7ebfbd727c60db3948
680,968
import re def research(needle, haystack, result): """ Look for rgx *needle* in str *haystack*. Put any match in result. If a match was found, return True, else return False. Note that result must be a list. """ found = re.findall(needle, haystack) if found: result.append(found[0]) ...
06abf1d234c598eddab450b4d780f8f9a11794c1
680,969
def bisect_right(a, x, lo=0, hi=None, *, key=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will insert just after the right...
780780f7d444eca6067e82d4c2534b83336ff806
680,974
import ast def check_return(node): """ Returns `False` if `ast.Return` only appears at the end of `ast.FunctionDef`. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_Return(self, node): self.found ...
3ef86b9a88c04c78738606215df55f411bfd46c7
680,977
def ndvi( redchan, nirchan ): """ Normalized Difference Vegetation Index ndvi( redchan, nirchan ) """ redchan = 1.0*redchan nirchan = 1.0*nirchan if( ( nirchan + redchan ) == 0.0 ): result = -1.0 else: result = ( nirchan - redchan ) / ( nirchan + redchan ) return result
ca35eb06a9f38eb2052af0cc1b0e33e753992729
680,980
import json def getDefaultColumnsForScope(syn, scope): """ Fetches the columns which would be used in the creation of a file view with the given scope. Parameters ---------- syn : synapseclient.Synapse scope : str, list The Synapse IDs of the entites to fetch columns for. Returns...
55f3a4d13f9cc88d11f1cce2e157f0d88600803d
680,984
def bootstrap_field(field, param1=''): """Take a FormField and produce nice HTML for its label, input, etc.""" value = '' if hasattr(field.form, 'cleaned_data'): value = field.form.cleaned_data.get(field.name, '') return { 'field': field, 'type': field.__class__.__name__, 'value': value, 'param1': param1...
d78ef588613862c0e760cbb73cbc02d2070ef1fc
680,986
import requests def icmp_echo(baseurl, host, cookie_header): """ Test IP connectivity to a given host :param baseurl: Imported from yaml :param host: IP address of destination :param cookie_header: Object created by loginOS.login_os() :return: REST call response JSON """ url = baseurl ...
2a2489931fb01d6a32c2bfb64c7df094fe424ada
680,990