content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python #coding=utf-8 import os import re import requests import datetime import BeautifulSoup #url requests setting host_url = 'https://oj.leetcode.com' login_url = 'https://oj.leetcode.com/accounts/login/' question_list_url = 'https://oj.leetcode.com/problems/' code_base_url = 'https://oj.leetcode.com/submissions/detail/%s/' code_list_base_url = 'https://oj.leetcode.com/submissions/%d/' github_login_url = 'https://oj.leetcode.com/accounts/github/login/' code_regex = re.compile("storage\.put\('(python|cpp|java)', '([^']+)'\);") leetcode_request_header = { 'Host': 'oj.leetcode.com', 'Origin': 'https://oj.leetcode.com', 'Referer': 'https://oj.leetcode.com/accounts/login/' } github_request_header = { 'Host': 'github.com', 'Origin': 'https://github.com', 'Referer': 'https://github.com/' } #code setting ext_dic = {'python': '.py', 'cpp': '.cpp', 'java': '.java'} comment_char_dic = {'python': '#', 'cpp': '//', 'java': '//'} if __name__ == '__main__': #login form leetcode account USERNAME = 'YOUR USERNAME' PASSWORD = 'YOUR PASSWORD' #login form github account #downloader.login_from_github(username='YOUR USERNAME', password='YOUR PASSWORD') from taskbar import TaskBar downloader = LeetcodeDownloader() print "Logging..." if downloader.login(username=USERNAME, password=PASSWORD): print "ok, logged in." else: print "error, logging failed." exit() task_bar = TaskBar(40) print "Loading submissions..." task_param_list = task_bar.processing( task=lambda: list((func, ([table_data_list], {})) for table_data_list in downloader.page_code_all()), title=" Loading submissions...", show_total=False ) print "ok, %s submissions found in %.2fs." % (len(task_param_list), task_bar.time_cost) print "Downloading submissions..." task_bar.do_task(task_param_list)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 66, 7656, 28, 40477, 12, 23, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 7007, 198, 11748, 4818, 8079, 198, 11748, 23762, 50, 10486, 198, 198, 2, 6371, 7007, 4634, 198, 4...
2.387097
837
# -*- encoding: utf-8 -*- ############################################################## ## Author: Abdulmumen Naas ## Description: Arabic Natural Language Processor (Kalam-lp) ## Version: 0.0.1 ## Copyright (c) 2014 Abdulmumen Naas ############################################################## import re import string from constants import * if __name__ == "__main__": main()
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 29113, 14468, 7804, 4242, 2235, 201, 198, 2235, 220, 6434, 25, 23547, 76, 20080, 11013, 292, 201, 198, 2235, 197, 11828, 25, 17526, 12068, 15417, 32893, 357, 41428, ...
3.381356
118
__author__ = 'techsparksguru' from selenium.webdriver.common.by import By from .base_page_object import BasePage
[ 834, 9800, 834, 796, 220, 705, 13670, 82, 1845, 591, 70, 14717, 6, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 1525, 1330, 2750, 198, 6738, 764, 8692, 62, 7700, 62, 15252, 1330, 7308, 9876, 198 ]
2.923077
39
import unittest import collatz if __name__ == "__main__": unittest.main()
[ 198, 11748, 555, 715, 395, 198, 11748, 2927, 27906, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 628, 220 ]
2.515152
33
from sklearn.ensemble import RandomForestRegressor from openbox.utils.config_space import ConfigurationSpace from openbox.utils.config_space import UniformFloatHyperparameter, \ CategoricalHyperparameter, Constant, UniformIntegerHyperparameter import numpy as np from openbox.utils.config_space.util import convert_configurations_to_array import threading from joblib import Parallel, delayed from sklearn.utils.fixes import _joblib_parallel_args from sklearn.utils.validation import check_is_fitted from sklearn.ensemble._base import _partition_estimators def _accumulate_prediction(predict, X, out, lock): """ This is a utility function for joblib's Parallel. It can't go locally in ForestClassifier or ForestRegressor, because joblib complains that it cannot pickle it when placed there. """ prediction = predict(X, check_input=False) with lock: if len(out) == 1: out[0] += prediction else: for i in range(len(out)): out[i] += prediction[i] def _collect_prediction(predict, X, out, lock): """ This is a utility function for joblib's Parallel. It can't go locally in ForestClassifier or ForestRegressor, because joblib complains that it cannot pickle it when placed there. """ prediction = predict(X, check_input=False) with lock: out.append(prediction) n_obs = 50 n_new = 5 cs = get_cs() cs.seed(1) configs = cs.sample_configuration(n_obs) new_configs = cs.sample_configuration(n_new) X = convert_configurations_to_array(configs) Y = np.random.RandomState(47).random(size=(n_obs,)) pX = convert_configurations_to_array(new_configs) print('shape of pX', pX.shape) rf = RandomForestRegressor(random_state=np.random.RandomState(47), n_estimators=3) rf.fit(X, Y) preds = rf.predict(pX) print(preds) ppp = predictmv(rf, pX) print('final predict', ppp) m = np.mean(ppp, axis=0) v = np.var(ppp, axis=0) print(m, v) print(type(m), type(v)) from joblib import effective_n_jobs print(effective_n_jobs(None))
[ 6738, 1341, 35720, 13, 1072, 11306, 1330, 14534, 34605, 8081, 44292, 198, 6738, 1280, 3524, 13, 26791, 13, 11250, 62, 13200, 1330, 28373, 14106, 198, 6738, 1280, 3524, 13, 26791, 13, 11250, 62, 13200, 1330, 35712, 43879, 38197, 17143, 235...
2.751009
743
import subprocess, os # constants with global scope INPUT = "--input" OUTPUT = "--output" FILTERS = "--filters" SUPPPLEMENTS = "--supplements" JAR_DIRECTORY = "target" JAR_NAME = "report-engine.jar" if __name__ == '__main__': main()
[ 11748, 850, 14681, 11, 28686, 201, 198, 201, 198, 2, 38491, 351, 3298, 8354, 201, 198, 1268, 30076, 796, 366, 438, 15414, 1, 201, 198, 2606, 7250, 3843, 796, 366, 438, 22915, 1, 201, 198, 46700, 51, 4877, 796, 366, 438, 10379, 1010,...
2.417476
103
##======================================================================================== import numpy as np from scipy import linalg from sklearn.preprocessing import OneHotEncoder from scipy.spatial import distance #========================================================================================= #========================================================================================= # generate coupling matrix w0: wji from j to i #========================================================================================= #========================================================================================= # 2018.10.27: generate time series by MCMC #=================================================================================================== # 2018.12.22: inverse of covariance between values of x #========================================================================================= # 2018.12.28: fit interaction to residues at position i # additive update #========================================================================================= # 2019.02.25: fit interaction to residues at position i # multiplicative update (new version, NOT select each pair as the old version) #========================================================================================= # 2019.05.15: add ridge regression term to coupling w #===================================================================================================
[ 2235, 23926, 4770, 2559, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 300, 1292, 70, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 1881, 21352, 27195, 12342, 198, 6738, 629, 541, 88, 13, 2777, 34961, 1330, 5253, ...
7.033493
209
import sys if __name__ == '__main__': # Set the defaults a = '' b = '' # If arguments were passed to this script, use those try: a = sys.argv[1] b = sys.argv[2] except Exception: pass # Sets the result to the longer of the two Strings result = a if len(a) > len(b) else b
[ 11748, 25064, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 5345, 262, 26235, 198, 220, 220, 220, 257, 796, 10148, 198, 220, 220, 220, 275, 796, 10148, 198, 220, 220, 220, 220, 198, 22...
2.278912
147
""" PGN Scraper is a small program which downloads each of a user's archived games from chess.com and stores them in a pgn file. When running the user is asked for the account name which shall be scraped and for game types. The scraper only downloads games of the correct type. Supported types are: bullet, rapid, blitz rated, unrated standard chess, other ruless (chess960, oddchess, etc.) """ from datetime import datetime import json import urllib.request import os def CheckFileName(file_name): """ This function checks if a file with file_name already exists. If yes an error message is printed and the script aborted. """ if os.path.isfile(os.getcwd()+f"/{file_name}"): print(f"Error: A file named '{file_name}' already exists.") print("Exiting...") quit() def GameTypeTrue(game,game_type,rated,rules): """ This function checks if the game is of the type defined in game_type (bullet, rapid or blitz) and returns either True or False. """ # Check if game is of the correct type for type in game_type: for ra in rated: for ru in rules: if (game["time_class"] == type) and (game["rated"] == ra) and ( (game["rules"] == "chess") == ru): return True # If not correct type return False return False def initScrape(): """ This functions is used to set up the scraping parameters like account name and game type. """ # Input account name acc_name = input("Enter account name: ").strip() # Check if acc_name is empty if bool(acc_name) == False: print("Error: Empty account name!") quit() # Input game type #game_type_code = input("Enter game type [1] All (default), [2] Rapid, [3] Blitz, [4] Bullet, [5] Rapid and Blitz: ").strip() # If game_type_code is empty set to 1 #if bool(game_type_code) == False: game_type_code = "1" # Create dictionary for different game type options und apply input game_type_dict = { "1" : ["bullet", "blitz", "rapid"], "2" : ["rapid"], "3" : ["blitz"], "4" : ["bullet"], "5" : ["blitz", "rapid"] } game_type = game_type_dict["1"] # Input rated/unrated #rated_code = input("Consider [1] only rated games (default), [2] only unrated or [3] all games: ").strip() # If rated_code is empty set to 1 #if bool(rated_code) == False: rated_code = "1" # Create dictionary for rated/unraked and apply input rated_dict = { "1" : [True], "2" : [False], "3" : [True, False] } # try: rated = rated_dict["3"] # except KeyError: # print("Error: Invalid input!\nExiting...") # quit() # Input rules ("chess"/other) # rules_code = input("Consider [1] only standard chess (default), [2] only other modes (oddchess, bughouse etc.) or [3] any type: ").strip() # If rules_code is empty set to 1 # if bool(rules_code) == False: rules_code = "1" # Create dictionary for rules and apply input rules_dict = { "1" : [True], "2" : [False], "3" : [True, False] } #try: rules = rules_dict[rules_code] # except KeyError: # print("Error: Invalid input!\nExiting...") # quit() # Print warning if only rated and only other rules are selected if (rated_code == "1") and (rules_code == "2"): print("Warning: You selected only rated AND only other chess modes!") print(" Other chess modes are often unrated!") return [acc_name, game_type, rated, rules] def beginScrape(params): """ The downloading of the PGN archives happens here. The file is saved as "username_YYYY-MM-dd.pgn" """ # Passing the predefined parameters acc_name = params[0] game_type = params[1] rated = params[2] rules = params[3] # Create name of pgn file now = datetime.now() date = now.strftime("%Y-%m-%d") game_type_string = "_".join(game_type) file_name = f"{acc_name}_{date}_{game_type_string}.pgn" # Check if file already exists CheckFileName(file_name) # Run the request, check games for type and write correct ones to file with urllib.request.urlopen(f"https://api.chess.com/pub/player/{acc_name}/games/archives") as url: archives = list(dict(json.loads(url.read().decode()))["archives"]) for archive in archives: with urllib.request.urlopen(archive) as url: games = list(dict(json.loads(url.read().decode()))["games"]) for game in games: if GameTypeTrue(game,game_type,rated,rules): with open(file_name, "a") as text_file: print(game["pgn"], file=text_file) print("\n", file=text_file) def main(): """ Scrape PGN files from chess.com . """ params = initScrape() beginScrape(params) if __name__ == '__main__': main()
[ 37811, 198, 6968, 45, 1446, 38545, 318, 257, 1402, 1430, 543, 21333, 1123, 286, 257, 2836, 338, 33962, 1830, 422, 19780, 13, 785, 290, 7000, 606, 287, 257, 279, 4593, 2393, 13, 198, 2215, 2491, 262, 2836, 318, 1965, 329, 262, 1848, ...
2.46582
2,048
import sqlite3 import codecs # for using '' import os # f = codecs.open("jjd_info_title.txt", "r") title_list = [] while True: line = f.readline() # if not line: break # break the loop when it's End Of File title_list.append(line) # split the line and append it to list f.close() # f = codecs.open("jjd_info_date.txt", "r") date_list = [] while True: line = f.readline() # if not line: break # break the loop when it's End Of File date_list.append(line) # split the line and append it to list f.close() # f = codecs.open("jjd_info_view.txt", "r") view_list = [] while True: line = f.readline() if not line: break view_list.append(line) f.close # href() f = codecs.open("jjd_info_href.txt", "r") href_list = [] while True: line = f.readline() if not line: break href_list.append(line) f.close ################################################################################ ###################################### DB ###################################### # below 'print' is for checking the data structure. Don't care. #print("saved data(1) : ", list[0][0]) #print("saved data(2) : ", list[1]) # connect 'db.sqlite3' in the django folder and manipulate it con = sqlite3.connect("db.sqlite3") cur = con.cursor() # use 'cursor' to use DB # you don't need to care the below CREATE TABLE command. # cur.execute("CREATE TABLE if not exists website1_crawlingdata(Name text, Period text);") total_list = [] for i in range(len(date_list)): temp = [str(i+1), title_list[i], date_list[i], view_list[i], href_list[i]] total_list.append(temp) # print(total_list) cur.execute("delete from website1_jjd_info;") idx = 0 # while idx < len(date_list): cur.execute("INSERT INTO website1_jjd_info VALUES(?, ?, ?, ?, ?);", total_list[idx]) # 'INSERT' each value of the total_list to the table of DB. idx += 1 con.commit() # The new input is gonna be saved in the DB with 'commit' command idx = 0 con.close()
[ 11748, 44161, 578, 18, 198, 11748, 40481, 82, 1303, 329, 1262, 10148, 198, 11748, 28686, 198, 198, 2, 220, 220, 220, 198, 69, 796, 40481, 82, 13, 9654, 7203, 41098, 67, 62, 10951, 62, 7839, 13, 14116, 1600, 366, 81, 4943, 198, 7839,...
2.548267
808
from opt_utils import * import argparse parser = argparse.ArgumentParser() parser.add_argument("-s", "--skip_compilation", action='store_true', help="skip compilation") args = parser.parse_args() if not args.skip_compilation: compile_all_opt_examples() for example in all_examples: args = [] output = run_example(example, args, True).decode('ascii') with open(example + ".log", "w") as text_file: text_file.write(output)
[ 6738, 2172, 62, 26791, 1330, 1635, 198, 11748, 1822, 29572, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 7203, 12, 82, 1600, 366, 438, 48267, 62, 5589, 10520, 1600, 2223, 11639, 8095, 62, ...
2.938356
146
# Generated by Django 3.1.1 on 2020-09-22 20:01 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 12131, 12, 2931, 12, 1828, 1160, 25, 486, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import argparse from logging import getLogger from deeppavlov.core.commands.infer import interact_model, predict_on_stream from deeppavlov.core.commands.train import train_evaluate_model_from_config from deeppavlov.core.common.cross_validation import calc_cv_score from deeppavlov.core.common.file import find_config from deeppavlov.download import deep_download from deeppavlov.utils.alexa.server import run_alexa_default_agent from deeppavlov.utils.alice import start_alice_server from deeppavlov.utils.ms_bot_framework.server import run_ms_bf_default_agent from deeppavlov.utils.pip_wrapper import install_from_config from deeppavlov.utils.server.server import start_model_server from deeppavlov.utils.telegram.telegram_ui import interact_model_by_telegram log = getLogger(__name__) parser = argparse.ArgumentParser() parser.add_argument("mode", help="select a mode, train or interact", type=str, choices={'train', 'evaluate', 'interact', 'predict', 'interactbot', 'interactmsbot', 'alexa', 'riseapi', 'download', 'install', 'crossval'}) parser.add_argument("config_path", help="path to a pipeline json config", type=str) parser.add_argument("-e", "--start-epoch-num", dest="start_epoch_num", default=None, help="Start epoch number", type=int) parser.add_argument("--recursive", action="store_true", help="Train nested configs") parser.add_argument("-b", "--batch-size", dest="batch_size", default=1, help="inference batch size", type=int) parser.add_argument("-f", "--input-file", dest="file_path", default=None, help="Path to the input file", type=str) parser.add_argument("-d", "--download", action="store_true", help="download model components") parser.add_argument("--folds", help="number of folds", type=int, default=5) parser.add_argument("-t", "--token", default=None, help="telegram bot token", type=str) parser.add_argument("-i", "--ms-id", default=None, help="microsoft bot framework app id", type=str) parser.add_argument("-s", "--ms-secret", default=None, help="microsoft bot framework app secret", type=str) parser.add_argument("--multi-instance", action="store_true", help="allow rising of several instances of the model") parser.add_argument("--stateful", action="store_true", help="interact with a stateful model") parser.add_argument("--no-default-skill", action="store_true", help="do not wrap with default skill") parser.add_argument("--https", action="store_true", help="run model in https mode") parser.add_argument("--key", default=None, help="ssl key", type=str) parser.add_argument("--cert", default=None, help="ssl certificate", type=str) parser.add_argument("-p", "--port", default=None, help="api port", type=str) parser.add_argument("--api-mode", help="rest api mode: 'basic' with batches or 'alice' for Yandex.Dialogs format", type=str, default='basic', choices={'basic', 'alice'}) if __name__ == "__main__": main()
[ 37811, 198, 15269, 2177, 47986, 27862, 290, 10766, 18252, 2248, 11, 337, 4061, 51, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 1...
3.075325
1,155
'''Read grammar specifications for test cases.''' import re import sys from pprint import pprint from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, Marker from cfg.table import END_MARKER, ParseTableNormalForm label_re = re.compile('^\s*==\s*(.*?)\s*==\s*$') comment_re = re.compile('^([^#]*)') shift_re = re.compile('^sh(\d+)$') reduce_re = re.compile('^re(\d+)$') def read_test_case(finname): '''Read a grammar test case from a file.''' label = 'grammar' sections = {} with open(finname, 'r') as fin: for line in filter(None, map(lambda s: comment_re.match(s).group(1).strip(), fin)): m = label_re.match(line) if m: label = m.group(1).lower() else: sections.setdefault(label, []).append(line) retype('grammar', read_grammar) retype('table', retype_table) retype('tablea', retype_table) retype('tableb', retype_table) retype('result', read_bool) return GrammarTestCase(sections, finname) if __name__ == '__main__': if len(sys.argv) != 2: sys.stderr.write('Usage: read_grammar.py <file>\n') sys.exit(1) print read_test_case(sys.argv[1])
[ 7061, 6, 5569, 23491, 20640, 329, 1332, 2663, 2637, 7061, 198, 198, 11748, 302, 198, 11748, 25064, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 30218, 70, 13, 7295, 1330, 30532, 11146, 38, 859, 3876, 11, 24523, 11, 8504, 23705, 2...
2.267552
527
import os import re import copy import json import pyblish.api import clique import pype.api import pype.lib
[ 11748, 28686, 198, 11748, 302, 198, 11748, 4866, 198, 11748, 33918, 198, 11748, 12972, 65, 1836, 13, 15042, 198, 11748, 537, 2350, 198, 11748, 279, 2981, 13, 15042, 198, 11748, 279, 2981, 13, 8019, 628 ]
3.142857
35
import unittest from unittest.mock import Mock import mock import peerfinder.peerfinder as peerfinder import requests from ipaddress import IPv6Address, IPv4Address if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 11748, 15290, 198, 11748, 12720, 22805, 13, 33350, 22805, 355, 12720, 22805, 198, 11748, 7007, 198, 6738, 20966, 21975, 1330, 25961, 21, 20231, 11, 25961, 19...
3.257576
66
# -*- encoding: utf-8 -*- # # Copyright 2012 New Dream Network, LLC (DreamHost) # # Author: Julien Danjou <julien@danjou.info> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Handler for producing network counter messages from Neutron notification events. """ from oslo.config import cfg from ceilometer.openstack.common.gettextutils import _ # noqa from ceilometer.openstack.common import log from ceilometer import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('neutron_control_exchange', default='neutron', help="Exchange name for Neutron notifications", deprecated_name='quantum_control_exchange'), ] cfg.CONF.register_opts(OPTS) LOG = log.getLogger(__name__) class Network(NetworkNotificationBase): """Listen for Neutron network notifications in order to mediate with the metering framework. """ resource_name = 'network' class Subnet(NetworkNotificationBase): """Listen for Neutron notifications in order to mediate with the metering framework. """ resource_name = 'subnet' class Port(NetworkNotificationBase): """Listen for Neutron notifications in order to mediate with the metering framework. """ resource_name = 'port' class Router(NetworkNotificationBase): """Listen for Neutron notifications in order to mediate with the metering framework. """ resource_name = 'router' class FloatingIP(NetworkNotificationBase): """Listen for Neutron notifications in order to mediate with the metering framework. """ resource_name = 'floatingip' counter_name = 'ip.floating' unit = 'ip' class Bandwidth(NetworkNotificationBase): """Listen for Neutron notifications in order to mediate with the metering framework. """ event_types = ['l3.meter']
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 220, 2321, 968, 7610, 7311, 11, 11419, 357, 30571, 17932, 8, 198, 2, 198, 2, 6434, 25, 5979, 2013, 6035, 73, 280, 1279, 73, 377, 2013, 31, 25604, ...
3.117333
750
# Lint as: python3 # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for `update.py`.""" from absl.testing import absltest import chex import jax import jax.numpy as jnp from optax._src import update if __name__ == '__main__': absltest.main()
[ 2, 406, 600, 355, 25, 21015, 18, 198, 2, 15069, 13130, 10766, 28478, 21852, 15302, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 4...
3.798319
238
#!/usr/bin/env python """Provides the entities, the building blocks of the SMRCA hierachy representation of a macromolecular structure. The MultiEntity class is a special Entity class to hold multiple instances of other entities. All Entities apart from the Atom can hold others and inherit from the MultiEntity. The Entity is the most basic class to deal with structural and molecular data. Do not use it directly since some functions depend on methods provided by sub-classes. Classes inheriting from MultiEntity have to provide some attributes during init e.g: self.level = a valid string inside the SMCRA hierarchy). Holders of entities are like normal MultiEntities, but are temporary and are outside the parent-children axes. """ import cogent from cogent.core.annotation import SimpleVariable from numpy import (sqrt, arctan2, power, array, mean, sum) from cogent.data.protein_properties import AA_NAMES, AA_ATOM_BACKBONE_ORDER, \ AA_ATOM_REMOTE_ORDER, AREAIMOL_VDW_RADII, \ DEFAULT_AREAIMOL_VDW_RADIUS, AA_NAMES_3to1 from cogent.data.ligand_properties import HOH_NAMES, LIGAND_AREAIMOL_VDW_RADII from operator import itemgetter, gt, ge, lt, le, eq, ne, or_, and_, contains, \ is_, is_not from collections import defaultdict from itertools import izip from copy import copy, deepcopy __author__ = "Marcin Cieslik" __copyright__ = "Copyright 2007-2012, The Cogent Project" __credits__ = ["Marcin Cieslik"] __license__ = "GPL" __version__ = "1.5.3" __maintainer__ = "Marcin Cieslik" __email__ = "mpc4p@virginia.edu" __status__ = "Development" ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_ ' HIERARCHY = ['H', 'S', 'M', 'C', 'R', 'A'] AREAIMOL_VDW_RADII.update(LIGAND_AREAIMOL_VDW_RADII) # error while creating a structure (non-recoverable error) # warning while creating a structure # (something wrong with the input, but recoverable) def sort_id_list(id_list, sort_tuple): """Sorts lists of id tuples. The order is defined by the PDB file specification.""" (hol_loc, str_loc, mod_loc, chn_loc, res_loc, at_loc) = sort_tuple # even a simple id is a tuple, this makes sorting general # this assumes that the implementation of sorting is stable. # does it work for others then cPython. if res_loc or res_loc is 0: id_list.sort(key=itemgetter(res_loc), cmp=lambda x, y: residue(x[0], y[0])) # by res_name if at_loc or at_loc is 0: id_list.sort(key=itemgetter(at_loc), cmp=lambda x, y: space_last(x[1], y[1])) # by alt_loc if at_loc or at_loc is 0: id_list.sort(key=itemgetter(at_loc), cmp=lambda x, y: atom(x[0], y[0])) # by at_id if res_loc or res_loc is 0: id_list.sort(key=itemgetter(res_loc), cmp=lambda x, y: cmp(x[2], y[2])) # by res_ic if res_loc or res_loc is 0: id_list.sort(key=itemgetter(res_loc), cmp=lambda x, y: cmp(x[1], y[1])) # by res_id if chn_loc or chn_loc is 0: id_list.sort(key=itemgetter(chn_loc), cmp=space_last) # by chain if mod_loc or mod_loc is 0: id_list.sort(key=itemgetter(mod_loc)) # by model if str_loc or str_loc is 0: id_list.sort(key=itemgetter(str_loc)) # by structure return id_list def merge(dicts): """Merges multiple dictionaries into a new one.""" master_dict = {} for dict_ in dicts: master_dict.update(dict_) return master_dict def unique(lists): """Merges multiple iterables into a unique sorted tuple (sorted set).""" master_set = set() for set_ in lists: master_set.update(set_) return tuple(sorted(master_set))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 15946, 1460, 262, 12066, 11, 262, 2615, 7021, 286, 262, 9447, 7397, 32, 13550, 35586, 220, 198, 15603, 341, 286, 257, 8352, 398, 2305, 10440, 4645, 13, 198, 220, 220, 220, 220, ...
2.453887
1,518
import unittest from ..dispatcher import Dispatcher class TestDispatcher(unittest.TestCase):
[ 11748, 555, 715, 395, 198, 6738, 11485, 6381, 8071, 2044, 1330, 3167, 8071, 2044, 628, 198, 198, 4871, 6208, 7279, 8071, 2044, 7, 403, 715, 395, 13, 14402, 20448, 2599, 198 ]
3.096774
31
from itertools import product import struct import pickle import numpy as np from scipy import sparse from scipy import isnan as scipy_isnan import numpy.matlib ASCII_FACET = """facet normal 0 0 0 outer loop vertex {face[0][0]:.4f} {face[0][1]:.4f} {face[0][2]:.4f} vertex {face[1][0]:.4f} {face[1][1]:.4f} {face[1][2]:.4f} vertex {face[2][0]:.4f} {face[2][1]:.4f} {face[2][2]:.4f} endloop endfacet """ BINARY_HEADER ="80sI" BINARY_FACET = "12fH" def get_quad(center, n, side=1.): x, y, z = np.array(center).astype('float64') n1, n2, n3 = np.array(n).astype('float64') l = side/2. nm = np.linalg.norm s = np.sign if any(np.isnan(v) for v in n): return if np.allclose(n, np.zeros(n.shape)): return # Build two vectors orthogonal between themselves and the normal if (np.abs(n2) > 0.2 or np.abs(n3) > 0.2): C = np.array([1, 0, 0]) else: C = np.array([0, 1, 0]) ortho1 = np.cross(n, C) ortho1 *= l / np.linalg.norm(ortho1) ortho2 = np.cross(n, ortho1) ortho2 *= l / np.linalg.norm(ortho2) #ortho1[[2,1]] = ortho1[[1,2]] #ortho2[[2,1]] = ortho2[[1,2]] ortho1[1] = -ortho1[1] ortho2[1] = -ortho2[1] return [[ center + ortho1, center + ortho2, center - ortho1, center - ortho2, ]] def surfaceFromNormals(normals): valid_indices = ~np.isnan(normals) w, h, d = normals.shape nx = np.transpose(np.hstack(( normals[:,:,0].ravel(), normals[:,:,0].ravel(), ))) ny = np.transpose(np.hstack(( normals[:,:,1].ravel(), normals[:,:,1].ravel(), ))) nz = np.transpose(np.hstack(( normals[:,:,2].ravel(), normals[:,:,2].ravel(), ))) vectorsize = nz.shape valid_idx = ~np.isnan(nz) M = sparse.dia_matrix((2*w*h, w*h), dtype=np.float64) # n_z z(x + 1, y) - n_z z(x,y) = n_x M.setdiag(-nz, 0) M.setdiag(nz, 1) # n_z z(x, y + 1) - n_z z(x,y) = n_y M.setdiag(-nz, -w*h) M.setdiag(np.hstack(([0] * w, nz)), -w*h + w) # Boundary values # n_y ( z(x,y) - z(x + 1, y)) = n_x ( z(x,y) - z(x, y + 1)) # TODO: Redo for boundaries in Y-axis M = M.tolil() half_size = valid_idx.size // 2 bidxd = np.hstack((np.diff(valid_idx.astype('int8')[:half_size]), [0])) inner_boundaries = np.roll(bidxd==1, 1) | (bidxd==-1) outer_boundaries = (bidxd==1) | (np.roll(bidxd==-1, 1)) nz_t = np.transpose(valid_idx.reshape((w,h,d*2//3)), (1, 0, 2)).ravel() valid_idx_t = ~np.isnan(nz_t) bidxd = np.hstack((np.diff(valid_idx_t.astype('int8')[:half_size]), [0])) inner_boundaries |= np.roll(bidxd==1, 1) | (bidxd==-1) outer_boundaries |= (bidxd==1) | (np.roll(bidxd==-1, 1)) bidx = np.zeros((half_size,), dtype=np.bool) bidx[inner_boundaries] = True bidx = np.indices(bidx.shape)[0][bidx] M[bidx, bidx] = nx[bidx] M[bidx, bidx + w] = -nx[bidx] M[bidx + half_size, bidx] = ny[bidx] M[bidx + half_size, bidx + 1] = -ny[bidx] M = M.tocsr()[valid_idx] weight = 1 OB = np.zeros((outer_boundaries.sum(), w*h,)) OB[np.indices((outer_boundaries.sum(),))[0], np.where(outer_boundaries==True)] = weight M = sparse.vstack((M,OB)) # Build [ n_x n_y ]' m = np.hstack(( normals[:,:,0].ravel(), normals[:,:,1].ravel(), )).reshape(-1, 1) print(inner_boundaries.shape, m.shape) i_b = np.hstack((inner_boundaries, inner_boundaries)).reshape(-1,1) print(i_b.shape, m.shape) m[i_b] = 0 m = m[valid_idx] m = np.vstack(( m, np.zeros((outer_boundaries.sum(), 1)), )) # Solve least squares assert not np.isnan(m).any() # x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var = sparse.linalg.lsqr(M, m) x, istop, itn, normr, normar, norma, conda, normx = sparse.linalg.lsmr(M, m) # Build the surface (x, y, z) with the computed values of z surface = np.dstack(( np.indices((w, h))[0], np.indices((w, h))[1], x.reshape((w, h)) )) return surface def writeMesh(surface, normals, filename): s = surface with open(filename, 'wb') as fp: writer = Binary_STL_Writer(fp) for x in range(0, s.shape[0], 5): for y in range(0, s.shape[1], 5): #for x, y in product(range(s.shape[0]), range(s.shape[1])): quad = get_quad( s[x,y,:], normals[x,y,:], 4, ) if quad: writer.add_faces(quad) writer.close() def write3dNormals(normals, filename): with open(filename, 'wb') as fp: writer = Binary_STL_Writer(fp) for x in range(0, normals.shape[0], 5): for y in range(0, normals.shape[1], 5): quad = get_quad( (0, x, y), normals[x,y,:], 4, ) if quad: writer.add_faces(quad) writer.close() def surfaceToHeight(surface): minH = np.amin(surface[:,:,2]) maxH = np.amax(surface[:,:,2]) scale = maxH - minH height = (surface[:,:,2] - minH) / scale return height def writeObj(surface, normals, filename): print('obj here') if __name__ == '__main__': with open('data.pkl', 'rb') as fhdl: normals = pickle.load(fhdl) writeMesh(normals)
[ 6738, 340, 861, 10141, 1330, 1720, 198, 11748, 2878, 198, 11748, 2298, 293, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 29877, 198, 6738, 629, 541, 88, 1330, 2125, 272, 355, 629, 541, 88, 62, 271, 12647, ...
1.890197
2,887
''' This is a python script that requires you have python installed, or in a cloud environment. This script scrapes the CVS website looking for vaccine appointments in the cities you list. To update for your area, update the locations commented below. If you receive an error that says something is not installed, type pip install requests etc. Happy vaccination! ''' import requests import time import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from datetime import datetime, timedelta if __name__ == '__main__': try: findAVaccine() except KeyboardInterrupt: print('Exiting...')
[ 7061, 6, 198, 1212, 318, 257, 21015, 4226, 326, 4433, 345, 423, 21015, 6589, 11, 393, 287, 257, 6279, 2858, 13, 198, 198, 1212, 4226, 15881, 274, 262, 327, 20304, 3052, 2045, 329, 12319, 23976, 287, 262, 4736, 345, 1351, 13, 198, 25...
3.409326
193
from .pefile import *
[ 6738, 764, 431, 7753, 1330, 1635, 198 ]
3.142857
7
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2016-2017 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # ###########################################################################*/ """This script illustrates the use of :class:`silx.gui.plot3d.ScalarFieldView`. It loads a 3D scalar data set from a file and displays iso-surfaces and an interactive cutting plane. It can also be started without providing a file. """ from __future__ import absolute_import, division, unicode_literals __authors__ = ["T. Vincent"] __license__ = "MIT" __date__ = "05/01/2017" import argparse import logging import os.path import sys import numpy from silx.gui import qt from silx.gui.plot3d.ScalarFieldView import ScalarFieldView from silx.gui.plot3d import SFViewParamTree logging.basicConfig() _logger = logging.getLogger(__name__) import h5py def load(filename): """Load 3D scalar field from file. It supports 3D stack HDF5 files and numpy files. :param str filename: Name of the file to open and path in file for hdf5 file :return: numpy.ndarray with 3 dimensions. """ if not os.path.isfile(filename.split('::')[0]): raise IOError('No input file: %s' % filename) if h5py.is_hdf5(filename.split('::')[0]): if '::' not in filename: raise ValueError( 'HDF5 path not provided: Use <filename>::<path> format') filename, path = filename.split('::') path, indices = path.split('#')[0], path.split('#')[1:] with h5py.File(filename) as f: data = f[path] # Loop through indices along first dimensions for index in indices: data = data[int(index)] data = numpy.array(data, order='C', dtype='float32') else: # Try with numpy try: data = numpy.load(filename) except IOError: raise IOError('Unsupported file format: %s' % filename) if data.ndim != 3: raise RuntimeError( 'Unsupported data set dimensions, only supports 3D datasets') return data def default_isolevel(data): """Compute a default isosurface level: mean + 1 std :param numpy.ndarray data: The data to process :rtype: float """ data = data[numpy.isfinite(data)] if len(data) == 0: return 0 else: return numpy.mean(data) + numpy.std(data) # Parse input arguments parser = argparse.ArgumentParser( description=__doc__) parser.add_argument( '-l', '--level', nargs='?', type=float, default=float('nan'), help="The value at which to generate the iso-surface") parser.add_argument( '-sx', '--xscale', nargs='?', type=float, default=1., help="The scale of the data on the X axis") parser.add_argument( '-sy', '--yscale', nargs='?', type=float, default=1., help="The scale of the data on the Y axis") parser.add_argument( '-sz', '--zscale', nargs='?', type=float, default=1., help="The scale of the data on the Z axis") parser.add_argument( '-ox', '--xoffset', nargs='?', type=float, default=0., help="The offset of the data on the X axis") parser.add_argument( '-oy', '--yoffset', nargs='?', type=float, default=0., help="The offset of the data on the Y axis") parser.add_argument( '-oz', '--zoffset', nargs='?', type=float, default=0., help="The offset of the data on the Z axis") parser.add_argument( 'filename', nargs='?', default=None, help="""Filename to open. It supports 3D volume saved as .npy or in .h5 files. It also support nD data set (n>=3) stored in a HDF5 file. For HDF5, provide the filename and path as: <filename>::<path_in_file>. If the data set has more than 3 dimensions, it is possible to choose a 3D data set as a subset by providing the indices along the first n-3 dimensions with '#': <filename>::<path_in_file>#<1st_dim_index>...#<n-3th_dim_index> E.g.: data.h5::/data_5D#1#1 """) args = parser.parse_args(args=sys.argv[1:]) # Start GUI app = qt.QApplication([]) # Create the viewer main window window = ScalarFieldView() # Create a parameter tree for the scalar field view treeView = SFViewParamTree.TreeView(window) treeView.setSfView(window) # Attach the parameter tree to the view # Add the parameter tree to the main window in a dock widget dock = qt.QDockWidget() dock.setWindowTitle('Parameters') dock.setWidget(treeView) window.addDockWidget(qt.Qt.RightDockWidgetArea, dock) # Load data from file if args.filename is not None: data = load(args.filename) _logger.info('Data:\n\tShape: %s\n\tRange: [%f, %f]', str(data.shape), data.min(), data.max()) else: # Create dummy data _logger.warning('Not data file provided, creating dummy data') coords = numpy.linspace(-10, 10, 64) z = coords.reshape(-1, 1, 1) y = coords.reshape(1, -1, 1) x = coords.reshape(1, 1, -1) data = numpy.sin(x * y * z) / (x * y * z) # Set ScalarFieldView data window.setData(data) # Set scale of the data window.setScale(args.xscale, args.yscale, args.zscale) # Set offset of the data window.setTranslation(args.xoffset, args.yoffset, args.zoffset) # Set axes labels window.setAxesLabels('X', 'Y', 'Z') # Add an iso-surface if not numpy.isnan(args.level): # Add an iso-surface at the given iso-level window.addIsosurface(args.level, '#FF0000FF') else: # Add an iso-surface from a function window.addIsosurface(default_isolevel, '#FF0000FF') window.show() app.exec_()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 11900, 29113, 29113, 7804, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 12, 5539, 3427, 16065, 354, 10599, 1313, 47532, 29118, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, ...
2.748448
2,417
# __init__.py # Copyright 2017 Roger Marsh # Licence: See LICENCE (BSD licence) """Miscellaneous modules for applications available at solentware.co.uk. These do not belong in the solentware_base or solentware_grid packages, siblings of solentware_misc. """
[ 2, 11593, 15003, 834, 13, 9078, 198, 2, 15069, 2177, 13637, 9786, 198, 2, 10483, 594, 25, 4091, 38559, 18310, 357, 21800, 17098, 8, 198, 198, 37811, 31281, 25673, 13103, 329, 5479, 1695, 379, 1540, 298, 1574, 13, 1073, 13, 2724, 13, ...
3.421053
76
__author__ = "Music" # MNIST For ML Beginners # https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html
[ 834, 9800, 834, 796, 366, 22648, 1, 198, 2, 29060, 8808, 1114, 10373, 16623, 2741, 198, 2, 3740, 1378, 2503, 13, 83, 22854, 11125, 13, 2398, 14, 47178, 14, 81, 15, 13, 24, 14, 83, 44917, 82, 14, 10295, 396, 14, 27471, 2741, 14, ...
2.645833
48
#!/usr/bin/python # mapper.py import sys for line in sys.stdin: row, values = line.strip().split('\t') row_values = values.split(' ') for (col, col_value) in enumerate(row_values): # out: <col> <row> <value> print("{0}\t{1}\t{2}".format(col, row, col_value))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 285, 11463, 13, 9078, 198, 11748, 25064, 198, 198, 1640, 1627, 287, 25064, 13, 19282, 259, 25, 198, 220, 220, 220, 5752, 11, 3815, 796, 1627, 13, 36311, 22446, 35312, 10786, 59, 83, 1153...
2.177778
135
from ray.rllib.algorithms.maddpg.maddpg import ( MADDPGConfig, MADDPGTrainer, DEFAULT_CONFIG, ) __all__ = ["MADDPGConfig", "MADDPGTrainer", "DEFAULT_CONFIG"]
[ 6738, 26842, 13, 81, 297, 571, 13, 282, 7727, 907, 13, 76, 2860, 6024, 13, 76, 2860, 6024, 1330, 357, 198, 220, 220, 220, 45878, 6322, 38, 16934, 11, 198, 220, 220, 220, 45878, 6322, 38, 2898, 10613, 11, 198, 220, 220, 220, 5550, ...
2.1375
80
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Perform RTM on marmousi """ import os import numpy as np import h5py as h5 from scipy.ndimage.filters import gaussian_filter import sys import shutil from SeisCL import SeisCL names = ['fp32', 'fp16io', 'fp16com'] filedata = os.getcwd() + '/marmfp32' seis = SeisCL() seis.file = os.getcwd() + '/marmfp32' seis.read_csts(workdir="") seis.file = 'SeisCL' seis.file_datalist = filedata + '_din.mat' seis.file_din = filedata + '_din.mat' file = h5.File(filedata + '_model.mat', "r") models = {'vp': gaussian_filter(np.transpose(file['vp']), sigma=3), 'vs': np.transpose(file['vs']), 'rho': np.transpose(file['rho'])} file.close() """ _________________Set inversion parameters for SeisCL____________________ """ seis.csts['gradout'] = 1 # SeisCl has to output the gradient seis.csts['scalerms'] = 0 # We don't scale each trace by the rms of the data seis.csts['scalermsnorm'] = 0 # We don't scale each trave by the rms its rms seis.csts['scaleshot'] = 0 # We don't scale each shots seis.csts['back_prop_type'] = 1 seis.csts['restype'] = 1 # Migration cost function seis.csts['tmin'] = 0*(np.float(seis.csts['NT'])-2) * seis.csts['dt'] for ii, FP16 in enumerate([1, 2, 3]): """ _______________________Constants for inversion__________________________ """ filework = os.getcwd() + '/marmgrad_' + names[ii] seis.csts['FP16'] = FP16 """ _________________________Perform Migration______________________________ """ if not os.path.isfile(filework + '_gout.mat'): seis.set_forward(seis.src_pos_all[3, :], models, withgrad=True) seis.execute() shutil.copy2(seis.workdir + "/" + seis.file_gout, filework + '_gout.mat') sys.stdout.write('Gradient calculation completed \n') sys.stdout.flush()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 5990, 687, 11923, 44, 319, 1667, 76, 516, 72, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 299, 32...
2.401299
770
#!/usr/bin/python3 from typing import List from registry import the_registry from param_collector import the_collector NO_DEFAULT = Unique() NO_DEFAULT_TYPE = type(NO_DEFAULT) for x in Foobar.columns: print(x)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 19720, 1330, 7343, 198, 6738, 20478, 1330, 262, 62, 2301, 4592, 198, 6738, 5772, 62, 33327, 273, 1330, 262, 62, 33327, 273, 628, 628, 198, 198, 15285, 62, 7206, 38865, 796, 3...
2.8
80
""" File : argonneV14.py Language : Python 3.6 Created : 7/13/2018 Edited : 7/13/2018 San Digeo State University Department of Physics and Astronomy #https://journals.aps.org/prc/pdf/10.1103/PhysRevC.51.38 --argonneV18 This code implements Argonne V14 potential outlined in ... --CONSTANTS -- Hbar*c | 197.33 MeV fm pion-Mass | 138.03 MeV Wood-Saxon| R | 0.5 fm a | 0.2 fm Operator | p | Ip | Sp | Index | ----------------------------------------------------------- central | c | -4.801125 | 2061.5625 | 0 | tao dot tao | tao | 0.798925 | -477.3125 | 1 | sigma dot sigma| sigma | 1.189325 | -502.3125 | 2 | (sigma)(tao) | sigma-tao | 0.182875 | 97.0625 | 3 | Sij | t | -0.1575 | 108.75 | 4 | Sij(tao) | t-tao | -0.7525 | 297.25 | 5 | L dot S | b | 0.5625 | -719.75 | 6 | L dot S (tao) | b-tao | 0.0475 | -159.25 | 7 | L squared | q | 0.070625 | 8.625 | 8 | L^2(tao) | q-tao | -0.148125 | 5.625 | 9 | L^2(sigma | q-sigma | -0.040625 | 17.375 | 10 | L^2(sigma)(tao)| q-sigma-tao | -0.001875 | -33.625 | 11 | (L dot S)^2 | bb | -0.5425 | 391.0 | 12 | (LS)^2(tao) | bb-tao | 0.0025 | 145.0 | 13 | """ import numpy as np
[ 37811, 201, 198, 8979, 220, 220, 220, 220, 1058, 1822, 47476, 53, 1415, 13, 9078, 201, 198, 32065, 1058, 11361, 513, 13, 21, 201, 198, 41972, 220, 1058, 767, 14, 1485, 14, 7908, 201, 198, 45882, 220, 220, 1058, 767, 14, 1485, 14, ...
1.586916
1,070
# -*- coding: utf-8 -*- """ 1556. Thousand Separator Given an integer n, add a dot (".") as the thousands separator and return it in string format. Constraints: 0 <= n < 2^31 """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1314, 3980, 13, 39255, 8621, 283, 1352, 198, 198, 15056, 281, 18253, 299, 11, 751, 257, 16605, 5855, 19570, 355, 262, 4138, 2880, 1352, 290, 1441, 340, 287, ...
2.815385
65
''' Controller para fornecer dados da CEE ''' from flask_restful import Resource from service.qry_options_builder import QueryOptionsBuilder from model.thematic import Thematic def get_domain(self): ''' Carrega o modelo de domnio, se no o encontrar ''' if self.domain is None: self.domain = Thematic() return self.domain def set_domain(self): ''' Setter invoked from constructor ''' self.domain = Thematic()
[ 7061, 6, 22741, 31215, 329, 710, 2189, 9955, 418, 12379, 327, 6500, 705, 7061, 198, 6738, 42903, 62, 2118, 913, 1330, 20857, 198, 6738, 2139, 13, 80, 563, 62, 25811, 62, 38272, 1330, 43301, 29046, 32875, 198, 6738, 2746, 13, 1169, 138...
2.685714
175
# -*- coding: utf-8 -*- CHECKLIST_MAPPING = { 'checklist_retrieve': { 'resource': '/checklists/{id}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsid' ), 'methods': ['GET'], }, 'checklist_field_retrieve': { 'resource': '/checklists/{id}/{field}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidfield' ), 'methods': ['GET'], }, 'checklist_board_retrieve': { 'resource': '/checklists/{id}/board', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidboard' ), 'methods': ['GET'], }, 'checklist_card_retrieve': { 'resource': '/checklists/{id}/cards', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcards' ), 'methods': ['GET'], }, 'checklist_item_list': { 'resource': '/checklists/{id}/checkItems', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcardscheckitems' ), 'methods': ['GET'], }, 'checklist_item_retrieve': { 'resource': '/checklists/{id}/checkItems/{idCheckItem}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcardscheckitemscheckitemid' ), 'methods': ['GET'], }, 'checklist_update': { 'resource': '/checklists/{id}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsid-1' ), 'methods': ['PUT'], }, 'checklist_item_update': { 'resource': '/checklists/{id}/checkItems/{idCheckItem}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcheckitemsidcheckitem' ), 'methods': ['PUT'], }, 'checklist_name_update': { 'resource': '/checklists/{id}/name', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidname' ), 'methods': ['PUT'], }, 'checklist_create': { 'resource': '/checklists', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklists' ), 'methods': ['POST'], }, 'checklist_item_create': { 'resource': '/checklists/{id}/checkItems', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcheckitems' ), 'methods': ['POST'], }, 'checklist_delete': { 'resource': '/checklists/{id}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsid-2' ), 'methods': ['DELETE'], }, 'checklist_item_delete': { 'resource': '/checklists/{id}/checkItems/{idCheckItem}', 'docs': ( 'https://developers.trello.com/v1.0/reference' '#checklistsidcheckitemsid' ), 'methods': ['DELETE'], }, }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 50084, 45849, 62, 44, 24805, 2751, 796, 1391, 198, 220, 220, 220, 705, 9122, 4868, 62, 1186, 30227, 10354, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 705, 3109...
1.864657
1,692
import json import os acoes = ler_arquivo("acoes.json") opcao=chamarMenu() while opcao > 0 and opcao < 5: if opcao == 1: print(registrar(acoes, "acoes.json")) elif opcao == 2: exibir("acoes.json") elif opcao == 3: sair() opcao = chamarMenu()
[ 11748, 33918, 198, 11748, 28686, 628, 198, 198, 330, 3028, 796, 300, 263, 62, 283, 421, 23593, 7203, 330, 3028, 13, 17752, 4943, 198, 404, 66, 5488, 28, 354, 39236, 23381, 3419, 198, 4514, 1034, 66, 5488, 1875, 657, 290, 1034, 66, 5...
1.972222
144
# this version is adapted from http://wiki.ipython.org/Old_Embedding/GTK """ Backend to the console plugin. @author: Eitan Isaacson @organization: IBM Corporation @copyright: Copyright (c) 2007 IBM Corporation @license: BSD All rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} """ # this file is a modified version of source code from the Accerciser project # http://live.gnome.org/accerciser from gi.repository import Gtk from gi.repository import Gdk import re import sys import os from gi.repository import Pango from io import StringIO from functools import reduce try: import IPython except Exception as e: raise "Error importing IPython (%s)" % str(e) ansi_colors = {'0;30': 'Black', '0;31': 'Red', '0;32': 'Green', '0;33': 'Brown', '0;34': 'Blue', '0;35': 'Purple', '0;36': 'Cyan', '0;37': 'LightGray', '1;30': 'DarkGray', '1;31': 'DarkRed', '1;32': 'SeaGreen', '1;33': 'Yellow', '1;34': 'LightBlue', '1;35': 'MediumPurple', '1;36': 'LightCyan', '1;37': 'White'}
[ 2, 428, 2196, 318, 16573, 422, 2638, 1378, 15466, 13, 541, 7535, 13, 2398, 14, 19620, 62, 31567, 6048, 278, 14, 19555, 42, 198, 198, 37811, 198, 7282, 437, 284, 262, 8624, 13877, 13, 198, 220, 198, 31, 9800, 25, 412, 18642, 19068, ...
2.163328
649
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^get', views.index, name='index'), url(r'^details/(?P<id>\w)/$', views.details, name='details'), url(r'^add', views.add, name='add'), url(r'^delete', views.delete, name='delete'), url(r'^update', views.update, name='update'), # url(r'^signup', views.signup, name='signup'), # url(r'^login', views.login, name='login'), # url(r'^login/$', auth_views.login), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 3, 3256, 5009, 13, 9630, 11, 1438, 11639, 9630, 33809, 198, 2...
2.419811
212
days = int(input()) sladkar = int(input()) cake = int(input()) gofreta = int(input()) pancake = int(input()) cake_price = cake*45 gofreta_price = gofreta*5.8 pancake_price = pancake*3.2 day_price = (cake_price + gofreta_price + pancake_price)*sladkar total_price = days*day_price campaign = total_price - (total_price/8) print(campaign)
[ 12545, 796, 493, 7, 15414, 28955, 198, 6649, 324, 21070, 796, 493, 7, 15414, 28955, 198, 30560, 796, 493, 7, 15414, 28955, 198, 70, 1659, 1186, 64, 796, 493, 7, 15414, 28955, 198, 79, 1192, 539, 796, 493, 7, 15414, 28955, 198, 30560...
2.545455
132
###################################################################### ## DeepBiome ## - Loss and metrics (mse, cross-entropy) ## ## July 10. 2019 ## Youngwon (youngwon08@gmail.com) ## ## Reference ## - Keras (https://github.com/keras-team/keras) ###################################################################### import numpy as np import sklearn.metrics as skmetrics from keras.callbacks import Callback import tensorflow as tf import keras.backend as K from keras.losses import mean_squared_error, mean_absolute_error, binary_crossentropy, categorical_crossentropy, sparse_categorical_crossentropy from keras.metrics import binary_accuracy, categorical_accuracy, sparse_categorical_accuracy from sklearn.metrics import roc_auc_score, f1_score, precision_score, recall_score ############################################################################################################################### # tf loss functions # TODO # https://stackoverflow.com/questions/41032551/how-to-compute-receiving-operating-characteristic-roc-and-auc-in-keras # def auc(y_true, y_pred): # return NotImplementedError() ############################################################################################################################### # helper ############################################################################################################################### # if __name__ == "__main__": # test_metrics = {'Accuracy':binary_accuracy, 'Precision':precision, 'Recall':recall} # print('Test loss functions %s' % test_metrics.keys()) # y_true_set = np.array([[[0,0,0,0,0], # [0,0,0,0,0], # [0,1,1,0,0], # [1,1,1,0,0], # [0,1,0,0,0]]]) # y_pred_set = np.array([[[0,0,0,0,1], # [0,0,0,0,0], # [0,1,0.6,0,0], # [0,1,1,0,0], # [0,0.3,0,0,0]]]) # def test(acc, y_true_set, y_pred_set): # sess = tf.Session() # K.set_session(sess) # with sess.as_default(): # return acc.eval(feed_dict={y_true: y_true_set, y_pred: y_pred_set}) # # tf # y_true = tf.placeholder("float32", shape=(None,y_true_set.shape[1],y_true_set.shape[2])) # y_pred = tf.placeholder("float32", shape=(None,y_pred_set.shape[1],y_pred_set.shape[2])) # metric_list = [binary_accuracy(y_true, y_pred), # precision(y_true, y_pred), # recall(y_true, y_pred)] # # numpy # print('%15s %15s %15s' % tuple(test_metrics.keys())) # print('tf : {}'.format([test(acc, y_true_set, y_pred_set) for acc in metric_list])) # print('np : {}'.format(np.round(metric_test(y_true_set[0],y_pred_set[0]),8)))
[ 29113, 29113, 4242, 2235, 198, 2235, 10766, 23286, 462, 198, 2235, 532, 22014, 290, 20731, 357, 76, 325, 11, 3272, 12, 298, 28338, 8, 198, 2235, 198, 2235, 2901, 838, 13, 13130, 198, 2235, 6960, 26502, 357, 35465, 26502, 2919, 31, 148...
2.312754
1,231
import cv2 import numpy as np import matplotlib.pyplot as plt #from matplotlib import pyplot as plt from tkinter import filedialog from tkinter import * root = Tk() root.withdraw() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files",".jpg"))) img = cv2.imread(root.filename) root.destroy() # Convert to gray-scale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Blur the image to reduce noise img_blur = cv2.medianBlur(gray, 5) # Apply hough transform on the image8 $$$img.shape[0]/16, param1=100, param2=11, minRadius=62, maxRadius=67 # Draw detected circles; circles = cv2.HoughCircles(img_blur, cv2.HOUGH_GRADIENT, 1, img.shape[0]/16, param1=200, param2=25, minRadius=60, maxRadius=67) face_cascade = cv2.CascadeClassifier('C:/Users/andre/Desktop/NovenoSemestre/VisionArtificial/Python/haarcascade_frontalface_alt.xml') gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: center = (x + w//2, y + h//2) #circles = cv2.HoughCircles(img_blur, cv2.HOUGH_GRADIENT, 1, img.shape[0]/128, param1=100, param2=11, minRadius=50, maxRadius=100) circles = cv2.HoughCircles(img_blur, cv2.HOUGH_GRADIENT, 1, img.shape[0]/128, param1=100, param2=11, minRadius=(w//2-10), maxRadius=(w//2+10)) (h, w) = img_blur.shape[:2] #Calcular tamao de la imageb (pointRefX,pointRefY) = center puntoMinimo =100 if circles is not None: circles = np.uint16(np.around(circles)) for i in circles[0, :]: #Definir el circulo mas cercano de la xCercano =np.absolute(i[0]-pointRefX) yCercano =np.absolute(i[1]-pointRefY) puntoCercano = xCercano+yCercano if (puntoCercano < puntoMinimo): puntoMinimo = puntoCercano circuloCercano = i # Draw outer circle #frame = cv2.ellipse(img, center, (w//2, h//2), 0, 0, 360,(100, 7, 55), 2) cv2.ellipse(img, (circuloCercano[0], circuloCercano[1]),(circuloCercano[2],circuloCercano[2]+15),0,0,360,(0, 255, 0), 2) # Draw inner circle cv2.circle(img, (circuloCercano[0], circuloCercano[1]), circuloCercano[2], (0, 255, 0), 2) cv2.circle(img, (circuloCercano[0], circuloCercano[1]), 2, (0, 0, 255), 3) """ cv2.circle(img, (circuloCercano[0], circuloCercano[1]), circuloCercano[2], (0, 255, 0), 2) # Draw inner circle cv2.circle(img, (circuloCercano[0], circuloCercano[1]), 2, (0, 0, 255), 3) """ """ if circles is not None: circles = np.uint16(np.around(circles)) for i in circles[0, :]: #Definir el circulo mas cercano de la xCercano =np.absolute(i[0]-pointRefX) yCercano =np.absolute(i[1]-pointRefY) puntoCercano = xCercano+yCercano if (puntoCercano < puntoMinimo): puntoMinimo = puntoCercano circuloCercano = i # Draw outer circle cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2) # Draw inner circle cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3) """ cv2.imshow("Mascara",img) cv2.waitKey(0)
[ 11748, 269, 85, 17, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 2, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 201, 198, 6738, 256, 74, 3849, 1...
2.056995
1,544
# Binary Sentiment Analysis using Recurrent Neural Networks # Import libraries & dataset list import tensorflow as tf import tensorflow_datasets as dslist # Load Dataset print("\nLoading dataset...") # Download dataset and dataset info DATASET_CODE = 'imdb_reviews/subwords8k' # Using a TensorFlow binary sentiment classification dataset dataset, dsinfo = dslist.load(DATASET_CODE, with_info=True, as_supervised=True) # Separate into training and testing data. training = dataset['train'] testing = dataset['test'] # Declare encoder (maps each word in a string to its index in the dataset's vocabulary) encoder = dsinfo.features['text'].encoder print("Dataset loaded.") # Setup for training # Prepare data. Create batches of encoded strings and zero-pad them. BUFFER_SIZE = 10000 BATCH_SIZE = 64 # Max number of encoded strings in batch padded_shapes = ([None], ()) training = (training .shuffle(BUFFER_SIZE) .padded_batch(BATCH_SIZE, padded_shapes=padded_shapes)) testing = (testing .padded_batch(BATCH_SIZE, padded_shapes=padded_shapes)) # Setup Recurrent Neural Network (RNN) # Create RNN model using Keras. OUTPUT_SIZE = 64 rnn_model = tf.keras.Sequential([ # Keras Sequential model: processes sequence of encoded strings (indices), embeds each index into vector, then processes through embedding layer tf.keras.layers.Embedding(encoder.vocab_size, OUTPUT_SIZE), # Add embedding layer: stores each word as trainable vector tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), # Make input sequence iterate both directions through LTSM layer (helps learn long-range dependencies). # Add layers tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(1) ]) # Compile RNN model rnn_model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(1e-4), metrics=['accuracy']) # Train RNN NUM_ITERATIONS = 1 print("\nTraining neural network...") history = rnn_model.fit(training, epochs=NUM_ITERATIONS, validation_data=testing) print("Training complete.") # Test RNN. print("\nTesting on dataset...") loss, accuracy = rnn_model.evaluate(testing) # Return test loss and test accuracy print("Testing complete.") # Process and print results loss = round(loss, 3) accuracy = round(accuracy*100, 2) print("Test Loss: {}".format(loss)) print("Test Accuracy: {}%".format(accuracy)) # Prediction # Zero-pads a vector up to a target size. # Predicts sentiment. Output will be a decimal number. # Predictions with value over 0.5 are positive sentiments. # Predict sentiment of user-inputted review user_query = input("\nEnter a review to predict its sentiment, or enter nothing to exit the program:\n") while(user_query != ""): prediction = predict_sentiment(user_query) sentiment = interpret_prediction(prediction) print("\nSentiment: {} (Value: {})".format(sentiment, prediction)) user_query = input("\n\nEnter a review to predict its sentiment, or enter nothing to exit the program:\n")
[ 2, 45755, 11352, 3681, 14691, 1262, 3311, 6657, 47986, 27862, 201, 198, 201, 198, 2, 17267, 12782, 1222, 27039, 1351, 201, 198, 11748, 11192, 273, 11125, 355, 48700, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.638756
1,254
import selenium from selenium import webdriver import time import requests import os from PIL import Image import io import hashlib # All in same directory DRIVER_PATH = 'chromedriver.exe' if __name__ == '__main__': ''' chromedriver.execmd python google_image_scraping_script_for_arg.py python google_image_scraping_script_for_arg.py 30 python google_image_scraping_script_for_arg.py 50 ''' import sys import ast if len(sys.argv) == 3: query_name = sys.argv[1] number_of_picture = sys.argv[2] print("query_name:",query_name) #str print("number_of_picture:",number_of_picture) #str wd = webdriver.Chrome(executable_path=DRIVER_PATH) queries = [query_name] #change your set of queries here for query in queries: wd.get('https://google.com') search_box = wd.find_element_by_css_selector('input.gLFyf') search_box.send_keys(query) links = fetch_image_urls(query,int(number_of_picture),wd) # 200 denotes no. of images you want to download images_path = './' for i in links: persist_image(images_path,query,i) wd.quit() else: print("Error input format")
[ 11748, 384, 11925, 1505, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 11748, 640, 198, 11748, 7007, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 33245, 198, 11748, 12234, 8019, 198, 198, 2, 1439, 287, 976, 86...
2.215889
579
""" MIT License Copyright (c) 2020 Maxim Krivich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import re url_pattern = re.compile( r"^(?:http)s?://" # http:// or https:// # domain... r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)" r"+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|" r"localhost|" # localhost... r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" # ...or ip r"(?::\d+)?" # optional port r"(?:/?|[/?]\S+)$", re.IGNORECASE )
[ 37811, 198, 36393, 13789, 198, 198, 15269, 357, 66, 8, 12131, 38962, 509, 15104, 488, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 1659, 428, 3788, 290, 3917, 10314, 3696, 357...
2.864542
502
"""The geojson module provides data model classes for initialization and storing of GeoJSON objects. """ import typing import typing_extensions import pydantic import numpy as np import brahe.astro as astro import brahe.coordinates as coords import brahe.frames as frames geographic_point = pydantic.conlist(float, min_items=2, max_items=3)
[ 37811, 464, 4903, 13210, 1559, 8265, 3769, 1366, 2746, 6097, 329, 37588, 290, 23069, 198, 1659, 32960, 40386, 5563, 13, 198, 37811, 198, 198, 11748, 19720, 198, 11748, 19720, 62, 2302, 5736, 198, 11748, 279, 5173, 5109, 198, 11748, 299, ...
3.43
100
n = int(input()) lst = list(map(int, input().split())) sort1(lst)
[ 77, 796, 493, 7, 15414, 28955, 198, 75, 301, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 4008, 628, 198, 198, 30619, 16, 7, 75, 301, 8, 198 ]
2.225806
31
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ################################################################################## # File: c:\Projects\KENYA ONE PROJECT\CORE\engines\Gudmundsson_Constraint.py # # Project: c:\Projects\KENYA ONE PROJECT\CORE\engines # # Created Date: Thursday, January 9th 2020, 8:56:55 pm # # Author: Geoffrey Nyaga Kinyua ( <info@geoffreynyaga.com> ) # # ----- # # Last Modified: Thursday January 9th 2020 8:56:55 pm # # Modified By: Geoffrey Nyaga Kinyua ( <info@geoffreynyaga.com> ) # # ----- # # MIT License # # # # Copyright (c) 2020 KENYA ONE PROJECT # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of# # this software and associated documentation files (the "Software"), to deal in # # the Software without restriction, including without limitation the rights to # # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # # of the Software, and to permit persons to whom the Software is furnished to do # # so, subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included in all # # copies or substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # # SOFTWARE. # # ----- # # Copyright (c) 2020 KENYA ONE PROJECT # ################################################################################## import sys sys.path.append("../") from CORE.API.db_API import write_to_db, read_from_db # type: ignore from math import sqrt, pi import numpy as np # type: ignore import matplotlib.pyplot as plt # type: ignore grossWeight = read_from_db("finalMTOW") cruiseSpeed = read_from_db("cruiseSpeed") ROC = read_from_db("rateOfClimb") * 3.28 * 60 vLof = read_from_db("stallSpeed") * 1.1 AR = read_from_db("AR") cdMin = read_from_db("cdMin") wsfromsizing = read_from_db("WS") rhoSL = read_from_db("rhoSL") propEff = read_from_db("propEff") cruiseAltitude: int = 10000 # ft gForce: float = 2.0 V_ROC: float = 80.0 groundRun: int = 900 serviceCeiling: int = 18000 wsInitial: float = 22.6 # lb/f**2 g: float = 32.174 CDto: float = 0.04 CLto: float = 0.5 groundFriction: float = 0.04 e = oswaldEff(AR) k: float = 1 / (pi * AR * e) write_to_db("k", k) # dynamic pressure at altitude rhoCruise = rhoAlt(cruiseAltitude) # print ('air density at cruise altitude, rho = ' +str(rhoCruise)) qAltitude = 0.5 * rhoCruise * (1.688 * cruiseSpeed) ** 2 # print('dynamic pressure at altitude = ' +str(qAltitude)) # Gag Ferrar Model def gagFerrar(bhp): "takes in bhp and returns normalised bhp" normBhp = bhp / (1.132 * (rhoCruise / rhoSL) - 0.132) return normBhp WS = np.arange(10, 30) twTurn = qAltitude * ((cdMin / WS) + k * (gForce / qAltitude) ** 2 * (WS)) qROC = 0.5 * rhoSL * (V_ROC * 1.688) ** 2 Vv = ROC / 60 twROC = (Vv / (V_ROC * 1.688)) + (qROC * cdMin / WS) + (k * WS / qROC) qVlof = 0.5 * rhoSL * (vLof * 1.688 / sqrt(2)) ** 2 twVlof = ( ((vLof * 1.688) ** 2 / (2 * g * groundRun)) + (qVlof * CDto / WS) + (groundFriction * (1 - (qVlof * CLto / WS))) ) rhoCeiling = rhoAlt(serviceCeiling) # print(rhoCeiling) twCruise = qAltitude * cdMin * (1 / WS) + (k) twCeiling = (1.667 / (np.sqrt((2 * WS / rhoCeiling) * sqrt(k / 3 * cdMin)))) + ( (k * cdMin / 3) * 4 ) plt.figure(1) plt.subplot(121) plt.plot(WS, twTurn, label="Rate of Turn") plt.plot(WS, twROC, label="Rate of Climb") plt.plot(WS, twVlof, label="Vlof") plt.plot(WS, twCruise, label="Cruise") plt.plot(WS, twCeiling, label="Ceiling") plt.axvline(x=wsfromsizing) plt.title(" Graph 1 \n HP/Weight ratio") plt.legend() # ax = plt.gca() # ax.set_xticklabels([]) ###NORMAlization norm_twTurn = gagFerrar((grossWeight * twTurn * 1.688 * cruiseSpeed / (propEff * 550))) test = grossWeight * twTurn * 1.688 * cruiseSpeed / (propEff * 550) norm_twROC = gagFerrar((grossWeight * twROC * 1.688 * V_ROC / (propEff * 550))) norm_twVlof = gagFerrar((grossWeight * twVlof * 1.688 * vLof / (propEff * 550))) norm_twCruise = gagFerrar( (grossWeight * twCruise * 1.688 * cruiseSpeed / (propEff * 550)) ) norm_twCeiling = gagFerrar( (grossWeight * twCeiling * 1.688 * cruiseSpeed / (propEff * 550)) ) plt.subplot(122) plt.plot(WS, norm_twTurn, label="Rate of Turn") plt.plot(WS, norm_twROC, label="Rate of Climb") plt.plot(WS, norm_twVlof, label="Vlof") plt.plot(WS, norm_twCruise, label="Cruise") plt.plot(WS, norm_twCeiling, label="Ceiling") plt.title("Graph 2 \n Normalised BHP") plt.legend() plt.axvline(x=wsfromsizing) plt.tight_layout() if __name__ == "__main__": plt.show() # print(find_nearest(ws, plotWS)) plotWS = read_from_db("WS") myidx = find_nearest(WS, plotWS) finalBHP = point() write_to_db("finalBHP", finalBHP) print(finalBHP, "The Final normalised BHP") # now switch back to figure 1 and make some changes
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 201, 198, 29113, 29113, 14468, 2235, 201, 198, 2, 9220, 25, 269, 7479, 16775, 82, 59, 43959, 44947, 16329, 21965, 2368...
2.019608
3,162
from nose.tools import raises from blocks.bricks import Bias, Linear, Logistic from blocks.bricks.parallel import Merge from blocks.filter import VariableFilter from blocks.graph import ComputationGraph from blocks.roles import BIAS, FILTER, PARAMETER, OUTPUT from theano import tensor
[ 6738, 9686, 13, 31391, 1330, 12073, 198, 198, 6738, 7021, 13, 65, 23706, 1330, 347, 4448, 11, 44800, 11, 5972, 2569, 198, 6738, 7021, 13, 65, 23706, 13, 1845, 29363, 1330, 39407, 198, 6738, 7021, 13, 24455, 1330, 35748, 22417, 198, 67...
3.683544
79
from collections import Counter import pandas as pd import ipywidgets as widgets import techminer.core.dashboard as dash from techminer.core import ( CA, Dashboard, TF_matrix, TFIDF_matrix, add_counters_to_axis, clustering, corpus_filter, exclude_terms, ) # from techminer.core.params import EXCLUDE_COLS from techminer.plots import counters_to_node_sizes, xy_clusters_plot from techminer.core.filter_records import filter_records ############################################################################### ## ## MODEL ## ############################################################################### ############################################################################### ## ## DASHBOARD ## ############################################################################### COLUMNS = [ "Author_Keywords_CL", "Author_Keywords", "Index_Keywords_CL", "Index_Keywords", "Keywords_CL", ] ############################################################################### ## ## EXTERNAL INTERFACE ## ############################################################################### def comparative_analysis( limit_to=None, exclude=None, years_range=None, ): return App( limit_to=limit_to, exclude=exclude, years_range=years_range, ).run()
[ 6738, 17268, 1330, 15034, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 20966, 88, 28029, 11407, 355, 40803, 198, 198, 11748, 7261, 1084, 263, 13, 7295, 13, 42460, 3526, 355, 14470, 198, 6738, 7261, 1084, 263, 13, 7295, 1330, ...
3.321867
407
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import qtawesome import matplotlib.pyplot as plt import csv import numpy as np import datetime import os def main(): app = QApplication(sys.argv) gui = MainUI() gui.show() sys.exit(app.exec_()) def finddatepos(date): i = 0 while result[i][0] != date: i += 1 return i def calAtr(result, start_time, end_time, tr_list): # Calculate atr counter = 0 atr_list = [] for i in range(1, len(result)-1): if result[i][0] == start_time: counter = 1 if counter == 1: tr = max(float(result[i][2])-float(result[i][3]), float(result[i][2])-float(result[i-1][4]), float(result[i-1][4])-float(result[i][3])) tr_list.append([result[i][0], tr]) atr_list.append(tr) if result[i][0] == end_time: counter = 0 atr = int(np.floor(np.mean(atr_list))) atr_half = int(np.floor(0.5 * atr)) return [atr, atr_half] def calDon(result, time, atr_half, Dontime = 30): # Calculate Donchian tunnel for i in range(Dontime, len(result)-1): high_list = [] low_list = [] if result[i][0] == time: for j in range(i-Dontime, i): high_list.append(result[j][2]) low_list.append(result[j][3]) don_open = np.max(high_list) don_close = np.min(low_list) short_add_point = don_close - atr_half short_stop_loss = don_close + atr_half long_add_point = don_open + atr_half long_stop_loss = don_open - atr_half return [long_add_point, long_stop_loss, short_add_point, short_stop_loss] def on_bar(date, atrtime = 10): i = 0 while result[i][0] != date: i += 1 yesterday = result[i-1][0] startatrday = result[i-atrtime][0] open = result[i][1] atr = calAtr(result, startatrday, yesterday, tr_list)[0] atr_half = calAtr(result, startatrday, yesterday, tr_list)[1] Donlst = calDon(result, date, atr_half) long_add_point = Donlst[0] long_stop_loss = Donlst[1] short_add_point = Donlst[2] short_stop_loss = Donlst[3] date_pos = 0 while cash[date_pos][0] != date: date_pos += 1 position_long[date_pos][1] = position_long[date_pos - 1][1] position_short[date_pos][1] = position_short[date_pos - 1][1] cash[date_pos][1] = cash[date_pos - 1][1] if position_long[date_pos][1] == 0 and position_short[date_pos][1] == 0: if open > long_add_point - atr_half: # if cash[date_pos][1] >= (1 + backtest_commission_ratio) * open * unit(current_asset(yesterday),yesterday): position_long[date_pos][1] = unit(current_asset(yesterday),yesterday) print(date, '%.1f'%(unit(current_asset(yesterday),yesterday))) cash[date_pos][1] -= (1 + backtest_commission_ratio) * open * unit(current_asset(yesterday),yesterday) else: position_long[date_pos][1] = cash[date_pos][1] / (1 + backtest_commission_ratio) / open print(date, '%.1f'%(cash[date_pos][1] / (1 + backtest_commission_ratio) / open)) cash[date_pos][1] = 0 if open < short_add_point + atr_half: # position_short[date_pos][1] = unit(current_asset(yesterday),yesterday) print(date, '%.1f'%(unit(current_asset(yesterday),yesterday))) cash[date_pos][1] += (1 - backtest_commission_ratio) * open * unit(current_asset(yesterday),yesterday) if position_long[date_pos][1] != 0: if open > long_add_point: # 1/2atr if cash[date_pos][1] >= (1 + backtest_commission_ratio) * open * unit(current_asset(yesterday), yesterday): position_long[date_pos][1] += unit(current_asset(yesterday),yesterday) print(date, '%.1f'%(unit(current_asset(yesterday),yesterday))) cash[date_pos][1] -= (1 + backtest_commission_ratio) * open * unit(current_asset(yesterday), yesterday) else: position_long[date_pos][1] += cash[date_pos][1] / (1 + backtest_commission_ratio) / open print(date, '%.1f' % (cash[date_pos][1] / (1 + backtest_commission_ratio) / open)) cash[date_pos][1] = 0 if open < long_stop_loss: # if position_long[date_pos][1] - unit(current_asset(yesterday),yesterday) >= 0: print(date, '%.1f'%(unit(current_asset(yesterday),yesterday))) cash[date_pos][1] += (1 - backtest_commission_ratio) * open * unit(current_asset(yesterday), yesterday) else: print(date, '%.1f' % (position_long[date_pos][1])) cash[date_pos][1] += (1 - backtest_commission_ratio) * position_long[date_pos][1] * open position_long[date_pos][1] = max(position_long[date_pos][1] - unit(current_asset(yesterday),yesterday), 0) '''print(date, '%.1f'%(position_long[date_pos][1])) cash[date_pos][1] += (1 - backtest_commission_ratio) * open * position_long[date_pos][1] position_long[date_pos][1] = 0''' if position_short[date_pos][1] != 0: if open < short_add_point: # 1/2atr position_short[date_pos][1] += unit(current_asset(yesterday),yesterday) print(date, '%.1f'%(unit(current_asset(yesterday),yesterday))) cash[date_pos][1] += (1 - backtest_commission_ratio) * open * unit(current_asset(yesterday), yesterday) if open > short_stop_loss: # m = min(position_short[date_pos][1] * open, open * unit(current_asset(yesterday),yesterday), cash[date_pos][1] / (1 + backtest_commission_ratio)) print(date, '%.1f'%(m / open)) cash[date_pos][1] -= (1 + backtest_commission_ratio) * m position_short[date_pos][1] = position_short[date_pos][1] - m / open '''m = position_short[date_pos][1] * open print(date, '%.1f'%(m / open)) cash[date_pos][1] -= (1 + backtest_commission_ratio) * m position_short[date_pos][1] = position_short[date_pos][1] - m / open''' if __name__ == '__main__': csvFile = open("data.csv", "r") reader = csv.reader(csvFile) result = [] for item in reader: # Ignore first line if reader.line_num == 1: continue result.append( [item[0], float(item[1]), float(item[2]), float(item[3]), float(item[4])]) # date, open, high, low, close csvFile.close() initial_cash = 0 backtest_commission_ratio = 0.0001 start_time = '2021-03-01' end_time = '2021-04-27' tr_list = [] cash = [] position_short = [] position_long = [] atrtime = 20 Dontime = 30 unit_rate = 0.01 winningRate = 0 date = 0 time = 0 baseline = 0 annualized_rate = 0 l_time = [] l_asset = [] l_index = [] xs=[] l_initial = [] main()
[ 11748, 25064, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1635, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1635, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1635, 201, ...
1.981275
3,685
from datetime import datetime from django.db import connection from posthog.models import Person from posthog.test.base import BaseTest # How we expect this function to behave: # | call | value exists | call TS is ___ existing TS | previous fn | write/override # 1| set | no | N/A | N/A | yes # 2| set_once | no | N/A | N/A | yes # 3| set | yes | before | set | no # 4| set | yes | before | set_once | yes # 5| set | yes | after | set | yes # 6| set | yes | after | set_once | yes # 7| set_once | yes | before | set | no # 8| set_once | yes | before | set_once | yes # 9| set_once | yes | after | set | no # 10| set_once | yes | after | set_once | no # 11| set | yes | equal | set | no # 12| set_once | yes | equal | set | no # 13| set | yes | equal | set_once | yes # 14| set_once | yes | equal | set_once | no FUTURE_TIMESTAMP = datetime(2050, 1, 1, 1, 1, 1).isoformat() PAST_TIMESTAMP = datetime(2000, 1, 1, 1, 1, 1).isoformat() # Refers to migration 0176_update_person_props_function # This is a Postgres function we use in the plugin server
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4637, 198, 198, 6738, 1281, 31897, 13, 27530, 1330, 7755, 198, 6738, 1281, 31897, 13, 9288, 13, 8692, 1330, 7308, 14402, 198, 198, 2, 1374, 356, 1607, 4...
1.718982
943
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup(name='aif360', version='0.1.0', description='IBM AI Fairness 360', author='aif360 developers', author_email='aif360@us.ibm.com', url='https://github.com/IBM/AIF360', long_description=long_description, long_description_content_type='text/markdown', license='Apache License 2.0', packages=find_packages(), # python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <3.7', install_requires=[ 'numpy', 'scipy', 'pandas==0.23.3', 'scikit-learn', 'numba', ], include_package_data=True, zip_safe=False)
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 40406, ...
2.053908
371
radiobutton_style = ''' QRadioButton:disabled { background: transparent; } QRadioButton::indicator { background: palette(dark); width: 8px; height: 8px; border: 3px solid palette(dark); border-radius: 7px; } QRadioButton::indicator:checked { background: palette(highlight); } QRadioButton::indicator:checked:disabled { background: palette(midlight); } '''
[ 6335, 72, 672, 21115, 62, 7635, 796, 705, 7061, 198, 48, 26093, 21864, 25, 47730, 1391, 198, 220, 220, 220, 4469, 25, 13245, 26, 198, 92, 198, 198, 48, 26093, 21864, 3712, 521, 26407, 1391, 198, 220, 220, 220, 4469, 25, 27043, 7, ...
2.746479
142
from __future__ import annotations import lzma, pickle from typing import TYPE_CHECKING from numpy import e from tcod.console import Console from tcod.map import compute_fov import exceptions, render_functions from message_log import MessageLog if TYPE_CHECKING: from entity import Actor from game_map import GameMap, GameWorld
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 11748, 300, 89, 2611, 11, 2298, 293, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 6738, 299, 32152, 1330, 304, 198, 198, 6738, 256, 19815, 13, 41947, 1330, 24371, 198, 6738, 256, 19815,...
3.541667
96
# # PySNMP MIB module ERI-DNX-STS1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ERI-DNX-STS1-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:51:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection") DecisionType, LinkCmdStatus, PortStatus, LinkPortAddress, FunctionSwitch, devices, trapSequence = mibBuilder.importSymbols("ERI-DNX-SMC-MIB", "DecisionType", "LinkCmdStatus", "PortStatus", "LinkPortAddress", "FunctionSwitch", "devices", "trapSequence") eriMibs, = mibBuilder.importSymbols("ERI-ROOT-SMI", "eriMibs") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Integer32, Gauge32, IpAddress, Counter64, ObjectIdentity, iso, Unsigned32, MibIdentifier, Counter32, Bits, TimeTicks, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Integer32", "Gauge32", "IpAddress", "Counter64", "ObjectIdentity", "iso", "Unsigned32", "MibIdentifier", "Counter32", "Bits", "TimeTicks", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") eriDNXSts1MIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 644, 3, 4)) if mibBuilder.loadTexts: eriDNXSts1MIB.setLastUpdated('200204080000Z') if mibBuilder.loadTexts: eriDNXSts1MIB.setOrganization('Eastern Research, Inc.') dnxSTS1 = MibIdentifier((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3)) sts1Config = MibIdentifier((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1)) sts1Diag = MibIdentifier((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2)) sts1MapperConfigTable = MibTable((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1), ) if mibBuilder.loadTexts: sts1MapperConfigTable.setStatus('current') sts1MapperConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1), ).setIndexNames((0, "ERI-DNX-STS1-MIB", "sts1MapperAddr")) if mibBuilder.loadTexts: sts1MapperConfigEntry.setStatus('current') sts1MapperAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 1), LinkPortAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperAddr.setStatus('current') sts1MapperResource = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperResource.setStatus('current') sts1VtGroup1 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 3), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup1.setStatus('current') sts1VtGroup2 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 4), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup2.setStatus('current') sts1VtGroup3 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 5), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup3.setStatus('current') sts1VtGroup4 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 6), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup4.setStatus('current') sts1VtGroup5 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 7), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup5.setStatus('current') sts1VtGroup6 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 8), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup6.setStatus('current') sts1VtGroup7 = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 9), VtGroupType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtGroup7.setStatus('current') sts1VtMapping = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("standardVT", 0), ("sequencialFrm", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1VtMapping.setStatus('current') sts1Timing = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("internal", 0), ("ec1-Line", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1Timing.setStatus('current') sts1ShortCable = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 12), FunctionSwitch()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1ShortCable.setStatus('current') sts1MaprCmdStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 1, 1, 13), LinkCmdStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1MaprCmdStatus.setStatus('current') sts1T1E1LinkConfigTable = MibTable((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2), ) if mibBuilder.loadTexts: sts1T1E1LinkConfigTable.setStatus('current') sts1T1E1LinkConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1), ).setIndexNames((0, "ERI-DNX-STS1-MIB", "sts1T1E1CfgLinkAddr")) if mibBuilder.loadTexts: sts1T1E1LinkConfigEntry.setStatus('current') sts1T1E1CfgLinkAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 1), LinkPortAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1T1E1CfgLinkAddr.setStatus('current') sts1T1E1CfgResource = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1T1E1CfgResource.setStatus('current') sts1T1E1CfgLinkName = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1CfgLinkName.setStatus('current') sts1T1E1Status = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 4), PortStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1Status.setStatus('current') sts1T1E1Clear = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("framed", 1), ("unframed", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1Clear.setStatus('current') sts1T1E1Framing = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(5, 6, 7))).clone(namedValues=NamedValues(("t1Esf", 5), ("t1D4", 6), ("t1Unframed", 7)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1Framing.setStatus('current') sts1T1E1NetLoop = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 7), FunctionSwitch()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1NetLoop.setStatus('current') sts1T1E1YelAlrm = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 8), DecisionType()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1YelAlrm.setStatus('current') sts1T1E1RecoverTime = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(3, 10, 15))).clone(namedValues=NamedValues(("timeout-3-secs", 3), ("timeout-10-secs", 10), ("timeout-15-secs", 15)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1RecoverTime.setStatus('current') sts1T1E1EsfFormat = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("att-54016", 0), ("ansi-t1-403", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1EsfFormat.setStatus('current') sts1T1E1IdleCode = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("busy", 0), ("idle", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1IdleCode.setStatus('current') sts1T1E1CfgCmdStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 12), LinkCmdStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1T1E1CfgCmdStatus.setStatus('current') sts1T1E1Gr303Facility = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 1, 2, 1, 13), DecisionType()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1T1E1Gr303Facility.setStatus('obsolete') sts1MapperStatusTable = MibTable((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1), ) if mibBuilder.loadTexts: sts1MapperStatusTable.setStatus('current') sts1MapperStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1), ).setIndexNames((0, "ERI-DNX-STS1-MIB", "sts1MapperStatusAddr")) if mibBuilder.loadTexts: sts1MapperStatusEntry.setStatus('current') sts1MapperStatusAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 1), LinkPortAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusAddr.setStatus('current') sts1MapperStatusResource = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusResource.setStatus('current') sts1MapperStatusState = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 32, 256, 512, 1024, 8192, 131072, 2147483647))).clone(namedValues=NamedValues(("ok", 0), ("lof", 32), ("lop", 256), ("oof", 512), ("ais", 1024), ("los", 8192), ("lomf", 131072), ("errors", 2147483647)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusState.setStatus('current') sts1MapperStatusLOSErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusLOSErrs.setStatus('current') sts1MapperStatusOOFErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusOOFErrs.setStatus('current') sts1MapperStatusLOFErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusLOFErrs.setStatus('current') sts1MapperStatusLOPtrErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusLOPtrErrs.setStatus('current') sts1MapperStatusAISErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusAISErrs.setStatus('current') sts1MapperStatusMultiFErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusMultiFErrs.setStatus('current') sts1MapperStatusRxTraceErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusRxTraceErrs.setStatus('current') sts1MapperStatusTotErrSecs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1MapperStatusTotErrSecs.setStatus('current') sts1MapperStatusCmdStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 14, 101, 114, 200, 206, 500, 501, 502))).clone(namedValues=NamedValues(("ready-for-command", 0), ("update", 1), ("clearErrors", 14), ("update-successful", 101), ("clear-successful", 114), ("err-general-test-error", 200), ("err-field-cannot-be-set", 206), ("err-snmp-parse-failed", 500), ("err-invalid-snmp-type", 501), ("err-invalid-snmp-var-size", 502)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1MapperStatusCmdStatus.setStatus('current') sts1LIUTable = MibTable((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2), ) if mibBuilder.loadTexts: sts1LIUTable.setStatus('current') sts1LIUEntry = MibTableRow((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1), ).setIndexNames((0, "ERI-DNX-STS1-MIB", "sts1LIUAddr")) if mibBuilder.loadTexts: sts1LIUEntry.setStatus('current') sts1LIUAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 1), LinkPortAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUAddr.setStatus('current') sts1LIUResource = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUResource.setStatus('current') sts1LIUBertState = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(45, 44))).clone(namedValues=NamedValues(("off", 45), ("liu-bert", 44)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1LIUBertState.setStatus('current') sts1LIUBertErrSecs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUBertErrSecs.setStatus('current') sts1LIUBertDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUBertDuration.setStatus('current') sts1LIULoopType = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 39))).clone(namedValues=NamedValues(("off", 0), ("mapper", 1), ("liu", 39)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1LIULoopType.setStatus('current') sts1LIUDigitalErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUDigitalErrs.setStatus('current') sts1LIUAnalogErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUAnalogErrs.setStatus('current') sts1LIUExcessZeros = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUExcessZeros.setStatus('current') sts1LIUCodingViolationErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUCodingViolationErrs.setStatus('current') sts1LIUPRBSErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sts1LIUPRBSErrs.setStatus('current') sts1LIUCmdStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 2, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 14, 101, 114, 200, 202, 203, 205, 206, 500, 501, 502))).clone(namedValues=NamedValues(("ready-for-command", 0), ("update", 1), ("clearErrors", 14), ("update-successful", 101), ("clear-successful", 114), ("err-general-test-error", 200), ("err-invalid-loop-type", 202), ("err-invalid-bert-type", 203), ("err-test-in-progress", 205), ("err-field-cannot-be-set", 206), ("err-snmp-parse-failed", 500), ("err-invalid-snmp-type", 501), ("err-invalid-snmp-var-size", 502)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sts1LIUCmdStatus.setStatus('current') dnxSTS1Enterprise = ObjectIdentity((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 0)) if mibBuilder.loadTexts: dnxSTS1Enterprise.setStatus('current') sts1MapperConfigTrap = NotificationType((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 0, 1)).setObjects(("ERI-DNX-SMC-MIB", "trapSequence"), ("ERI-DNX-STS1-MIB", "sts1MapperAddr"), ("ERI-DNX-STS1-MIB", "sts1MaprCmdStatus")) if mibBuilder.loadTexts: sts1MapperConfigTrap.setStatus('current') sts1T1E1ConfigTrap = NotificationType((1, 3, 6, 1, 4, 1, 644, 2, 4, 2, 3, 0, 2)).setObjects(("ERI-DNX-SMC-MIB", "trapSequence"), ("ERI-DNX-STS1-MIB", "sts1T1E1CfgLinkAddr"), ("ERI-DNX-STS1-MIB", "sts1T1E1CfgCmdStatus")) if mibBuilder.loadTexts: sts1T1E1ConfigTrap.setStatus('current') mibBuilder.exportSymbols("ERI-DNX-STS1-MIB", sts1MapperStatusCmdStatus=sts1MapperStatusCmdStatus, sts1MapperStatusTotErrSecs=sts1MapperStatusTotErrSecs, sts1MapperStatusEntry=sts1MapperStatusEntry, PYSNMP_MODULE_ID=eriDNXSts1MIB, sts1T1E1YelAlrm=sts1T1E1YelAlrm, sts1Config=sts1Config, sts1VtGroup5=sts1VtGroup5, sts1MapperStatusState=sts1MapperStatusState, sts1LIUDigitalErrs=sts1LIUDigitalErrs, sts1Diag=sts1Diag, sts1LIUBertDuration=sts1LIUBertDuration, sts1T1E1NetLoop=sts1T1E1NetLoop, sts1MapperResource=sts1MapperResource, sts1ShortCable=sts1ShortCable, sts1MapperStatusAISErrs=sts1MapperStatusAISErrs, sts1LIUCodingViolationErrs=sts1LIUCodingViolationErrs, sts1VtGroup1=sts1VtGroup1, sts1MapperAddr=sts1MapperAddr, sts1LIUResource=sts1LIUResource, sts1LIUBertState=sts1LIUBertState, dnxSTS1=dnxSTS1, sts1T1E1CfgLinkName=sts1T1E1CfgLinkName, sts1LIULoopType=sts1LIULoopType, sts1T1E1ConfigTrap=sts1T1E1ConfigTrap, sts1T1E1CfgResource=sts1T1E1CfgResource, sts1LIUAnalogErrs=sts1LIUAnalogErrs, sts1MapperStatusLOPtrErrs=sts1MapperStatusLOPtrErrs, sts1LIUAddr=sts1LIUAddr, sts1VtGroup6=sts1VtGroup6, sts1T1E1Status=sts1T1E1Status, sts1VtMapping=sts1VtMapping, VtGroupType=VtGroupType, sts1VtGroup3=sts1VtGroup3, sts1T1E1IdleCode=sts1T1E1IdleCode, sts1LIUBertErrSecs=sts1LIUBertErrSecs, sts1VtGroup4=sts1VtGroup4, sts1MapperConfigTable=sts1MapperConfigTable, sts1MapperStatusAddr=sts1MapperStatusAddr, sts1T1E1Gr303Facility=sts1T1E1Gr303Facility, sts1Timing=sts1Timing, sts1MapperStatusOOFErrs=sts1MapperStatusOOFErrs, sts1MapperStatusResource=sts1MapperStatusResource, sts1VtGroup2=sts1VtGroup2, eriDNXSts1MIB=eriDNXSts1MIB, sts1T1E1Framing=sts1T1E1Framing, sts1MapperStatusLOFErrs=sts1MapperStatusLOFErrs, sts1LIUTable=sts1LIUTable, sts1T1E1LinkConfigTable=sts1T1E1LinkConfigTable, sts1MapperStatusMultiFErrs=sts1MapperStatusMultiFErrs, sts1LIUExcessZeros=sts1LIUExcessZeros, sts1VtGroup7=sts1VtGroup7, sts1MapperStatusLOSErrs=sts1MapperStatusLOSErrs, sts1T1E1CfgLinkAddr=sts1T1E1CfgLinkAddr, sts1T1E1RecoverTime=sts1T1E1RecoverTime, dnxSTS1Enterprise=dnxSTS1Enterprise, sts1MaprCmdStatus=sts1MaprCmdStatus, sts1T1E1EsfFormat=sts1T1E1EsfFormat, sts1MapperStatusRxTraceErrs=sts1MapperStatusRxTraceErrs, sts1MapperConfigEntry=sts1MapperConfigEntry, sts1T1E1LinkConfigEntry=sts1T1E1LinkConfigEntry, sts1LIUCmdStatus=sts1LIUCmdStatus, sts1MapperConfigTrap=sts1MapperConfigTrap, sts1LIUEntry=sts1LIUEntry, sts1LIUPRBSErrs=sts1LIUPRBSErrs, sts1T1E1CfgCmdStatus=sts1T1E1CfgCmdStatus, sts1MapperStatusTable=sts1MapperStatusTable, sts1T1E1Clear=sts1T1E1Clear)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 412, 7112, 12, 35504, 55, 12, 2257, 50, 16, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378, 14, 14...
2.393897
7,898
# flake8: noqa # pylint: disable=cyclic-import from .base import db, Model, metadata from .link import Link from .user import User from .event import Event, Repeat from .bookmark import Bookmark from .tag import Tag from .doc import Doc, DocTag from .recipe import Recipe, RecipeImage from .pagination import paginate, Pagination from .todo import TodoItem
[ 2, 781, 539, 23, 25, 645, 20402, 198, 2, 279, 2645, 600, 25, 15560, 28, 15539, 291, 12, 11748, 198, 6738, 764, 8692, 1330, 20613, 11, 9104, 11, 20150, 198, 6738, 764, 8726, 1330, 7502, 198, 6738, 764, 7220, 1330, 11787, 198, 6738, ...
3.432692
104
import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense from activations.activations import tan_sigmoid, exponential, ReLU
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 27530, 1330, 9104, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 360, 1072, 198, 6738, 1753, 602, 13, 15791, 602, 1330, 25706, 6...
3.45098
51
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import re from pathlib import Path from parakeet.frontend.zh_frontend import Frontend as zhFrontend from parakeet.utils.error_rate import word_errors SILENCE_TOKENS = {"sp", "sil", "sp1", "spl"} if __name__ == "__main__": main()
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845...
3.436508
252
# VOC import os import random import shutil trainval_percent = 0.1 train_percent = 0.9 imgfilepath = '../myData/JPEGImages' # total_img = os.listdir(imgfilepath) sample_num = len(total_img) trains = random.sample(total_img,int(sample_num*train_percent)) for file in total_img: if file in trains: shutil.copy(os.path.join(imgfilepath,file),"./myData/coco/images/train/"+file) else: shutil.copy(os.path.join(imgfilepath,file),"./myData/coco/images/val/"+file) print(file)
[ 198, 2, 569, 4503, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4423, 346, 198, 198, 27432, 2100, 62, 25067, 796, 657, 13, 16, 198, 27432, 62, 25067, 796, 657, 13, 24, 198, 9600, 7753, 6978, 796, 705, 40720, 1820, 6601, 14, 1288...
2.406542
214
"""Example SciUnit model classes.""" import random from sciunit.models import Model from sciunit.capabilities import ProducesNumber from sciunit.utils import class_intern, method_cache from sciunit.utils import method_memoize # Decorator for caching of capability method results. from typing import Union ################################################################ # Here are several examples of caching and sharing can be used # to reduce the computational load of testing. ################################################################
[ 37811, 16281, 10286, 26453, 2746, 6097, 526, 15931, 198, 198, 11748, 4738, 198, 6738, 20681, 20850, 13, 27530, 1330, 9104, 198, 6738, 20681, 20850, 13, 11128, 5738, 1330, 21522, 728, 15057, 198, 6738, 20681, 20850, 13, 26791, 1330, 1398, ...
5.138889
108
from sentence_transformers import SentenceTransformer from semantic.config import CONFIG model = SentenceTransformer(CONFIG["model_name"])
[ 6738, 6827, 62, 35636, 364, 1330, 11352, 594, 8291, 16354, 198, 6738, 37865, 13, 11250, 1330, 25626, 198, 198, 19849, 796, 11352, 594, 8291, 16354, 7, 10943, 16254, 14692, 19849, 62, 3672, 8973, 8, 198 ]
4
35
from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Flatten, Dropout, Input from tensorflow.keras.layers import MaxPooling1D, Conv1D from tensorflow.keras.layers import LSTM, Bidirectional from tensorflow.keras.layers import BatchNormalization, GlobalAveragePooling1D, Permute, concatenate, Activation, add import numpy as np import math
[ 6738, 11192, 273, 11125, 13, 6122, 292, 13, 27530, 1330, 9104, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 360, 1072, 11, 1610, 41769, 11, 14258, 448, 11, 23412, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, ...
3.099174
121
# Copyright 2022 The AI Flow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import os import unittest import sqlalchemy from ai_flow.store.db.base_model import base from ai_flow.util import sqlalchemy_db SQLITE_FILE = 'ai_flow.db' TEST_URL = 'sqlite:///ai_flow.db' if __name__ == '__main__': unittest.main()
[ 2, 15069, 33160, 383, 9552, 27782, 46665, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 9...
3.275591
254
#!/usr/bin/env python3 from isEven import isEven if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 318, 6104, 1330, 318, 6104, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 1388, 3419, 198 ]
2.558824
34
#! /usr/bin/python # encoding=utf-8 import os import datetime,time from selenium import webdriver import config import threading import numpy as np #Create Threading Pool
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 198, 2, 21004, 28, 40477, 12, 23, 198, 198, 11748, 28686, 198, 11748, 4818, 8079, 11, 2435, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 11748, 4566, 198, 11748, 4704, 278, 220, 198, 1...
3.125
56
import re from abc import ABC, abstractmethod from sherlockpipe.star.EpicStarCatalog import EpicStarCatalog from sherlockpipe.star.KicStarCatalog import KicStarCatalog from sherlockpipe.star.TicStarCatalog import TicStarCatalog
[ 11748, 302, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 15059, 5354, 34360, 13, 7364, 13, 13807, 291, 8248, 49015, 1330, 16781, 8248, 49015, 198, 6738, 15059, 5354, 34360, 13, 7364, 13, 42, 291, 8248, 49015, 1330, 509, ...
3.677419
62
#!/bin/env python3 # coding: utf8 ''' My implementation of DFT Assignment 5.1: Hartree energy for H-atom GS Taught by Ren Wirnata in 2019/2020. Links: https://tu-freiberg.de/fakultaet2/thph/lehre/density-functional-theory https://github.com/PandaScience/teaching-resources This script uses the last assignment's code to determine a solution of the radial Schrdinger equation for the hydrogen ground state (n=1, l=0). After normalizing, the Hartree potential energy w(r) = r*vh(r) is computed in a second "integration" step and numerically integrated to the Hartree energy (~0.3125 Ha). For hydrogen, the homogeneous solution w_hom(r) = beta * r is not required in order to match the boundary condition (--> beta = 0). Note, that the integration limits (tmin, tmax) and step size (h) need to be identical for solve_rseq() and solve_poisson() or you must use interpolated versions of the functions w(r) and u(r) when computing the Hartree energy. Further, tmin for solve_poisson() should not be smaller than tmin for solve_rseq(), because extrapolating u(r) beyond the computed data points may result in errors. ''' import time import numpy as np import matplotlib.pyplot as plt from scipy.integrate import solve_ivp, trapz from scipy.interpolate import interp1d nsteps = 10000 rmin = 0.000001 rmax = 20 def secant(f, x1=-12345, x2=6789, maxiter=10000, tol=1e-10): """secant method; x1 and x2 are crucial for finding the desired root""" for itr in range(maxiter): xnew = x2 - (x2 - x1) / (f(x2) - f(x1)) * f(x2) if abs(xnew - x2) < tol: break x1 = x2 x2 = xnew else: print("Calculation exceeded maximum number of iterations!") exit() return xnew, itr def trapezoidal(f, a, b, n=10000): """trapez method for numerical integration""" s = 0.0 h = (b - a) / n for i in range(0, n): s += f(a + i * h) return h * (s + 0.5 * (f(a) + f(b))) def rad_seq(t, y, energy): """returns radial SEQ as system of two 1st order differential equations""" # input: y = [y1, y2]; return y = [y1', y2'] # y1' = y2; y2' = (...)*y1 return [y[1], (- 2 * (1 / t + energy)) * y[0]] def initValues(r): """getting initial values for numeric intergration from correct solution""" u = 2 * r * np.exp(-r) uPrime = (1 - r) * 2 * np.exp(-r) return [u, uPrime] def solve_rad_seq(energy): """wrapper for ODE integration; energy and l as parameter, integration from rmax to rmin (inwards)""" sol = solve_ivp( lambda t, y: rad_seq(t, y, energy), t_span=[rmax, rmin], t_eval=np.linspace(rmax, rmin, nsteps), y0=initValues(rmax)) u = sol.y[0] r = sol.t return u[::-1], r[::-1] def u0(energy): """get first value of integrated Schrdinger equation; since the array is reversed, u[0] corresponds to the u-value at r = 0 (y-interscetion); different energies are passed in by secant method""" u, r = solve_rad_seq(energy) return u[0] def normalize(energy): """integrating with calculated energy eigenvalue and normalization""" u, r = solve_rad_seq(energy) norm = trapz(u * u, r) u_norm = u / np.sqrt(norm) return u_norm, r, norm def poisson(t, y, u): """returns poisson equation w''(t) = - u(t) / t as system of two 1st order differential equations""" # input: y = [y1, y2]; return y = [y1', y2'] # y1' = y2; y2' = - u(t) / t return [y[1], -u(t) ** 2 / t] def solve_poisson(f_int): """solve radial poisson equation; input is u(r) from interpolation""" sol = solve_ivp( lambda t, y: poisson(t, y, f_int), t_span=[rmin, rmax], t_eval=np.linspace(rmin, rmax, nsteps), y0=[0, 1]) return sol.y[0], sol.t if __name__ == "__main__": main()
[ 2, 48443, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 25, 3384, 69, 23, 198, 198, 7061, 6, 198, 3666, 7822, 286, 360, 9792, 50144, 642, 13, 16, 25, 11345, 631, 2568, 329, 367, 12, 37696, 26681, 198, 198, 51, 3413, 416, 7152, 370, ...
2.618879
1,409
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from sklearn import datasets, linear_model from difflib import SequenceMatcher import seaborn as sns from statistics import mean from ast import literal_eval from scipy import stats from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from pygam import LinearGAM, s, l, f from matplotlib import lines import six def extract_boar_teloFISH_as_list(path): """ FUNCTION FOR PULLING KELLY'S TELOFISH DATA FOR 40 BOARS into a LIST.. TO BE MADE INTO A DATAFRAME & JOINED W/ MAIN DATAFRAME if possible These excel files take forever to load.. the objective here is to synthesize all the excel files for telomere FISH data into one dataframe, then save that dataframe to csv file to be retrieved later loading one whole csv file containing all the data will be much, much faster than loading the parts of the whole Along the way, we'll normalize the teloFISH data using controls internal to each excel file """ boar_teloFISH_list = [] for file in os.scandir(path): if 'Hyb' in file.name: print(f'Handling {file.name}...') full_name = path + file.name # making a dict of excel sheets, where KEY:VALUE pairs are SAMPLE ID:TELO DATA telo_excel_dict = pd.read_excel(full_name, sheet_name=None, skiprows=4, usecols=[3], nrows=5000) if 'Telomere Template' in telo_excel_dict.keys(): del telo_excel_dict['Telomere Template'] excel_file_list = [] for sample_id, telos in telo_excel_dict.items(): telos_cleaned = clean_individ_telos(telos) if sample_id != 'Control': excel_file_list.append([sample_id, telos_cleaned.values, np.mean(telos_cleaned)]) elif sample_id == 'Control': control_value = np.mean(telos_cleaned) #normalize teloFISH values by control value for sample in excel_file_list: sample_data = sample #normalize individual telos sample_data[1] = np.divide(sample_data[1], control_value) #normalize telo means sample_data[2] = np.divide(sample_data[2], control_value) boar_teloFISH_list.append(sample_data) print('Finished collecting boar teloFISH data') return boar_teloFISH_list # elif hue == 'Sex' and col == 'Sex': # fig.suptitle(f'{x} vs. {y}\nper Sex in Fukushima Wild Boar', fontsize=16, weight='bold') # fig.legend(fontsize='large') # ax.savefig(f"../graphs/{x} vs {y} per sex.png", dpi=400) def linear_regression_scores_X_y(df, y, y_name, dose_types): """ specifically for EDA """ for Xn in dose_types: features_list = [[Xn], [Xn, 'Age (months)'], [Xn, 'Age (months)', 'encoded sex']] for features in features_list: X = df[features].values.reshape(-1, len(features)) fit_lm = LinearRegression().fit(X, y) print(f'OLS | {features} vs. {y_name} --> R2: {fit_lm.score(X, y):.4f}') print('') return fit_lm
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1341, 35720, 1330, 40522, 11, 14174, 62, 19849, 198, 6738, 814, 8019, 1330,...
2.167196
1,573
import json import os import sys from collections import OrderedDict import iotbx.phil import xia2.Handlers.Streams from dials.util.options import OptionParser from jinja2 import ChoiceLoader, Environment, PackageLoader from xia2.Modules.Report import Report from xia2.XIA2Version import Version phil_scope = iotbx.phil.parse( """\ title = 'xia2 report' .type = str prefix = 'xia2' .type = str log_include = None .type = path include scope xia2.Modules.Analysis.phil_scope json { indent = None .type = int(value_min=0) } """, process_includes=True, ) help_message = """ """
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 1312, 313, 65, 87, 13, 28864, 198, 11748, 2124, 544, 17, 13, 12885, 8116, 13, 12124, 82, 198, 6738, 5980, 82, 13, 22602...
2.838863
211
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.views.generic import TemplateView from . import views # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html')), url(r'^admin/', include(admin.site.urls)), #login url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), #home url(r'^home/$', views.home), ) # Uncomment the next line to serve media files in dev. # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12708, 1330, 9037, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 33571, ...
2.684397
282
from algorithm.InsertionLengthAlgorithm import InsertionLengthAlgorithm from algorithm.PhysicalCoverageAlgorithm import PhysicalCoverageAlgorithm from algorithm.SequenceCoverageAlgorithm import SequenceCoverageAlgorithm from algorithm.CigarAlgorithm import CigarAlgorithm from algorithm.KmersAlgorithm import KmersAlgorithm
[ 6738, 11862, 13, 44402, 295, 24539, 2348, 42289, 1330, 35835, 295, 24539, 2348, 42289, 198, 6738, 11862, 13, 31611, 7222, 1857, 2348, 42289, 1330, 16331, 7222, 1857, 2348, 42289, 198, 6738, 11862, 13, 44015, 594, 7222, 1857, 2348, 42289, ...
4.438356
73
from tkinter import * from attack import * #calls letter frequency attack #defining main window root = Tk() root.title('Letter Frequency Attack') root.configure( background='#221b1b', ) root.option_add('*Font', 'helvatica 12') root.option_add('*Foreground', 'whitesmoke') root.option_add('*Background', '#221b1b') root.option_add('*Entry.HighlightColor', 'whitesmoke') #key value pairs for radio buttons types = [ ('MONOALPHABETIC_CIPHER', 'MONOALPHABETIC_CIPHER'), ('ADDITIVE_CIPHER', 'ADDITIVE_CIPHER') ] #variable to store current selection of radio button attackOn= StringVar() attackOn.set('MONOALPHABETIC_CIPHER') Label(root, text='ATTACK ON').grid(row=0, column=0, padx=20) #radio buttons for i in range(2): Radiobutton( root, text=types[i][0], value=types[i][1], variable=attackOn, highlightthickness=0, activebackground='#221b1b', activeforeground='whitesmoke' ).grid( row=0, column=i+1, padx=20, pady=20 ) #label to show the result answer = Label(root, text='ANSWER HERE', wraplength=700, justify=CENTER) answer.grid(row=1, column=0, columnspan=3, pady=20) #entry widget to input cipher text to crack Label(root, text='CIPHER TXT').grid(row=6, column=0) cipherTxt = Entry(root) cipherTxt.grid(row=6, column=1, columnspan=2, pady=20) #button to call attack() Button( root, text='DECRYPT', justify=CENTER, command=lambda: attack( attackOn.get(), cipherTxt.get() ) ).grid( row=7, column=0, columnspan=3, pady=20 ) #mainloop of tkinter window root.mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 1368, 1330, 1635, 198, 198, 2, 66, 5691, 3850, 8373, 1368, 220, 198, 220, 220, 220, 220, 198, 2, 4299, 3191, 1388, 4324, 198, 15763, 796, 309, 74, 3419, 198, 15763, 13, 7839, 10786, 45708,...
2.284924
723
from random import randint import copy # Auxiliary Function for rotating the DNA in each cycle. # History is the object responsible for accounting all the organisms. # Organism is the structure for the living organisms. # QuantumPackages are the "food" of this simulation. The name comes from the concept used in operative systems. # Enviroment is the class responsible for holding all the living organisms. # Time is the class responsible for aging the living organisms. # Death is the class responsible for killing old or starving organisms. # Interpreter is the class that gives life to the organism. It executes the code in their DNA. if __name__ == '__main__': book = History() earth = Enviroment(10) earth.reportStatus() earth.landscape[0][0] = QuantumPackage(10) earth.landscape[1][1] = Organism("Eva", [8,7,0,9,7,1,10,7,2,11,7,3,12,7,4], 15) #Poblemos Tierra for i in range(0,4): x = randint(0, earth.size-1) y = randint(0, earth.size-1) if earth.landscape[x][y] == 0: dna = [] for a in range(1,11): dna.append(randint(0,12)) earth.landscape[x][y] = Organism("Eva"+str(i), dna, 15) earth.reportStatus() chronos = Time() parca = Death() god = Interpreter() for i in range(0,200): if earth.countOrgs() > 0: print("ciclo: ", i) god.interprete((earth)) chronos.aging(earth) parca.kill(earth) earth.reportStatus() for i in range(1,4): x = randint(0,9) y = randint(0,9) if earth.landscape[x][y] == 0: earth.landscape[x][y] = QuantumPackage(randint(5,10)) for org in earth.getOrganisms(): if not org in book.orgs: book.addOrganism(org) else: print("SE MURIERON TODOS EN EL CICLO: ", i) break print("Living:", len(earth.getOrganisms())) print("GENEPOOL:", book.getGenepool())
[ 6738, 4738, 1330, 43720, 600, 201, 198, 11748, 4866, 201, 198, 201, 198, 2, 47105, 28129, 15553, 329, 24012, 262, 7446, 287, 1123, 6772, 13, 201, 198, 201, 198, 2, 7443, 318, 262, 2134, 4497, 329, 14317, 477, 262, 20296, 13, 201, 19...
2.039143
1,073
import os import datetime from pathlib import Path import pandas as pd import luigi PROCESSED_DIR = 'processed' ROLLUP_DIR = 'rollups' if __name__ == '__main__': luigi.run()
[ 11748, 28686, 198, 11748, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 300, 84, 25754, 198, 198, 4805, 4503, 7597, 1961, 62, 34720, 796, 705, 14681, 276, 6, 198, 13252, 3069, 8...
2.527778
72
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() # Metadata def Name(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.String(o + self._tab.Pos) return None # Metadata def MetadataStart(builder): builder.StartObject(2) # MetadataT def Pack(self, builder): if self.name is not None: name = builder.CreateString(self.name) MetadataStart(builder) if self.name is not None: MetadataAddName(builder, name) MetadataAddBuffer(builder, self.buffer) metadata = MetadataEnd(builder) return metadata
[ 2, 6338, 7560, 416, 262, 21939, 36474, 364, 17050, 11, 466, 407, 13096, 198, 198, 2, 25745, 25, 256, 2704, 578, 198, 198, 11748, 6228, 36873, 364, 198, 6738, 6228, 36873, 364, 13, 5589, 265, 1330, 1330, 62, 77, 32152, 198, 37659, 79...
2.45122
328
"""Read the Kukur configuration.""" # SPDX-FileCopyrightText: 2021 Timeseer.AI # # SPDX-License-Identifier: Apache-2.0 import glob import toml def from_toml(path): """Read the configuration from a TOML file, processing includes.""" config = toml.load(path) for include_options in config.get("include", []): if "glob" not in include_options: raise InvalidIncludeException('"glob" is required') for include_path in glob.glob(include_options["glob"]): include_config = toml.load(include_path) for k, v in include_config.items(): if k not in config: config[k] = v elif isinstance(config[k], list): config[k].append(v) elif isinstance(config[k], dict): config[k].update(v) else: config[k] = v return config
[ 37811, 5569, 262, 509, 2724, 333, 8398, 526, 15931, 198, 2, 30628, 55, 12, 8979, 15269, 8206, 25, 33448, 3782, 28153, 13, 20185, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 11748, 15095, ...
2.115207
434
import time from datetime import datetime import numpy as np from matplotlib import pyplot as plt from matplotlib.dates import epoch2num import device_factory if __name__ == '__main__': amount = 50 devices = [] for i in range(amount): device = device_factory.ecopower_4(i, i) devices.append(device) start = int(time.mktime(datetime(2010, 1, 2).timetuple()) // 60) end = int(time.mktime(datetime(2010, 1, 3).timetuple()) // 60) sample_time = start + 15 * 24 sample_dur = 16 P = [[] for d in devices] T = [[] for d in devices] Th = [[] for d in devices] for now in range(start, sample_time): for idx, device in enumerate(devices): device.step(now) P[idx].append(device.components.consumer.P) T[idx].append(device.components.storage.T) Th[idx].append(device.components.heatsink.in_heat) samples = [] for d in devices: # d.components.sampler.setpoint_density = 0.1 samples.append(d.components.sampler.sample(100, sample_dur)) # samples = [d.components.sampler.sample(100, sample_dur) for d in devices] schedule = np.zeros(sample_dur) for idx, device in enumerate(devices): # min_schedule_idx = np.argmin(np.sum(np.abs(samples[idx]), axis=1)) # device.components.scheduler.schedule = samples[idx][min_schedule_idx] # schedule += samples[idx][min_schedule_idx] max_schedule_idx = np.argmax(np.sum(np.abs(samples[idx]), axis=1)) device.components.scheduler.schedule = samples[idx][max_schedule_idx] schedule += samples[idx][max_schedule_idx] for now in range(sample_time, end): for idx, device in enumerate(devices): device.step(now) P[idx].append(device.components.consumer.P) T[idx].append(device.components.storage.T) Th[idx].append(device.components.heatsink.in_heat) P = np.sum(P, axis=0) Th = np.sum(Th, axis=0) T = np.mean(T, axis=0) ax = plt.subplot(2, 1, 1) ax.grid(True) tz = 60 # timezone deviation in minutes x = epoch2num(np.arange((start + tz) * 60, (end + tz) * 60, 60)) Th = np.reshape(Th, (len(x) // 15, 15)).mean(axis=1) ax.plot_date(x[::15], Th, color='magenta', label='P$_{th,out}$ (kW)', ls='-', marker=None) ax.legend() ax = plt.subplot(2, 1, 2, sharex=ax) ax.grid(True) l1 = ax.plot_date(x, P, label='P$_{el}$ (kW)', ls='-', marker=None) sched_x = epoch2num(np.arange( (sample_time + tz) * 60, ((sample_time + tz) + sample_dur * 15) * 60, 60)) l2 = ax.plot_date(sched_x[::15], schedule, color='r', label='Schedule', ls='-', marker=None) ax = plt.twinx() l3 = ax.plot_date(x, T, color='g', label='T (\\textdegree C)', ls='-', marker=None) lines = l1 + l2 + l3 labels = [l.get_label() for l in lines] ax.legend(lines, labels) plt.gcf().autofmt_xdate() # # Samples plot # fig, ax = plt.subplots(len(samples)) # if len(samples) == 1: # ax = [ax] # for i, sample in enumerate(samples): # t = np.arange(len(sample[0])) # for s in sample: # ax[i].plot(t, s) plt.show()
[ 11748, 640, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 201, 198, 6738, 2603, 29487, 8019, 13, 19581, 1330, 36835,...
2.060719
1,614
expected_output = { "location": { "R0 R1": { "auto_abort_timer": "inactive", "pkg_state": { 1: { "filename_version": "17.08.01.0.149429", "state": "U", "type": "IMG", } }, } } }
[ 40319, 62, 22915, 796, 1391, 198, 220, 220, 220, 366, 24886, 1298, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 49, 15, 371, 16, 1298, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 366, 23736, 62, 397, ...
1.455752
226
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys sys.path.append('..') sys.path.append('.') from auto_scan_test import FusePassAutoScanTest, IgnoreReasons from program_config import TensorConfig, ProgramConfig, OpConfig, CxxConfig, TargetType, PrecisionType, DataLayoutType, Place import numpy as np from functools import partial from typing import Optional, List, Callable, Dict, Any, Set from test_conv_util import UpdatePaddingAndDilation, ConvOutputSize, ConvTransposeOutputSize import unittest import hypothesis from hypothesis import given, settings, seed, example, assume, reproduce_failure import hypothesis.strategies as st if __name__ == "__main__": unittest.main(argv=[''])
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845...
3.637931
348
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ import boto3 import copy import unittest from botocore.stub import ANY from cfn_policy_validator.tests import account_config, offline_only, only_run_for_end_to_end from cfn_policy_validator.tests.boto_mocks import mock_test_setup, BotoResponse, get_test_mode, TEST_MODE from cfn_policy_validator.tests.validation_tests import FINDING_TYPE, mock_access_analyzer_resource_setup, \ MockAccessPreviewFinding, MockNoFindings, MockInvalidConfiguration, MockUnknownError, \ MockTimeout, MockValidateResourcePolicyFinding from cfn_policy_validator.validation.validator import validate_parser_output, Validator from cfn_policy_validator.application_error import ApplicationError from cfn_policy_validator.parsers.output import Output, Policy, Resource resource_policy_with_no_findings = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': '*', 'Principal': { 'AWS': account_config.account_id }, 'Resource': f'arn:aws:sqs:{account_config.region}:{account_config.account_id}:resource1' } ] } lambda_permissions_policy_with_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {}, "Action": "lambda:InvokeFunction", "Resource": f"arn:aws:lambda:{account_config.region}:{account_config.account_id}:function:my-function" }] } class WhenValidatingResources(BaseResourcePolicyTest): sqs_queue_policy_that_allows_external_access = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": ["*"] }, "Action": "sqs:SendMessage", "Resource": "*" }] } sqs_queue_policy_with_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {}, "Action": "sqs:SendMessage", "Resource": "*" }] } sqs_queue_policy_with_no_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": [f'{account_config.account_id}'] }, "Action": "sqs:SendMessage", "Resource": "*" }] } sqs_queue_invalid_policy = { "Version": "2012-10-17", "Statement": [{ "Effect": {"not": "valid"}, "Principal": { "AWS": [f'{account_config.account_id}'] }, "Action": "sqs:SendMessage", "Resource": "*" }] } kms_key_policy_that_allows_external_access = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "kms:*", "Resource": "*" }] } kms_key_policy_with_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {}, "Action": "kms:*", "Resource": "*" }] } kms_key_policy_with_no_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": f"arn:aws:iam::{account_config.account_id}:root" }, "Action": "kms:*", "Resource": "*" }] } kms_key_invalid_policy = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": f"arn:aws:iam::{account_config.account_id}:root" }, "Action": {"not": "valid"}, "Resource": "*" }] } s3_bucket_invalid_policy = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"AWS": [f"arn:aws:iam::{account_config.account_id}:root"]}, "Action": ["s3:PutObject", "s3:PutObjectAcl"], "Resource": {"not": "valid"} }] } secrets_manager_resource_policy_that_allows_external_access = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::777888999444:root"}, "Action": "secretsmanager:GetSecretValue", "Resource": "*" }] } secrets_manager_resource_policy_with_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {}, "Action": "secretsmanager:GetSecretValue", "Resource": "*" }] } secrets_manager_resource_policy_with_no_findings = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": f"arn:aws:iam::{account_config.account_id}:root" }, "Action": "secretsmanager:GetSecretValue", "Resource": "*" }] } secrets_manager_resource_invalid_policy = { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": f"arn:aws:iam::{account_config.account_id}:root" }, "Action": {"not": "valid"}, "Resource": "*" }] }
[ 37811, 198, 15269, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 4303, 36227, 12, 34156, 12, 33234, 7483, 25, 17168, 12, 15, 198, 37811, 198, 11748, 275, 2069, 18, 198, 11748, 4866, 198, 11748, 555, 7...
2.387397
1,825
""" Tests for the h5py.Datatype class. """ from __future__ import absolute_import from itertools import count import numpy as np import h5py from ..common import ut, TestCase
[ 37811, 198, 220, 220, 220, 30307, 329, 262, 289, 20, 9078, 13, 27354, 265, 2981, 1398, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 340, 861, 10141, 1330, 954, 198, 11748, 299, 32152, 355, ...
3.101695
59
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re from typing import Pattern, Tuple, Iterator, Match, Union, Optional, List, Dict from conmon.conan import storage_path DECOLORIZE_REGEX = re.compile(r"[\u001b]\[\d{1,2}m", re.UNICODE) CONAN_DATA_PATH = re.compile( r"""(?x) (?P<path> ([a-zA-Z]:)? (?P<sep>[\\/]) (?:[\w\-.]+(?P=sep)){5,} # conservative choice of characters in path names (?:build|package)(?P=sep) [a-f0-9]{40} (?P=sep) ) """ ) REF_PART_PATTERN = r"\w[\w\+\.\-]{1,50}" REF_REGEX = re.compile( rf"""(?x) (?P<ref> (?P<name>{REF_PART_PATTERN})/ (?P<version>{REF_PART_PATTERN}) (?: @ (?: (?P<user>{REF_PART_PATTERN})/ (?P<channel>{REF_PART_PATTERN}) )? )? ) """ ) def compact_pattern(regex: Pattern) -> Tuple[str, int]: """take verbose pattern and remove all whitespace and comments""" flags = regex.flags # remove inline flags pattern = re.sub(r"\(\?([aiLmsux])+\)", "", regex.pattern, flags=re.ASCII) # remove whitespace in verbose pattern if flags & re.VERBOSE: pattern = re.sub(r"(?<!\\)\s+|\\(?= )|#[^\n]+\n", "", pattern, flags=re.ASCII) flags -= re.VERBOSE return pattern, flags
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 11748, 302, 198, 6738, 19720, 1330, 23939, 11, 309, 29291, 11, 40806, 1352, 11, 13225, 11, 4479, 11, 32233, 11, 7343,...
1.865123
734
#!/usr/bin/env python import sysrepo as sr import argparse from prompt_toolkit import PromptSession from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.completion import Completer import sys import os import logging import asyncio from .base import Object, InvalidInput, BreakLoop from .onlp import Platform from .tai import Transponder logger = logging.getLogger(__name__) stdout = logging.getLogger('stdout') def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-c', '--command-string') parser.add_argument('-k', '--keep-open', action='store_true') parser.add_argument('-x', '--stdin', action='store_true') args = parser.parse_args() formatter = logging.Formatter('[%(asctime)s][%(levelname)-5s][%(name)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') console = logging.StreamHandler() console.setLevel(logging.INFO) if args.verbose: console.setLevel(logging.DEBUG) log = sr.Logs() log.set_stderr(sr.SR_LL_DBG) console.setFormatter(formatter) sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) shf = logging.Formatter('%(message)s') sh.setFormatter(shf) stdout.setLevel(logging.DEBUG) stdout.addHandler(sh) shell = GoldstoneShell() asyncio.run(_main()) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25064, 260, 7501, 355, 19677, 198, 198, 11748, 1822, 29572, 198, 198, 6738, 6152, 62, 25981, 15813, 1330, 45965, 36044, 198, 6738, 6152, 62, 25981, 15813, 13, 2539, 62, 30786...
2.583486
545
cus_list=[8,4,23,42,16,15] selection_sort(cus_list)
[ 198, 198, 9042, 62, 4868, 41888, 23, 11, 19, 11, 1954, 11, 3682, 11, 1433, 11, 1314, 60, 198, 198, 49283, 62, 30619, 7, 9042, 62, 4868, 8, 198 ]
1.896552
29
import requests from bs4 import BeautifulSoup from prettytable import PrettyTable # html = requests.get( # 'http://jwzx.cqu.pt/student/xkxfTj.php', # cookies={'PHPSESSID': 'o2r2fpddrj892dp1ntqddcp2hv'}).text # soup = BeautifulSoup(html, 'html.parser') # for tr in soup.find('table', {'id': 'AxfTjTable'}).findAll('tr')[1:]: # tds = tr.findAll('td') # print(tds[1:5]) table = PrettyTable(['aaa', 'bbb']) print(table)
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 2495, 11487, 1330, 20090, 10962, 198, 198, 2, 27711, 796, 7007, 13, 1136, 7, 198, 2, 220, 220, 220, 220, 705, 4023, 1378, 73, 86, 42592, 13, 66, 421, 13, 457,...
2.241026
195
# create an object of person p1 = Person("KvT") # creating another instance p2 = Person("Shin") # accessing the class method directly print(Person.num_of_people())
[ 198, 198, 2, 2251, 281, 2134, 286, 1048, 198, 79, 16, 796, 7755, 7203, 42, 85, 51, 4943, 198, 198, 2, 4441, 1194, 4554, 198, 79, 17, 796, 7755, 7203, 44592, 4943, 198, 198, 2, 22534, 262, 1398, 2446, 3264, 198, 4798, 7, 15439, 1...
3.230769
52
from django import template from django.conf import settings from webpack_manifest import webpack_manifest if not hasattr(settings, 'WEBPACK_MANIFEST'): raise webpack_manifest.WebpackManifestConfigError('`WEBPACK_MANIFEST` has not been defined in settings') if 'manifests' not in settings.WEBPACK_MANIFEST: raise webpack_manifest.WebpackManifestConfigError( '`WEBPACK_MANIFEST[\'manifests\']` has not been defined in settings' ) register = template.Library()
[ 6738, 42625, 14208, 1330, 11055, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 3992, 8002, 62, 805, 8409, 1330, 3992, 8002, 62, 805, 8409, 198, 198, 361, 407, 468, 35226, 7, 33692, 11, 705, 8845, 20866, 8120, 62, 10725, 5...
2.96319
163
import os import itertools as it import pandas as pd
[ 11748, 28686, 198, 11748, 340, 861, 10141, 355, 340, 198, 11748, 19798, 292, 355, 279, 67, 198 ]
3.117647
17
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## from Interface import Interface from Interface.Attribute import Attribute # testInstancesOfClassImplements # YAGNI IC=Interface.impliedInterface(C) C.__implements__=IC foo_instance = Foo() new = Interface.__class__ FunInterface = new('FunInterface') BarInterface = new('BarInterface', [FunInterface]) BobInterface = new('BobInterface') BazInterface = new('BazInterface', [BobInterface, BarInterface])
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 5878, 11, 6244, 1168, 3008, 10501, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, ...
3.868132
273
from collections import defaultdict from noise_robust_cobras.noise_robust.datastructures.constraint import Constraint from noise_robust_cobras.noise_robust.datastructures.constraint_index import ( ConstraintIndex, ) def get_sorted_constraint_list(self): """ :return: a list of all constraints in the order by which they appear in the cycle with an arbitrary starting constraints """ all_constraints = list(self.constraints) start_constraint = all_constraints[0] temp_index = ConstraintIndex() for constraint in all_constraints[1:]: temp_index.add_constraint(constraint) current_list = [(start_constraint.get_instance_tuple(), start_constraint)] current_instance = start_constraint.i2 while len(temp_index.constraints) > 0: matching_constraints = temp_index.find_constraints_for_instance( current_instance ) if len(matching_constraints) == 1: matching_constraint = list(matching_constraints)[0] else: raise Exception("Not a valid cycle!") other_instance = matching_constraint.get_other_instance(current_instance) current_list.append( ((current_instance, other_instance), matching_constraint) ) current_instance = other_instance temp_index.remove_constraint(matching_constraint) # check if the cycle is complete if start_constraint.i1 != current_instance: raise Exception("Not a valid cycle!") return current_list
[ 6738, 17268, 1330, 4277, 11600, 198, 198, 6738, 7838, 62, 22609, 436, 62, 66, 672, 8847, 13, 3919, 786, 62, 22609, 436, 13, 19608, 459, 1356, 942, 13, 1102, 2536, 2913, 1330, 1482, 2536, 2913, 198, 6738, 7838, 62, 22609, 436, 62, 66...
2.332378
698
import unittest from main import Solution if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 1388, 1330, 28186, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419 ]
2.870968
31
SEPARATOR: list = [':', ',', '*', ';', '#', '|', '+', '%', '>', '?', '&', '=', '!']
[ 5188, 27082, 25633, 25, 1351, 796, 685, 10354, 3256, 46083, 3256, 705, 9, 3256, 705, 26, 3256, 705, 2, 3256, 705, 91, 3256, 705, 10, 3256, 705, 4, 3256, 705, 29, 3256, 705, 30, 3256, 705, 5, 3256, 705, 28, 3256, 705, 13679, 60, ...
1.795918
49
import csv from core.exceptions import InvalidFileException
[ 11748, 269, 21370, 198, 198, 6738, 4755, 13, 1069, 11755, 1330, 17665, 8979, 16922, 628, 628, 628, 198 ]
3.722222
18
import googlemaps import secret from datetime import datetime import requests import pickle import time gmaps = googlemaps.Client(key=secret.PLACES_API_KEY) # lat = 45.411400 # lon = 11.887491 coordinates = [ (45.411400, 11.887491), # torre archimede (45.409218, 11.877915), # piazza garibaldi (45.407698, 11.873351), # piazza dei signori (45.401403, 11.880813), # basilica di sant'antonio ] # def find_places(): # results = gmaps.places_nearby(location=(lat, lon), type='bar', radius=500) # print(len(results)) # return results d = read_data() occ = text_analysis(d) word2vec_analysis(occ.keys(), list(occ.values()), N=12, translate=True)
[ 11748, 23645, 31803, 198, 11748, 3200, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 7007, 198, 11748, 2298, 293, 198, 11748, 640, 198, 198, 70, 31803, 796, 23645, 31803, 13, 11792, 7, 2539, 28, 21078, 13, 6489, 2246, 1546, 62, ...
2.518382
272
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import logging import pytest import threading import time from azure.iot.device.common import handle_exceptions from azure.iot.device.iothub import client_event from azure.iot.device.iothub.sync_handler_manager import SyncHandlerManager, HandlerManagerException from azure.iot.device.iothub.sync_handler_manager import MESSAGE, METHOD, TWIN_DP_PATCH from azure.iot.device.iothub.inbox_manager import InboxManager from azure.iot.device.iothub.sync_inbox import SyncClientInbox logging.basicConfig(level=logging.DEBUG) # NOTE ON TEST IMPLEMENTATION: # Despite having significant shared implementation between the sync and async handler managers, # there are not shared tests. This is because while both have the same set of requirements and # APIs, the internal implementation is different to an extent that it simply isn't really possible # to test them to an appropriate degree of correctness with a shared set of tests. # This means we must be very careful to always change both test modules when a change is made to # shared behavior, or when shared features are added. # NOTE ON TIMING/DELAY # Several tests in this module have sleeps/delays in their implementation due to needing to wait # for things to happen in other threads. all_internal_receiver_handlers = [MESSAGE, METHOD, TWIN_DP_PATCH] all_internal_client_event_handlers = [ "_on_connection_state_change", "_on_new_sastoken_required", "_on_background_exception", ] all_internal_handlers = all_internal_receiver_handlers + all_internal_client_event_handlers all_receiver_handlers = [s.lstrip("_") for s in all_internal_receiver_handlers] all_client_event_handlers = [s.lstrip("_") for s in all_internal_client_event_handlers] all_handlers = all_receiver_handlers + all_client_event_handlers # ############## # # PROPERTIES # # ############## class SharedHandlerPropertyTests(object): # NOTE: We use setattr() and getattr() in these tests so they're generic to all properties. # This is functionally identical to doing explicit assignment to a property, it just # doesn't read quite as well.
[ 2, 16529, 45537, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321, 13, 198, 2, 16529, 35937, 198, 1...
3.675305
656
import grpc import helloworld_pb2 import helloworld_pb2_grpc from grpc.beta import implementations if __name__ == '__main__': run()
[ 11748, 1036, 14751, 198, 11748, 5968, 322, 1764, 62, 40842, 17, 198, 11748, 5968, 322, 1764, 62, 40842, 17, 62, 2164, 14751, 198, 6738, 1036, 14751, 13, 31361, 1330, 25504, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
2.833333
48
#!/usr/bin/env python """ PCA done via matrix multiplication out-of-core. """ import argparse import time import h5py import hickle as hkl import numpy as np if __name__ == '__main__': p = input_parse() args = p.parse_args() main(**vars(args))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 198, 5662, 32, 1760, 2884, 17593, 48473, 503, 12, 1659, 12, 7295, 13, 198, 198, 37811, 198, 11748, 1822, 29572, 198, 11748, 640, 198, 198, 11748, 289, 20, 9078, 198, 11748,...
2.60396
101
# ----------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ----------------------------------------------------------------------------- # pylint: disable=line-too-long import argparse from knack.arguments import ArgumentsContext from azdev.completer import get_test_completion
[ 2, 16529, 32501, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321, 13, 198, 2, 16529, 32501, 198, 1...
5.202247
89
import gamry_parser as parser
[ 11748, 9106, 563, 62, 48610, 355, 30751, 628 ]
3.875
8
import json import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table col_data_comps = [ {"name": ['Component'], "id": "componentName"}, {"name": ['Version'], "id": "componentVersionName"}, {"name": ['Ignored'], "id": "ignored"}, # {"name": ['Ignored'], "id": "ignoreIcon"}, {"name": ['Reviewed'], "id": "reviewStatus"}, {"name": ['Policy Violation'], "id": "policyStatus"}, # {"name": ['Policy Status'], "id": "polIcon"}, {"name": ['Usage'], "id": "usages"}, {"name": ['Match Types'], "id": "matchTypes"}, ] def make_comp_toast(message): """ Helper function for making a toast. dict id for use in pattern matching callbacks. """ return dbc.Toast( message, id={"type": "toast", "id": "toast_comp"}, key='toast_comp', header="Component Processing", is_open=True, dismissable=False, icon="info", duration=8000, )
[ 11748, 33918, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 11748, 19798, 292, 355, 279, ...
2.507282
412
''' Desenvolva um programa que leia o comprimento de trs retas e diga ao usurio se elas podem ou no formar um tringulo. ''' reta1 = float(input('Digite o comprimento da primeira reta: ')) reta2 = float(input('Digite o comprimento da segunda reta: ')) reta3 = float(input('Digite o comprimento da terceira reta: ')) if reta1 < 0 or reta2 < 0 or reta3 < 0: print('\nValor Invlido!') print('No EXISTE medida de lado NEGATIVA!') else: if reta1 + reta2 > reta3 and reta1 + reta3 > reta2 and reta2 + reta3 > reta1: print('\nAs trs retas podem formar tringulo!') else: print('\nAs trs retas NO podem formar tringulo!')
[ 7061, 6, 198, 5960, 268, 10396, 6862, 23781, 1430, 64, 8358, 443, 544, 267, 552, 3036, 50217, 390, 491, 82, 1005, 292, 304, 3100, 64, 257, 78, 39954, 952, 384, 1288, 292, 198, 33320, 368, 267, 84, 645, 1296, 283, 23781, 491, 278, ...
2.295374
281