content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def valid_mask(mask): """From a tensor [1,C,h,w] create [1,C,1,1] 0/1 mask saying which IDs are present""" B,C,h,w = mask.shape valid = mask.flatten(2,3).sum(-1) > 0 valid = valid.type_as(mask).view(B,C,1,1) return valid
a873ddc1e5aa9c37db686386a1009a44fc33af34
651,079
import random def get_random_number(): """ Returns a random number Returns: float: A random number """ return random.random()
5a94505389554bdab54b46082c2ae4ca48432175
651,080
def stan_init(m): """Retrieve parameters from a trained model. Retrieve parameters from a trained model in the format used to initialize a new Stan model. Parameters ---------- m: A trained model of the Prophet class. Returns ------- A Dictionary containing retrieved parameters of...
b3da4c8b7383a61982ab9673a52dc1c40a58365a
651,081
def getnullables (grammar) : """only if binned (less of a headache to implement) returns a list of all nullable rules in a grammar Parameters grammar : grammar input Returns list of unique nullables """ production_rules = grammar.production_rules nullables = [] lenG = 0 for key, rules in production_ru...
f694a00d72ec820a6b110b454c1863840f898396
651,082
import string def getAvailableLetters(lettersGuessed): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ # return a string of all unused letters after subtracting the ones in let...
a6978e444de4c4a417bb9f9f5d9c9a7a2dab3c1c
651,083
def pylist(param): """ Takes a comma separated string or list and renders a python list source code :param param: :return: """ prefix = '["' suffix = '"]' if isinstance(param, str): param = param.split(' ') if isinstance(param, list): param = '","'.join(param) r...
1a24b372d99b06fcd759852e1d82016f6a29856f
651,084
def even_split(hash_str, k): """将hash_str按顺序均匀拆为k+1份,将余数均匀分给之前的每一份,任意两份长度差最大为1""" quotient, remainder = divmod(len(hash_str), k + 1) # 拆分为remainder * (quotient + 1) + (k + 1 - remainder) * 4 k1s = [] # 长度+1的部分 for i in range(remainder): size = quotient + 1 k1s.append(hash_str[siz...
209f7d8b28a29b786b21d8d56a6fcfe10d245f41
651,085
from datetime import datetime def _human_readable_delta(start, end): """ Return a string of human readable time delta. """ start_date = datetime.fromtimestamp(start) end_date = datetime.fromtimestamp(end) delta = end_date - start_date result = [] if delta.days > 0: result.appe...
d11af629f1bb9db238616d3eb847d205f5238512
651,086
def test_files(paths): """ Get the number of the test related files." """ # This feature assumes that test files contain word "test test_files_count = len([path for path in paths if "test" in path.lower()]) return test_files_count
49de2ed0a5361b15141e127860b01f72a164f76c
651,087
def get_subclasses(c): """Get all subclasses of a class. Args: c (type): Class to get subclasses of. Returns: list[type]: List of subclasses of `c`. """ scs = c.__subclasses__() return scs + [x for sc in scs for x in get_subclasses(sc)]
9c4977a091e0de85daab284a7d7778a88d79ac1f
651,088
def data_from(file_: "str") -> list: """Returns data from given file.""" data = [] with open(file_, "r") as f: for line in f.readlines(): data.append(line.replace("-", " ").replace(":", "").split()) return data
1e84bdf32487e994c635af00b0b48963f515b17f
651,089
import sys def trap_error(func, on_error = None): """ Where error_handler builds a new functor with built-in error handling capability, this function calls *func* immediately, and calls *on_error* if it is callable, passing it sys.exc_info(), or returns *on_error* if it is not callable. Exampl...
64edd70344df66a47684a4420868c68c925d728e
651,091
def process_request_items(items): """takes a list of 2-tuples returns dict of list items uses first value of tuple as key, and uses second value of tuple as value """ request_dict = {} for item in items: request_dict[item[0]] = item[1] return request_dict
1ecb6ecf1b4cc937181a6fcdf39de130be8d9c19
651,092
def bbox_crop(x, bbox): """ Crop image by slicing using bounding box indices (2D/3D) Args: x: (numpy.ndarray, shape (N, ch, *dims)) bbox: (list of tuples) [*(bbox_min_index, bbox_max_index)] Returns: x cropped using bounding box """ # slice all of batch and channel ...
a7e9f5b805c363a7efaee0491a42c2960a2f69f5
651,093
def patched(f): """Patches a given API function to not send.""" def wrapped(*args, **kwargs): kwargs['return_response'] = False kwargs['prefetch'] = True config = kwargs.get('config', {}) config.update(safe_mode=True) kwargs['config'] = config return f(*args,...
75d1dc7c2bd55795f20728f1e5142b48eac61968
651,094
import re def tag_extract_version(tag): """ >>> tag_extract_version('random') is None True >>> tag_extract_version('random-1.23.4') 'v1.23.4' >>> tag_extract_version('random0.5') 'v0.5' >>> tag_extract_version('random-a.b.c') is None True >>> tag_extract_version('random-5') is ...
699f9bf851dc5fe728a7347ae71d5308a2a3f852
651,095
import requests import json def request_dataset_metadata_from_data_portal(data_portal_api_base: str, explorer_url: str): """ Check the data portal metadata api for datasets stored under the given url_path If present return dataset metadata object else return None """ headers = {"Content-Type": "ap...
d18c364c4d76d1eebde54e44277ce56823a505b5
651,096
def get_nest(data, *args): """https://stackoverflow.com/questions/10399614/accessing-value-inside-nested-dictionaries""" if args and data: element = args[0] if element: value = data.get(element) return value if len(args) == 1 else get_nest(value, *args[1:])
534f09ad53f88967fddfd9bd4cf505d7bd199506
651,097
def add_currency_filter_to_query(query, currency): """ Adds the currency filter to the query :param query: the query dictionary :type query: dict :param currency: currency type :type currency: str :return: the query dictionary :rtype: dict """ if "filters" not in query["query"]:...
a69579e37914064d8d6327f74db929b4827c41f6
651,098
def swe_headerfile_name(dt, infile_type): """Return SWE headerfile name for a given datetime""" dtstr = dt.strftime('%Y%m%d') if infile_type.upper() == 'UNMASKED': return 'zz_ssmv11034tS__T0001TTNATS{}05HP001.txt.gz'.format(dtstr) elif infile_type.upper() == 'MASKED': return 'us_ssmv11...
ced0ea1dfd518fab1148c36677738702d8377a8e
651,099
import torch def to_concatenated_real(input, flatten=None, dim=-1): """Map real tensor input `... x [2 * D]` to a pair (re, im) with dim `... x D`.""" assert flatten is None return torch.cat([input.real, input.imag], dim=dim)
369d7d444e038f67ea066233982abb39231dd432
651,100
def get_job_ids(labelled_jobs): """gets job ids""" return [job["id"] for job in labelled_jobs]
b0e9df927b4860db9187563757ba94340d5fb2ed
651,101
def template_data_nested_json_to_flat_json(template_data_value): """ Helper function to convert nested JSON of template data to flat JSON. """ def process_value_parameter(data, parameter): # Just process the first layer of attributes. No value is needed # from any nested attributes as t...
ad4499122ca60dfd67c60a590094007d8c223e81
651,102
def get_books_by_publisher(data, ascending=True): """Returns the books by each publisher as a pandas series Args: data: The pandas dataframe to get the from ascending: The sorting direction for the returned data. Defaults to True. Returns: The sorted data as a pandas series...
e1f309c7e2796bb22d611af403871c9971e43e81
651,103
def fixture_region(): """ Return the region settings for the grdsample tests. """ return [-53, -47, -20, -15]
5d1b642bfe92fcecbdea05cef6913424b08c6c5f
651,104
import logging def parse_vis(vis, manufacturer): """Parse the Vehicle Indicator Section (VIS). Return `None` if it is invalid. The year and/or plant is encoded in this section. It is recommended that the year encodes the first character of the VIS, and the plant of manufacture by the ...
9cf07c94ce55539881c359dd8b62b9fc8b8b3d87
651,105
def get_count(list_): """gives a dictionary showing how many times a character appears""" st = '' for i in list_: st += i new_d = {} for i in 'abcdefg': new_d[i] = st.count(i) return new_d
7d7c01229bfcc4c2471e8b3836ace0d50b46f2b5
651,107
def get_sel_programmer_info(arduino_info): """.""" sel_programmer = arduino_info['selected'].get('programmer') programmer_info = arduino_info['programmers'].get(sel_programmer, {}) return programmer_info
5743650b42ab8fab29134762361c3fc79e7e9f81
651,108
import socket def from_address(address): """ Reverse resolve an address to a hostname. Given a string containing an IPv4 or IPv6 address, this functions returns a hostname associated with the address, using an LRU cache to speed up repeat queries. If the address does not reverse, the function ret...
87b739edc1795bedbcc8f0cbc337f9a17364b6e9
651,109
def formatScores(gamedata): """Calculate team points from scores.""" new_gamedata = [] for game in gamedata: team1, team2 = game["teams"][0], game["teams"][1] scores1, scores2 = game["score"][team1], game["score"][team2] overtime = 4 in (scores1 + scores2) shootout = len(sc...
c4a3711f244092e5f8742274a49111578e723add
651,110
import numpy as np def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. ...
ce3a003608c80e8bea4e32f0c72d2316cbbadcbf
651,111
def update_route_events(veh, timeind): """Check if the next event from a vehicle's route_events should be applied, and apply it if so. route_events are a list of events which handles any lane changing behavior related to a vehicle's route, i.e. route events ensure that the vehicle follows its route. Ea...
3a79f2372c5ef3c40c0bb4e74b966c1b9927db4f
651,112
def modified_dict(input_dict, modification_dict): """Returns a dict, with some modifications applied to it. Args: input_dict: a dictionary (which will be copied, not modified in place) modification_dict: a set of key/value pairs to overwrite in the dict """ output_dict = input_dict.copy() output_dict...
e67e366552702df523b4f3dfdd262674ac3a9340
651,113
def residuals_linear(params, t, data): """Calculate cubic growth and subtract data""" #Get an ordered dictionary of parameter values v = params.valuesdict() #Cubic model model = v['a']*t**3 + v['b']*t**2 + v['c']*t + v['d'] return model - data #Return residuals
b26824bafc70196cefb90d478dc679f691922b0b
651,114
from typing import Optional def parse_bool(value: str, default: Optional[bool] = None) -> Optional[bool]: """ Parse bool from some quintly tables being a string with the value "1" or "0" Args: value (str): The value from the quintly dataframe default (Optional[bool]): Default value in cas...
3251c486002aaf933131f11ef2d60c49f3ce317b
651,115
from typing import List def check_data(land: List[tuple], point: tuple) -> bool: """ Checking if given data is correct """ if len(land) != 4: raise TypeError('Given data is not valid') if len(point) != 2 or type(point) != tuple: raise TypeError('Given data is not valid') for tu...
fc0d9bbe706d60271355b949043907c9eb84973b
651,116
def notes(*num, sit=False): # Function to return a dictionary and check all the conditions """ => Program that checks the quantify of school grades, highest, lowest, the class mean and the student's situation :param num: variable that receive the amount of notes :param sit: (optional) if wish know the...
dcc3833756045eae4a1e6e863e4a782403663512
651,118
def convert_units(typ,constant,f,t): """Converts units type should be one of them 'metric','time' f and t should be one of them: 'pico','nano','micro','mili','centi','deci','base','deca','hecta','kilo','mega','giga','tera' Attributes ---------- constant: int constant numb...
c4737204db5316264be69c54d26a3640de05f7f3
651,119
import textwrap def wrap(text, width, *args, **kwargs): """ Like :func:`textwrap.wrap` but preserves existing newlines which :func:`textwrap.wrap` does not otherwise handle well. See Also -------- :func:`textwrap.wrap` """ return sum([textwrap.wrap(line, width, *args, **kwargs) ...
555b157a253750b3e2239df700a72efd5efa897c
651,120
def example_image_shape(example): """Gets the image shape field from example as a list of int64.""" if len(example.features.feature['image/shape'].int64_list.value) != 3: raise ValueError('Invalid image/shape: we expect to find an image/shape ' 'field with length 3.') return example.featu...
b067b311d201a47bc5035f7ddf9de9fb0605e088
651,121
import socket def get_lan_ip(): """ Return the LAN IPV4 address for this computer. Taken from https://stackoverflow.com/a/28950776/2279323 """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("10.255.255.255", 1)) inet = sock.getsockname()[0] exce...
fa3cfc4c38c7a13bbe835171cb4b82f5d8ee16cb
651,124
from typing import OrderedDict def _get_exp_post(): """Return expected basic result for HttpPost action.""" return OrderedDict( ( ("@type", "HttpPOST"), ("name", "Run tests"), ("target", "http://jenkins.com?action=trigger"), ) )
31119ffbc6dc55c4bfadbff6fedc45340ec9d0d7
651,125
def parse_parameters(a): """Filter/check params from dict.""" mandatory_parameters = ( 'test temperature pressure ' 'sampler_class timestep state_update_steps checkpoint_iterations ' 'reference_thermodynamic_state thermodynamic_states ' 'metadata ms_container').split() defau...
ff770a2664f04ac8a6195f146c3667f9d9bc7d58
651,128
import csv def write_auc(fpR,tpR,saveDir): """ Summary : Parameters ---------- fpR : TYPE, DESCRIPTION tpR : TYPE, DESCRIPTION saveDir : TYPE, DESCRIPTION Returns ------- 0 """ with open(saveDir,'w',newline='') as csvfile: spamwriter...
796f69eb96e0212f28a3086c32143065514821db
651,129
def _eval_expr(expr, vals, x): """ This function tries calling expr.eval. Calls expr.cpp_object().eval if the first fails. This is for FEniCS 2018.1.0 compatibility. """ try: expr.eval(vals, x) except AttributeError: expr.cpp_object().eval(vals, x) return None
e7453847748fc9936d54232e79f7ec87203472f1
651,130
def format_column_name(string): """Automatically reformats feature names into something more machine-readable.""" string = ' '.join(string.strip().split()) string = (string .replace('_', ' ') .replace('[', '') .title() .replace('- Um', '') ...
47c45931b7a3ed06540ba49214220f574e247b64
651,131
def format_zet(state, speler, zet): """Opmaak van de status, speler en de zet.""" return "State: {0:<20} {1:<20} Move: {2}".format(str(state), str(speler), str(zet))
8395ca4a739c8dce151eda2e0f7bda5639b0749f
651,132
def ethereum_chain_id(ethereum_network_id): """For now, we always use the same network id and chain id""" return ethereum_network_id
fe12e479e087cc11c5addfe6c943236ac9b29e20
651,133
def infer_leading_dims(array, dim): """Param 'dim': number of data dimensions, check for [B] or [T,B] leading.""" assert array.ndim in (dim, dim + 1, dim + 2) shape = array.shape[-dim:] T = B = 1 has_T = has_B = False if array.ndim == dim + 2: T, B = array.shape[:2] has_T = has_B...
f4d4cdf0bd2663c8e564a84828232a4b7c8e8351
651,134
from datetime import datetime def voto(ano_nascimento): """ Recebe o ano de nascimento introduzido e calcula a idade do usuario, utilizando a data atual. :param ano_nascimento: recebe o ano de nascimento :return: idade e status do voto """ idade = datetime.today().year - ano_nascimento ...
0eaed43851da6db705e71ebe035c82b2e0a54efa
651,135
import torch def predict_from_logits(logits): """Takes logits and retrieves max predictions""" probs = torch.softmax(logits, dim=-1) pred = torch.argmax(probs, dim=-1) return pred
20f34204c14db7366074d71908d61cf9146f18a9
651,136
def discard_search_results(searchId: str) -> dict: """Discards search results from the session with the given id. `getSearchResults` should no longer be called for that search. Parameters ---------- searchId: str Unique search session identifier. **Experimental** """ return...
79a24e2e62754bb3a8a8d19684a93d8175aa92e8
651,137
from typing import List from typing import Dict def _update_sequences_with_new_word_index_map( raw_sequences: List[List[int]], raw_index_to_word: Dict[int, str], word_to_index: Dict[str, int]) -> List[List[int]]: """ Converts the raw sequences to a sequence with an updated word_to_inde...
db47e4e594d8431cd0a29fb21d1e011e860da601
651,138
def get_spec_matched(): """ Retrieves the table spec for backup rules (matched). :return: the `field->field-type` and `sorting` mapping """ return { 'fields': { 'state': str, 'entity': str, 'explanation': str, }, 'sorting': { ...
af88b37de7b1de4576a38c1361294426aa31cc2f
651,139
def peters_f(e): """f(e) from Peters and Mathews (1963) Eq.17 This function gives the integrated enhancement factor of gravitational radiation from an eccentric source compared to an equivalent circular source. Parameters ---------- e : `float/array` Eccentricity Returns -----...
87e6a447fafd6cab4b25e91f89f0464594ba650f
651,140
from bs4 import BeautifulSoup def parse_sgm_file(sgm_data): """ Returns a dictionary with titles + articles of an SGM file :param sgm_data: Data read from an SGM file :return: A dictionary mapping titles to article contents """ soup = BeautifulSoup(sgm_data, features="html5lib") texts = ...
ceafdb6dac3677c93e4829e47324519f516bdf33
651,141
def range_overlap(ranges): """Return common overlap among a set of [left, right] ranges.""" lefts = [] rights = [] if ranges: for (left, right) in ranges: lefts.append(left) rights.append(right) max_left = max(lefts) min_right = min(rights) if min...
f8f8a907e6847dc308a537dab5033b8c49149674
651,142
from typing import Tuple from typing import Optional def get_homogeneous_type(type_dict) -> Tuple[Optional[str], bool]: """ Returns ------- Optional[str] Homogeneous-type, if any. Ex) 'dict', 'list', 'str', 'int', 'float', 'bool', 'None', or None bool Whether optionally typ...
06de05926a79b2d0c311f7bb177b54fd2341e8cd
651,143
def allowed(file_name, allowed_extentions): """The allowed file extensions Args: file_name: The file name to check allowed_extensions: The allowed file extensions Return: Return true or false """ return '.' in file_name and \ file_name.rsplit('.', 1)[1].lower() i...
891113655598162cd3a59d0a09fccb06199973a9
651,145
def _quote_wrap(value): """Wrap a value in quotes.""" return '"{}"'.format(value)
8a5cb862c1b374b7d82c50072fe84b91a7989bbe
651,146
def listBranchUsage(err=''): """ Prints the usage stmt for listBranch """ m = '' if len(err): m += '%s\n\n' %err m += 'List status information for a single branch.\n' m += '\n' m += 'Usage:\n' m += ' lsbr -s <stream> -b <branch_Name>\n' return m
220ff8fc3f604bcc441c5ef2fd09b79ec8d4a5b1
651,147
def _method_(name): """ getter factory """ def _getter_(self): return getattr(self, self.get_private_name(name)) return _getter_
057591dd5fbb287a0328daab07cab5f5c8831d06
651,148
import gzip def get_handle(filen, rw): """ Returns file handle using gzip if file ends in .gz """ if filen.split('.')[-1] == 'gz': return gzip.open(filen, rw) else: return open(filen, rw)
376856d8753c4660c39cacbe61a835cda3d09212
651,150
def LoadGypFile(gyp_filename): """Load the contents of a gyp file. Arguments: filename: filename of a .gyp file. Returns: Raw dict from .gyp file. """ return eval(open(gyp_filename).read(), {}, {})
4c2477ea69f259a02daa6c3ed3cb75d09a3da5a4
651,151
def has(i): """Returns the form of the verb 'avoir' based on the number i.""" # Note: this function is used only for the third person if i == 1: return 'a' else: return 'ont'
60002d083050e443dfd52f9fb752387068a7bdb0
651,152
import argparse def parse_args(): """Parse the arguments.""" parser = argparse.ArgumentParser( description='Converts VGM to PVM', epilog="""Example: $ %(prog)s my_music.vgm """) parser.add_argument('filenames', metavar='<filename>', nargs='+', type=argp...
58768babbf6768f6103f4e556004dac7f40ef5ab
651,154
from typing import Union def get_bool(value: str) -> Union[bool, None]: """When given a string, returns a boolean value based on the string Parameters ---------- value : str A string representing a user response Returns ------- Union[bool, None] whether the string is true...
bfc25a4d1bfdf194c68141d9027e0d3543ffdc0d
651,155
def magtoflux(marr, fzero): """Convert from magnitude to flux. marr--input array in mags fzero--zero point for the conversion """ return fzero * 10 ** (-0.4 * marr)
9b554361099eb0c3e6c9178451ccf0a5e49c60c0
651,156
import requests def check_network_connection(): """The top-level method to checking network connection. Returns: bool: status. """ url = 'http://www.google.com/' timeout = 5 try: _ = requests.get(url, timeout=timeout) return True except requests.ConnectionError: ...
ae6aa0d04ebd0732bb0d961db358f63df8d2af8f
651,157
def promote_terms(self, terms="*.*"): """Move all leaf terms into the arg properties""" def yield_leaves(t): for c in t.children: yield from yield_leaves(c) else: if t.parent_term_lc != 'root': yield t moved = [] for arg in set(leaf.record_term...
771521da909d04e1d9394ca408cdfb64ebc21810
651,158
def partition(arr, left, right): """ *--------*----------*-----------* left mid frontier right left is the pivot, it has been moved to the beginning of the array. frontier marks all the elements we've alreay looked at. mid is the new index of the pivot, everything to the left i...
c411eaa2e9a1a50a20f45fcfd7d7d49a6fc592b6
651,159
def index_settings(table_name): """ Return the Elasticsearch mapping for a given table in the database. :param table_name: The name of the table in the upstream database. :return: """ settings = { "index": { "number_of_shards": 18, "number_of_replicas": 0, ...
0865c4961a8ee092c1dc87f327164eda6b8d4532
651,160
def to_ascii(s): """Convert the bytes string to a ASCII string Usefull to remove accent (diacritics)""" if s is None: return s if isinstance(s, str): return s try: return str(s, 'utf-8') except UnicodeDecodeError: return s
c9fcb074176afda448ee8c1d1a2e25062ac9ec95
651,161
from datetime import datetime def _time_of_day(dt: datetime) -> float: """Convert a given datetime `dt` to a point on the unit circle, where the 'period' corresponds to one day. :param datetime.datetime dt: input datetime UTC :returns: `float` between 0 and 1 corresponding to the phase """ midnig...
cd82b312de706445ba00e391bb33e2b6e056d0bd
651,162
import sysconfig import sys def distutils_dir_name(dname): """Returns the name of a distutils build directory""" f = "{dirname}.{platform}-{version[0]}.{version[1]}" return f.format(dirname=dname, platform=sysconfig.get_platform(), version=sys.version_info)
45df1f9d3234c1fa518176ca225a92ed549907cd
651,163
import torch def objtrack_collect(batch): """Collect the objtrack data for one batch. """ targets = [] imgs = [] frame_id = [] indexs = [] for sample in batch: imgs.append(sample[0]) targets.append(sample[1]) frame_id.append(sample[2]) indexs.append(sample[3...
7df24ca59496634ba7d40c0cfaea1e12564b681d
651,164
def frequency(total: float, percentage: float, value: float, invert: bool = False) -> float: """Return frequency of a given value . Freq = v*t/p v-> value t-> total p-> percentage Args: total (float): total value percentage (float): percentage value between 0 and 1 val...
516e06044cfec14af166f3e8fc1b1db646f518ad
651,167
def zip_errors(z): """ Validate z as either NNNNN or NNNNN-NNNN. """ l = len(z) if l not in (5, 10): return "Zip codes should be 5 or 10 characters long" if (not z[:5].isdigit() or len(z) == 10 and not z[6:].isdigit()): return "Zip code contains non-numeric characters" ...
7e478e0312e394775b5309d11b4c1f818f44e661
651,168
def str_to_bool(status:str) -> bool: """将'enable','disable','enabled'和'disabled'字符串转换为bool类型 Args: status (str): 待转换的字符串 Returns: bool: 'enable'和'enabled'转换为True,'disable'和'disabled'字符串转换为False """ status = status.strip().lower() assert status in ['enable','disable', 'ena...
6ca205796c5278bb1a082762cd6e6bf06d143bf4
651,169
def A(b: int, c: int) -> int: """Function that should become part of the graph - A""" return b + c
05f1822e98cbb079a159b4c359b57fc31e7e3828
651,170
def cartisian2enu(CARTCOORDS): """ This function will transform Cartisian coordinates to ENU coordinates, the only difference being that ENU coordinates are in meters and Cartisian are in km. Input CARTCOORDS - A 3xN numpy array with X, Y and Z in a Cartisian coordinate space. The coordinates are in...
4b725e93045889aca6356e171f9610a8d3ed11a0
651,172
def get_query_string(params) -> str: """ Gets the query string of a URL parameter dictionary.abs :param params: URL params. :return: Query string. """ if not params: return '' return '?' + '&'.join([str(k) + '=' + str(v) for k, v in params.items()])
7bc08e0f68333c2f42d31e8879d3978dd94850ac
651,174
def flatt_on_level(it, d=-1, level=None): """ >>> list(flatt_on_level([[[['a']]]], level=3)) [['a']] """ if d == -1: return list(flatt_on_level(it, d=d + 1, level=level)) if d == level: return (i for i in [it]) res = [] for x in it: res.extend( flatt_on_level(x...
03b033f7ea7af03a3124e8cb4be61c3b3609d4ef
651,175
import collections def split_inputs(ctx, features, labels): """Splits the dense and sparse tensors inside the features and labels.""" sparse_features = collections.OrderedDict() if ctx.embedding_config: tpu_embedding_ = ctx.embedding_config.tpu_embedding for feature_key in tpu_embedding_.feature_to_tabl...
d6b4d786a4088684930f195ffb30937a25683f84
651,176
import re def format_string(prop_string): """ Formats a property string to remove spaces and go from CamelCase to pep8 from: http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case """ if prop_string is None: return '' st_r = re.sub...
4e5ff40b02edd51e927bb30083102e388c76b4b5
651,177
def _has_converged(centroids, old_centroids): """ Stop if centroids stop to update Parameters ----------- centroids: array-like, shape=(K, n_samples) old_centroids: array-like, shape=(K, n_samples) ------------ returns True: bool """ return (set([tuple(a) for a ...
cb843c5a2bb54fe610f94666fcc38e27be58a4a5
651,178
def memo_checker(func): """ Decorator for memoization. """ def inner_func(self, temperature, pressure=None): # will contain pressure if temperature in self.memos: if func in self.memos[temperature]: return self.memos[temperature][func] # you can use fi...
4ef4e9a330738c5b84fce206468355194aff6048
651,179
def average_index(n1, n2, v1=None, v2=None, vr=None): """Compute volume weighted average refractive index Args: n1, n2 (float/ndarray): refractive index of material 1 and 2 v1, v2 (float): volume of materials 1 and 2 vr (float): volume ratio of v1/(v1+v2) used instead of v1 and v2 ""...
373146c0e5e55fa09dcfa2c90cc12f48a89fe674
651,180
import logging def init(config, database): """Called once on yuu's initialization. The return value of this function is passed on every call to hooks. Therefore, you can initialize a state class here and access it in did_update_record/did_delete_record. Arguments: - config: The ...
2fab45487e6658a2cfd39a02444769e2a7a1f204
651,182
def with_meta_result(func): """Meta result that expects dictionary with status and supports as return value""" def wrapper(*args, **kwargs): returned = func(*args, **kwargs) print('--RESULT--') if returned['status'] == True: print('OK') else: print(return...
847e01f309e169074ba5e16d409648fd7347d1e1
651,183
def build_run_name(group1, group2): """ :param group1: :param group2: :return: """ map1 = dict((k, v) for k, v in zip(group1[0], group1[1])) map2 = dict((k, v) for k, v in zip(group2[0], group2[1])) shared = sorted(set(map1.keys()).intersection(set(map2.keys()))) name = '' for s ...
79399f0787d16554c7e5dbfb1ba9e32e5436d4aa
651,184
import math def meter(val,char="{p#",empty=" ",lcap="[",rcap="]",align="left",width=20): """Return a horizontal meter representing a numeric value ranging between [0,1].""" width = width-len(lcap)-len(rcap) + (lcap.count("{")+rcap.count("{"))*2 hatches = int(math.floor(width*abs(val))) hatche...
89d9b8957e86799148d3a2f0899d9d9beee71401
651,185
def verify_name(prior_name, inferred_name): """Verfies that the given/prior name matches with the inferred name. """ if prior_name is None: prior_name = inferred_name else: assert prior_name == inferred_name, f"""given name {prior_name} does not mach with ...
02466d179e37ffab5271b7b06a74b07404aa574a
651,186
def readfile(): """ Reads data from locations.csv file and returns it as a generator object. :return: generator object """ f = open('../data/locations.csv', 'r', errors='ignore', encoding='utf-8') data = (tuple(line.strip().split(',')) for line in f) return data
e8d577e8741716c7631d25a90183a70d0c604258
651,187
import logging def list_all_servers(): """ list all server nickname and IP. """ server_nickname = open('ENV/available_servers').read().strip().split('\n') hosts = [] try: hosts += open('/etc/hosts').read().strip().split('\n') except: pass try: hosts += open('/et...
b40e17accd0fd3a82f872f161afd70795678df26
651,189
import os import numpy def keras_generate(lstm_model_data=None, raw_text="", sequence_length=10, article_length=1000, weight_filename='./weights-records.hdf5'): """ 產生文章 - 訓練模型記住文章的風格,根據風格推斷接下來的文字為何 lstm_model_data - LSTM Model 相關資料 raw_text sequence_length - 用於預測新字的句子長度 articl...
71808f8fd14647d2049afe68de46fab4092bd947
651,190
import math def dist(a0, a1, b0, b1): """Returns the Eucleadean distance between two points in 2D.""" da = a1-a0 db = b1-b0 return math.sqrt(da*da + db*db)
e2db45aed6912f1d0c38f1176f86a10c83f0fda0
651,191
def _create_interface(phase, graph, references): """Creates an interface instance using a dynamic type with graph and references as attributes. """ interface = {'graph': graph} interface.update(references) return type(phase + 'Interface', (object,), interface)
8f8c6d6cf531dcec0dd4bb72d21547de66ef340c
651,192
def is_leap(year): """returns True if the given year was a leap year, otherwise False. Written to sooth the complaints from pycodestyle and pyflakes regarding this "one-line" lambda that works but is rather ugly and un-pythonic. is_leap = lambda y: True if y % 400 is 0 else False if y % 100 is 0 \ ...
4adeab3ca3ec87f75289ca6a4c6f5baedfabed6a
651,193
def calc_table_variable_volumes(line, table_vols): """ Calculates the table volumes. :param line: :param table_vols: :return: table_vols """ varVolDict = {} l = line.split('::') table_var = l[0].strip().split('.') table, var, vol = table_var[0], table_var[1], float(l[-1].strip(...
b065191253078a3745b3d69f0748c7be096ba3e8
651,194