content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _get_QActionGroup(self): """ Get checked state of QAction """ if self.checkedAction(): return self.actions().index(self.checkedAction()) return None
0581a9176c6291714f81b5f6570fac1504153ddb
675,103
def update_parameters(parameters, grads, learning_rate): """ Using gradient descent to update parameters Arguments: parameters is python dictionary containing the parameters grads is python dictionary containing gradients and the output of L_model_backward Returns: parameters that are upd...
897a0cd90bcafe146d6ced332bf6d77261d286e3
412,214
def host_and_page(url): """ Splits a `url` into the hostname and the rest of the url. """ url = url.split('//')[1] parts = url.split('/') host = parts[0] page = "/".join(parts[1:]) return host, '/' + page
db035aeeaf2c1ae7b9eb00f00daf5673a9551edf
100,865
import torch def construct_optimizer(model, cfg): """ Construct a stochastic gradient descent or ADAM optimizer with momentum. Details can be found in: Herbert Robbins, and Sutton Monro. "A stochastic approximation method." and Diederik P.Kingma, and Jimmy Ba. "Adam: A Method for Stochasti...
63569f73c1d0e5aba9bdd6785d745ddc542c345e
494,792
def strip_type(caller): """ strip the -indel or -snp from the end of a caller name """ vartype = '' if caller.endswith('-snp'): caller = caller[:-len('-snp')] vartype = 'snp' elif caller.endswith('-indel'): caller = caller[:-len('-indel')] vartype = 'indel' ...
146a972c9110ce6f39f7cc68cee6d8da889816f0
163,814
from typing import List def get_records(project) -> List[dict]: """ Obtain all data from a project :param project: :return: """ all_data = project.export_records() return all_data
eb8b8c04d86dc536f4aef38b8f10f2c73f3597b5
349,490
def _tagged2tuples(tagged_dicts): """ >>> _tagged2tuples(get_tagged_from_server("who has starred in the movie die hard?")) [('who', 'O', 'WP'), ('has', 'O', 'VBZ'), ('starred', 'O', 'VBN'), ('in', 'O', 'IN'), ('the', 'O', 'DT'), ('movie', 'O', 'NN'), ('die', 'O', 'VB'), ('hard', 'O', 'RB'), ('?', 'O', '.')]...
183c9f48af51d8c5ea82bc47e599acd703ab4672
523,077
from typing import SupportsFloat def _format_float(value: SupportsFloat, *, decimals: int = 6) -> str: """Format a node position into a string. This uses the format requested by 2DM: up to nine significant digits followed by an exponent, e.g. ``0.5 -> 5.0e-01``. :param value: A object that supports ...
c1e5f52c1529652a2130c195300d257f66854101
166,506
import functools import operator def product_of_list(iterable): """ Returns the product of an iterable If the list is empty, returns 1 """ product_ = functools.reduce(operator.mul, iterable, 1) return product_
10d873ab86667f5eab3d2d4957c1218259a0f674
558,697
def autocrop_array_shapes(input_shapes, cropping): """Computes the shapes of the given arrays after auto-cropping is applied. For more information on cropping, see the :func:`autocrop` function documentation. # Arguments input_shapes: the shapes of input arrays prior to cropping in ...
acf407935814ae9ffb77a8b7ff3dd747be04bb03
663,013
def rem3(lst): """Remove all 3's from lst""" i = 0 while i < len(lst): if lst[i] == 3: del lst[i] else: i = i + 1 return lst
0ae008555d53c48b5eeaecb49ad526d501327af3
311,751
def alphadump(d, indent=2, depth=0): """Dump a dict to a str, with keys in alphabetical order. """ sep = "\n" + " " * depth * indent return "".join( ( "{}: {}{}".format( k, alphadump(d[k], depth=depth + 1) if isinstance(d[k], dict) ...
0511fec7a61454f93fbe7b55244b7349c9175baf
479,944
def problem_9_6(matrix, key): """ Given a matrix in which each row and each column is sorted, write a method to find an element in it. Matrix is size M*N such that each row is sorted left to right and each column is sorted top to bottom. Solution: divide and conquer. Start in the top-right and go down ...
f9f379aca6650764525b34252802786024a11fb7
429,541
def _list_at_index_or_none(ls, idx): """Return the element of a list at the given index if it exists, return None otherwise. Args: ls (list[object]): The target list idx (int): The target index Returns: Union[object,NoneType]: The element at the target index or None """ if ...
46651d93140b63bcb85b3794848921f8ea42d7bf
682,002
def compute_precision(golden_standard, mappings): """ Computes the precision between the mappings and the gold standard. If the mappings is an empty list, the precision is 0 :param golden_standard: The list of tuples containing the correct mappings :param mappings: The list of tuples generated by th...
acd76fd9a5442d77273efb1d294b122e57bb9556
231,394
def rem_var(var, subs): """Deletes any substitutions of var in subs.""" newsubs = subs.copy() try: del newsubs[var.constant()] except KeyError: pass try: del newsubs[var.variable()] except KeyError: pass return newsubs
161c62470ad648e2d062d021b528ece4e1555509
65,962
def get_ident_string(module_class): """Returns a string which can be used to identify a module class. Normal comparison marks the same class as different after reloading it so this string has to be used to compare modules after reloading instead of a direct comparison of a type. """ return modu...
95d231be9d895340b7e9bc8c325cd284b17f00a6
425,790
def _exists(index, nx, ny): """ Checks whether an index exists an array :param index: 2D index tuple :return: true if lower than tuple, false otherwise """ return (0 <= index[0] < nx) and (0 <= index[1] < ny)
6f7283beec9cbe370648e5b07997ec77b57be9f5
423,965
def _sum_frts(results:dict): """ Get total number of FRTs Arguments: results {dict} -- Result set from `get_total_frts` Returns: int -- Total number of FRTs in the nation """ if results == None: return 0 total_frts = 0 for result in results: if result['...
44d56d9e35c2b910ea10e25bb3de7ba9ae0c6294
107,152
def image_data(image): """Get components and bytes for an image""" # NOTE: We might want to check the actual image.mode # and convert to an acceptable format. # At the moment we load the data as is. data = image.tobytes() components = len(data) // (image.size[0] * image.size[1]) ...
f2298efba3ac49ef15c4afa56beb37ed9774af72
165,127
def divide_list_into_equal_chunks(alist, chunks): """ Divide a list into equal chunks :param alist: list :param chunks: int :return: list """ return [alist[i:i + chunks] for i in range(0, len(alist), chunks)]
543e42256e46fbd1ff56feb4b684b5c18eae7acc
224,773
def getCasing(word): """Returns the casing for a word""" casing = 'other' numDigits = 0 for char in word: if char.isdigit(): numDigits += 1 digitFraction = numDigits / float(len(word)) if word.isdigit(): #Is a digit casing = 'numeric' elif digitFraction > 0.5: ...
69c48dd1f6943257570ac98a794909d01fd1db0e
588,418
def _make_sro(object_generator, source_id, rel_type, target_id): """ Make an SRO. :param source_id: The ID of the source object (string) :param rel_type: The relationship type (string) :param target_id: The ID of the target object (string) :return: The SRO, as a dict """ rel = object_g...
a258c0bd17e05a9e8cc979a2061b8c328882e199
318,973
def length(listed): """ return length of list """ count = 0 for item in listed: count += 1 return count
6052d82388a16896c74ee3287064095cfc84f787
456,765
def _calculate_development_risk(module): """ Function to calculate Software risk due to the development environment. This function uses the results of RL-TR-92-52, Worksheet 1B to determine the relative risk level. The percentage of development environment characteristics (Dc) applicable to the sys...
f27193929eccd96090944b5c69fb71b5afc3d477
190,884
def split_data(dataframe): """ Split the dataset into features and labels Parameters ---------- dataframe : the full dataset Returns ------- features : the features of the dataset labels : the attack flag label of the dataset """ label = ...
99f982def66318f3ab40de5cb868cce6548f19f8
665,585
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ if len(input_list) == 0: return -1 list_len = len(input_list...
347c6ed30b580746f7df96e8155a245f5c35c68a
146,719
def slice_repr(slice_obj): """ Get the best guess of a minimal representation of a slice, as it would be created by indexing. """ slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step] if slice_items[-1] is None: slice_items.pop() if slice_items[-1] is None: if slice...
c894f66478ec830a4968d0cfc5d9e146457012b6
705,237
def time_minutes(dt): """Format a datetime as time only with precision to minutes.""" return dt.strftime('%H:%M')
93288a8f0204dd56c59b18b75c62a5c1e059e159
670,469
def _invoke_codegen_rule_name(plugin, target_name, thrift_src): """Returns the name of the rule that invokes the plugin codegen binary.""" return "{}-cpp2-{}-{}".format(target_name, plugin.name, thrift_src)
04fe614abbce2049720b7636074dee6cc7b3184b
190,641
def _get_types(prop): """ Returns a property's `type` as a list. """ if 'type' not in prop: return [] if isinstance(prop['type'], str): return [prop['type']] return prop['type']
b6fbb21a7e1faf6f97d24ccb185e4f6e0229d6a5
151,378
def hamming(str1, str2): """Hamming distance between two strings""" return sum(a!=b and not( a=='N' or b=='N' ) for a,b in zip(str1, str2))
247bde164b51708a504c9aabbf429daeed62a07e
314,005
def wrap(x, low=0, high=360): """ Extended modulo function. Converts a number outside of a range between two numbers by continually adding or substracting the span between these numbers. Parameters ---------- x : int or float number to be wrapped low : int or float, optional ...
9cc2cd48cee745c8330da06462d00630271818f0
356,030
def map_value(in_v, in_min, in_max, out_min, out_max): """Helper method to map an input value (v_in) between alternative max/min ranges.""" v = (in_v - in_min) * (out_max - out_min) / (in_max - in_min) + out_min return max(min(out_max, v), out_min)
f6ccb04d4c5e49e6e228fb4498555204b35b91c6
322,791
def find_midpoint(low, high): """ Find the midpoint between two numbers. Expects low <= high. Args: low (int): Low number high (int): High number Returns: (int): midpoint between low and high """ if high < low: raise ValueError("Expected arg \"low\" to be less t...
d9cf25f6888eabd7d629e60f04b59c5880814589
317,219
def extractDigits(key): """Split a string which may contain a number into a tuple of the string without the digits, and the integer value of the digits. We can then use that as a good thing to sort on, so that we get "a5" and "a15" right. """ text = "" digits = "" for c in key: ...
e2c5acad9dbff04019f2197c1f5c42f5b9a36512
177,910
def _present_config_results(config_records, resource_ids): """ If resource_id is in config_records add to dictionary and return dictionary :param config_records: config compliance records :param resource_ids: list of resource ids :returns: dictionary of resource_id: compliance_type """ ...
4e72bd97bc8bbca3e00dd1aa095cee9b5744b0ca
241,299
import binascii def to_utf8_unicode_point_string(arg): """Given a string, encode it as UTF-8 and return a human-readable unicode point representation. Example:: >> to_utf8_unicode_point_string('A') U+41 >> to_utf8_unicode_point_string('hi ルーカスǃ') U+686920e383abe383bce382abe382...
6b98ccaf4ee4f85a2f54f86f50b1130d4d8a7304
239,108
def doc_flat_to_nested(key_list, val): """ Convert a flat keys and value into a nested document. e.g.: { a.b.c: 1 } => { a: { b: { c: 1 } } } """ res = {} if len(key_list) > 1: res[key_list[0]] = doc_flat_to_nested(key_list[1:], val) elif len(key_list) == 1: res[ke...
6959a9027b4e901557d6ce3f37e864b3892bb710
252,825
def normalize_url(url): """If passed url doesn't include schema return it with default one - http.""" if not url.lower().startswith('http'): return 'http://%s' % url return url
b957056e8ca32f6294c85466b6e52c56bb1dba84
693,995
import re from typing import OrderedDict def get_example_sections(example): """Parses a multipart example and returns them in a dictionary by type. Types will be by language to highlight, except the special "__doc__" section. The default section is "html". """ parts = re.split(r'<!-- (.*) -->', ...
a28ede469e82755528013a3b1cc08a56ed024577
663,834
from typing import Callable def has_non(function: Callable) -> Callable: """ A convenient operator that takes a function (presumed to have the same signature as all of the other functions in this section), and returns the logical "converse" - that is, a function which returns True if any part of the ...
f95c140bb7d295b8557dc9d7ddb3e42b1bf74ebf
71,190
import json def _get_metadata(dataset): """Get the layer metadata if exist""" metadata = [k for k in dataset['keywords'] if k.startswith('layer_info:')] if not metadata: return "" else: return json.loads(metadata[0].split("layer_info:")[1])
9c8a0269e9c841caeb299b4b489e8531ee9c5d0a
489,354
def pop_required_arg(arglist, previousArg) : """ Pop the first element off the list and return it. If the list is empty, raise an exception about a missing argument after the $previousArgument """ if not len(arglist) : raise Exception, "Missing required parameter after %s" % previousArg head = arglist[0...
ed35be7859326979dceb5843a07769e5a022a30b
56,157
import math def get_grid_size(k: int) -> int: """ returns the grid size (total number of elements for a cgr of k length kmers :param: k int -- the value of k to be used :return: int -- the total number of elements in the grid """ return int(math.sqrt(4 ** k))
2a770d0be8093a16f7c795fb6b8dfeccd8c8e140
568,752
from typing import List def hello_world(cities: List[str] = ["Berlin", "Paris"]) -> bool: """ Hello world function. Arguments: - cities: List of cities in which 'hello world' is posted. Return: - success: Whether or not function completed successfully. """ try: [print("Hello...
a24f0f47c9b44c97f46524d354fff0ed9a735fe3
706,644
def get_section_from_chunk(chunk, sectionname): """Extract a named section of a chunk""" section = [] in_section = False for line in chunk: if line == sectionname: in_section = True continue if in_section: if line == "": # We've reache...
d2e40c599545f5c770a50f260ce0ac858814a80e
72,187
import importlib def import_modules(*modules): """This function imports and returns one or more modules to utilize in a unit test. .. versionadded:: 2.7.4 :param modules: One or more module paths (absolute) in string format :returns: The imported module(s) as an individual object or a tuple of objec...
9b347215b95aa20dbb21b20fcfc926abac705558
213,142
import torch import math def nanmean(values: torch.Tensor) -> torch.Tensor: """ Computes the average of all values in the tensor, skipping those entries that are NaN (not a number). If all values are NaN, the result is also NaN. :param values: The values to average. :return: A scalar tensor contai...
424ffbb9a13d71c76d982f951c7691e700ccdd18
388,262
def pedir_entero(msj): """ Ejecuta input(msj) hasta que se ingrese un entero. """ while True: try: entero = int(input(msj)) except ValueError: print('El valor ingresado no es válido.') else: return entero
ee892b3b129916bb917d825c22975630b37cb414
493,979
import posixpath def _join_posixpaths_and_append_absolute_suffixes(prefix_path, suffix_path): """ Joins the POSIX path `prefix_path` with the POSIX path `suffix_path`. Unlike posixpath.join(), if `suffix_path` is an absolute path, it is appended to prefix_path. >>> result1 = _join_posixpaths_and_appe...
5ed573c7707f0a8e64a3f606597aafc7489e0edb
250,401
from string import ascii_lowercase def decimalToAlphabetical(index): """ Converts int to an alphabetical index. e.g.: 0 -> 'a', 1 -> 'b', 2 -> 'c', 'yama' -> 440414 :param index: int :return: str """ assert isinstance(index, int) and index >= 0 alphanum = '' index += 1 # because alpha...
c10d5e281cbc29ea6d835d9223cfacaa7d4ee9d6
418,699
import re def parse_show_snmp_community(raw_result): """ Parse the 'show snmp community' command raw output. :param str raw_result: vtysh raw result string. :rtype: list :return: The parsed result of the show snmp community\ command in a list of strings :: [ 'pub...
ce962b9030135153fd458440b2232a5546a9345f
192,712
import yaml def generate_rke_yaml(ips, user, ssh_private_key): """ Make the YAML file that RKE is going to use to create the kubernetes cluster :param ips: What IP addresses are we working with? Array of strings :param user: What user should we create? :param ssh_private_key: Private key text (utf...
889e3d73420ee4eb0c5d7c84531e37127c454368
366,456
import csv def parse_ngram_file(csv_file): """Parse a single ngram wordlist into a hashtable.""" ngrams = {} with open(csv_file, newline='') as f: for row in csv.reader(f): ngram = tuple(row[0].split()) ngrams[ngram] = True return ngrams
eec50a6a88104cec27809bf938a12c862d7deba2
383,077
def _process_init_command(args, _model): """Handle the init command: create an empty password database.""" assert args.command == 'init' # Keep the model empty and let the main() function write out the database. return 0
684d6f8c68bceb79dd1c18a934a4009762bd238d
162,911
from typing import List from typing import Dict from typing import Any def format_sents_for_output(sents: List[str], doc_id: str) -> Dict[str, Dict[str, Any]]: """ Transform a list of sentences into a dict of format: { "sent_id": {"text": "sentence text", "label": []} } """ ...
d6178ac48da4d95e8d3727ca9220168e06ba223e
8,177
def _get_fuzzer_module_name(fuzzer: str) -> str: """Returns the name of the fuzzer.py module of |fuzzer|. Assumes |fuzzer| is an underlying fuzzer.""" return 'fuzzers.{}.fuzzer'.format(fuzzer)
7fcebf65168d6dc4e4f70a941fe6b0e30cb5790c
218,469
def filter_matching_taxon_ids(query_set, taxon_id=None): """Filters out all instances with a taxonomy id that does not match `taxon_id` if taxon_id is not None. Taxonomy id must be one supported by `UniProt`. Parameters ---------- query_set : :class:`Query` A query instance from `sqlalc...
55cae9addfe1db488a1cbb26c9c9408dfd86780e
132,941
def Top1Accuracy(predictions, recognition_solution): """Computes top-1 accuracy for recognition prediction. Note that test images without ground-truth are ignored. Args: predictions: Dict mapping test image ID to a dict with keys 'class' (integer) and 'score' (float). recognition_solution: Dict ma...
456344b5fcf12e1523cb7dc2f4f5d0064e596db4
498,801
def loop_noise_coupling_functions(olg, clp, chp, lock='active'): """Control loop coupling functions for a opto-mechanical cavity. Inputs: ------- olg: array of complex floats Open loop gain clp: array of complex floats Cavity low pass chp: array of complex floats Cavity h...
1ff646772254fe07435493f98c76570d303fc670
122,564
def size_table_name(model_selector): """ Returns canonical name of injected destination desired_size table Parameters ---------- model_selector : str e.g. school or workplace Returns ------- table_name : str """ return "%s_destination_size" % model_selector
5309738dd0b59c745c88e30e64f301d0b2cbf949
563,932
import re def strings(filename, minChars=4): """Search printable strings in binary file :param filename: The file to be read :type filename: str :param minChars: Min-len of characters to return string *(default 4)* :type minChars: int :returns: List of printable strings :rtype: list ...
caacb1385fa2676b24d38b9b749cdd6a5a497599
597,725
from random import gauss def random_mbh(type='agn'): """randomizes a black hole mass (in solar masses). one can choose between ``agn`` and ``xrb``.""" if type == 'agn': # log M_bh = N(7.83, 0.63) (jin12) return 10**gauss(7.83, 0.63) elif type == 'xrb': return 10**gauss(1.1, 0.15) ...
58a1b638fc1acf1a0bf90a25bc3f929f92f338b7
112,279
def second_valid_range_str(second_valid_range): """ Fixture that yields a string representation of a range within the bounds of the "second" field. """ start, stop = second_valid_range[0], second_valid_range[-1] return '{0}-{1}'.format(start, stop)
fc58fd7191289986d50a5302565a3c000f9154b6
331,974
def set_time_resolution(datetime_obj, resolution): """Set the resolution of a python datetime object. Args: datetime_obj: A python datetime object. resolution: A string indicating the required resolution. Returns: A datetime object truncated to *resolution*. Examples: .. ...
449d5ac691ea04ce2a19fb825743d081add5990c
101,120
def handle_title(block): """ Extracts information from a title block (from a README doctree). Args: block: A title doctree block Returns: A dictionary with the extracted information """ ret = { 'type': 'title', 'text': '\n'.join((block.astext(), '~' * 20)), } r...
671a76fbd6757d6036c16d94dd40e1729ecb6025
469,182
def generate_test_description(local_symbols, *variable_names): """ Generate test description. :param local_symbols: local symbol table from where the function was called :param variable_names: variable names :return: test description """ variables_text = ', '.join('{} = {}'.format(variable_...
4eddea7075994cc8e3d9e5da4bdb4bf8c85c8aad
64,897
def two_pts_to_line(pt1, pt2): """ Create a line from two points in form of a1(x) + a2(y) = b """ pt1 = [float(p) for p in pt1] pt2 = [float(p) for p in pt2] try: slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0]) except ZeroDivisionError: slp = 1e5 * (pt2[1] - pt1[1]) a1 =...
d607008c41eaa052c0988a7ac66588b464aab8e0
701,271
def getKeyByValue(dictOfElements, valueToFind): """Get the first key that contains the specified value.""" for key, value in dictOfElements.items(): if value == valueToFind: return key
b568ab7d6e901d548a1295ef8885c67e698a2cf0
308,639
def get_resultant(X,Y,Z): """This function gets the resultant magnitudes of three arrays of vector quantities: X, Y, and Z.""" resultant = [] for i in range(len(X)): resultant.append((X[i]**2 + Y[i]**2 + Z[i] **2)**0.5) return resultant
494f819008a86a1a60e52f2f1bb9b5ac011b0508
598,773
def gillespie (r, *args, **kwargs): """ Run a Gillespie stochastic simulation. Examples: rr = te.loada ('S1 -> S2; k1*S1; k1 = 0.1; S1 = 40') # Simulate from time zero to 40 time units result = rr.gillespie (0, 40) # Simulate on a grid with 10 points from start 0 to end...
420c1c5b2d97ded73dc077cad30f6fa94a4e5c79
110,257
def substract(v1, v2): """ Returns the difference of a two 2-D vectors. """ return (v2[0] - v1[0], v2[1] - v1[1])
39a99b79dbe6e9ee638ed7c001ec84119e70160b
177,852
import torch def get_loss_cumu(loss_dict, cumu_mode): """Combine different losses to obtain a single scalar loss. Args: loss_dict: A dictionary or list of loss values, each of which is a torch scalar. cumu_mode: a 2-tuple. Choose from: ("generalized-mean"/"gm", {order}): generaliz...
27fe5ac266cde59333c5c7f0c40da7ae9f483abe
359,166
def make_progress_bar_text(percentage: float, bar_length: int = 2) -> str: """ Get the progress bar used by seasonal challenges and catalysts and more Translations: "A" -> Empty Emoji "B" -> Empty Emoji with edge "C" -> 1 Quarter Full Emoji "D" -> 2 Quarter Full Emoji ...
6422dfbb7f4bb9b875491398fab57e9f8af5a380
677,345
def _is_kind(cell, kinds:str) -> bool: """Internal function: Check if cell is of one of the given kinds.""" if kinds == 'all' or cell.cell_type in kinds: return True if 'jollity' in cell.metadata: return f'md:{cell.metadata.jollity.kind}' in kinds return False
aa0c41fba6c8bf4f847dfc229e31808fd9482b14
262,760
import re def clean_license_name(license_name): """Remove the word ``license`` from the license :param str license_name: Receives the license name :return str: Return a string without the word ``license`` """ return re.subn(r'(.*)\s+license', r'\1', license_name, flags=re.IGNORECASE)[0]
970d933911b69ba9a1f33a768bc68032334d41c3
15,213
def short_time(time): """ Better readable time - remove subseconds """ return str(time)[:-4]
43cda011a592b49a525c2ddfa2786a391871331a
160,094
import torch def load_model(model, model_path, optimizer_path=None): """ Loads model and optimizer (if given) from state_dict """ model.load_state_dict( torch.load(model_path)) if optimizer_path: optim = torch.load(optimizer_path) return model, optim return model
f91da26579309114a459be9d9c93d84f25b88432
140,121
import errno def read_file(path): """Returns contents of a file or None if missing.""" try: with open(path, 'r') as f: return f.read() except IOError as e: if e.errno == errno.ENOENT: return None raise
9e8f8727eb453169045c7259f690fa3b0504266d
458,208
def clean_game_date(season_year: int, date: str) -> str: """Creates a date string from a season year and date string. Args: season_year (int): The season year. date (str): The date string. Returns: str: The date string if the date is part of the regular season, otherwise ...
361f4516332f3f4eb9dc8fcfcd831f7acd4da709
455,213
def getusername(cursor, displayname): """Retrieve internal username from display name.""" cursor.execute("select username from profile where displayname = ?;", (displayname,)) username = cursor.fetchone() if username is None: return None return username[0]
48caeb3de8101788280a9eca069e6be5dc51e6ee
523,503
def rgb_tuple_to_hex_str(rgb, a=None): """ Return a hex string representation of the supplied RGB tuple (as used in SVG etc.) with alpha, rescaling all values from [0,1] into [0,255] (ie hex x00 to xff). Parameters: rgb - (r,g,b) tuple (each of r,g,b is in [0,1]) a - (default None) al...
fb009639fab6f1e6779397a91b5875820632e713
497,288
def freq_id_to_stream_id(f_id): """ Convert a frequency ID to a stream ID. """ pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256)) stream_id = ( (pre_encode[0] & 0xF) + ((pre_encode[1] & 0xF) << 4) + ((pre_encode[2] & 0xF) << 8) + ((pre_encode[3] & 0xF) << 12) ) ...
f89d52adf4390f665e069c2b5f4f5accc22709b8
702,189
def best_evaluation(history): """Return the best-ever loss and accuracy. Not necessarily from the same epoch.""" best_loss = min(history.history['val_loss']) best_accuracy = max(history.history['val_acc']) return best_loss, best_accuracy
49a5087819acd7d69760d4cf3c60d976dc360262
198,571
def one_or_none(values): """Fetch the first value from values, or None if values is empty. Raises ValueError if values has more than one thing in it.""" if not values: return None if len(values) > 1: raise ValueError('Got more than one value.') return values[0]
e3d1517d6dd32a8f1f04a0eee56d49d844028ca2
284,243
def make_batch_indexes(size, data_len): """ Creates a list of start and stop indexes where start is <size> away from end. The start and stop indexes represent the start and stop index of each batch ranging for the entire data set. Parameters ---------- size: int The size of the batches...
20c0ad14f8460f155342b0d443062c201dcbc891
210,678
def getBoundingBox(veclist): """Calculate bounding box (pair of vectors with minimum and maximum coordinates). >>> getBoundingBox([(0,0,0), (1,1,2), (0.5,0.5,0.5)]) ((0, 0, 0), (1, 1, 2))""" if not veclist: # assume 3 dimensions if veclist is empty return (0,0,0), (0,0,0) # fin...
a2c035f85071e5a9f8dfee2c98cc46e86439a0cc
22,033
def is_child_class(target, base): """ Check if the target type is a subclass of the base type and not base type itself """ return issubclass(target, base) and target is not base
731c551149f94401a358b510aa124ee0cba6d0bd
41,567
def pretty_print_dict(dtmp): """Pretty prints an un-nested dictionary Parameters ---------- dtmp : dict Returns ------- str pretty-printed dictionary """ ltmp = [] keys = dtmp.keys() maxlen = 2 + max([len(K) for K in keys]) for k, v in sorted(dtmp.items(), ...
1033777a6a79e4a86bc0b2f4edbaa3a3124e161f
248,998
import hashlib def string_hash(obj): """Returns a SHA-1 hash of the object. Not used for security purposes.""" return hashlib.sha1(str(obj).encode('utf-8')).hexdigest()
957958b1e2623c28cdb4b12ee0163fab43199ded
123,797
def depth(root): """ root is a tree node pointer that has access to left and right, returns the height of the tree + 1 """ if root is None: return 0 return 1 + max(depth(root.l), depth(root.r))
1c9fcd578189a7b4200644fb1bfb80d818bf5a46
325,595
def _get_end(posn, alt, info): """Get record end position.""" if "END" in info: # Structural variant return info['END'] return posn + len(alt)
f26e6bd9049fb32d5a5fcf305014b81c16bd799d
221,527
def floatToStr(number: float, showNumOfDigits: int = 2) -> str: """ Convert float number with any number of decimal digits and return string with ``showNumbOfDigits`` places after ``.``. Args: number: float number to convert to string. showNumOfDigits: number of decimal places (characters)...
71099609ea05211d8f3a35401685f355e8ddaa21
554,494
def get_potential_compressed_names(path): """ Get a list of all possible variants of @path with supported compressions (including the uncompressed path). """ return [path + x for x in ('', '.gz', '.bz2', '.lzma', '.xz')]
2f5f3cf26f9324805de8db7858bfe31e2f5d466e
200,196
import re def clean_name(name: str) -> str: """ Clean a name so it can be used as a python identifier. """ if not re.match("[a-zA-Z_]", name[0]): name = "_" + name name = re.sub("[^0-9a-zA-Z_]+", "_", name) if all(c == "_" for c in name): name = "v" return name
e37bc249104c03b25da6e39e59d7084c6ae9b95d
439,231
def spherical_index_k(degree: int, order: int = 0) -> int: """returns the mode `k` from the degree `degree` and order `order` Args: degree (int): Degree of the spherical harmonics order (int): Order of the spherical harmonics Raises: ValueError: if `order < -degree` or `order > deg...
592b0dd5550fe28ce79568b74ab4a071b57bf99b
220,147
def produce_tel_list(tel_config): """Convert the list of telescopes into a string for FITS header""" tel_list = "".join("T" + str(tel) + "," for tel in tel_config["TelType"]) return tel_list[:-1]
46a69c9c2b1f006376dc1fe730023c6d8a7db859
156,172
def GetListOfFeatureNames(feature_names): """Extract the list of feature names from string of comma separated values. Args: feature_names: string containing comma separated list of feature names Returns: List of the feature names Elements in the list are strings. """ list_of_feature_names =...
1e922c49afd978cb31d0883cf361f298b2c0aa25
470,726
def segments_from_time_to_frame_idx(segments, hop_length_seconds): """ Converts a sequence of segments (start, end) in time to their values in frame indexes. Parameters ---------- segements : list of tuple The list of segments, as tuple (start, end), to convert. hop_length_seconds : flo...
029b0dedc5fbedbf590e89f976f23b555c5a60bf
416,668