content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def position(T, s): """renvoie la position de la chaine s dans la liste T Si s n'appartient pas à la liste T, la fonction renvoie -1 à la place. T: liste de chaine de caractères s: chaine de caractère résultat: nombre entier """ try: return T.index(s) except ValueError: ...
8ddb1b3ea414fc84531f4c076b2836ec97def4bc
679,698
def IdToString(peg_bitfield): """ input peg position bitfield returns the peg positions as a string """ my_string = [''] * 36 result_string = [''] * 7 cur_pos = 0 for row in ['A', 'B', 'C', 'D', 'E', 'F']: for col in ['1', '2', '3', '4', '5', '6']: my_string[cur_...
319ff2c5277cb4c270618aca8db93e9ed576b8de
679,699
import os def file_is_missing_or_empty(file_path:str): """ Returns true if the file corresponding to the file argument exists or the file size is zero; false otherwise """ return not os.path.exists(file_path) or os.path.getsize(file_path) == 0
622479efe16355ad628a9bacb6d4acc4ac0cf58b
679,700
from warnings import warn def rssi2dist(ctx, rssi, rexp=2): """ simple r^2 loss ctx = transmitter EIRP [dBm] received at 1 meter (reference quantity) rssi: currently received signal strength [dBm] """ if ctx > 0: warn("does your BLE transmitter really give {} dBm at one meter distance?".fo...
dfb9adb43d3bf0cbd7c8414f9b546b2b4fe8a905
679,701
def last_common_item(xs, ys): """Search for index of last common item in two lists.""" max_i = min(len(xs), len(ys)) - 1 for i, (x, y) in enumerate(zip(xs, ys)): if x == y and (i == max_i or xs[i+1] != ys[i+1]): return i return -1
76baebee425dda29c08af32659a4418bef83e9bb
679,702
import argparse def get_command_line_arguments(): """ Get the command line arguments return: args: The command line arguments as an ArgumentParser """ parser = argparse.ArgumentParser(description='Training script for CartPole-v0 RL model.') parser.add_argument('--population', help='Tot...
20f3a69e62e675525badf4036c674fb6ba9a72e7
679,703
def gen_anytext(*args): """ Convenience function to create bag of words for anytext property """ bag = [] for term in args: if term is not None: if isinstance(term, list): for term2 in term: if term2 is not None: bag.a...
54749b40142465c03a8ac19cb7a1175b7e7ee0e7
679,704
def args_for_blocking_v_whatsapp_net_https(): """ Returns arguments for blocking v.whatsapp.net over https """ # # 00 00 <SNI extension ID> # 00 13 <full extension length> # 00 11 <first entry length> # 00 <DNS hostname type> # 00 0e <stri...
2432d1f6711d38f0807d5dc7b548948c7e603360
679,705
import sys import math def int_to_float(n): """ Correctly-rounded integer-to-float conversion. """ PRECISION = sys.float_info.mant_dig + 2 SHIFT_MAX = sys.float_info.max_exp - PRECISION Q_MAX = 1 << PRECISION ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1] if n == 0: ...
915d9ed7ff1370f5856e1f6058fc80284bbfdba8
679,706
def return_none(): """ Simple method that returns None for defaultdict to allow pickling :return: None """ return None
ffa85eec013a212a204923e365701e2b7cf39ef4
679,707
import math def mean_earth_sun_distance(when): """Mean Earth-Sun distance is the arithmetical mean of the maximum and minimum distances between a planet (Earth) and the object about which it revolves (Sun). However, the function is used to calculate the Mean earth sun distance. Parameters ------...
5df2229a39cb2ac9232a984ab10d6616a11a2711
679,708
import requests import json def sumByAccId(_reg, _aId, _apiKey): """Get a summoner by account ID""" response = requests.get("https://" + _reg + ".api.riotgames.com/lol/summoner/v4/summoners/by-account/"+ _aId + "?api_key=" + _apiKey) data = json.loads(response.text) #print(json.dumps(data, indent=4)...
b31f301664c5b4755bbea3a291a38655c138a1d2
679,709
def get_catalog_record_data_catalog_id(cr): """ Get identifier for a catalog record. :param cr: :return: """ return cr.get('data_catalog', {}).get('catalog_json', {}).get('identifier', '')
b59515152878a5d3c1b44370689acadfc1ebe7b6
679,711
import random def Die(faces): """ :return: 返回一个 1 到 faces 的随机数 """ roll = random.randint(1, faces) return roll
d0595c40a3966835f9aa1bd0352099646c6cd68b
679,712
import random def getSubject(): """ Returns a string """ choose = ("This is it", "It's finally here", "Countdown ends", "Hope you prayed", "There is hope", "D3@D", "Don't panic!", "You'll be surprised", "Okay Okay Okay", "Not a prank", "There's always next sem", "Doomsday",...
80df9fbbc589209dbff9ce36fc7c0cccdcecfead
679,713
def watchdog(badger, endBlock): """ Watchdog Ensure that the root has been updated within the maximum interval If not, the system is not functioning properly, notify admin """ return False
b5cd293f46c5f5d32a7158a7bcecd3d33e9a2115
679,715
def energy(data_list): """Returns energy column from the given data, which was presumably made using the standard clobber() function :data_list: double numpy array :returns: list of second composition values """ return data_list[:,3]
df4864b28b731e662f449f031d8485b5c8bed57b
679,716
def bool_on_off(value): """Convert True/False to on/off correspondingly.""" return 'on' if value else 'off'
387cee885ccc47a5415d810d1064f2d66bca6131
679,718
def _GetAminoAcidResidueNames(): """Get list of amino acid residue names. """ ResidueNames = ["ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL"] return ResidueNames
b0fa54297e45daa2615a0c482da10b46402465ce
679,720
def getStereoPair(pipeline, monoLeft, monoRight): """ Generates a stereo node. Takes left and right camera streams as inputs and generates outputs """ stereo = pipeline.createStereoDepth() stereo.setLeftRightCheck(True) monoLeft.out.link(stereo.left) monoRight.out.link(stereo.right) return stereo
5ef27fdb4f2a635adcf026d1e148a484a66f7718
679,721
import os def ensure_dirs(fpath): """ Given a file path, ensure parent folders exist. If path is intended to be a directory -- use os.makedirs(path) instead. May throw exception -- caller should handle. :path: path a file """ d = os.path.dirname(fpath) if d and not os.path.isdir(d): ...
7a39d2ae49e99f78b82e683d32d4d0cb633512ef
679,722
from fractions import Fraction def compile_continued_fraction_representation(seq): """ Compile an integer sequence (continued fraction representation) into its corresponding fraction. """ # sanity check assert seq # initialize the value to be returned by working backwards from the last number...
6140f5e74c88734b8f9be1f0df191ed82c8540e3
679,723
def get_skin_num(id, skin_id): """ Returns Skin Number from the Skin ID """ skin = str(id) length = len(skin) new_id = str(skin_id)[length:] return int(new_id)
0ade64b93280efc5662c1d7fcfa7627d7aae3cb6
679,724
def check_int(value: int) -> bool: """Check whether value can be written as 2^p * 5^q where p and q are natural numbers.""" if value == 1: return True else: if value % 2 == 0: return check_int(value//2) if value % 5 == 0: return check_int(value//5) ret...
754d89997e73acd81dd8d08f50a88f29f50b6783
679,725
def make_ngrams(tokens: list, n: int) -> list: """Creates n-grams for the given token sequence. Args: tokens (list): a list of tokens as strings n (int): the length of n-grams to create Returns: list: list of tuples of strings, each tuple being one of the individual n-grams """ n_grams ...
17699d058d2d8707e68642bc22f91996757882c3
679,726
import inspect def get_channelmethods(obj): """ Returns a sorted list of the names of all channelmethods defined for an object. """ channelmethods = list() # getmembers() returns a list of tuples already sorted by name for name, method in inspect.getmembers(obj, inspect.ismethod): # To...
2443434f3b4141272cbf6266cfec2da5c57d1e90
679,727
def IsDuplicateMethod(aType, methodName): """Duplicate Method?""" for method in aType.methods: if method.name == methodName: return True return False
70f4ac990b04abebd089d8a0066ad2f2925ec83b
679,728
def bd_ba(listing): """Score based on number of bedrooms.""" score = 0.0 if listing.bedrooms is None: return score size = listing.size if listing.size is not None else 250 * listing.bedrooms bathrooms = 1.5 if listing.bathrooms is None else listing.bathrooms if bathrooms > 2 and bathroom...
a22f850f9ea5bf01be07c6edb344e38c077dba63
679,729
def index_of(val, in_list): """ :param val: String variable to test :param in_list: list of Strings :return: index of the value if it's in the list """ try: return in_list.index(val) except ValueError: return -1
bc59faf2f1d0a8f3de7ac4eba8b138c7fa26fb4e
679,730
def map_range(value, from_lower, from_upper, to_lower, to_upper): """Map a value in one range to another.""" mapped = (value - from_lower) * (to_upper - to_lower) / ( from_upper - from_lower ) + to_lower return round(min(max(mapped, to_lower), to_upper))
dd4bd400e4b117af4ff73a551771b7921b6148f6
679,731
def default_logfile_names(script, suffix): """Method to return the names for output and error log files.""" suffix = script.split('.')[0] if suffix is None else suffix output_logfile = '{}_out.txt'.format(suffix) error_logfile = '{}_err.txt'.format(suffix) return output_logfile, error_logfile
b28b03f1b3f49efdb2d286bb431b9ad99145b32f
679,732
import re def str_split(string, split_length=1): """Method splits string to substrings Args: string (str): original string split_length (int): substrin length Returns: list: list of strings """ return list(filter(None, re.split('(.{1,%d})' % split_length...
65dd325fb7fda7ac1af2b18840e42f567d1b971d
679,733
import os def del_empty_dirs(s_dir): """Delete empty directories.""" b_empty = True for s_target in os.listdir(s_dir): s_path = os.path.join(s_dir, s_target) if os.path.isdir(s_path): if not del_empty_dirs(s_path): b_empty = False else: b_emp...
a01edf3f9fcfcf0959a80f0025297cd5174e0679
679,734
from datetime import datetime import os import tempfile def generateRandomFile(size, prefix="", suffix=""): """ Generate a randomly named file of size, <size>, with random contents. Returns a handle to the file. """ if prefix: # add file prefix if set. prefix += "_" if suffix: # add...
02da33ca1b8c8385932ad7a7e47768ba544f72ee
679,735
def bui_calc(ndbi, ndvi): """ Buil-up index """ return ndbi-ndvi
c5943c1b93ea978da337e05e6b25f2b8400c0877
679,736
def min_depth(root): """Figure out minimum depth of binary tree.""" if root is None: return 0 if root.left and root.right: return min(min_depth(root.left), min_depth(root.right)) + 1 else: return max(min_depth(root.left), min_depth(root.right)) + 1
0fc868acb6dfd924b2b7bada054819919ada426b
679,737
def get_goods_linked_to_destination_as_list(goods, country_id): """ Instead of iterating over each goods list of countries without the ability to break loops in django templating. This function will make a match for which goods are being exported to the country supplied, and return the list of goods...
4a794d76cbc204e8cf48ab2703d7a4734d0b4305
679,738
from collections import Counter from typing import List def majority_element2(nums: 'List[int]') -> int: """ 解法2:使用Counter. """ c = Counter(nums) # return max(c.keys(), key=c.get) return c.most_common(1)[0][0]
75679a224bab997caae64d7f1a987ee1dd894269
679,739
import sys def version(): """ version of python Returns: integer version of python (2 or 3) """ return int(sys.version_info[0])
99c51f18b3f67747b36f2ecd49b82c1108b4f76e
679,740
import os def _try_read_from_file (potential_filename): """ Reads data from a file or returns the data 'as is'. Args: potential_filename(str): the data, which can also be a filename. Returns: str: data read from file or the content of parameter 'potential_filename' """ _data ...
5464bb9bcb54c4ac62326b423b97e98563d91108
679,741
def isAnagram4(self, s, t): """ :type s: str :type t: str :rtype: bool """ arr = [0]*26 for char in s: arr[ord(char) - ord('a')] += 1 for char in t: arr[ord(char) - ord('a')] -= 1 for num in arr: if num is not 0: return False return True
b1de11d45157f6c4f1a491b3dabc1046d143b26f
679,742
def flatten(l): """Flattens a list of lists to the first level. Given a list containing a mix of scalars and lists, flattens down to a list of the scalars within the original list. Args: l (list): Input list Returns: list: Flattened list. """ if not isinstance(l, list...
87cf038798ce562b0bdce5efbd573f4a800d1ebf
679,743
import argparse def get_args(): """! Command line parser """ parser = argparse.ArgumentParser(description='Mixture dataset ' 'creator') parser.add_argument("--dataset", type=str, help="Dataset name", default="timit") parser.add_a...
507b45b6d2c780c14116c539721612c140ad3120
679,744
def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): """ returns: (family, type, proto, canonname, sockaddr) """ return_value = [ ("family", "type", "proto", "canonname", ("192.168.1.1", 80)), ("family", "type", "proto", "canonname", ("192.168.1.2", 80)), ("fa...
233213b058674e54c0604743549077b1cc12e69a
679,745
def is_annotation_size_unusual(annotation, minimum_size, minimum_aspect_ratio, maximum_aspect_ratio): """ Checks if object described by annotation has unusual size - is too small or has unusual aspect ratio :param annotation: net.utilities.Annotation instance :param minimum_size: int, minimum size objec...
d9f62e3600faeee0662d29aaba4d0d26a6b9252f
679,746
def make_wrapped(text): """Wrap text so it does not wrap on a 80-column display, with extra tabs.""" outbuf = ['\t'] pos = 8 last_space = -1 for ch in text: outbuf.append(ch) pos = pos + 1 if ch == '\n': outbuf.append('\t') pos = 8 if ch == ' ...
e79516c70bf4bc37d668228c88e44df7c53101ef
679,747
def makespan(orders): """ Finish time of last task """ return max(v[-1].end for v in orders.values() if v)
bbf781422aa34bf2249fb70e233fa6eac870431f
679,748
def to_json_list(objs): """ Wrap strings in lists. Other iterables are converted to lists directly. """ if isinstance(objs, str): return [objs] if not isinstance(objs, list): return list(objs) return objs
b2541ca880856aa07e8178ac6924caab0a2ffa00
679,749
def make_list(item_or_items): """ Makes a list out of the given items. Examples: >>> make_list(1) [1] >>> make_list('str') ['str'] >>> make_list(('i', 'am', 'a', 'tuple')) ['i', 'am', 'a', 'tuple'] >>> print(make_list(None)) None >>> # ...
5769e6331fce84d9ae236ddb1c38d081379c08ab
679,750
import os def remove_file(path): """ Just removes a file. Used for deleting original files (uploaded by user) and result files (result of converting) """ return os.remove(path)
90692e196739947bffdf896781ce07d52bea7a08
679,751
def check(these_bytes): """Tests a file for presence of a valid header""" test = str(these_bytes[8:12]) if test[2:6] != 'logo': return 1 return 0
36e4df36be229fc280ba4db2b568c02717102e19
679,752
def get_polynomial_points(coefficients, num_points, prime): """ Calculates the first n polynomial points. [ (1, f(1)), (2, f(2)), ... (n, f(n)) ] """ points = [] for x_coeff in range(1, num_points+1): # start with x=1 and calculate the value of y y_coeff = coefficients[0] ...
c957eb472136a0f565a469ab7b3cbee8020a3a0f
679,753
def safe_get(lst, index, default=None): """ An implementation of the similar :meth:`get` of the dictionary class. :param lst: the list to perform the operation on :param index: the index to query :param default: the default value if not found :return: the result if exists or the def...
d1f1410663ed4ff090e38594ff5dac1d304fecc3
679,755
def getParameters(member, groups, section, events): """ Extracts and constructs a section's parameters """ params = {} if ('parameters' in section) and \ (section['parameters'] is not None): plist = [] for sp in section['parameters']: p = str(sp) if (p ...
e0e43b00097fe21758f6d36a225c357ff7e06692
679,756
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int: """Calculates the sum (or difference) of two numbers. Parameters: `x` : int The first number `y` : int, optional The second number (default is 1) `subtraction`: bool, optional Whether to perform subtraction...
8f46dadf73536167c23e17d3b5da0f57fd084d7e
679,757
def order_and_format_updates(updates, subject_type, locale, format_function, attr_index='attribute'): """Orders attribute updates in the same order specified by subject_type.attribute_names, in the given locale.""" updates_by_name = dict((update[attr_index], update) for update i...
0a9e7bd49c85f8fd6fbec620f8f4fd8c98ec55d2
679,758
def elevation_line(client, format_in, geometry, format_out='geojson', dataset='srtm', validate=True, dry_run=None): """ POSTs 2D point to be enriched with elevation. :param format_in: Format of input geometry. One of ['geojson'...
cc53bc954ec9b110ef0858cfd34236b8c1d77070
679,759
def get_extension(format, default, **alternates): """get the extension for the result, needs a default and some specialisations Example: filetype = get_extension(format, "png", html="svg", latex="eps") """ try: return alternates[format] except KeyError: return default
7ccc9626b025b3ebe60e4d5bbf07a14d803250cd
679,761
import unicodedata def wide_chars(s): """return the extra width for wide characters ref: http://stackoverflow.com/a/23320535/1276501""" return sum(unicodedata.east_asian_width(x) == 'W' for x in s)
4960dea103afcc8546f3e75682a25d5bca40b260
679,762
import sqlite3 def commit_data(conn): """Commit data to db""" try: conn.commit() conn.close() except sqlite3.Error as e: print(e) return None
5107563c659c0acdd9d2d59c526284ffe38a4740
679,763
def right_trim(seq1, seq2): """Trim 3'bases if they are identical Args: seq1, seq2 (str): alleles in .vcf Returns: seq1, seq2 (str) """ if len(seq1) == 1 or len(seq2) == 1: return seq1, seq2 while seq1[-1] == seq2[-1] and len(seq1) > 1 and len(seq2) > 1: seq1, seq2 =...
d3351a2bfe09b92b546674552bd9c3c360b75820
679,764
import torch def warp_network_in_dataparallel(net, gpuid): """ Wrap the network in Dataparallel """ # torch.cuda.set_device(gpuid) # net.cuda(gpuid) net = torch.nn.parallel.DistributedDataParallel(net, device_ids=[gpuid], find_unused_parameters=True) # net = torch.nn.parallel.Distribut...
eef0a263742ab063a0d90dfad1745937b4717aa0
679,765
def _get_regular_TYC_name(*args): """Convert a TYC name in *Tycho-2 Catalogue* to its regular form `"TYC NNN-NNN-N"`. """ if len(args) == 1 and isinstance(args[0], str): name = args[0].strip() return 'TYC ' + name[3:].strip() elif len(args) == 3: return 'TYC '+'-'.join([str(a...
401914160ab347d1bf399cf80dac9fbd0004584a
679,766
import re def _strip_terminal_commas(data: str) -> str: """Remove all terminal commas. Samples sheets have a large number of commas append to the end of the various sections. I think this is an artifact of exporting to a CSV forcing each row to have the same number of columns as the main Data sec...
656e0114fe4ce94937bfbc1a4b99f61510cf6762
679,767
import subprocess def _jupyter_notebook_list(): """Runs the jupyter notebook list command and returns the output string""" process = subprocess.run( "jupyter notebook list".split(), stdout=subprocess.PIPE, text=True ) if process.returncode == 0: return process.stdout else: ...
97e430f5a23d37737f169ec33366a14c3a59e6ba
679,768
def _get_runfile_path(ctx, f): """Return the runfiles relative path of f.""" if ctx.workspace_name: return ctx.workspace_name + "/" + f.short_path else: return f.short_path
50b64d1e90ebfb4599b081d1789b0f7b789b2e28
679,769
import os def parse_label(label_fname, inv_lbl_dict): """Parse label information from mat files Args: label_fname: full path of the mat file, storing label information inv_lbl_dict: inverse label dictionary Return: start: list of start frame id stop: list of stop frame id...
1f290205f64221293b739ce0c8229070cebf2d34
679,771
def calculate_cn_values(m, sigma_veff): """ CN parameter from CPT, Eq 2.15a """ CN = (100 / sigma_veff) ** m if CN > 1.7: CN = 1.7 return CN
d1dfb14414bfe0f59a5a432e6c5dfd4994ee29ff
679,772
def gather_locks(context, lock_a, lock_b): """ Gather all locks for the materialization process. """ return [lock_a, lock_b]
85a4f4ad34ce443bf5d3434c4645f7913d965570
679,773
def _underlyingfctxifabsent(filectx): """Sometimes when resolving, our fcd is actually an absentfilectx, but we want to write to it (to do the resolve). This helper returns the underyling workingfilectx in that case. """ if filectx.isabsent(): return filectx.changectx()[filectx.path()] e...
faf9ba8ba1c48e0769991ffcc4e5c4f94f92e21c
679,774
def check_args(args): """ eval and check arguments """ if not args.log_name: args.log_name = "blabber.log" if not args.log_level: args.log_level = "INFO" return args
028275e2589171d9ec5dc5c3f3c16008ba6e512f
679,775
import torch def shuffle_data(inputs, outputs): """Shuffle the first dimension of a set of input/output data""" n_examples = outputs.shape[0] shuffled_indices = torch.randperm(n_examples) inputs = inputs[shuffled_indices] outputs = outputs[shuffled_indices] return inputs, outputs
6c264ae3840c4c0c338c9423e3a74a1598e6946b
679,776
import traceback import sys def add_task_and_subtasks(analysisTask, analysesToGenerate, verbose, callCheckGenerate=True): # {{{ """ If a task has been requested through the generate config option or if it is a prerequisite of a requested task, add it to the dictionary of ...
b7d934a748d86a9599e1d143353fecab520f637d
679,777
import re def is_valid_entity(line: str) -> bool: """Check if the line is a valid entity annotation.""" regex = r'^T\d+\t\w+ \d+ \d+(;\d+ \d+)*\t.+$' return re.search(regex, line) is not None
7340603532b6ec9891e1d73047261c3ef1a23a49
679,778
def example_file(request): """An example file from the documentation directory""" return request.param
5b1799373ab878e1559b864962a91481bba8d61c
679,779
def _blob_and_weights(net, layer_name): """Get the activation blob and the weights blob for the named layer in the Caffe network. """ # Get the activation blob for this layer and its parameters # (weights). blob = net.blobs[net.top_names[layer_name][0]] weights = net.params[layer_name][0] ...
07fb1a2c363f710d6f53691facb3a07ef33a3475
679,780
def cli(ctx, group_name, user_ids=None, role_ids=None): """Create a new group. Output: A (size 1) list with newly created group details, like:: [{u'id': u'7c9636938c3e83bf', u'model_class': u'Group', u'name': u'My Group Name', u'url': u'/api/gro...
ec2cb7ba38bdc25a4161d32f3a9f46212ec7589e
679,781
import os def config_from_environment(struct: tuple) -> dict: """Return dict from environment.""" return { x: y(os.environ['WIRELOGD_' + x.upper().replace('-', '_')]) for x, y, _ in struct if os.getenv('WIRELOGD_' + x.upper().replace('-', '_')) }
5a40262641fd1cea59c9edf6a02abf790227bde9
679,782
def correct_normal(normal, incident): """Corrects a vector so that is in a given half plane Parameters ---------- normal : Base.Vector incident : Base.Vector Returns ------- """ if normal.dot(incident) > 0: return normal * (-1) else: return normal
789c3b9a470d79c65dd0880d9ea995ad498278e8
679,783
def gauss(A, b): """ @param A: matrix @param b: vector @return: reduced echelon form of A|b """ n = len(A) for i in range (0,n): if A[i][i] != 0: p = 1 / A[i][i] for j in range (i,n): A[i][j] *= p b[i]*p for k in ran...
89b284afe22d50827f0e63900cfb9e08a97bbb35
679,784
def null_val(val): """Return True if the value is a mmCIF NULL charactor: ? or . """ if val == "?" or val == ".": return True return False
7a9c778e4bdf917cc94d453e458d4212a925677a
679,785
def locf_sort(data, sort_vars, group_vars): """ Put data into pandas groupby for LOCF interpolation Parameters ---------- data : pandas.DataFrame Data frame to put into groupby. group_vars : list Variables to group by in pandas. This is typically a unique identifier (pidp/hidp). ...
bd6760d3f38207b6b36f8fa3f426cc0fa1913c53
679,786
import torch def radius_gaussian(sq_r, sig, eps=1e-9): """ Compute a radius gaussian (gaussian of distance) :param sq_r: input radiuses [dn, ..., d1, d0] :param sig: extents of gaussians [d1, d0] or [d0] or float :return: gaussian of sq_r [dn, ..., d1, d0] """ return torch.exp(-sq_r / (2 *...
22dbe61ef2930313ec7f1e5fc1726c3e643350f8
679,787
import re def check_res_id(res_id): """ "Used to attempt to validate a res_id before submitting to the API" :param res_id: a resource ID :return: TRUE/FALSE indicating the validity of the res_id """ res_id_regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" if not isi...
eb15942e3be6a8678254005709ae050566b72d48
679,788
import logging import sys def get_console_handler() -> logging.StreamHandler: """Get console handler Returns: logging.StreamHandler which logs into stdout """ console_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(mes...
82448f1189da8f5ebe8cea67c3c8c2891c3c8d33
679,789
def path_length(path): """ this one's obvious """ return sum([e.param for e in path])
7bd8ab25fc19b25299d35a84842c3a91ec140d77
679,790
def human_to_mb(s): """Translates human-readable strings like '10G' to numeric megabytes""" if len(s) == 0: raise Exception("unexpected empty string") md = dict(M=1, G=1024, T=1024 * 1024, P=1024 * 1024 * 1024) suffix = s[-1] if suffix.isalpha(): return float(s[:-1]) * md[suffi...
1cf5a6afbb4e51d415de4307a07947a741af71bc
679,791
import os def get_file_path(file_dir, basename, extensions=[".yml", ".yaml"], raise_err=True): """Get the file path allowing for multiple file extensions """ for ext in extensions: path = os.path.join(file_dir, basename + ext) if os.path.exists(path): return p...
5843e235c510dbde413d9f34dbe71121a07e262b
679,792
import collections def longest_substring_deque_rotations(s: str) -> int: """ find the longest substring without repeating characters 512 ms 14.5 MB >>> longest_substring_deque_rotations("abac") 3 >>> longest_substring_deque_rotations("abcabcbb") 3 >>> longest_substring_deque_rotations...
f19ed9735007ead22405c6cd2f361973625f333e
679,793
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ): """Return the 1-based UTF-16 code unit offset equivalent to the 1-based unicode codepoint offset |codepoint_offset| in the Unicode string |line_value|""" # Language server protocol requires offsets to be in utf16 code _units_. # Each code unit is...
976daeb55916dbfeeff7f92e5352ee3ab135a608
679,794
import importlib def _import_name(generator): """Import a class from its module name.""" # A generator 'path' try: mod_name, func_name = generator.rsplit(".", 1) except ValueError: raise ValueError("Invalid generator class name %s" % generator) try: mod = importlib.import_...
e79ef1c5d66e799a35eb7b6db9b93557fe1fa91b
679,795
import os import csv def get_renamed_sheets(cogs_dir): """Get a set of renamed sheets from renamed.tsv as a dict of old name -> new name & path.""" renamed = {} if os.path.exists(f"{cogs_dir}/renamed.tsv"): with open(f"{cogs_dir}/renamed.tsv", "r") as f: reader = csv.reader(f, delimite...
d9eaceb18d70abcdca5ac774c8439188194194e9
679,796
def solution(a: list) -> int: """ >>> solution([-3, 1, 2, -2, 5, 6]) 60 >>> solution([6, 5, 4]) 120 """ a.sort() return max(a[0] * a[1] * a[-1], a[-3] * a[-2] * a[-1])
8ea24d6f0b753a2159396a01e5b0fde49730c86a
679,797
def desiredState(): """ This function returns the state vector of the desiredState as list where ith element is the ith coefficient of the state vector. """ # wf = [c0,c1,c2,c3] wf = [ 0.15913149 + 0.05285494j, 0.16971038 + 0.16935005j, 0.20387004 + 0.07045581j, 0...
72001a6ab929382d5dd408b680d2bb1143596290
679,798
import math def obtener_tamano_mozaico(num_pixels, tile_size=400): """ num_pixels es el número de píxeles en una dimensión de la imagen. tile_size es el tamaño de mosaico deseado. """ # ¿Cuántas veces podemos repetir un mosaico del tamaño deseado?. num_tiles = int(round(num_pixels / tile_size...
d53d24929e01be5c4ecf2af981bd1fc77093f948
679,799
def sciNot(x): """Returns scientific notation of x value""" return '%.2E' % x
cf30d76318ed1c0a86c3b59d767e3ee2292ca16b
679,800
import ctypes def struct_to_dict(struct: ctypes.Structure) -> dict: """Create a dict from a struct's fields and their values.""" return {name: getattr(struct, name) for name, _ in getattr(struct, "_fields_")}
ddb1789e90f60ae8916e93affa0fa6a7d346181d
679,801
def parse_hkey(idx): """parse index and convert to str Args: idx (pd.DatetimeIndex): datetime index Returns: str: zero padded 24-clock hour(%H) """ return str(idx.hour).zfill(2)
e3c1e41bf28ad1d340b54e155c02105486435c37
679,802
def skipIn37(reason): """Skip the test in Python 3.7.""" def decorate(f): # See test_base.main for how this attribute is used to skip the test. f.__pytype_skip__ = reason return f return decorate
bc60d6bd253966c7fcdf275317ca7f6cf9dbdec0
679,804
def apparent_latitude(t='now'): # pylint: disable=W0613 """Returns the true latitude. Set to 0 here.""" return 0
c7b4a0c9e262a8c7ba219626ae3b1e3e6886185d
679,805