content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_glyph_horizontal_advance(font, glyph_id): """Returns the horiz advance of the glyph id.""" hmtx_table = font['hmtx'].metrics adv, lsb = hmtx_table[glyph_id] return adv
75af73d3dd824391c9058d501fa0883ebdce8bcf
24,177
def _is_array(data): """Return True if object implements all necessary attributes to be used as a numpy array. :param object data: Array-like object (numpy array, h5py dataset...) :return: boolean """ # add more required attribute if necessary for attr in ("shape", "dtype"): if not hasattr(data, attr): return False return True
72e8225d9fa74ac31f264d99764d94c62013cb06
24,185
from typing import Iterator def deepmap(func, *seqs): """ Apply function inside nested lists >>> inc = lambda x: x + 1 >>> deepmap(inc, [[1, 2], [3, 4]]) [[2, 3], [4, 5]] >>> add = lambda x, y: x + y >>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]]) [[11, 22], [33, 44]] """ if isinstance(seqs[0], (list, Iterator)): return [deepmap(func, *items) for items in zip(*seqs)] else: return func(*seqs)
4a3ee7d15b150cc3cbf1ee22b254c224783ecece
24,187
import logging def get(name=""): """ Get the specified logger :param name: the name of the logger :return: the logger """ return logging.getLogger(f"wafflebot{'.' + name if name else ''}")
8102a2f55d4b9badf290fec68d63e11434bcd45d
24,191
def success_response(data): """ When an API call is successful, the function is used as a simple envelope for the results, using the data key, as in the following: { status : "success", data : { "posts" : [ { "id" : 1, "title" : "A blog post", "body" : "Some useful content" }, { "id" : 2, "title" : "Another blog post", "body" : "More content" }, ] } required keys: status: Should always be set to "success data: Acts as the wrapper for any data returned by the API call. If the call returns no data (as in the last example), data should be set to null. """ return {'status': 'success','data': data}
26ca231fcb9e0204c80307b7eebf03b434faca70
24,201
def solve(n, ar): """ Given an integer array ar of size n, return the decimal fraction of the number of positive numbers, negative numbers and zeroes. Test cases are scaled to 6 decimal places. """ num_pos = 0 num_neg = 0 num_zero = 0 for i in ar: if i > 0: num_pos += 1 elif i < 0: num_neg += 1 else: num_zero += 1 # Return the ratios but cast to float to ensure preservation of precision. return (float(num_pos) / float(n), float(num_neg) / float(n), float(num_zero) / float(n))
b61b179c357dcf70ac887af20588324624a84ea3
24,202
def create_phone_number_v2(n): """ Turns an array of integers into phone number form. :param n: an array of integers. :return: numbers in phone number form. """ return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
659daecdbb8a0e8a1f02826c35fc26eadef14598
24,205
def isInSequence(word): """ Checks if the string passed is a sequence of digits logically connected ("e.g. 369") """ if len(word)<3: return False else: increment = int(word[0]) - int(word[1]) for i in range(len(word) - 2): if int(word[i+1]) - int(word[i+2]) != increment: return False return True
d4749bc5cd656ec2fd2886743ad1848062d3e1db
24,206
def get_file_id(string): """ Returns file_id from a information string like Ferrybox CMEMS: <file_id> :param string: :return: """ return string.split(':')[-1].strip()
a5e58147e4a6e08298ecb6cd34614cff99e7bdac
24,209
from datetime import datetime import calendar def month_bounds(date=None): """ Return month start and end datetimes """ if date is None: date=datetime.now() firstday,lastday=calendar.monthrange(date.year,date.month) start=datetime(date.year,date.month,firstday,0,0,0) end=datetime(date.year,date.month,lastday,23,59,59) return (start,end)
f007bbea414f4ea5756c22ba9228ff74e93a5a09
24,212
import re def enum_calculate_value_string(enum_value): """ Calculate the value of the enum, even if it does not have one explicitly defined. This looks back for the first enum value that has a predefined value and then applies addition until we get the right value, using C-enum semantics. Args: enum_value: an EnumValue node with a valid Enum parent Example: <enum> <value>X</value> <value id="5">Y</value> <value>Z</value> </enum> enum_calculate_value_string(X) == '0' enum_calculate_Value_string(Y) == '5' enum_calculate_value_string(Z) == '6' Returns: String that represents the enum value as an integer literal. """ enum_value_siblings = list(enum_value.parent.values) this_index = enum_value_siblings.index(enum_value) def is_hex_string(instr): return bool(re.match('0x[a-f0-9]+$', instr, re.IGNORECASE)) base_value = 0 base_offset = 0 emit_as_hex = False this_id = enum_value_siblings[this_index].id while this_index != 0 and not this_id: this_index -= 1 base_offset += 1 this_id = enum_value_siblings[this_index].id if this_id: base_value = int(this_id, 0) # guess base emit_as_hex = is_hex_string(this_id) if emit_as_hex: return "0x%X" %(base_value + base_offset) else: return "%d" %(base_value + base_offset)
b6df34ea221cd485f1ca730192bc1fda3fa34a98
24,221
def _is_gs_offloader(proc): """Return whether proc is a gs_offloader process.""" cmdline = proc.cmdline() return (len(cmdline) >= 2 and cmdline[0].endswith('python') and cmdline[1].endswith('gs_offloader.py'))
d8a8bd1ec03bcdef05b683e2e7cb88b4521de0ab
24,225
def drop_features(df, to_drop): """Drop unwanted features Parameters ---------- df : panda dataframe to_drop : array with name of features to be dropped Returns ------- Original dataframe with all original features but those in to_drop """ return df.drop(to_drop, axis=1)
30d6c270a7c4ac2c63a9472362b844a11eb5c119
24,232
def first(collection, callback): """ Find the first item in collection that, when passed to callback, returns True. Returns None if no such item is found. """ return next((item for item in collection if callback(item)), None)
ebecfb1b4264a17dc24c4aeedb8c987e9ddde680
24,235
import re def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" # Note that we cannot use cgi.escape() here since it is not supported by # Python 3. s = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;') # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x80-\xff]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s
d64a0c51d79f2384fd14dae8c46ef26fc49c888c
24,240
def deg_to_arcmin(angle: float) -> float: """ Convert degrees to arcminutes. Args: angle: Angle in units of degrees. Returns: Angle in units of arcminutes. """ return float(angle) * 60.
2c075362f4163cb70587eb9fac69ef669c337e2d
24,241
def _get_datetime_beginning_of_day(dt): """ Truncates hours, minutes, seconds, and microseconds to zero on given datetime. """ return dt.replace(hour=0, minute=0, second=0, microsecond=0)
12ddcaed68db08740e4edc851a299aa08c23f91c
24,243
def ordinal(n): """Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc. :param int n: the index to be translated. :return: (*str*) -- Ordinal. """ ord_dict = {1: "st", 2: "nd", 3: "rd"} return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, "th")
e6b8583bfb9fbb8a2b2443bc5fad233b1f7a9038
24,247
def bresenham(p0, p1): """ Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it uses only integer addition, subtraction and bit shifting, all of which are very cheap operations in standard computer architectures. Args: p0 (np.array): Starting point (x, y) p1 (np.array): End point (x, y) Returns: A list of (x, y) intermediate points from p0 to p1. """ x0, y0 = p0 x1, y1 = p1 dx = abs(x1 - x0) dy = abs(y1 - y0) sx = 1.0 if x0 < x1 else -1.0 sy = 1.0 if y0 < y1 else -1.0 err = dx - dy line = [] while True: line.append([x0, y0]) if x0 == x1 and y0 == y1: return line e2 = 2 * err if e2 > -dy: # overshot in the y direction err = err - dy x0 = x0 + sx if e2 < dx: # overshot in the x direction err = err + dx y0 = y0 + sy
8948059454213c35b11917ac02a846d1d22e26e3
24,248
def c_git_commit_handler(value, **kwargs): """ Return a git VCS URL from a package commit. """ return {f'vcs_url': f'git+http://git.alpinelinux.org/aports/commit/?id={value}'}
e9036241be3816a0296caf895a9b323cb297f35a
24,251
def psi_ising(x_1,x_2,alpha): """ Ising potential function :param float x_1: first argument of the potential, eventually ndarray. :param float x_2: second argument, eventually ndarray of the same size that x_1. :param float alpha: granularity parameter :returns: **res** *(ndarray)* - output of the potential, eventually ndarray. """ res = alpha * (1.-2.*(x_2==x_1)) return res
071d6256f400b836c392eef739e60a9e1eb4cbbe
24,253
def map_obj_to_string(obj): """ Function to create a string version from an object. Parameters ---------- obj Some python object Returns ------- str_version Examples -------- >>> map_obj_to_string(1) "1" >>> map_obj_to_string("1") "1" >>> map_obj_to_string([1,"2"]) ["1", "2"] >>> map_obj_to_string(("1", 2)) ("1", "2") >>> map_obj_to_string({"a" : 1, "b" : "2"}) {"a" : "1", "b" : "2"} """ if isinstance(obj, list): rv = list(map_obj_to_string(i) for i in obj) elif isinstance(obj, tuple): rv = tuple(map_obj_to_string(i) for i in obj) elif isinstance(obj, dict): rv = dict((k,map_obj_to_string(v)) for k, v in obj.items()) else: rv = str(obj) return rv
913e2c99021976a745fcf5ede5c224060defabc1
24,256
def clear_grid(ax, pos=["x","y"]): """Clear a grid Args: ax (Axes) : The ``Axes`` instance. pos (list) : Positions to clean a grid Examples: >>> from pyutils.matplotlib import clear_grid, FigAxes_create >>> fig,ax = FigAxes_create(nplots=1)[0] >>> ax = clear_grid(ax=ax, pos=["x", "y"]) >>> ax = clear_grid(ax=ax, pos=list("ltrb")) """ if isinstance(pos, str): pos = [pos] for p in pos: if p in ["x", "b", "bottom"]: ax.tick_params(labelbottom=False, bottom=False) ax.set_xticklabels([]) elif p in ["y", "l", "left"]: ax.tick_params(labelleft=False, left=False) ax.set_yticklabels([]) elif p in ["r", "right"]: ax.tick_params(labelright=False, right=False) elif p in ["t", "top"]: ax.tick_params(labeltop=False, top=False) elif p == "all": ax.set_axis_off() return ax
1f5a148f2e8c885735aaef0c676355299f1a21a4
24,261
def queenCanTattack(board, size, row, column): """Check if the new queen will not be able to attack an other one. Args: board (array): board on which the queen will be size (int): size of the board row (int): row position on the board column (int): column position on the board Returns: [boolean]: True, if unable to attack """ can_t_attack = True # check cardinals for idx_row in range(size): if idx_row != row and board[idx_row][column] == 1: return not can_t_attack for idx_column in range(size): if idx_column != column and board[row][idx_column] == 1: return not can_t_attack # check diagonals for idx_row, idx_column in zip(range(row - 1, -1, -1), range(column + 1, size)): if board[idx_row][idx_column] == 1: return not can_t_attack for idx_row, idx_column in zip(range(row + 1, size), range(column + 1, size)): if board[idx_row][idx_column] == 1: return not can_t_attack for idx_row, idx_column in zip(range(row - 1, -1, -1), range(column - 1, -1, -1)): if board[idx_row][idx_column] == 1: return not can_t_attack for idx_row, idx_column in zip(range(row + 1, size), range(column - 1, -1, -1)): if board[idx_row][idx_column] == 1: return not can_t_attack return can_t_attack
b06c60b797c928caf1fed405f820e8b45a2a61f0
24,262
def xor(bytes_1: bytes, bytes_2: bytes) -> bytes: """ Return the exclusive-or of two 32-byte strings. """ return bytes(a ^ b for a, b in zip(bytes_1, bytes_2))
1f9eb00848ab963536c01d0c0321321f0c3be887
24,265
def residual_variance(y_true, y_pred): """ Manual calculation of residual variance. It is obtained calculating the square error for every entry of every point, summarizing all of them and then dividing the sum for n-2, where n is the length of the array. Please refer to this specification: https://www.coursera.org/lecture/regression-models/residual-variance-WMAET :param y_true: ground truth :param y_pred: the estimated y :return: float, residual variance of our model """ sum = 0 for idx, value in enumerate(y_true): sum += (value - y_pred[idx]) ** 2 return float(sum / len(y_true))
013f2b0d220ce3bd4e26c506302d4a843f8fdd95
24,266
from typing import Callable from typing import Any from typing import Sequence from typing import Tuple from typing import Optional def _find_last(condition: Callable[[Any], bool], sequence: Sequence) -> Tuple[Optional[int], Any]: """条件に合う要素をシーケンスの末尾から順に探す。 複数存在する場合、もっとも index が大きいものが返される。 Args: condition: 条件 sequence: 要素を探すシーケンス Returns: 要素が見つかればその index と 要素。見つからなければ None と None。 """ target_list = tuple(sequence) for i in reversed(range(len(target_list))): if condition(target_list[i]): return i, target_list[i] return None, None
362575e13e1f0a64560b4c29cf4e97fbff8a248b
24,267
def _defaultHeaders(token): """Default headers for GET or POST requests. :param token: token string.""" return {'Accept': '*/*', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token}
33125604bcb3c7af3d71ae2c7c21f0dd82d141ac
24,270
def load_pizza_data(source): """ This function loads a text file as dataset from a source path. The data structure is supposed to be like: <15 4 2 3 5 6> Parameters ---------- source : String Global path to text file to be loaded. Returns ------- participants : int Number of people to be ordered for. n_types : int Number of pizza types available. n_type_slices : list[int] Number of slices per pizza type. """ print('Load data: {}'.format(source)) with open(source, 'r') as file: content = file.read().splitlines() # Read first line line = content[0].split(' ') participants = int(line[0]) n_types = int(line[1]) # Read second line line = content[-1].split(' ') n_type_slices = [int(val) for val in line] # Check validity of input file if len(n_type_slices) != n_types: raise ValueError('Input file corrupted!') return participants, n_types, n_type_slices
e032619dc01e021f06a9c4eafe2e9f9353bbb66b
24,277
def russian(a, b): """ The Russian Peasant Algorithm: Multiply one integer by the other integer. Input: a, b: integers Returns: a*b """ c = 0 while a > 0: if a % 2 == 1: c = c + b b = b << 1 a = a >> 1 return c
1ef601dbeced430ca7d09093ad7338319bb128d4
24,278
def service(app): """Vocabularies service object.""" return app.extensions['invenio-vocabularies'].service
d440e300581fdf71a2f36c8f00c6f0e163f646f0
24,284
import time def _get_event_file_active_filter(flags): """Returns a predicate for whether an event file load timestamp is active. Returns: A predicate function accepting a single UNIX timestamp float argument, or None if multi-file loading is not enabled. """ if not flags.reload_multifile: return None inactive_secs = flags.reload_multifile_inactive_secs if inactive_secs == 0: return None if inactive_secs < 0: return lambda timestamp: True return lambda timestamp: timestamp + inactive_secs >= time.time()
6d8faeac218293643f0df9d9ffe198d24323ba52
24,285
def rightRow(r, c): """ >>> rightRow(5, 4) [(5, 4), (5, 5), (5, 6), (5, 7), (5, 8)] """ x = [r, ] * (9-c) y = range(c, 9) return zip(x, y)
476ad7f757162c0bd70c41f33564ee8ddf307547
24,288
def get_uuids(things): """ Return an iterable of the 'uuid' attribute values of the things. The things can be anything with a 'uuid' attribute. """ return [thing.uuid for thing in things]
c71a659c96ea0bd7dbb22a92ccca46e29fa072b8
24,295
def all_black_colors(N): """ Generate all black colors """ black = [(0, 0, 0) for i in range(N)] return black
191a6211caa58b88c62fb327b18d8eef023b74c4
24,301
def growTracked(mesh, growSet, allSet): """ Grow a set of verts along edges and faces This function takes a set of vertices and returns two dicts. One that is vert:(edgeAdjVerts..), and another that is vert:(faceAdjVerts..) While I'm growing a vert, if all vertices adjacent to that vert are matched, then I no longer need to grow from there. Args: growSet: A set of Vertex objects to grow. This set will have all useless verts removed and will be changed in-place. allSet: A set of Vertex objects to exclude from the growth Returns: edgeDict: A dictionary with verts as keys and all edge adjacent vertices as the value faceDict: A dictionary with verts as keys and all face adjacent vertices as the value newGrowSet: The original growSet with all used-up vertices removed """ edgeDict = {} faceDict = {} # Verts that are grown, but have no adjacent verts # that aren't in the allSet rem = [] for vert in growSet: edgeFound = False faceFound = False for eadj in mesh.adjacentVertsByEdge(vert): if eadj not in allSet: edgeFound = True edgeDict.setdefault(eadj, []).append(vert) for fadj in mesh.adjacentVertsByFace(vert): if fadj not in allSet: faceFound = True faceDict.setdefault(fadj, []).append(vert) if not edgeFound and not faceFound: rem.append(vert) newGrowSet = growSet - set(rem) return edgeDict, faceDict, newGrowSet
8930e0b5579ce9a009d71340aeed7366184189dc
24,302
import hashlib def generate_aes_key(token, secret): """ Generates and returns a 256 bit AES key, based on sha256 hash. """ return hashlib.sha256(token + secret).digest()
f058402ad893c614c9cde8e9c96a2fdb2ff9ea95
24,312
def is_identical_typedateowner(ev1, ev2): """Check if two events are identical in type, date, and owner. Args: ev1: roxar event ev2: roxar event Returns: True if the two events are identical in type, date, and owner; otherwise False. """ ident = False if ev1.type == ev2.type: if ev1.date == ev2.date: if ev1.owner == ev2.owner: ident = True return ident
13490e918abd38161324836dbe002cee552b86b2
24,327
def get_ele_list_from_struct(struct): """ Get elements list from pymatgen structure objective Parameters ---------- struct : pymatgen objective The structure Returns ------- ele_list : [str] The list of elements """ ele_list = [] for ele in struct.species: ele_list.append(str(ele)) return ele_list
4a6fa05518ff0725d85b270b8d8b0003eb139e5e
24,328
from typing import Dict from typing import List def convert_by_vocab(vocab: Dict, items: List) -> List: """Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output
440f1936baafae06a4a38c205e877e71a7ed37e9
24,337
def get_iou_th_min_th_dila_from_name(folder, mode='str'): """ This function gets the iou_th, min_th and dila values from the folder name :param: folder: The folder name of interest for extraction :param: mode: The format of extraction, currently support either 'str' or 'num' """ iou_th = folder[folder.find('iou_th_')+7:].split('_')[0] min_th = folder[folder.find('min_th_')+7:].split('_')[0] dila = folder[folder.find('dila_')+5:].split('_')[0] if mode is not 'num' and mode is not 'str': exit('Your mode in get_iout_min_th_dila_from_name should be either str or num!! reset the argument pls!') if mode is 'num': return float(iou_th), int(min_th), int(dila) return iou_th, min_th, dila
8dfa3b3b58dc15f72ccb51cd7076c4bc9bd9cf9f
24,338
from typing import OrderedDict def extractKeyIndexTimeValue(dic={0 : 0}, frameRange=(0, 30), **kwargs): """this is extract animCurve's time and value in any frame range. Parameters ---------- dic : dict(in int or float) key = time, value = value. frameRange : tupple(in int or float) input spicifid range of frameRange. Returns ------- dict ectracted keyframe has index, time and value dictonary. """ range_idtv = OrderedDict() st, end = frameRange idx = 0 for t, v in dic.items(): if st <= t and t <= end : range_idtv[idx] = { t : v } idx += 1 return range_idtv
27cca6ffe38026a4d4b9b5fc732e7c2aa9347e6d
24,340
def print_matrix(m, rownames, colnames): """Pretty-print a 2d numpy array with row and column names.""" # Max column width: col_width = max([len(x) for x in rownames + colnames]) + 4 # Row-formatter: def fmt_row(a): return "".join(map((lambda x : str(x).rjust(col_width)), a)) # Printing: print(fmt_row([''] + colnames)) for i, rowname in enumerate(rownames): row = [rowname] for j in range(len(colnames)): row.append(round(m[i, j], 2)) print(fmt_row(row))
83b9f6ca8a2683398344c57c0bbd509a776cffa3
24,355
def settingsLink(translator, settings, tag): """ Render the URL of the settings page. """ return tag[translator.linkTo(settings.storeID)]
413e2ec27a27e77b1850f47f20af45ddbb8d4f6f
24,356
import tarfile from typing import Optional def _cache_filter(tar_info: tarfile.TarInfo) -> Optional[tarfile.TarInfo]: """ Filter for ``tarfile.TarFile.add`` which removes Python and pytest cache files. """ if '__pycache__' in tar_info.name: return None if tar_info.name.endswith('.pyc'): return None return tar_info
5dd54cc8c2532cc89bcf2e357803e9036ce18322
24,357
import base64 def b64_decode(s): """ Decode input string with base64url safe without padding scheme. """ mod = len(s) % 4 if mod >= 2: s += (4 - mod) * "=" return base64.urlsafe_b64decode(s)
e82a6cbffe30b9a27bdd0a58c7f7bf11cc4066f4
24,359
def _cast_types(args): """ This method performs casting to all types of inputs passed via cmd. :param args: argparse.ArgumentParser object. :return: argparse.ArgumentParser object. """ args.x_val = None if args.x_val == 'None' else int(args.x_val) args.test_size = float(args.test_size) args.max_depth = int(args.max_depth) args.learning_rate = float(args.learning_rate) args.n_estimators = int(args.n_estimators) args.verbosity = int(args.verbosity) # objective. # booster. # tree_method. args.n_jobs = int(args.n_jobs) args.gamma = float(args.gamma) args.min_child_weight = int(args.min_child_weight) args.max_delta_step = int(args.max_delta_step) args.subsample = int(args.subsample) args.colsample_bytree = float(args.colsample_bytree) args.colsample_bylevel = float(args.colsample_bylevel) args.colsample_bynode = float(args.colsample_bynode) args.reg_alpha = float(args.reg_alpha) args.reg_lambda = float(args.reg_lambda) args.scale_pos_weight = float(args.scale_pos_weight) args.base_score = float(args.base_score) args.random_state = int(args.random_state) args.missing = None if args.missing == 'None' else float(args.missing) return args
5db5f9569849a868bc180e38bd9bcec618b7cb5d
24,360
def rgb_to_hsv(rgb): """ Convert an RGB color representation to an HSV color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: HSV representation of the input RGB value. :rtype: tuple """ r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255 _min = min(r, g, b) _max = max(r, g, b) v = _max delta = _max - _min if _max == 0: return 0, 0, v s = delta / _max if delta == 0: delta = 1 if r == _max: h = 60 * (((g - b) / delta) % 6) elif g == _max: h = 60 * (((b - r) / delta) + 2) else: h = 60 * (((r - g) / delta) + 4) return round(h, 3), round(s, 3), round(v, 3)
aa2c75b92c9830c7e798b0ca6ee9feac20793de4
24,361
import logging import re def get_landsat_angles(productdir): """ Get Landsat angle bands file path. Parameters: productdir (str): path to directory containing angle bands. Returns: sz_path, sa_path, vz_path, va_path: file paths to solar zenith, solar azimuth, view (sensor) zenith and vier (sensor) azimuth. """ img_list = list(productdir.glob('**/*.tif')) logging.info('Load Landsat Angles') pattern = re.compile('.*_solar_zenith_.*') sz_path = list(item for item in img_list if pattern.match(str(item)))[0] pattern = re.compile('.*_solar_azimuth_.*') sa_path = list(item for item in img_list if pattern.match(str(item)))[0] pattern = re.compile('.*_sensor_zenith_.*') vz_path = list(item for item in img_list if pattern.match(str(item)))[0] pattern = re.compile('.*_sensor_azimuth_.*') va_path = list(item for item in img_list if pattern.match(str(item)))[0] return sz_path, sa_path, vz_path, va_path
8b22cb6fc1ea8ae3f3869664aff2f165c418f20c
24,364
import time def roundtime(seconds, rounding=None): """ Round the provided time and return it. `seconds`: time in seconds. `rounding`: None, 'floor' or 'ceil'. """ Y, M, D, h, m, s, wd, jd, dst = time.localtime(seconds) hms = {None: (h, m, s), 'floor': (0, 0, 0), 'ceil': (23, 59, 59)} h, m, s = hms[rounding] seconds_rounded = time.mktime((Y, M, D, h, m, s, wd, jd, dst)) return seconds_rounded
8cbbc0c8e684e8ea6d1f58e8f9ffc2a40e185b06
24,368
def envelope_to_geom(env): """convert envelope array to geojson """ geom = { "type": "Polygon", "coordinates": [ [ env[0], env[1], env[2], env[3], env[0] ] ] } return geom
550765136207b898bac9202847fe8b239a91a20d
24,372
def is_json_object(json_data): """Check if the JSON data are an object.""" return isinstance(json_data, dict)
7b72fc51752f9cfd00ba4815230401f1d40e888f
24,373
import typing def naive_ctz2(x: int) -> typing.Tuple[int, int]: """Count trailing zeros, naively. Args: x: An int. Returns: A tuple (zeros, x >> zeros) where zeros is the number of trailing zeros in x. I.e. (x >> zeros) & 1 == 1 or x == zeros == 0. This is a slow reference implementation for checking correctness. Since it never needs to check the bit_length of x or do any multiplication, it may be acceptably fast for numbers that have a very small number of trailing zeros. As it inherently tracks the remaining significant bits of x, this implementation returns them as well as the number of zeros, hence its name "ctz2". >>> naive_ctz2(0) (0, 0) >>> naive_ctz2(1) (0, 1) >>> naive_ctz2(-1) (0, -1) >>> naive_ctz2(2) (1, 1) >>> naive_ctz2(-2) (1, -1) >>> naive_ctz2(40) # 0b101000 = 2**3 * 5 (3, 5) >>> naive_ctz2(-40) # 0b1..1011000 (3, -5) >>> naive_ctz2(37 << 100) (100, 37) """ if x == 0: return 0, 0 else: zeros: int = 0 while x & 1 == 0: x = x >> 1 zeros += 1 return zeros, x
863998c3c7a8b8bd812910d07a911843f43bc549
24,374
def safe_tile(tile) -> bool: """Determines if the given tile is safe to move onto.""" if tile["type"] == "Blank": return True if tile["type"] == "Doodah": return True if tile["type"] == "SnakeTail" and tile["seg"] == 0: return True return False
ffdd3ace46dfe094b49c28e56bebe10e82311158
24,378
def _field_column_enum(field, model): """Returns the column enum value for the provided field""" return '{}_{}_COL'.format(model.get_table_name().upper(), field.name.upper())
f0653eb6ccf4c0864a05715643021759cf99e191
24,379
def get_reply_message(message): """Message the `message` is replying to, or `None`.""" # This function is made for better compatibility # with other versions. return message.reply_to_message
b2d253047eb1bdcb037b979f1819089ae88fb771
24,380
from typing import Callable from typing import List import inspect def _get_fn_argnames(fn: Callable) -> List[str]: """Get argument names of a function. :param fn: get argument names for this function. :returns: list of argument names. """ arg_spec_args = inspect.getfullargspec(fn).args if inspect.ismethod(fn) and arg_spec_args[0] == "self": # don't include "self" argument arg_spec_args = arg_spec_args[1:] return arg_spec_args
a464f1fb21a454f4e6a854a64810ba48cdb6f9f8
24,381
def get_primary_key(s3_index_row): """ returns the primary key of the s3Index dynamo table. Args: s3_index_row(dict): dynamo table row for the s3Index Returns: (dict): primary key """ primary = {"object-key": s3_index_row["object-key"], "version-node": s3_index_row["version-node"]} return primary
b5ca8ccb82dd1410626f205f0a8ea5486a2bcb8a
24,390
import csv def read_student_names(file): """If file ends in .csv, read the CSV file where each username should reside in the second column and the first column contains "student". If not, the file should contain several lines, one username per line. Return a list of students thus extracted.""" with open(file, 'r') as f: if not file.endswith(".csv"): return f.read().splitlines() return [row[1] for row in csv.reader(f) if row[0] == "student"]
d52716648bba85e776ef431ce879b8ea37068e8d
24,392
def project_list(d, ks): """Return a list of the values of `d` at `ks`.""" return [d[k] for k in ks]
62b82429e4c8e18f3fb6b1f73de72b1163f460bf
24,393
def list_users(iam_client): """ List all IAM users """ return iam_client.list_users()['Users']
da3509377968d642469e384bd6143783528e7f76
24,394
def snip(content): """ This is a special modifier, that will look for a marker in ``content`` and if found, it will truncate the content at that point. This way the editor can decide where he wants content to be truncated, for use in the various list views. The marker we will look for in the content is {{{snip}}} """ return content[:content.find('{{{snip}}}')] + "..."
6d836f610dfe1b49d4f1971cc3c6a471b789f475
24,397
def build_search_query(query, page, per_page) -> dict: """ Build the multi-search query for Elasticsearch. :param str query: :param int page: :param int per_page: """ search_query = { "query": {"multi_match": {"query": query, "fields": ["*"]}}, "from": (page - 1) * per_page, "size": per_page, } return search_query
f82dfdd11b0ad9bf2e3dfce9d723b46944ed2e53
24,399
def white_dwarfs(ds, data): """ Returns slicing array to determine white dwarf particles """ pcut = data['particle_type'] == 12 pcut = pcut * (data['particle_mass'] > 0.0) return pcut
83217024591af0e6f6918227be68251c452a0a08
24,400
import json def key_dumps(obj): """Return serialized JSON keys and values without wrapping object.""" s = json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) # first and last lines will be "{" and "}" (resp.), strip these return '\n'.join(s.split('\n')[1:-1])
c1b303de6ed34d5308aa2486f2e04a1f6d932bb8
24,401
def getUnique(df): """Calcualtes percentage of unique reads""" return ( df.loc[df[0] == "total_nodups", 1].values[0] / df.loc[df[0] == "total_mapped", 1].values[0] )
d5922fe59b95ec56c7310dce955ff85d97d6d9f1
24,411
def no_none_get(dictionary, key, alternative): """Gets the value for a key in a dictionary if it exists and is not None. dictionary is where the value is taken from. key is the key that is attempted to be retrieved from the dictionary. alternative is what returns if the key doesn't exist.""" if key in list(dictionary.keys()): if dictionary[key] is not None: return dictionary[key] else: return alternative else: return alternative
68b6f1d3cdd736f5f373093058e630db039be781
24,413
def similar(real, predicted): """ Compare if the captcha code predicted is close to the real one :param real string: Real captcha string :param predicted string: Predicted captcha string :return wrong_letter_count float: Percentage of wrong letter wrong_letter_dict dict: Dict of all wrong letters as key and a counter of failed as value """ wrong_letter_count = 0 wrong_letter_dict = {} for real_letter, preddicted_letter in zip(real, predicted): if real_letter != preddicted_letter: wrong_letter_dict[real_letter] = \ wrong_letter_dict.get(real_letter, 0) + 1 wrong_letter_count += 1 wrong_letter_count /= len(real) wrong_letter_count = 1.0 - wrong_letter_count return wrong_letter_count, wrong_letter_dict
e5595e34b81e770604b383dbd48906efc5a91173
24,414
from typing import List import requests def get_github_ips() -> List[str]: """Gets GitHub's Hooks IP Ranges Returns: List of IP Ranges """ resp = requests.get( 'https://api.github.com/meta', headers={ 'User-Agent': 'hreeder/security-group-synchronizer' } ) data = resp.json() return data['hooks']
74a5c4fb62b94dc9bf8cba41cf75da4dbb11f15c
24,417
def _num_matured(card_reviews): """Count the number of times the card matured over the length of time. This can be greater than one because the card may be forgotten and mature again.""" tot = 0 for review in card_reviews.reviews: if review.lastIvl < 21 and review.ivl >= 21: tot += 1 return tot
fe955d7a1322b995b12d030337008b99da9f8c1f
24,422
import re import fnmatch def build_pattern(pattern_algorithm: str, pattern: str, case_insensitive: bool) -> re.Pattern[str]: """ Build a matching object from the pattern given. :param pattern_algorithm: A pattern matching algorithm. :param pattern: A pattern text. :param case_insensitive: True if the matching is performed in case-insensitive, False otherwise. :return A matching object built. """ if pattern_algorithm == 'basic': pattern = re.escape(pattern) elif pattern_algorithm == 'wildcard': pattern = fnmatch.translate(pattern) elif pattern_algorithm == 'regex': pass else: raise ValueError(f'Invalid pattern algorithm: {pattern_algorithm}') return re.compile(pattern, re.IGNORECASE if case_insensitive else 0)
9935285e3590d285aa97a3eaa6cd9bc17cc3fc32
24,423
def search(metadata, keyword, include_readme): """Search for the keyword in the repo metadata. Args: metadata (dict) : The dict on which to run search. keyword (str) : The keyword to search for. include_readme (bool) : Flag variable indicating whether to search keyword inside the README.md or not. Returns: list : List of repo names which confirm with the search. """ keyword = keyword.lower() result = list() for action, action_metadata in metadata.items(): if keyword in action.lower(): result.append(action) elif include_readme: if keyword in action_metadata['repo_readme'].lower(): result.append(action) return result
a7ff3900547518fbf3e774df8954d383ba1227b5
24,428
def format_moz_error(query, exception): """ Format syntax error when parsing the original query. """ line = exception.lineno column = exception.col detailed_message = str(exception) msg = query.split('\n')[:line] msg.append('{indent}^'.format(indent=' ' * (column - 1))) msg.append(detailed_message) return '\n'.join(msg)
fb558e1c3149aa9191db76c153e24a9435f6bec3
24,430
def bitarray_to_bytes(b): """Convert a bitarray to bytes.""" return b.tobytes()
d4851f60a056953c3862968e24af5db5597e7259
24,431
def get_field_value(instance, field_name, use_get): """Get a field value given an instance.""" if use_get: field_value = instance.get(field_name) else: field_value = getattr(instance, field_name, '') return field_value
71e89e9c0f52a71d78bc882d45ae2dda8100a1f7
24,435
def removesuffix(s, suffix): """ Removes suffix a string :param s: string to remove suffix from :param suffix: suffix to remove :type s: str :type suffix: str :return: a copy of the string with the suffix removed :rtype: str """ return s if not s.endswith(suffix) else s[:-len(suffix)]
7503e7ca390434936cdda8f706f5ca1eb7b80b98
24,437
def chomp(text): """ Removes the trailing newline character, if there is one. """ if not text: return text if text[-2:] == '\n\r': return text[:-2] if text[-1] == '\n': return text[:-1] return text
8813631dd201a281dd4d879b7ec8d87e9425b9c7
24,438
def to_list(inp): """ Convert to list """ if not isinstance(inp, (list, tuple)): return [inp] return list(inp)
55350d48bd578252213710fd4c5e672db8ba1f8e
24,439
def get_ra(b, d): """ Converts birth and death to turnover and relative extinction rates. Args: b (float): birth rate d (float): extinction rate Returns: (float, float): turnover, relative extinction """ return (b - d, d / b)
64e6e9752c623b17745de92ecfe2ce96c43bc381
24,441
def all_angles_generator(board: list): """ This function is a generator for all angles of a board >>> board = [\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"] >>> [a for a in all_angles_generator(board)][0] [' ', ' ', '3', '1', ' ', '9', ' ', '5', ' '] """ def angle(start_i, start_j, board): return [ board[i][start_j] for i in range(start_i, start_i + 5) ] + [ board[start_i + 4][j] for j in range(start_j + 1, start_j + 5) ] for start_j, start_i in zip(range(4, -1, -1), range(5)): yield angle(start_i, start_j, board)
3ea04a9b1aea2236e6bbc1595982cc8d50f9dbb3
24,446
def GetBraviasNum(center,system): """Determine the Bravais lattice number, as used in GenHBravais :param center: one of: 'P', 'C', 'I', 'F', 'R' (see SGLatt from GSASIIspc.SpcGroup) :param system: one of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic', 'trigonal' (for R) 'monoclinic', 'triclinic' (see SGSys from GSASIIspc.SpcGroup) :return: a number between 0 and 13 or throws a ValueError exception if the combination of center, system is not found (i.e. non-standard) """ if center.upper() == 'F' and system.lower() == 'cubic': return 0 elif center.upper() == 'I' and system.lower() == 'cubic': return 1 elif center.upper() == 'P' and system.lower() == 'cubic': return 2 elif center.upper() == 'R' and system.lower() == 'trigonal': return 3 elif center.upper() == 'P' and system.lower() == 'hexagonal': return 4 elif center.upper() == 'I' and system.lower() == 'tetragonal': return 5 elif center.upper() == 'P' and system.lower() == 'tetragonal': return 6 elif center.upper() == 'F' and system.lower() == 'orthorhombic': return 7 elif center.upper() == 'I' and system.lower() == 'orthorhombic': return 8 elif center.upper() == 'A' and system.lower() == 'orthorhombic': return 9 elif center.upper() == 'B' and system.lower() == 'orthorhombic': return 10 elif center.upper() == 'C' and system.lower() == 'orthorhombic': return 11 elif center.upper() == 'P' and system.lower() == 'orthorhombic': return 12 elif center.upper() == 'C' and system.lower() == 'monoclinic': return 13 elif center.upper() == 'P' and system.lower() == 'monoclinic': return 14 elif center.upper() == 'P' and system.lower() == 'triclinic': return 15 raise ValueError('non-standard Bravais lattice center=%s, cell=%s' % (center,system))
06c4c4f4ac2a0b915fb544df2f99a305e143cea2
24,453
def format_attribute(attribute): """Format a tuple describing an attribute. :param attribute: attribute tuple, which may be either ``(key, value)`` or ``(value,)``. :return: the formatted string If given, `key` is either formatted as itself, if it's a `str`, or else as ``repr(key)``, and is separated from `value` by an equal sign ("="). `value` is always formatted as ``repr(value)``. """ if len(attribute) == 1: (value,) = attribute return repr(value) key, value = attribute value_str = repr(value) if isinstance(key, str): key_str = key else: key_str = repr(key) return f"{key_str}={value_str}"
e5926e13da947240bf0efb215f2f75aad308c251
24,454
from typing import Iterator from typing import Any from typing import List def take(it: Iterator[Any], n: int) -> List[Any]: """Take n elements of the iterator.""" return [next(it) for _ in range(n)]
d12b7a26e0bc7712174f75e99fd9a9103df1b86e
24,455
def _text_choose_characters(player): """Display the menu to choose a character.""" text = "Enter a valid number to log into that character.\n" characters = player.db._playable_characters if len(characters): for i, character in enumerate(characters): text += "\n |y{}|n - Log into {}.".format(str(i + 1), character.name) else: text += "\n No character has been created in this account yet." text += "\n" if len(characters) < 5: text += "\n |yC|n to create a new character." if len(characters) > 0: text += "\n |yD|n to delete one of your characters." return text
1a94934f838f3fcae85a62ac867191b630b39f3d
24,456
def create_charm_name_from_importable(charm_name): """Convert a charm name from the importable form to the real form.""" # _ is invalid in charm names, so we know it's intended to be '-' return charm_name.replace("_", "-")
983c7b9796e8987c66d22aa01b9f3d273969f18a
24,459
def find_null_net_stations(db, collection="arrival"): """ Return a set container of sta fields for documents with a null net code (key=net). Scans collection defined by collection argument. """ dbcol = db[collection] net_not_defined = set() curs = dbcol.find() for doc in curs: if not 'net' in doc: sta = doc['sta'] net_not_defined.add(sta) return net_not_defined
582dc0a0b14e091e3b54fb3c2040669216ec4bf5
24,460
def FindApprovalValueByID(approval_id, approval_values): """Find the specified approval_value in the given list or return None.""" for av in approval_values: if av.approval_id == approval_id: return av return None
d4e14ad235dae859559376a99d14bf1fe8156054
24,461
def get_nice_address(address): """ Take address returned by Location Service and make it nice for speaking. Args: address: Address as returned by Location Service Place Index. Returns: str: Spoken address. """ spoken_street = address['Street'] if spoken_street.endswith('St'): spoken_street+= 'reet' if spoken_street.endswith('Av'): spoken_street += 'enue' spoken_number = address['AddressNumber'] if len(spoken_number) >= 4: spoken_number = spoken_number[:2] + ' ' + spoken_number[2:] spoken_address = spoken_number + " " + spoken_street return spoken_address
bc18427d5453646e766185e1e347839fa4e1b168
24,462
def is_pure_word(text: str) -> bool: """ Words containing parentheses, whitespaces, hyphens and w characters are not considered as proper words :param text: :return: """ return "-" not in text and "(" not in text and ")" not in text and " " not in text and "w" not in text
af364ebaab38c17543db238169f3a26587c69eae
24,463
def apply_substitution(subst_dict, cleaned_string): """ Apply a substitution dictionary to a string. """ encoded_string = '' # Slightly confusing, the get function will get the value of the # key named letter or will return letter. for letter in cleaned_string: letter = letter.lower() if letter in subst_dict: encoded_string += subst_dict.get(letter, letter) else: encoded_string += letter return encoded_string
b823139dff91e02e5765670c645b1977f21340c8
24,466
def _merge_config(entry, conf): """Merge configuration.yaml config with config entry.""" return {**conf, **entry.data}
b29404005bfd7578999bb982da27a7291f186228
24,467
from typing import Set import csv def get_all_ids(filename: str) -> Set: """Function that returns the set of all ids of all items saved in the file. Args: filename (str): File where items are saved. Returns: Set: Set of ids. """ ids = set() with open(filename, mode="r") as csvfile: reader = csv.DictReader(csvfile) for row in reader: ids.add(row['id']) return ids
4d4ff1374d273dbdc0fc499e1b634ea2bf604b3d
24,469
def and_list(items): """ Create a comma-separated list of strings. """ assert isinstance(items, list) match len(items): case 0: return '' case 1: return items[0] case 2: return f'{items[0]} and {items[1]}' case _: return ', '.join(items[0:-1]) + f', and {items[-1]}'
b0cea95bfe95d613986b6130fd7acabaef6a1d7c
24,477
def set_optional_attr(in_args, classifier): """ This function applies all the optional commandline arguments. This is designed to call after the instantiation of classifier object Parameters: in_args - This is parsed command line arguments classifier - This is an object of type Flower_Classifier. All the optional attributes of this object will be set using setters. Return: classifier - Classifer object will the optional attributes set to it. """ if in_args.save_dir != None: classifier.save_dir = in_args.save_dir if in_args.learning_rate != None: classifier.learning_rate = in_args.learning_rate if in_args.hidden_units != None: classifier.hidden_units = in_args.hidden_units if in_args.epochs != None: classifier.epochs = in_args.epochs if in_args.gpu != None: classifier.gpu = in_args.gpu return classifier
b850ee150143d4727430f9d2077844fa687f26ee
24,482
def modify_column(func, rows): """Apply 'func' to the first column in all of the supplied rows.""" delta = [] for columns in rows: delta.append([func(columns[0])] + columns[1:]) return delta
1362fd3a54df44a132e47563d8ffe2d472ceb934
24,491
def bool_from_native(value): """Convert value to bool.""" if value in ('false', 'f', 'False', '0'): return False return bool(value)
5f9cbcef5c862b5a507d376ffca8d814acfee87b
24,494
from typing import Counter import math def shannon_entropy(data): """Calculates shannon entropy value Arguments: data {string} -- the string whose entropy must be calculated Returns: [float] -- value that represents the entropy value on the data {string} """ p, lns = Counter(data), float(len(data)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
d383054f33639136182751a6d884839595ec4efd
24,500
def note_to_f(note: int, tuning: int=440) -> float: """Convert a MIDI note to frequency. Args: note: A MIDI note tuning: The tuning as defined by the frequency for A4. Returns: The frequency in Hertz of the note. """ return (2**((note-69)/12)) * tuning
55201b54e525966ee7f8133c217111b22a26d827
24,501
def _get_iso_name(node, label): """Returns the ISO file name for a given node. :param node: the node for which ISO file name is to be provided. :param label: a string used as a base name for the ISO file. """ return "%s-%s.iso" % (label, node.uuid)
3d73236bfa2b8fab8af39b9a3083b540e93eb30d
24,510
def open_file(file): """Open a file and read the content """ if not file: return '' content = '' try: with open(file, 'r+', encoding="utf-8") as f: content = f.read() except Exception as err: print('Something wrong happened while trying to open the file ' + file) return content
0b0308256b2a68cdc5a84fad850cdaa086d3541d
24,513