content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def point_touches_rectangle(point, rect): """Returns ``True`` (``1``) if the point is in the rectangle or touches it's boundary, otherwise ``False`` (``0``). Parameters ---------- point : {libpysal.cg.Point, tuple} A point or point coordinates. rect : libpysal.cg.Rectangle A rec...
11b2f3b672cf32aa7dd66290362a206fc9e8c010
687,452
import glob def get_photos(folder_path, pics_extension): """Function create a list of photos from given folder""" pics_path = folder_path + "/*." + pics_extension return glob.glob(pics_path)
3d32d5b173d74a2425f1229ee5e45784c1283053
687,453
def _full_index(sample_id_col): """Return all columns necessary to uniquely specify a junction""" return [sample_id_col, 'chrom', 'intron_start', 'intron_stop', 'strand']
db2bc661e0faef0234216c7426f23780ea25dd4d
687,456
def chain(*args): """Applies a list of chainable update transformations. Given a sequence of chainable transforms, `chain` returns an `init_fn` that constructs a `state` by concatenating the states of the individual transforms, and returns an `update_fn` which chains the update transformations feeding the ap...
74643ddf7d88e05640c9549048ddd19f9616c2c2
687,461
def _solve_method_3(arr): """ https://github.com/JaredLGillespie/HackerRank/blob/master/Python/minimum-swaps-2.py Couldn't really figure it out via my method, but I found this solution that was very small and I understand. One thing I did was factor out a portion of it into a function call, for ...
fca3a8ace9f026eed0d56a1b80c56073842f3249
687,463
def _calculate_build_timeout(features): """Return maximum allowed time for build (in seconds).""" timeout = 60 if 'mysql' in features: timeout += 60 timeout *= 60 return timeout
710bacd0332b0dc4a1f9a50efe2121c7e7d45b1f
687,465
import io def trim_spaces_and_tabs_from_lines_in_txt(txt: str) -> str: """ This function will remove leading spaces and tabs from lines of text. :param txt: a str containing the text to be cleaned up. :return: a str containing text with all of the leading spaces removed from each line. """ clean...
a935af2954335c4c37b7d75fefcca435d38460b7
687,467
from operator import add def vadd(V1,V2): """ add the components of 2 vectors <div class=jython> VADD (V1, V2) = [ u1+u2, v1+v2 ] </div> """ return add(V1,V2)
5e050c5fb7864194d751faeff7112a2c338e4bfc
687,468
def log_mean_exp(ops, x, axis=None, keepdims=False): """ Compute :math:`\\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k)`. .. math:: \\begin{align*} \\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k) &= \\log \\left[\\exp(x_{max}) \\frac{1}{K} \\sum_{k=1}^K \\ex...
20c76480839839e26dd7cc4cb566da44158a26ee
687,470
def _use_and_del(d, k, v): """ Use a values from a dict and remove it. """ if k in d: v = d[k] del d[k] return v
01cb79df4787402415d21cbb792198b26267406e
687,471
import re def canonical(value): """Replace anything but 'a-z', 'A-Z' and '0-9' with '_'. """ return re.sub(r'[^a-zA-Z0-9]', '_', value)
dfd9b324a9c9ec273750e95a4bd7b1548af37108
687,472
def channel_shuffle(x, groups): """shuffle channels of a 4-D Tensor""" batch_size, channels, height, width = x.size() assert channels % groups == 0 channels_per_group = channels // groups # split into groups x = x.view(batch_size, groups, channels_per_group, height, width) # transpose 1, 2 a...
22d386728fac21c34932d0a64ce169bc7c5540f1
687,473
import re def language(text, wtl): """Return language from given text and using the provided language classifier and regex""" words = [ "recomendo", "amei", "entrega", "otim[ao]", "excelente", "rapida", "celular", "gostei", "facil", "lindo", "bonito", "comprei", "legal", "perfume", "preco", "...
8b5ecd781825b3ad7217c144cf70796a6ebde8d3
687,475
import json def readParams(control_file): """Reads a JSON control file for the paramaters. List of parameters: trajectoryFolder : string, folder where the trajectory data is trajectoryBasename : string, names of the trajectory files is numClusters : int, number of clusters to partition...
3d287f59c7939c2801f38a4686daf76c3c60f837
687,476
def operatingexpenses(taxes, insurance, pmi, managementfee, hoafee): """Annual expenses occured through normal cost of business. :param taxes: Annual taxes. :type taxes: double :param insurance: Annual insurance. :type insurance: double :param pmi: Annual pmi payment. :type pmi: double ...
b1b2e5b4e90c62e18c1b8dcbe81027c335c28b9d
687,477
from typing import Dict from typing import Any import json def parse_json(path: str) -> Dict[str, Any]: """ Parse a json file. Args: path (str): Json file path. Returns: Dict: Dictionary of parsed data. """ with open(path, "r") as stream: return json.load(stream)
b4c1d80aad7427f9f91e6ef26eff95053f509a9b
687,480
import base64 import six def UrlSafeB64Encode(message): """wrapper of base64.urlsafe_b64encode. Helper method to avoid calling six multiple times for preparing b64 strings. Args: message: string or binary to encode Returns: encoded data in string format. """ data = base64.urlsafe_b64encode(six.e...
7078d3257ebd968dd205dd73395149d22eddc21f
687,483
def mmcc(ds, xs, ys): """Fit a straight line (x, y) = (mx, my) * d + (cx, cy) to ordinates x, y in xs, ys as a function of d in ds.""" assert len(ds) == len(xs) assert len(ds) == len(ys) ds = [float(i) for i in ds] xs = [float(i) for i in xs] ys = [float(i) for i in ys] _d = su...
40d6d718f1e278110ac6fa7c405b63c9b470e5eb
687,484
from typing import Tuple def ego_coordinate_to_world_coordinate( egocentric_x: float, egocentric_y: float, current_location_x: float, current_location_y: float, current_forward_x: float, current_forward_y: float, ) -> Tuple[float, float]: """ :param location_x: The x-component of an eg...
f78065f1dcf3e6c9e989530f14fbb579dd49660e
687,485
def _unique_list(df_col): """Return a list of unique values without NA.""" return list(df_col.unique().dropna())
fac06777d1b7e6abbe7aa8daf491e4171b5ef713
687,486
def normalize(text: str) -> str: """Remove whitespace, lowercase, convert spaces to underscores""" return text.strip().lower().replace(' ', '_')
e2e14317e7a2ab66d6f70b362a1d9d6bc445b1ce
687,488
def unique_slug(manager, slug_field, slug): """ Ensure slug is unique for the given manager, appending a digit if it isn't. """ i = 0 while True: if i > 0: if i > 1: slug = slug.rsplit("-", 1)[0] slug = "%s-%s" % (slug, i) if not manager.fi...
247fe133cced76f89ebaf9b06fe3349bf4704e0d
687,489
def AddAuthFieldMask(unused_ref, args, request): """Adds auth-specific fieldmask entries.""" if args.auth_type is None: # Not set, not the 'none' choice return request if request.updateMask: request.updateMask += ',authentication' else: request.updateMask = 'authentication' return request
221ac3287c9f0a85cb1f8ff4a5d2b6241c5e88c6
687,490
def _flip_masks_up_down(masks): """Up-down flip masks. Args: masks: rank 3 float32 tensor with shape [num_instances, height, width] representing instance masks. Returns: flipped masks: rank 3 float32 tensor with shape [num_instances, height, width] representing instance masks. """ return...
d83d2273f4a936c3e1e526af8db78a08e494ca75
687,495
import re def tamper(payload, **kwargs): """ Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' and equals operator ('=') with 'BETWEEN # AND #' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 * Oracle 10g * PostgreSQL 8.3, 8.4, 9.0 Not...
a660b0a6b1176fd7d7377c50a29ff04620b46b2d
687,502
from typing import List import json def read_geometries(file_geometries: str) -> List[str]: """Read a list of geometries.""" with open(file_geometries, 'r') as f: data = json.load(f) return data
93632ff61f192251abc3ca1e6083dc4347761155
687,503
def extract_annealing_log(log): """ Parses a VPR log line by line. Extracts the table with simulated annealing data. Returns the table header and data line lists as separate. """ # Find a line starting with "# Placement" for i, line in enumerate(log): if line.startswith("# Placement"): ...
ef9c4ca8e907f956efa3dc965237893fd589b684
687,504
def get_subscribed_reports_addresses(location_reports): # workds """returns list of string addresses for given LocationReports""" addresses = [] for lr in location_reports: addresses.append(lr.address) return addresses
e580f607d30ca60d1dec5834c0945631a8508e49
687,505
from typing import Counter def wordle_judge(input_word: str, answer_word: str)-> int: """ Judge input word based on the wordle rule We assume input_word and answer_word are of the same length (but no check is conducted) Judge results are defined as a sequence of {0, 1, 2}, where 2: exact, ...
ebf545f44fe34425d938a4ab09a3418810c244f8
687,506
def is_list_match(item, value): """Check if a item match a value or (if it is a list) if it contains only one item and the item matches the value """ if isinstance(item, list): if len(item) == 1 and item[0] == value: return True else: return False else: ...
12c881ce311ea5237f35810cfe2058988ff11d26
687,511
from typing import List def collatz(number: int) -> List[int]: """Проверка гипотезы Коллатца Подробнее: https://en.wikipedia.org/wiki/Collatz_conjecture Параметры: :param number: число для которого проверяется гипотеза :type number: int :return: Сипсок чисел, соответствующих шагам п...
ee7e08c023d09f6e874aef05e76fc6cad63b3d78
687,512
def choose_unit_from_multiple_time_units_series(time_serie, time_key="seconds"): """Given a time series in the form [(x, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}), (y, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}), (z, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0...
98f9e57eeeafd951ffc19826573174ff44318fec
687,514
from typing import List def read_lines_from_file(path: str, strip: bool = False) -> List[str]: """Read file into stripped lines.""" with open(path, "r") as f: lines = f.readlines() if not strip: return lines return list([line.strip() for line in lines])
299466534b9d1646f42b5a3137794bde309f500d
687,519
def read_hc_tape(file_path, order=2): """ read_hc_tape :Read Hilbert Curve command from the table Read Hilbert Curve command from the table in this package. The command including these English alphabet {'o', 'u', 'd', 'l', 'r'} :param file_path: a path of HC table :type file_path: string ...
1ba682abf0f898ea9c2b16d363877af4dd96118f
687,521
import torch def from_flattened_numpy(x, shape): """Form a torch tensor with the given `shape` from a flattened numpy array `x`.""" return torch.from_numpy(x.reshape(shape))
3dc8fb7fb0240b82104f1a0fe6d1fa5681a5b2d2
687,523
def create_bit_mask(data_array, valid_bits, no_data=-9999): """Create a boolean bit mask from a list of valid bits Args: data_array: xarray data array to extract bit information for. valid_bits: array of ints representing what bits should be considered valid. no_data: no_data value for ...
198db8fed64a8c6143f245dc620eb59e711d900f
687,525
def calculate_len_get(headers): """ # Desc : Function to calculate total length of data received for a get request. # Calculated as sum of header length and the content length # Input : Header from a get request # Output: Returns the total length of data received """ sock_header_len = 0 sock_c...
076067efe0e2a68b12ded4bcc4890380434d6e2f
687,526
def get_samples_panfamilies(families, sample2family2presence): """Get the sorted list of all the families present in the samples Can be a subset of the pangenome's set of families""" panfamilies = set() for f in families: for s in sample2family2presence: if sample2family2presence[s][...
2ef12a0bb51e547171a61225333a2ebd91a3e9a2
687,530
def parse_rank_score(rank_score_entry, case_id): """Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float) """ rank_score = None if rank_score_entry: for family_info in rank_score_entry.split(","): ...
e8b89593477cfebef331e89ff5addf81e2b8038f
687,532
def str2bool(s): """Convert string to bool for argparse""" if isinstance(s, bool): return s values = { "true": True, "t": True, "yes": True, "y": True, "false": False, "f": False, "no": False, "n": False, } if s.lower() not in ...
9b8c369652dea20181e60c9fb336af280b4e0e8d
687,533
def classify(model, filepath): """ return a dictionary formatted as follows: { 'predicted y': <'2016' or '2020'>, 'log p(y=2016|x)': <log probability of 2016 label for the document>, 'log p(y=2020|x)': <log probability of 2020 label for the document> ...
5039d39473c36a9df228ad87fe2bfcc3921889b2
687,535
def unique_paths_with_obstacles(obstacle_grid: list[list[int]]) -> int: """ >>> print(unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]])) 2 >>> print(unique_paths_with_obstacles([[0,1],[0,0]])) 1 >>> print(unique_paths_with_obstacles([[0,1,0],[0,0,0],[0,0,1]])) 0 """ # If the ob...
de854da00b5c7e8608dbc7f8a4d352fc61956f28
687,536
def get_parameter_value(parameters, parameter_name, value_key='value'): """Returns the parameter value. :param parameters: parameter list :param parameter_name: parameter name :param value_key: parameter key containing the value :rtype : str """ for item in parameters: if item['name...
cb54d7c20d3a9a6790e0c16c0c78e0e05d24f9d9
687,538
import inspect import six import re def expand_docstring(**kwargs): """Decorator to programmatically expand the docstring. Args: **kwargs: Keyword arguments to set. For each key-value pair `k` and `v`, the key is found as `${k}` in the docstring and replaced with `v`. Returns: Decorated function...
fef19e81def3c27cac5e90d310363489a8251f20
687,541
def unique_vals(rows, column_number): """Find the unique values from a column in a dataset based on column number""" return set([row[column_number] for row in rows])
e009ae12b8c3f56168ab5849b30a3b655500faf2
687,543
def collapse_repeats(sequence): """Collapse repeats from sequence to be used for PER""" result = [] prev = None for x in sequence: if x == prev: continue result.append(x) prev = x return result
d9d9ff8bffbd6104ff109a55682525c701be9166
687,546
def _load_data_spacy(data_path, inc_outside=True): """ Load data in Spacy format: X = list of sentences (plural) / documents ['the cat ...', 'some dog...', ...] Y = list of list of entity tags for each sentence [[{'start': 36, 'end': 46, 'label': 'PERSON'}, {..}, ..], ... ] inc_outside = Fal...
11613013174abba8847aceb88cec932a5ab71312
687,547
def is_valid_trajectory(ext): """ Checks if trajectory format is compatible with GROMACS """ formats = ['xtc', 'trr', 'cpt', 'gro', 'g96', 'pdb', 'tng'] return ext in formats
2673343cb15886ea056a408c29ae9f23e2eb9e53
687,550
def is_hilbert_number(n): """ Simply check whether n is positive and the remainder of n is equal to 1 modulus 4. """ return n > 0 and n % 4 == 1
b55825b446282343cb87e3d6c83036a6bc9f1a6a
687,556
def string_to_list_only_digit(word): """ Take each character of the 'word' parameter and return a list populated with all the characters. The if clause allows only the digits to be added to the list. :param word: string :return: list of digit inside 'word' """ return [c for c in word if ...
9c5078e16515d93d0e3bb35376ee93c60119e71d
687,557
def flatten_beam_dim(x): """Flattens the first two dimensions of a non-scalar array.""" if x.ndim == 0: # ignore scalars (e.g. cache index) return x return x.reshape((x.shape[0] * x.shape[1],) + x.shape[2:])
4480ef5421407030f5cf217883600dbd4e63e196
687,558
def calendars_config_track() -> bool: """Fixture that determines the 'track' setting in yaml config.""" return True
e877fad2b55ede8c066b838365fb0acf98484d87
687,560
def verificar_arquivo(nome_arquivo='passwords'): """Verifica se o arquivo que conterá as senhas já existe. Keyword Arguments: nome_arquivo {str} -- (default: {'passwords'}) Returns: [bool] -- [Se já existir recebe True, senão recebe False] """ try: arquivo = open(n...
db035dd3b191118c831cc7f735e7bddd0d3a3c11
687,566
def get_fields_with_datatype( dataset_ids: list, field_info: dict, data_format: str ) -> dict: """ Returns the column name and its data type by looking up stream and log_fields json file. If a mapping column name is not present in log_fields.json it returns the column name as `col<idx>` and its dat...
ffbb112078abee51d769d44f80a6a200e9404322
687,567
def pRDP_asymp_subsampled_gaussian_best_case(params, alpha): """ :param params: :param alpha: The order of the Renyi Divergence :return: Evaluation of the pRDP's epsilon See Example 20 of Wang, Balle, Kasiviswanathan (2018) """ sigma = params['sigma'] prob = params['prob'] n = param...
9dabb8ba68c065d6346aeb775cffc72029ab9d4a
687,570
import string def make_title(line): """ Edits the given line so that it can be used as a title. Edit operations include removing unnecessary punctuations and converting the text into title case :param line: line of the poem chosen as the title :return: title of the poem """ # Removing pun...
15b91f0c8918122a201490603dc707be15053eac
687,571
from typing import Counter def filter_min(counter: Counter, min_freq: int): """ Filter counter by min frequency """ return Counter({t: c for t, c in counter.items() if c >= min_freq})
56b77dc486ad41fc7004b1db10f85a4813f835b3
687,572
def stack_map(topology): """Return dict mapping node ID to stack type Parameters ---------- topology : Topology The topology Returns ------- stack_map : dict Dict mapping node to stack. Options are: source | receiver | router | cache """ stack = {} for v...
b33531bd931428d8214dd5e969e057a5159a4b2a
687,574
def add(I1, I2): """Calculate the addition of two intervals as another interval Keyword arguments: I1 -- the first interval given as a tuple (a, b) I2 -- the second interval given as a tuple (c, d) """ (from1, to1) = I1 (from2, to2) = I2 return (from1 + from2, to1 + to2)
77a0b4a336da94e7b7d1690e750a82ee333efb3d
687,575
def _is_lt_position(first: tuple, second: tuple, position): """Compare the tuple at given position.""" if len(first) > position and first[position] is not None: if len(second) > position and second[position] is not None: return first[position] < second[position] return False # canno...
74df79c3da2f3d5c9b1e39a1c1651eb79ab90727
687,576
def mk_time_info_extractor(spec): """ Returns a function that will extract information from timestamps in a dict format. The specification should be a list of timetuple attributes (see https://docs.python.org/2/library/time.html#time.struct_time) to extract, or a {k: v, ...} dict where v are the tim...
808382a459064a31e95c481b16c66f92a0e70a16
687,579
def validate(identifier): """Validates a student id from the Pontifical Catholic University of Chile Args: identifier: student identifier (string or number) Returns: True if it is valid, False otherwise """ if not identifier: return False identifier = str(identifier) ...
0d58b8659774852894d96efeb6ad9acef6c05d13
687,580
def get_unique_notes_in_channel(notes_in_channel): """ Utility function to get an ordered set of unique notes in the channel """ all_notes = [] for notes in notes_in_channel: all_notes.append(notes.note) return sorted(set(all_notes))
898490d74811d36f9fbd37f62ed043336b0accdb
687,586
def get_whitespace_cnt(line): """ Return a count of leading tabs/spaces as (tab_cnt, space_cnt). """ tab_cnt = 0 space_cnt = 0 testline = line while testline.startswith('\t'): tab_cnt += 1 testline = testline[1:] testline = line while testline.startswith(' '): space_c...
719e2db0f045b30f715170ee1aec0e24bab87134
687,588
import re def argv_to_pairs(argv): """Convert a argv list to key value pairs. For example, -x 10 -y 20 -z=100 {x: 10, y: 20, z: 100} """ arg_dict = {} i = 0 while i < len(argv): if argv[i].startswith('-'): entry = re.sub('-+', '', argv[i]) items = entry.s...
e375d2cfc835d33c44f3646e41668852fb8be6d7
687,595
def _pixel_distance(a_x1, a_x2, b_x1, b_x2): """Calculates the pixel distance between bounding box a and b. Args: a_x1: The x1 coordinate of box a. a_x2: The x2 coordinate of box a. b_x1: The x1 coordinate of box b. b_x2: The x2 coordinate of box b. Returns: The pixel distanc...
3ebfd8576240ad662c7c41ebae22733b2354f01b
687,596
def extract_function_from_command(command): """ Extracts and returns the function used in the current command. for example: `lc.ln(a,52)` -> ln :return: function name """ function_name = command.split(".")[1] end_index = function_name.index("(") function_name = function_name[:end_index]...
d4f1859b6e1026f700f097c1b871444ed8b6b535
687,600
from typing import Tuple def _partition_satellite_input( line: Tuple[str, str], num_partitions: int = 2) -> int: # pylint: disable=unused-argument """Partitions Satellite input into tags (0) and rows (1). Args: line: an input line Tuple[filename, line_content] num_partitions: number of partition...
5e49ce2de504fffed10069b1812fcb2224de1277
687,601
def cleanup_vm_data(vm_data, uuids): """ Remove records for the VMs that are not in the list of UUIDs. :param vm_data: A map of VM UUIDs to some data. :type vm_data: dict(str: *) :param uuids: A list of VM UUIDs. :type uuids: list(str) :return: The cleaned up map of VM UUIDs to data. :...
e433b450ceb608bcc094581ee040c180f370b0f8
687,602
def extract_solution(G, model): """ Get a list of vertices comprising a maximal clique :param G: a weighted :py:class:`~graphilp.imports.ilpgraph.ILPGraph` :param model: a solved Gurobi model for maximum clique :return: a list of vertices comprising a maximal clique """ clique_node...
3625a16bea6366a0107c8b3bf1ba8361e5fac9d6
687,603
import random def random_horizontal_flip(image, bboxes): """ Randomly horizontal flip the image and correct the box :param image: BGR image data shape is [height, width, channel] :param bboxes: bounding box shape is [num, 4] :return: result """ if random.random() < 0.5: _, w, _ = i...
2a865b32a9ed94fdee35b4b075313a5e9d733e90
687,605
def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks"): """ Draws a graph made of unicode characters. :param values: An array of values to graph. :param lower_limit: Minimum value for the y axis (or None for dynamic). :param upper_limit: Maximum value for the y axis (or None for...
e83fd64890b41eb8d8d05d88cad19dfdda061725
687,606
def do_two(Sol=341.0, epsilon=0.55, albedo=0.3): """ Calculate equlibrium fluxes for a two-layer atmosphere Parameters ---------- Sol: float day/night averaged TOA shortwave flux (W/m^2) epsilon: float longwave emissivity of layers 1 and 2 albedo: float ...
f19b1381d543b52af51a5fe29ad767ae0efb2023
687,607
def intersect_ray_plane(o,w,p,n): """[Compute the intersection point between a ray and a plane] Args: o ([ndarray]): [ray origin] w ([ndarray]): [ray direction] p ([ndarray]): [plane origin] n ([ndarray]): [plane normal vector] Returns: [ndarray]: [intersection point...
9878afb4438aff91ead49cc9c15ed4042f909688
687,609
def widget_generator(klass, fields): """ Takes in a class and a list of tuples consisting of field_name and an attribute dictionary :param klass: Class of the input widget :param fields: List of tuples mapping field names to attribute dictionaries :return: A dict of input widget instances """ ...
5e09950148f902ace17b6f52e06ee0f16760c195
687,610
def cap_allele(allele, cap=5): """ Cap the length of an allele in the figures """ if len(allele) > cap: allele = allele[:cap] + '*' return allele
92bd675d98369fbb0201e1aa436ef94b45aefa51
687,612
def rhs_replace(rhs, sublist, replacement): """Replace occurrences of sublist in rhs with replacement.""" sublist = tuple(sublist) rhs = tuple(rhs) if len(sublist) > len(rhs): raise ValueError if not sublist: raise ValueError new_list = [] idx = 0 while idx < len(rhs): if rhs[idx:idx + len(s...
9af00d6098536dbc032470e53bce87db1d07f5df
687,615
import importlib import pkgutil def get_submodule_names(module_name): """ Returns a list of the module name plus all importable submodule names. """ module = importlib.import_module(module_name) submodule_names = [module_name] try: module_path = module.__path__ except AttributeErr...
a3939cee553f0ecf462df25f9535eb7485db5abe
687,618
def two_bytes_to_int(hi_byte: int, low_byte: int) -> int: """ Converts two bytes to a normal integer value. :param hi_byte: the high byte :param low_byte: the low byte :return: converted integer that has a value between [0-65535] """ return ((hi_byte & 0xFF)*256) + (low_byte & 0xFF)
979f59ebb860c2294eaa644609345f1146e6dc0b
687,620
def time_interval_since(date_1, date_2): """ Calculate seconds between two times Arguments: date_1 -- datetime object #1 date_2 -- datetime object #2 Output: Num of seconds between the two times (with a sign) """ return (date_1 - date_2).total_seconds()
6a5f11b0e2705a4e577e037ba43dfed6bda06be4
687,624
from datetime import datetime def convert_to_datetime(globus_time): """ Converts a time given in Globus format to datetime. Globus format for time is as follows: YYYY-MM-DD HH:MM:SS+00:00 """ # use space separator to seperate date and time times = globus_time.split(" ") date_part ...
4e2945eb084aaa0b5dc64a77c1d2988ae9f83445
687,626
def sum67(nums): """Solution to the problem described in http://codingbat.com/prob/p108886 Ex: >>> sum67([1, 2, 2]) 5 >>> sum67([1, 2, 2, 6, 99, 99, 7]) 5 >>> sum67([1, 1, 6, 7, 2]) 4 :param nums: list :return: int """ sum = 0 between_6_and_7 = False for n in n...
a035a1443378d33852b6bbdc785a97210af0c866
687,629
import pickle def get_temp_data(filename, directory='temp', extension='.temp'): """get temp data from disk""" if '.temp' not in filename: filename += extension try: with open(directory + '/'+ filename, 'rb') as f: data_file = pickle.load(f) f.close() pr...
b8dde5ca72b1774c26a2020a2dcf9a561b133aed
687,633
def calculate_accumulation_distribution(open, high, low, close, volume): """ Calculates changes in accumulation/distribution line. A/D = ((Close - Low) - (High - Close))/(High - Low) Args: open: Float representing exchange rate at the beginning of an interval high: Float representing th...
d9f6bf6966f854082262313d5d6a7e51711af9b6
687,636
from datetime import datetime def datetime_name(output_name): """Creates a filename for the output according to the given format.""" now = datetime.now() return f'{output_name}-{now.strftime("%Y-%m-%d-%H-%M")}.csv'
43662f53042d5a1f9b8c395c8965b093eb6fb65e
687,637
def boxes_required(qty, box_capacity=6): """ Calculate how many egg boxes will be required for a given quatity of eggs. :param qty: Number of eggs :param box_capacity: How many eggs will fit in a box :return: The number of boxes that are required """ return int(qty / box_capacity) + 1
fe0604b7da779244189a5f32be6ab293e4ae79ca
687,638
def legend_from_ee(ee_class_table): """Extract legend from an Earth Engine class table on the Earth Engine Data Catalog page such as https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 Value Color Description 0 1c0dff Water 1 05450a Evergreen needleleaf forest 2 086a10...
6f61958a837bff89949717a7bfb70a0b27dade20
687,646
def _pseudo_alpha(rgb, opacity): """ Given an RGB value in [0, 1], return a new RGB value which blends in a certain amount of white to create a fake alpha effect. This allosws us to produce an alpha-like effect in EPS, which doesn't support transparency. """ return tuple((value * opacity - opa...
0326d306c8846b46a7b9225ee5b969ff88e4e47d
687,647
def convert_gps_degress_to_minutes(lat, lon): """ Convert GPS in degrees to degrees, minutes, seconds as needed for the Exif :param lat: Latitude in degrees :param lon: Longitude in degrees :return: Latitude and longitude in degrees, minutes, seconds """ lat_positive = lat >= 0 lon_posit...
eab4f7735fb26a787edee618ea4c2e0c219fc1f0
687,649
def has_os_path_join(block_dets): """ path = os.path.join('a', 'b') os.path.join('a/', 'b') <value> <Call lineno="2" col_offset="7"> <func> <Attribute lineno="2" col_offset="7" type="str" attr="join"> <value> <Attribute lineno="2" col_offset="7" type="st...
3d6abe066e228bbdf2e2a9aabcf45f6e5fd59994
687,651
import requests def patch_request(base_request): """ Performs PATCH request for the class provided. :param: base_request: Class with which to make request. :type: BaseRequest :return: response :rtype: requests.Response """ (headers, _, _, _, service) = base_request.get_request_vars() ...
1e6eddddfc2108bdb89e5436ed2253b265920c8e
687,652
def get_intercept(coords, m): """Calculates the intercept of a line from coordinates and slope""" x, y = coords[0], coords[1] b = y - m * x return b
923bce5d5fd4ee8a11fa5ae12c2b2a82233bdd54
687,653
def lte(x, y): """Creates an SMTLIB less than or equal to statement formatted string Parameters ---------- x, y: float First and second numerical arguments to include in the expression """ return "(<= " + x + " " + y + ")"
96d51fb1d7a7f96f99c96b025ec4938e5ef19dea
687,654
def parse_none_results(result_dict): """ Replace `None` value in the `result_dict` to a string '-' """ for key, value_list in result_dict.items(): for i in range(len(value_list)): if value_list[i] is None: result_dict[key][i] = '-' return result_dict
d1212cd9aa5c4246edd5d218bcaeb18527434233
687,655
def imagenet_mean_preprocess_image_tensor_fun(x): """ In: x - image tensor of size (#images, #channels, #dim1, #dim2) Out: image tensor x with subtracted imagenet mean """ y = x y[:,0,:,:] -= 103.939 y[:,1,:,:] -= 116.779 y[:,2,:,:] -= 123.68 return y
8bf058b4713683826bff304c50e3bdcfe05cde2b
687,665
def build_url(city_data, api_info): """Return a `request` compatible URL from api properties.""" # type: (Dict, Dict) -> str return "{}:{}{}".format( api_info["host"], str(api_info["port"]), api_info["path"].format( city=city_data["city"], state=city_data["state"]))
45a44b6c791711bcb801b30320f72b4f44fafb5c
687,666
def add_trailing_slash(s): """Add trailing slash. """ if not s.endswith('/'): s = s + '/' return(s)
6587568a758e31e591d0240a715fff8a12c5e30d
687,667
import torch def get_interior_points(N=10000, d=2): """ randomly sample N points from interior of [0,1]^d """ return torch.rand(N, d)
11b9b75735dd6251f590428018b779f2873b6eec
687,670
def calc_brightness(value: float, actual_brightness_value: int, max_brightness_value: int, function: str) -> int: """Calculate brightness value based on actual and maximal brightness. The function calculates a brightness value using the `function` string and the `value` as a percentage. If `function` is em...
6cd7f08569a7a841dc19238bb37e925fc99b9ec1
687,672
import requests def get_html(url): """ Get HTML document from GET request from URL :param url: str URL of request :return: str HTML document """ r = requests.get(url, headers={'User-Agent': 'Custom'}) r.encoding = r.apparent_encoding print(r) return r.text
709ba4e5e3f5f574c127bb868c2c14cf25ec83db
687,673