content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import typing def get_actions_with_permissions(user_id: int, permissions: Permissions, action_type_id: typing.Optional[int] = None) -> typing.List[Action]: """ Get all actions which a user has the given permissions for. Return an empty list if called with Permissions.NONE. :param user_id: the ID of ...
dc89f2dfb84c8217050b8718b08365ecbea5807f
3,619,262
def list2xml(datalist, roottag, elementname, pretty=False): """Converts a list to an UTF-8 encoded XML string. See also dict2et() """ root = list2et(datalist, roottag, elementname) return to_string(root, pretty=pretty)
d3e0780ea979a1adf66d07832dcbc5c2b2df05fd
3,619,264
import six def text_type(string, encoding='utf-8'): """ Given text, or bytes as input, return text in both python 2/3 This is needed because the arguments to six.binary_type and six.text_type change based on if you are passing it text or bytes, and if you simply pass bytes to six.text_type w...
5b962c348769ccb1029cd0d41fc23ddb6942d37d
3,619,265
import hmac import hashlib def intercom_user_hash(data): """ Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured. Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured. """ if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None): return hmac.new( ...
8bdc04eef363f939248d949eccb93cdfbafd989c
3,619,266
from model_utils.config import config import multiprocessing def create_yolox_dataset(image_dir, anno_path, batch_size, device_num, rank, data_aug=True, is_training=True): """ create yolox dataset """ cv2.setNumThreads(0) if is_training: filter_crowd = False remove...
aa6a4c869bc4be6f80d7b680ee506353ad0be464
3,619,267
def quote_value(value: str) -> str: """ Ensures values with ";" are quoted. >>> quote_value("foo") 'foo' >>> quote_value("foo;bar") '"foo;bar"' """ if value.find(";") != -1: return f'"{value}"' return value
e6bb23a17d554742115582feb90ba621ddd7fc66
3,619,268
import tokenize def parse_stories(lines, only_supporting=False): """Parse stories provided in the bAbi tasks format. If only_supporting is true, only the sentences that support the answer are kept. """ data = [] story = [] for line in lines: line = line.decode('utf-8').strip() ...
1684a3b33623b25169f2dbd2b31e86cc82a3ce54
3,619,269
from datetime import datetime def check_datetime_timetz(dt: datetime) -> ResultComparison: """ post: _ """ return compare_results(_invoker("timetz"), dt)
b44a96a27d915b2cb366715413d3501948a18854
3,619,270
def process_string(logger, content, ignore_unsuitable, old_platform, new_platform): """Add a configuration for a new platform to the modulemd document string. It returns an error code and a string. In case of no error, code will be 0 and the string will be the processed, output docum...
1dc9d7f61557136a3ffe639d3588bee2dd5637cd
3,619,271
def get_temporal_entropy(y: np.ndarray, fs: int, config: dict) -> float: """ Temporal entropy is a measure of the temporal dispersal of acoustic energy within a recording, has been shown to reflect the number of avian calls in a recording (Sueur, Pavoine et al. 2008). :param y: mono audio :param fs...
4991f6714f4a78b233d665d76c6cc444f15b6603
3,619,272
import json import logging def partitions_query(addr): """ Query the worker at the given address for its partition routing information. """ stdout = external_sender_query(addr, 'partition-query') try: return json.loads(stdout) except Exception as err: e = ObservabilityRespo...
4da58e87af7401427096f989187e2150e76ea2cd
3,619,273
def metrics(output_softmax, labels, num_classes): """ Builds the metrics for the model, including IoU and accuracy :param output_softmax: TF Tensor containing the sofmax operation on the last layer in the neural network before the decoder :param labels: TF Placeholder for th...
97206804234d0a98d0cd9cf9569e443bc0b2210c
3,619,274
def update_config(config: dict): """Update the passed config dictionary.""" version_classes = _get_version_classes() if 'version' not in config: config_version = (0, 1, 0) else: config_version = _version_value(config['version']) apply_classes = [x[1] for x in version_classes if confi...
5a3b1fe00366ed955480288c095b3d16350aa61f
3,619,275
from typing import Callable def join_docs(sep: Callable[[], Doc], docs: list[Doc]) -> list[Doc]: """Join a sequence of tokens with a separator""" list_vals = [] for i, doc in enumerate(docs): if i != 0: list_vals.append(sep()) list_vals.append(doc) return list_vals
507295860e0abfeb98a527564174aa7c6c4fca85
3,619,276
def make_literal_parser(*args: t.Any) -> comb.Parser: """Return parser for t.Literal[args].""" return comb.Or(*map(comb.Lit, args))
fba98f9c650bf401a32f093afb987620ccd04021
3,619,277
import numpy def xyz(date, velocity=False, equinox=1950.0): """ Calculate geocentric X,Y, and Z and velocity coordinates of the Sun. Parameters ---------- date : float Julian date equinox : float Equinox of output. If None, Equinox will be 1950. velocity : boolean ...
bf3ec3fee8affef4a5acf7eb755edece40b32384
3,619,278
def estimation_formula_bg(growth, eps): """ The stock price estimation formula suggested by Benjamin Graham According to "The Intelligent Investor" """ return (2*growth+8.5)*eps
b675c3ec8cd82d600473d2646cc759bc8f3279be
3,619,279
import numpy def grid3d2Order(unaries,regularizer,order='numpy',operator='adder'): """ returns a 2d-order model on a 3d grid (volume). The regularizer is the same for all 2.-order functions. Keyword arguments: unaries -- unaries as 4d numpy array where the last dimension iterates over the labels r...
f7dcbf83302989943823c7102598daeba6259690
3,619,280
import unittest def makeTestSuiteV201111(): """Set up test suite using v201111. Returns: TestSuite test suite using v201111. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(DfpWebServiceTestV201111)) return suite
8d0ca67ff0aac25a0848730bdc77b01eb791dd02
3,619,283
def refresh_handler(unused_addr, args): """ Refresh text """ logger.info("Refreshing text") send_questions_to_line_editor() return None
aff4e86350dc5bb2eed0e392b119e7b7637800f5
3,619,284
async def huobi_spot_tickers(api_key: str, secret_key: str, symbol: str = None): """ 获取行情数据 :param api_key: :param secret_key: :param symbol: :return: """ huobi = HuobiAPI(api_key, secret_key) return await huobi.tickers(symbol=symbol)
608415abb11a1291b322f271eb8620e63c2bd16c
3,619,285
def make_quality_step(env, run_time, route_to, transit_time=1, **kwargs): """ """ return { 'location': env['quality_bench'], 'worker': env['qual_inspector'], 'manned': True, 'setup_time': 0, 'run_time': run_time, 'teardown_time': 0, 'transit_time': tr...
3f4ac237f4d0d0cd9245d6e615495563a5152a23
3,619,286
def reverse_sorting_order(str_name): """Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True. Negation was introduced as the function is used to determine the order of the sorting depending on scoring function name: if scoring ends with "_error" or "_loss", it means th...
481b78912262fd086121b6281d3f53c13f3571ff
3,619,287
from typing import List from typing import Tuple def parse_keyval(line: str, valsplit: str = ':', csvsplit=',') -> List[Tuple[str, str]]: """ Parses a csv with key:value pairs such as:: John Alex:Doe,Jane Sarah:Doe Into a list with tuple pairs (can be easily converted to a dict):: ...
f96c32234436895edeb6a0fcc42d2ec2346a258c
3,619,288
def most_active(): """Finds the most active station based on count of temp records""" session=Session(engine) # same as above but with station ID , aslo trying subquery method active_station_id=session.query(\ Station.id,Station.station,\ func.count(Station.station).label('activity_c...
29d82d9b8c26073f0b53648b1dd493920b3f8e93
3,619,289
def getUserInput(): """ Purpose: to validate user Input Parameters: None Returns: x - validated user input """ x = input("Recursion Depth: ") try: x = int(x) except ValueError: x = getUserInput() return x
87a67cf12e1a45e16068bf7c64e53b33e3cdbdeb
3,619,290
def attr_subresource(raml_resource, route_name): """ Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. """ static_parent = get_static_parent(raml_resource, method='POST') i...
ef98f693ea37ac19d81fb9611eda26b3d1d30830
3,619,291
def translate_path_into_actions(rail_env, pathways, time_step): """Translates the solution paths of the CBS algorithm into an action for a given time step. :param rail_env: The Flatland environment. :param pathways: The solution paths of the CBS algorithm. :param time_step: The time step for which an a...
e769f5a6fdc9fefa37d7ef07edc2e347225c6824
3,619,293
def test_module(client: Client) -> str: """ Tests API connectivity and authentication' Returning 'ok' indicates that connection to the service is successful. Raises exceptions if something goes wrong. """ try: response = client.translate('I have the high ground!') success = de...
995ba791c1b7a19ed293349da91a0c0517fe2743
3,619,294
def plot_confusion_matrix(cm, label): """ Keyword Arguments: correct_labels -- These are your true classification categories. predict_labels -- These are you predicted classification categories label -- This is a list of string labels corresponding labels Returns: Figure """ fi...
873cb3b6524c11f340e8f808580ec6b70d912427
3,619,295
def _compare_numeric(src_num, dst_num): """Compare numerical values. You can use '<%d','>%d'.""" dst_num = float(dst_num) match = numeric_compare_regex.match(src_num) if not match: error = "Failed numeric comparison. Collected: {}. Expected: {}".format(dst_num, src_num) raise ValueError...
9279f671cac13d9cf29cffb9a3f85350c9e3d0da
3,619,296
def actionlstm_cell(x, h, a, num_units, action_dim, initializer=tf.contrib.layers.xavier_initializer(), bias_initializer=tf.constant_initializer(0.0), activation=tf.tanh, scope='action_lstm'): """ :param x: state input :param h: hidden state tuple...
0d8c486e1db2ec9e356cc04bc6b72d1231e22c6b
3,619,298
import numpy as np def extrapolate_accel_data_testing(filename): """Extrapolate data from a txt file data will have format: x1,y1,z1; x2,y2,z2; .. xn,yn,zn; :param filename: file to read from :return: datax, datay, dataz vectors (np.array) """ x = [] y = [] z = [] ...
53d6f44450285306b41eb8e4969a32d4d1c3ceb7
3,619,300
import warnings def get_loss_obj(cfg: Config) -> loss.BaseLoss: """Get loss object, depending on the run configuration. Currently supported are 'MSE', 'NSE', 'RMSE', 'GMMLoss', 'CMALLoss', and 'UMALLoss'. Parameters ---------- cfg : Config The run configuration. Returns ...
c01781431e7190b73c8b3c4bff6ac456a06463c3
3,619,301
def _melspecgrams_to_specgrams(melspecgrams: tf.Tensor, mel2l) -> tf.Tensor: """Converts melspecgrams to specgrams. Args: melspecgrams: Tensor of log magnitudes and instantaneous frequencies, shape [..., channels, time, freq, 2], mel scaling of frequencies. mel2l: Mel to linear matrix Re...
602348e81d8770249695dd5a65d03ca50b7b740c
3,619,302
import time def benchmark_descending_operator(rhoab, rhoba, w, v, u, num_layers): """ run benchmark for descending super operator Args: rhoab (tf.Tensor): reduced densit matrix on a-b lattice rhoba (tf.Tensor): reduced densit matrix on b-a lattice w (tf.Tensor): isometry ...
c64d34edbe31d33a1f172f591de6d1b4433d2cf2
3,619,303
import numpy def extract_sun_angles(xml): """Extract Sentinel-2 solar angle bands values from MTD_TL.xml. Parameters: xml (str): path to MTD_TL.xml. Returns: str, str: sz_path, sa_path: path to solar zenith image, path to solar azimuth image, respectively. """ solar_zenith_values = n...
801b5baeae3b863d9dec272ccf36143d3c69dff9
3,619,304
def get_citation_ids(semantic_results, direction: str = "citations", cit_n: int = 1): """Returns ids for AI paper citations and references below a threshold and above a citation threshold""" cit_df = pd.DataFrame( chain(*[get_citation_meta(art, direction) for art in semantic_results]) )[["arxiv...
d1d1f66d5cd3e8feed6b1fa6faf70600d08e8067
3,619,305
def spiral_grating(medium_groove=mp.Medium(epsilon=2), D=0.4, d=None, DBR_period=0.2, FF=0.5, N_rings=10, N_arms=2, thickness=0, center=mp.Vector3(0, 0, 0)): """ Elliptic DBR cavity created as a sequence of concentric cylinders. Parameters ---------- medium_gro...
36dab4826a117b9f93d8b2fee82002cf954bba45
3,619,306
def getDailyData(word: str, start_year: int = 2007, stop_year: int = 2018, geo: str = 'US', tz: int = 240, verbose: bool = True, wait_time: float = 5.0) -> pd.DataFrame: """Given a word, fetches daily search volume...
7409991a6ae805f34958586241a09e2afe296e6e
3,619,307
from Framework.ClassUtils.json_utils_class import JsonUtils import json import difflib def compare_xml(xml1, xml2, output_file=False, sorted_json=True, remove_namespaces=False, tag_list=[], attrib_list=[]): """ This will compare two xml files or strings by converting to json and then sorti...
46d8fdf38e5d2debbc4d2fc1a6a1434ac2b40396
3,619,308
def model_repr(models, key): """Get a model representation.""" m = [(char, proba) for char, proba in models[key].items() if proba > 0.0001] m = sorted(m, key=lambda n: n[1], reverse=True) s = "" for char, prob in m: s += u"{}={:4.2f}% ".format(char, prob * 100) return s
a4b658b8a7fd7529e14f452e426ca35447991042
3,619,309
def read_file(filename): """ Read a whole file into memory. Automatically detect gzipped files based on suffix. Args: filename (str): Name of file to read. Returns: str: Content of file as a string. Will return None if file cannot be read. """ try: with open_file_h...
440113df8851b4ef18006a3e0db1c90470dd1b48
3,619,310
import glob def findNewFiles(): """ Find all of the files that have been downloaded, and then determine all of those that have not been decrypted. Return a list of those that need to be decrypted now. """ allFiles = glob.glob('*.gpg') oldFiles = glob.glob('*.gz') retFiles = [] for...
0d9052856e1cf8ba605026f1a74e259b06e5f342
3,619,311
from bs4 import BeautifulSoup def parse_joa_html(inner_html): """ Retourne les cotes disponibles sur une page html joa """ match_odds_hash = {} match = None date_time = None soup = BeautifulSoup(inner_html, features="lxml") id_match = None for line in soup.findAll(): if "cl...
1a78a310092ef0d3b2272812b9847bc1aff29eee
3,619,313
def create_or_update_pipeline(origin_pipeline, api_url): """Create or update Storage Location and return it.""" pipeline = Pipeline.query.filter_by(origin_pipeline=origin_pipeline).first() request_url, request_url_without_api_key = get_storage_service_api_url( api_url, origin_pipeline ) resp...
b94cd89f6480bf920a05d171593697661d6bab4a
3,619,314
def _validate_additional_args(param_dict): """ :param param_dict: parameters to enter into the backing store :type param_dict: dictionary :returns: a string that tidies up the additional arguments :rtype: string """ if 'additional_arguments' not in param_dict: return "{}" param...
d711544761ac18b58b7ea5c3c1dc0135ebb68f9b
3,619,316
def fib_dp(n): """ Series - 1, 1, 2, 3, 5, 8, 13 `n` starts from 0. :param n: :return: """ fib_arr = empty_1d_array(n) if n < 2: return 1 if fib_arr[n-1] is None: fib_arr[n-1] = fib_rec(n-1) if fib_arr[n-2] is None: fib_arr[n-2] = fib_rec(n-2) return ...
43150d0d272315fd4651c4710722b9c06d540f97
3,619,317
def compute_distance_adjacent_finger(finger_name, adjacent_finger, hand_fingers_points): """ Cálcula a distância entre a ponta do dedo analisado e a ponta do dedo adjacente. Divide por fator de correção (distância de referência). :param finger_name: dedo analisado :param adjacent_finger: dedo adjace...
c97ad838ce5456c10d1e6ff922234ab6e4499591
3,619,318
def get_linters(files_to_lint, file_cache): """Creates GeneralPurposeLinter object and returns it. Args: files_to_lint: list(str). A list of filepaths to lint. file_cache: object(FileCache). Provides thread-safe access to cached file content. Returns: tuple(GeneralPurpo...
5b80cee233276a4aa6096c3bb3cb611904077aec
3,619,319
import functools def extract_common_countries(FILES, eu28_countries): """This function extract countries common to all data sets. Arguments of fucntion are FILES -> list of triples where elements are data set filename, column/row/header depending where the countries' names reside...
fe60673d09f36c444c1b70a45e1cd7cd4d61adc8
3,619,320
def generateTmatrixFullRandom(N,badf=0.2): # print("p_act01 < p01/(p01+p10)") """ Generates a Nx2x2x2 T matrix indexed as: T[patient_number][action][current_state][next_state] action=0 denotes passive action, a=1 is active action State 0 denotes NA and state 1 denotes A """ ...
83ed20f4cfbd386f43b4224988b5dba93d4ed4f3
3,619,322
def ResolveVersion(api_name, default_override=None): """Resolves the version for an API based on the APIs map and API overrides. Args: api_name: str, The API name (or the command surface name, if different). default_override: str, The override for the default version. Raises: apis_internal.UnknownAP...
533e858ce7095721a1cd71e416ce997fd2f4c66b
3,619,323
import hashlib def decrypt_master(master_pwd,master_dict): """Decrypt a master key with a master password""" secondary = hashlib.pbkdf2_hmac('sha256',master_pwd.encode(),master_dict['salt'],2**14,16) cipher = AES.new(secondary,AES.MODE_EAX,nonce=master_dict['nonce']) master = cipher.decrypt_and_verify...
1851be349280ef4f6ed8e0e1db6d912e90b45fd4
3,619,324
def runSingleFile(inputFile, outputDir, parser, databaseVersion, listOfExpRes, timeout, development, parameterFile): """ Call testPoint on inputFile, write crash report in case of problems :parameter inputFile: path to input file :parameter outputDir: path to directory where output ...
6ff64d6ce3516912ee1a4c1804e4d93b702d4b6d
3,619,325
def new_pipeline(tickers, start_date, end_date): """The pipeline implemented with Dask""" def compute(): # The pipeline construction will store 'get_signals', so we need to # delay it until we enter the 'intercept_function_arguments' context signals = get_full_pipeline(tickers, start_da...
4a0a172f39f55ede87ceb472110d6b211ac1f295
3,619,326
def handleNonAscii(text): """ If default locale supports UTF-8 reencode the string otherwise remove the offending characters. """ if preferred_encoding == 'ASCII': return ''.join([i if ord(i) < 128 else ' ' for i in text]) else: return text.encode(preferred_encoding)
1abf77873b1b1f4474fa931a91003d93bedac6aa
3,619,327
import pathlib def folding(eventfile,Porb,nbins): """ Folding the events by some orbital period """ times = fits.open(eventfile)[1].data['TIME'] #getting array of times gtis_data = fits.open(eventfile)[2].data #getting GTIs T = sum([ gtis_data[i]['STOP']-gtis_data[i]['START'] for i in range(le...
0da7863ee4ed1932cb12a0334a254af8278fcdb7
3,619,328
def is_global(wire): """Return true if a wire is part of the global clock network""" return bool(global_spine_tap_re.match(wire) or global_cmux_out_re.match(wire) or global_cmux_in_re.match(wire) or clock_pin_re.match(wire) or pll_out_re.match(wire...
b8bf9e10291e698aecd675c18484f1b7a2df8825
3,619,329
def create_lookup_tables( vocabulary_path, num_oov_buckets=1, as_asset=True, unk_token=None ): """Creates TensorFlow lookup tables from a vocabulary file. Args: vocabulary_path: Path to the vocabulary file. num_oov_buckets: Number of out-of-vocabulary buckets. as_asset: If ``True``, the v...
ea8cdbcb384c148f646c3cad9d038b7bfd0822fb
3,619,330
def get_bprop_less_equal(self): """Grad definition for `LessEqual` operation.""" def bprop(x, y, out, dout): return zeros_like(x), zeros_like(y) return bprop
c7802cb01ee98ed8f718da872e114f4d325b62fd
3,619,331
def group_by( l, key ): """ agrupa por alguna llave Arguments ========= l: list, tuple, finite iter key: callable or str funcion que separara los elementos si es un string se asume que los elementos son dicionarios y el valor de key se usara para obtener el valor Re...
3ab6b3ea7d9bcb7f0b864aee9382a7073cec2e1a
3,619,332
def get_lr_rotate(current_step, lr_max, max_step): """ Warmup training strategy. Args: current_step (int): current step lr_max (float): original learning rate max_step (int): total steps Returns: list of learning rate at each step """ lr_each_step = [] deca...
4a91e3821ac3bc82aabd8456ecb32706839e5065
3,619,333
from pathlib import Path def walk(_path: str) -> tuple: """ :param _path: :return: tuple(_path, tuple('dirs',), tuple('files',)) """ dirs = [] files = [] path = Path(_path) for i in path.iterdir(): if i.is_file(): files.append(str(i)) if i.is_dir(): ...
06c8a7daa310da8df3d52a05e3f950d9c1c5ef37
3,619,334
def zxxgamma(v, t, gamma, H0): """ Takes in: v = values at z=0; t = list of redshifts to integrate over; gamma = interaction term. Returns a function f = [dt/dz, d(a)/dz, d(e'_m)/dz, d(e'_de)/dz, d...
4b3a5439a6187afe017c70c285ba89c12aa445bf
3,619,335
def _meshgrid2d(x, y): """ Special-cased implementation of np.meshgrid. For just two arguments, (x, y). Found to be about 3x faster on some simple test arguments. Parameters ---------- x : TYPE DESCRIPTION. y : TYPE DESCRIPTION. Returns ------- r1 : TYPE ...
e5017bcf3fd1ba3ebe48209a3f04eb5a95ac53a1
3,619,336
def py(code, input): """python <commands> -- Execute Python inside of a sandbox""" query = input.group(2) try: answer = web.exec_py(query) if answer: answer = answer.replace('\n', ' ').replace('\t', ' ').replace('\r', '') return code.reply(answer) return code....
32a6ffea112ab6a88e42d363291ef1b957445ef9
3,619,337
def get_participial_constructions(tokens): """Identify, color and count participial constructions""" # get part pres and praets part_pres = [t for t in tokens if t.full_pos == 'ADJD' and t.mo.part == '<PPRES' and t.function in ['root','pn']] part_praet = [t for t in tokens if t.full_pos == 'VVPP' ...
211ad63c56b21e50cbf13be3606a200b5f594565
3,619,338
from typing import Optional from typing import Tuple def bin_stats(predictions: tf.Tensor, labels: tf.Tensor, prefix: Optional[str]=None, suffix: Optional[str]=None) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]: """ Calculate f1, precision and recall from binary classification expected and predicte...
3da2c15f9c468a5bd8f813ca90dab70b1bfa5e33
3,619,339
def idx2token(idx, reverse_vocab): """ index换取词 :param idx: index :param reverse_vocab: 反查表 @see chatbot.build_vocab :return: 词 """ return reverse_vocab[idx]
4ce26e6a6a103133ffe0212d01a4c52a8a23479d
3,619,340
import requests def bbc_news(to_say: str) -> str: """ This function provides the needed information for the news briefing. :param to_say: str - to_say :return: str - to say """ api_key2 = data["api_key2"] url = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" final...
8fe2925aade6088ccd8e66acbc50536096ccc11a
3,619,341
def commandPanelOverride(*args, **kwargs): """ Returns an command panel override wrapper for the supplied function. :rtype: method """ # Check number of arguments # numArgs = len(args) if numArgs == 0: return partial(commandPanelOverride, **kwargs) elif numArgs == 1: ...
f9d2650143ebbb5506b789f0ab1ad104965d27c4
3,619,342
import collections from dateutil import tz def combine_multiple_callers(samples): """Collapse together variant calls from multiple approaches into single data item with `variants`. """ by_bam = collections.OrderedDict() for data in (x[0] for x in samples): work_bam = tz.get_in(("combine", "wor...
b00bf6edbd9f78a81d6bd3930d0194a6887cb6e8
3,619,344
def add_category(): """Add a new category.""" if 'username' not in login_session: flash("Please log in to continue.") return redirect(url_for('login')) elif request.method == 'POST': if request.form['new-category-name'] == '': flash('The field cannot be empty.') ...
820804fbd4d404ed349a178d870e5d3bab2e1ae5
3,619,345
import typing def formatString(format: str, data: typing.Dict, structure=None, language=None): """Central entryPoint if string contains $( we use old formatstrings else we use evalStrings (core 3.0 draft) displayStrings actually only used in relations and records. This handler can be used with displ...
9698dd17e12739c81c6b07b829bcdf0faa439937
3,619,346
from typing import List def _analyzable_entities(ns: str, ws: str, workflow_name: str, etype: str, enames: List[str], days_back: int or None, count: int or None) -> List[str]: """ Given a homogeneous (in terms of etype) list of entities, return a sub-list of them who are analyzable no...
e87887d51e2cf0b63b2a36aab78ce03f49f9f5bf
3,619,347
def call(func: Types.Function) -> Types.Function: """ Call the function during module exection if microtest is running or doing configuration. """ if core.running or core.config_in_process: core.call_with_resources(func) return func
21867cea60940c9eddaee952190553869cfb13ae
3,619,348
from datetime import datetime def localize_utc(value): """ Localise a UTC datetime """ if isinstance(value, datetime): return value.replace(tzinfo=tzutc()).astimezone(tzlocal()) else: return value
26a8ebd46bc1f2572d241b1fe35070e61d72c9e4
3,619,349
def matches(event, name): """ Returns True if the given event represents the same key as the one given in `name`. """ if is_number(name): return event.scan_code == name normalized = _normalize_name(name) matched_name = ( normalized == event.name or 'left ' + normaliz...
33a046925c018785647a27b5e4246664c09b1817
3,619,351
import time def vectorize_unknown(content_to_analyze): """ """ try: start = time.time() print("Tfidf Vectorizing data to be analyzed...") unknown = pd.DataFrame({"content": [content_to_analyze]}) unknown_vectors = vectorizer.transform(unknown.content) unknown_words_df ...
8745ea362d34d9e6ffbb14dad4c60355719d2c39
3,619,353
def message_from_lax(data): """ format a message from a Lax response data """ return data.get("message") if data.get("message") else "(empty message)"
81ba7399bc0e3e86ee1967988a17fd7f3524d8ab
3,619,354
def b58decode(encoded): """Decodes a base58 string to its integer value""" value = 0 multiplier = 1 for c in encoded[::-1]: value += b58chars.index(c) * multiplier multiplier *= b58base return value
f5788a14d4ac0dc6e6f0296f4178c419d3173ffe
3,619,356
def calc_geyser_rewards(badger, periodStartBlock, endBlock, cycle): """ Calculate rewards for each geyser, and sum them userRewards = (userShareSeconds / totalShareSeconds) / tokensReleased (For each token, for the time period) """ rewardsByGeyser = {} # For each Geyser, get a list of user ...
642320722579c0f0b431649decd6a3ec49be18fe
3,619,357
def createWindow(mainWidget, theme=None, title='CandySweet', ico_path=''): """ 快速创建彩色窗 (带TitleBar) :param mainWidget: :param theme: :param title: :param ico_path: :return: """ coolWindow = WindowWithTitleBar.WindowWithTitleBar(mainWidget) coolWindow.setWindowTitle(title) cool...
163e6785ec303a2d74473d93e3e9ca834993886e
3,619,358
def center_image_in_frame3d(image, centroid, size): """Centers a point in an image. Parameters ---------- image : 3d np.ndarray Image. centroid : 2-tuple of int/float Point to center. Coordinates should be (rr, cc). size : 2-tuple of int Size of returned-image. Re...
18f9659384a14cfbca77aa4a3b913a03df0048fd
3,619,359
def part1(_input): """ part 1 """ dif1 = 0 dif3 = 0 for idx, num in enumerate(_input): try: nxt = abs(_input[idx+1] - num) if nxt == 1: dif1 += 1 if nxt == 3: dif3 += 1 except IndexError: break #...
5bd2e4edffe2cef9dc30d51025d54a7831675788
3,619,360
import itertools def get_n_bits_combinations(num_bits: int) -> list: """ Function returning list containing all combinations of n bits. Given num_bits binary bits, each bit has value 0 or 1, there are in total 2**n_bits combinations. :param num_bits: int, number of combinations to evaluate :r...
6813f76f856a639688d6b80ddce0e605707f8d1f
3,619,361
def counting_sort(nums): """ counting sort algorithm's complexity is: time = O(n + k) space = O(n + k) where k = max(nums) Apply this algorithm when O(k) <= O(n), and when all numbers in nums are >= 0 """ # get frequency list num_max = max(nums) freqs = [0] * (num_max + 1) fo...
7bfdd8db0f1b177d4e6d3749ef10b997c0c07f81
3,619,364
def make_dict(data_for_dict): """ takes all text from nubbe list and makes a dictionary. data_for_dict: nubbe list created with parse_file() """ column_name_list = data_for_dict[0] db_list = data_for_dict[1:] column_list1 = [] column_list2 = [] column_list3 = [] column...
cb4725d0d23a33ba9e0b699032478dd1e54940b2
3,619,365
def accuracy_wilson(y_true, y_pred): """Return a Wilson confidence interval for the accuracy metric. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth labels y_pred : array-like of shape (n_samples,) Predicted labels Returns ------- np.nda...
84d9cec0e69828a57fc67139ee7c1334a7a81a6d
3,619,366
def extract_object_boxes_for_scenes(name, scene_info, sids, padding, swap_yz, box_delta_t): """Extracts object boxes given scene IDs. Args: name: The object name. scene_info: The scene information. sids: [R, 1] tf.int32. Scene IDs. padding: float32. The amount of...
67065a3bb05cd471b2e211a513fd77d05c428473
3,619,367
def api_get_and_validate_credentials() -> (str, str): """ Sanitize access and secret keys from request """ access_key = request.values.get("access_key", None) secret_key = request.values.get("secret_key", None) # reject empty strings and value-not-present cases if not access_key or not secret_key: ...
fcb94c52e3c98e9eb0c0137607357cdf8193426d
3,619,368
import pkg_resources def resource_exists(filename: str) -> bool: """ Check if a package resource exists. Parameters ---------- filename : str The filename. Returns ------- bool True if the file exists otherwise False. """ return pkg_resources.resource_exists(...
5daafd2f371de90316229ff4aad3ae69fa993346
3,619,369
import re import urllib import string import time from datetime import datetime def getSerieData(serie, proxies=None, url="http://www.epguides.com/"): """Get all data for given series from epguides.com @param series a dict of {<name on epguides>:<long name>, ...} """ # line example # 1. 1-...
9b1087771f3ae8e128a49290fe07ded263a7b364
3,619,370
def guess_type(val, empty_as_null: bool) -> ColumnType: """Guess type of a value""" if val is None: return ColumnType.NULL assert isinstance(val, (int, float, str)), "Invalid column data" if fastnumbers.isfloat(val): return ColumnType.NUMBER else: if len(val.strip()) == 0 an...
358c9ef76040251449d3516ea06dd4b21c627c12
3,619,371
def get_centers(bins): """Return the center of the provided bins. Example: >>> get_centers(bins=np.array([0.0, 1.0, 2.0])) array([0.5, 1.5]) """ bins = bins.astype(float) return (bins[:-1] + bins[1:]) / 2
4f5b3454e1ef718302c7e5ea204954d498ca9e10
3,619,372
from typing import Concatenate def create_alexnet_model_2d(input_image_size, number_of_classification_labels=1000, number_of_dense_units=4096, dropout_rate=0.0, mode='classification'): """ 2-D imple...
ba24617a0bce806d5b0c9a9a5f512f1614268d03
3,619,374
def pretty_event_latex(event: EventType, nonexisting: str = r'\varnothing') -> str: """ Takes an event type an prettifies it. :param event: event type to prettify :param nonexisting: string to represent non-existing nodes :return: prettified event type as string \makebox[\elen][c]{{{}}} """ ...
174816048511bc6e3a32a0eecf21bc91b918b5fb
3,619,375
def hex_16bit(value): """Converts 16bit value into bytearray. args: 16bit value returns: bytearray of size 2 """ if value > 0xffff or value < 0: raise Exception('Sar file 16bit value %s out of range' % value) return value.to_bytes(2, 'little')
1c5aab076798b40459bf5afab73fd92e8dbb93a1
3,619,376
import torch def comp_subclusters_params_min_dist(codes_k, mu_sub_1, mu_sub_2): """ Comp assignments to subclusters by min dist to subclusters centers codes_k (torch.tensor): the datapoints assigned to the k-th cluster mu_sub_1, mu_sub_2 (torch.tensor, torch.tensor): the centroids of the first and sec...
5ca26cebf2dd21da3f2ca2510e73edb01ec102d1
3,619,377