hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
1cf20d41825b12529c428a35401ff7178dc73a6f
4,315
py
Python
logistic_regression_predict.py
JRMeyer/tensorflow-tutorial
dbbf65bc7e4516a61d27d30954bf59e1477e28f3
[ "MIT" ]
54
2016-02-01T16:45:00.000Z
2021-05-14T03:50:32.000Z
logistic_regression_predict.py
JRMeyer/tensorflow-tutorial
dbbf65bc7e4516a61d27d30954bf59e1477e28f3
[ "MIT" ]
3
2017-02-20T14:09:38.000Z
2020-06-09T18:38:34.000Z
logistic_regression_predict.py
JRMeyer/tensorflow-tutorial
dbbf65bc7e4516a61d27d30954bf59e1477e28f3
[ "MIT" ]
33
2016-02-23T20:20:02.000Z
2021-06-29T21:06:13.000Z
import numpy as np import tensorflow as tf import tarfile import os def csv_to_numpy_array(filePath, delimiter): return np.genfromtxt(filePath, delimiter=delimiter, dtype=None) def import_data(): if "data" not in os.listdir(os.getcwd()): # Untar directory of data if we haven't already tarObject = tarfile.open("data.tar.gz") tarObject.extractall() tarObject.close() print("Extracted tar to current directory") else: # we've already extracted the files pass print("loading training data") trainX = csv_to_numpy_array("data/trainX.csv", delimiter="\t") trainY = csv_to_numpy_array("data/trainY.csv", delimiter="\t") print("loading test data") testX = csv_to_numpy_array("data/testX.csv", delimiter="\t") testY = csv_to_numpy_array("data/testY.csv", delimiter="\t") return trainX,trainY,testX,testY ################### ### IMPORT DATA ### ################### trainX,trainY,testX,testY = import_data() ######################### ### GLOBAL PARAMETERS ### ######################### # Get our dimensions for our different variables and placeholders: # numFeatures = the number of words extracted from each email numFeatures = trainX.shape[1] # numLabels = number of classes we are predicting (here just 2: ham or spam) numLabels = trainY.shape[1] #create a tensorflow session sess = tf.Session() #################### ### PLACEHOLDERS ### #################### # X = X-matrix / feature-matrix / data-matrix... It's a tensor to hold our email # data. 'None' here means that we can hold any number of emails X = tf.placeholder(tf.float32, [None, numFeatures]) # yGold = Y-matrix / label-matrix / labels... This will be our correct answers # matrix. Every row has either [1,0] for SPAM or [0,1] for HAM. 'None' here # means that we can hold any number of emails yGold = tf.placeholder(tf.float32, [None, numLabels]) ################# ### VARIABLES ### ################# #all values must be initialized to a value before loading can occur weights = tf.Variable(tf.zeros([numFeatures,numLabels])) bias = tf.Variable(tf.zeros([1,numLabels])) ######################## ### OPS / OPERATIONS ### ######################## #since we don't have to train the model, the only Ops are the prediction operations apply_weights_OP = tf.matmul(X, weights, name="apply_weights") add_bias_OP = tf.add(apply_weights_OP, bias, name="add_bias") activation_OP = tf.nn.sigmoid(add_bias_OP, name="activation") # argmax(activation_OP, 1) gives the label our model thought was most likely # argmax(yGold, 1) is the correct label correct_predictions_OP = tf.equal(tf.argmax(activation_OP,1),tf.argmax(yGold,1)) # False is 0 and True is 1, what was our average? accuracy_OP = tf.reduce_mean(tf.cast(correct_predictions_OP, "float")) # Initializes everything we've defined made above, but doesn't run anything # until sess.run() init_OP = tf.initialize_all_variables() sess.run(init_OP) #initialize variables BEFORE loading #load variables from file saver = tf.train.Saver() saver.restore(sess, "trained_variables.ckpt") ##################### ### RUN THE GRAPH ### ##################### # Initialize all tensorflow objects # sess.run(init_OP) #method for converting tensor label to string label def labelToString(label): if np.argmax(label) == 0: return "ham" else: return "spam" #make prediction on a given test set item def predict(features, goldLabel): #run through graph tensor_prediction = sess.run(activation_OP, feed_dict={X: features.reshape(1, len(features)), yGold: goldLabel.reshape(1, len(goldLabel))}) #had to make sure that each input in feed_dict was an array prediction = labelToString(tensor_prediction) actual = labelToString(goldLabel) print("regression predicts email to be %s and is actually %s" %(prediction, actual)) if __name__ == "__main__": #show predictions and accuracy of entire test set prediction, evaluation = sess.run([activation_OP, accuracy_OP], feed_dict={X: testX, yGold: testY}) for i in range(len(testX)): print("regression predicts email %s to be %s and is actually %s" %(str(i + 1), labelToString(prediction[i]), labelToString(testY[i]))) print("overall accuracy of dataset: %s percent" %str(evaluation))
32.689394
208
0.673465
cd54172cf1f4cdc52fe76d965cbcefb43775cf21
4,202
py
Python
test/test_cli/test_restore_state.py
brenting/SMAC3
f628d8b83f9f1803054d6e39bce7a51ab033dff1
[ "BSD-3-Clause" ]
51
2019-02-01T19:43:37.000Z
2022-03-16T09:07:03.000Z
test/test_cli/test_restore_state.py
brenting/SMAC3
f628d8b83f9f1803054d6e39bce7a51ab033dff1
[ "BSD-3-Clause" ]
2
2019-02-23T18:54:22.000Z
2019-11-09T01:30:32.000Z
test/test_cli/test_restore_state.py
brenting/SMAC3
f628d8b83f9f1803054d6e39bce7a51ab033dff1
[ "BSD-3-Clause" ]
35
2019-02-08T02:00:31.000Z
2022-03-01T23:17:00.000Z
import os import sys import unittest from nose.plugins.attrib import attr import shutil import numpy as np from unittest import mock from ConfigSpace.hyperparameters import UniformFloatHyperparameter from smac.configspace import ConfigurationSpace from smac.smac_cli import SMACCLI from smac.scenario.scenario import Scenario from smac.facade.smac_facade import SMAC from smac.optimizer.smbo import SMBO from smac.stats.stats import Stats class TestSMACCLI(unittest.TestCase): def setUp(self): base_directory = os.path.split(__file__)[0] base_directory = os.path.abspath( os.path.join(base_directory, '..', '..')) self.current_dir = os.getcwd() os.chdir(base_directory) output_one_dir = "test/test_files/test_restore_state" # From scenario_one.txt self.output_one = output_one_dir + "/run_1" output_two_dir = "test/test_files/test_restored_state" # From scenario_two.txt self.output_two = output_two_dir + "/run_1" self.smaccli = SMACCLI() self.scenario_one = "test/test_files/restore_scenario_one.txt" self.scenario_two = "test/test_files/restore_scenario_two.txt" self.output_dirs = [output_one_dir, output_two_dir] def tearDown(self): for output_dir in self.output_dirs: if output_dir: shutil.rmtree(output_dir, ignore_errors=True) #pass os.chdir(self.current_dir) @attr('slow') def test_run_and_restore(self): """ Testing basic restore functionality. """ # Run for 5 algo-calls testargs = ["python", "scripts/smac", "--scenario_file", self.scenario_one, "--verbose", "DEBUG"] self.smaccli.main_cli(testargs[2:]) # Increase limit and run for 10 (so 5 more) by using restore_state testargs = ["python", "scripts/smac", "--restore_state", self.output_one, "--scenario_file", self.scenario_two, "--verbose", "DEBUG"] self.smaccli.main_cli(testargs[2:]) def test_missing_dir(self): """ Testing error if dir is missing. """ testargs = ["python", "scripts/smac", "--restore_state", "nonsense_test_dir", "--scenario_file", self.scenario_two, "--verbose", "DEBUG"] self.assertRaises(FileNotFoundError, lambda: self.smaccli.main_cli(testargs[2:])) def test_illegal_input(self): """ Testing illegal input in smbo """ cs = ConfigurationSpace() cs.add_hyperparameter(UniformFloatHyperparameter('test', 1, 10, 5)) scen = Scenario({'run_obj': 'quality', 'cs': cs}) stats = Stats(scen) # Recorded runs but no incumbent. stats.ta_runs = 10 smac = SMAC(scen, stats=stats, rng=np.random.RandomState(42)) self.output_dirs.append(scen.output_dir) self.assertRaises(ValueError, smac.optimize) # Incumbent but no recoreded runs. incumbent = cs.get_default_configuration() smac = SMAC(scen, restore_incumbent=incumbent, rng=np.random.RandomState(42)) self.assertRaises(ValueError, smac.optimize) @attr('slow') def test_same_dir(self): """ Testing possible error using same dir for restore """ # Run for 5 algo-calls testargs = ["python", "scripts/smac", "--scenario", self.scenario_one, "--verbose", "DEBUG"] self.smaccli.main_cli(testargs[2:]) # Increase limit and run for 10 (so 5 more) by using restore_state testargs = ["python", "scripts/smac", "--restore_state", self.output_one, "--scenario", self.scenario_two, "--verbose", "DEBUG"] # TODO: fix try: self.smaccli.main_cli(testargs[2:]) except FileNotFoundError: pass self.assertTrue(os.path.exists(self.output_one)) self.assertFalse(os.path.exists(self.output_one + '.OLD')) self.assertTrue(os.path.exists(self.output_two)) self.assertFalse(os.path.exists(self.output_two + '.OLD'))
37.185841
89
0.627082
6064ac97074de63384e40a5e63bc24fce3c4130d
824
py
Python
tests/view/test_headless_view.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
3
2021-01-17T23:32:07.000Z
2022-01-30T14:49:16.000Z
tests/view/test_headless_view.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
2
2021-01-17T13:37:56.000Z
2021-04-14T12:28:49.000Z
tests/view/test_headless_view.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
2
2021-04-02T14:53:38.000Z
2021-04-20T11:10:17.000Z
import unittest from datetime import datetime from chillow.model.cell import Cell from chillow.model.direction import Direction from chillow.model.game import Game from chillow.model.player import Player from chillow.view.headless_view import HeadlessView class HeadlessViewTest(unittest.TestCase): def setUp(self) -> None: self.sut = HeadlessView() def test_update(self): player1 = Player(1, 0, 0, Direction.up, 1, True, "p1") player2 = Player(2, 0, 1, Direction.down, 3, False, "") cells = [[Cell([player1])], [Cell([player2])]] game = Game(1, 2, cells, [player1, player2], 2, False, datetime.now()) self.sut.update(game) def test_end(self): self.sut.end() def test_read_next_action(self): self.sut.read_next_action()
28.413793
78
0.661408
805a4bdcc21f5ea55bb7475e812f845fb5e667c9
2,226
py
Python
data/cirq_new/cirq_program/startCirq_noisy626.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy626.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy626.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=19 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=5 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=16 c.append(cirq.X.on(input_qubit[1])) # number=17 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=18 c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=6 c.append(cirq.rx(-1.0053096491487337).on(input_qubit[2])) # number=10 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=13 c.append(cirq.X.on(input_qubit[3])) # number=14 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=15 c.append(cirq.X.on(input_qubit[3])) # number=9 c.append(cirq.X.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[2])) # number=12 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy626.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
32.735294
77
0.688679
8d84d15aa74edafe4471d61442c042b7f6b81d68
1,623
py
Python
chatBotStable/g4.py
JKhan01/SM446_TeamXYZ
721ba3694bb5d8ecc4cb36f5ad158fabcd8c5f7e
[ "Apache-2.0" ]
null
null
null
chatBotStable/g4.py
JKhan01/SM446_TeamXYZ
721ba3694bb5d8ecc4cb36f5ad158fabcd8c5f7e
[ "Apache-2.0" ]
null
null
null
chatBotStable/g4.py
JKhan01/SM446_TeamXYZ
721ba3694bb5d8ecc4cb36f5ad158fabcd8c5f7e
[ "Apache-2.0" ]
null
null
null
# Gmail initial file import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google.auth.transport.requests import Request def Create_Service(client_secret_file, api_name, api_version, *scopes): print(client_secret_file, api_name, api_version, scopes, sep='-') CLIENT_SECRET_FILE = client_secret_file API_SERVICE_NAME = api_name API_VERSION = api_version SCOPES = [scope for scope in scopes[0]] print(SCOPES) cred = None pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle' # print(pickle_file) if os.path.exists(pickle_file): with open(pickle_file, 'rb') as token: cred = pickle.load(token) if not cred or not cred.valid: if cred and cred.expired and cred.refresh_token: cred.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES) cred = flow.run_local_server() with open(pickle_file, 'wb') as token: pickle.dump(cred, token) try: service = build(API_SERVICE_NAME, API_VERSION, credentials=cred) print(API_SERVICE_NAME, 'service created successfully') return service except Exception as e: print('Unable to connect.') print(e) return None def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0): dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z' return dt
33.122449
88
0.693777
363808b57456ad700729f20b060dfa939e78f8d6
6,521
py
Python
migrations/dynamodb-migrations/2021-10-15T17:30:00Z-update-old-experiment-gem2s-params.py
ivababukova/iac
c4acbbaf82b51189db8238366b2f2620a1902790
[ "MIT" ]
13
2020-12-07T14:43:33.000Z
2021-12-19T10:09:13.000Z
migrations/dynamodb-migrations/2021-10-15T17:30:00Z-update-old-experiment-gem2s-params.py
ivababukova/iac
c4acbbaf82b51189db8238366b2f2620a1902790
[ "MIT" ]
19
2020-09-12T09:59:54.000Z
2022-01-03T13:11:36.000Z
migrations/dynamodb-migrations/2021-10-15T17:30:00Z-update-old-experiment-gem2s-params.py
ivababukova/iac
c4acbbaf82b51189db8238366b2f2620a1902790
[ "MIT" ]
6
2022-02-23T20:41:51.000Z
2022-03-16T19:30:34.000Z
import sys import boto3 from datetime import datetime import hashlib import json from collections import OrderedDict ### Background # This is a new script to ammmend script `2021-08-04T10:06:50Z-migrate-sampleids-to-experiment.py` # Insert endpoint_url='http://localhost:4566' as the 2nd param to test with localstack client = boto3.client('dynamodb') environment = 'production' experiments_table = f'experiments-{environment}' projects_table = f'projects-{environment}' samples_table = f'samples-{environment}' experiments = [] results = client.scan( TableName=experiments_table, ProjectionExpression="experimentId, createdAt, createdDate, projectId, meta", ) experiments = results['Items'] while results.get('LastEvaluatedKey', False): results = client.scan( TableName=experiments_table, ProjectionExpression="experimentId, createdAt, createdDate, projectId, meta", ExclusiveStartKey=results['LastEvaluatedKey'] ) experiments += results['Items'] # >> Uncomment lines below to test with a single experiment # test_experiment_id = "056076b4a6c6abec9f59989674532011" # experiments = client.get_item( # TableName=experiments_table, # Key={"experimentId": { "S" : test_experiment_id }}, # ProjectionExpression="experimentId, createdAt, projectId, meta.gem2s.paramsHash" # )['Item'] # experiments = [experiments] ## << Uncomment lines above to test # function to create gem2s hash def create_gem2s_hash(experiment, project, samples): organism = None # default value if experiment['meta']['M']['organism'].get('S'): organism = experiment['meta']['M']['organism']['S'] # Filter 'ids' key which is present in older samples object unsorted_sample_ids = [sample_id for sample_id in samples['M'] if sample_id != 'ids'] # Sample IDS is first sorted so that hash does not depend on order of samples sorted_sample_ids = unsorted_sample_ids.copy() sorted_sample_ids.sort() sample_names = [] # Sample names are created according to the sorted sampleIds so sample order doesn't matter for sample_id in sorted_sample_ids: sample_names.append(samples['M'][sample_id]['M']['name']['S']) input_type = experiment["meta"]['M']["type"].get('S', '10x') hash_params = OrderedDict() hash_params = { "organism": organism, "input": {"type" : input_type}, "sampleIds": sorted_sample_ids, "sampleNames": sample_names, } metadata_values = OrderedDict() metadata_keys = [metadata['S'] for metadata in project['M']['metadataKeys']['L']] if len(project['M']['metadataKeys']['L']) > 0: for key in metadata_keys: # Replace '-' in key to '_'if sanitizedKey = key.replace('-', '_') for sample_id in unsorted_sample_ids: metadata_value = "N.A." # default metadata value if samples['M'][sample_id]['M']['metadata']['M'].get(key): metadata_value = samples['M'][sample_id]['M']['metadata']['M'][key]['S'] if not metadata_values.get(sanitizedKey): metadata_values[sanitizedKey] = [] metadata_values[sanitizedKey].append(metadata_value) hash_params['metadata'] = metadata_values hash_params_string = json.dumps(hash_params).replace(", ", ",").replace(": ", ":").encode('utf-8') return hashlib.sha1(hash_params_string).hexdigest() print(f"=== Doing migration for PR 408 ===") for experiment in experiments: # try: experiment_id = experiment['experimentId'] print(f"\nExp: {experiment_id['S']}") # This inserts a new createdDate property for old experiments. # New experiments do not have createdAt, so it will always show this error. created_date = experiment['createdAt'] if experiment.get('createdAt') else { "S" : datetime.now().isoformat() } if not experiment.get('createdDate') : print('Project does not contain createdDate, inserting current timestamp') client.update_item( TableName=experiments_table, Key={"experimentId": experiment_id}, UpdateExpression="SET createdDate = :createdDate", ExpressionAttributeValues={ ":createdDate" : created_date, }, ) if not experiment.get('projectId') : print('Experiment does not have associated project') continue project_id = experiment['projectId'] project = client.get_item( TableName=projects_table, Key={"projectUuid" : project_id }, ProjectionExpression="projects" ) if not project.get('Item') : print('Project does not exist') continue samples = project['Item']['projects']['M']['samples'] if not samples.get('L') : print('Project does not contain samples') continue # Get variables experiment_record = client.get_item( TableName=experiments_table, Key={"experimentId": experiment_id } )['Item'] project_record = project['Item']['projects'] # Some broken projects do not have samples in the samples table try : samples_record = client.get_item( TableName=samples_table, Key={"experimentId": experiment_id } )['Item']['samples'] except KeyError : continue # Some experiments do not have a GEM2S hash try: old_hash = experiment['meta']['M']['gem2s']['M']['paramsHash']['S'] except KeyError: print(f"No meta GEM2S hash") continue if 'organism' not in experiment['meta']['M']: print("No organism in meta") continue new_hash = create_gem2s_hash(experiment_record, project_record, samples_record) createdAt = None createdDate = None if experiment.get('createdAt'): createdAt = experiment['createdAt']['S'] if experiment.get('createdDate'): createdDate = experiment['createdDate']['S'] if not old_hash == new_hash: print(f"createdDate: {createdDate}, createdAt: {createdAt} paramsHash [OLD, NEW]: {old_hash}, {new_hash}") client.update_item( TableName=experiments_table, Key={"experimentId": experiment_id}, UpdateExpression="SET createdDate = :createdDate, sampleIds = :samples, meta.gem2s.paramsHash = :hashParams", ExpressionAttributeValues={ ":createdDate" : created_date, ":samples" : samples, ":hashParams" : { "S" : new_hash } }, )
31.809756
121
0.651894
665d9e9a4b412e9c5775f96cf0de67bef89b538c
718
py
Python
setup.py
AlexFlipnote/pug_watcher.py
fdbee921685ef48a1f6e10d0b05ea633b69a4f56
[ "Apache-2.0" ]
4
2021-05-30T14:28:57.000Z
2021-09-13T06:10:33.000Z
setup.py
AlexFlipnote/pug_watcher.py
fdbee921685ef48a1f6e10d0b05ea633b69a4f56
[ "Apache-2.0" ]
null
null
null
setup.py
AlexFlipnote/pug_watcher.py
fdbee921685ef48a1f6e10d0b05ea633b69a4f56
[ "Apache-2.0" ]
null
null
null
import re from setuptools import setup version = "" with open("pug_watcher/__init__.py") as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) requirements = [] with open("requirements.txt") as f: requirements = f.read().splitlines() setup( name="pug-watcher", author="AlexFlipnote", url="https://github.com/AlexFlipnote/pug_watcher.py", version=version, packages=["pug_watcher"], description="Simple command-line Pug watcher/compiler made in Python", include_package_data=True, install_requires=requirements, entry_points={ "console_scripts": [ "pug_watcher=pug_watcher.main:main" ] } )
23.933333
99
0.650418
b93a856e4a71f5d83eafe9086f5cdbba7ed728cd
8,416
py
Python
deepswarm/storage.py
tatonka21/DeepSwarm
a0e85ff296c2496a2a46e017a05bbd3980b4150b
[ "MIT" ]
312
2019-05-03T13:01:48.000Z
2022-01-19T18:07:05.000Z
deepswarm/storage.py
tatonka21/DeepSwarm
a0e85ff296c2496a2a46e017a05bbd3980b4150b
[ "MIT" ]
10
2019-05-20T15:37:43.000Z
2021-09-02T18:40:43.000Z
deepswarm/storage.py
tatonka21/DeepSwarm
a0e85ff296c2496a2a46e017a05bbd3980b4150b
[ "MIT" ]
40
2019-05-03T16:37:09.000Z
2022-03-02T06:40:34.000Z
# Copyright (c) 2019 Edvinas Byla # Licensed under MIT License import hashlib import pickle from datetime import datetime from . import base_path, cfg, left_cost_is_better class Storage: """Class responsible for backups and weight reuse.""" DIR = { "MODEL": "models", "OBJECT": "objects", } ITEM = {"BACKUP": "backup"} def __init__(self, deepswarm): self.loaded_from_save = False self.backup = None self.path_lookup = {} self.models = {} self.deepswarm = deepswarm self.setup_path() self.setup_directories() def setup_path(self): """Loads existing backup or creates a new backup directory.""" # If storage directory doesn't exist create one storage_path = base_path / 'saves' if not storage_path.exists(): storage_path.mkdir() # Check if user specified save folder which should be used to load the data user_folder = cfg['save_folder'] if user_folder is not None and (storage_path / user_folder).exists(): self.current_path = storage_path / user_folder self.loaded_from_save = True # Store deepswarm object to backup self.backup = self.load_object(Storage.ITEM["BACKUP"]) self.backup.storage.loaded_from_save = True return # Otherwise create a new directory directory_path = storage_path / datetime.now().strftime('%Y-%m-%d-%H-%M-%S') if not directory_path.exists(): directory_path.mkdir() self.current_path = directory_path return def setup_directories(self): """Creates all the required directories.""" for directory in Storage.DIR.values(): directory_path = self.current_path / directory if not directory_path.exists(): directory_path.mkdir() def perform_backup(self): """Saves DeepSwarm object to the backup directory.""" self.save_object(self.deepswarm, Storage.ITEM["BACKUP"]) def save_model(self, backend, model, path_hashes, cost): """Saves the model and adds its information to the dictionaries. Args: backend: Backend object. model: model which represents neural network structure. path_hashes [string]: list of hashes, where each hash represents a sub-path. cost: cost associated with the model. """ sub_path_associated = False # The last element describes the whole path model_hash = path_hashes[-1] # For each sub-path find it's corresponding entry in hash table for path_hash in path_hashes: # Check if there already exists model for this sub-path existing_model_hash = self.path_lookup.get(path_hash) model_info = self.models.get(existing_model_hash) # If the old model is better then skip this sub-path if model_info is not None and left_cost_is_better(model_info[0], cost): continue # Otherwise associated this sub-path with a new model self.path_lookup[path_hash] = model_hash sub_path_associated = True # Save model on disk only if it was associated with some sub-path if sub_path_associated: # Add an entry to models dictionary self.models[model_hash] = (cost, 0) # Save to disk self.save_specified_model(backend, model_hash, model) def load_model(self, backend, path_hashes, path): """Loads model with the best weights. Args: backend: Backend object. path_hashes [string]: list of hashes, where each hash represents a sub-path. path [Node]: a path which represents the model. Returns: if the model exists returns a tuple containing model and its hash, otherwise returns a tuple containing None values. """ # Go through all hashes backwards for idx, path_hash in enumerate(path_hashes[::-1]): # See if particular hash is associated with some model model_hash = self.path_lookup.get(path_hash) model_info = self.models.get(model_hash) # Don't reuse model if it hasn't improved for longer than allowed in patience if model_hash is not None and model_info[1] < cfg['reuse_patience']: model = self.load_specified_model(backend, model_hash) # If failed to load model, skip to next hash if model is None: continue # If there is no difference between models, just return the old model, # otherwise create a new model by reusing the old model. Even though, # backend.reuse_model function could be called to handle both # cases, this approach saves some unnecessary computation new_model = model if idx == 0 else backend.reuse_model(model, path, idx) # We also return base model (a model which was used as a base to # create a new model) hash. This hash information is used later to # track if the base model is improving over time or is it stuck return (new_model, model_hash) return (None, None) def load_specified_model(self, backend, model_name): """Loads specified model using its name. Args: backend: Backend object. model_name: name of the model. Returns: model which represents neural network structure. """ file_path = self.current_path / Storage.DIR["MODEL"] / model_name model = backend.load_model(file_path) return model def save_specified_model(self, backend, model_name, model): """Saves specified model using its name without and adding its information to the dictionaries. Args: backend: Backend object. model_name: name of the model. model: model which represents neural network structure. """ save_path = self.current_path / Storage.DIR["MODEL"] / model_name backend.save_model(model, save_path) def record_model_performance(self, path_hash, cost): """Records how many times the model cost didn't improve. Args: path_hash: hash value associated with the model. cost: cost value associated with the model. """ model_hash = self.path_lookup.get(path_hash) old_cost, no_improvements = self.models.get(model_hash) # If cost hasn't changed at all, increment no improvement count if old_cost is not None and old_cost == cost: self.models[model_hash] = (old_cost, (no_improvements + 1)) def hash_path(self, path): """Takes a path and returns a tuple containing path description and list of sub-path hashes. Args: path [Node]: path which represents the model. Returns: tuple where the first element is a string representing the path description and the second element is a list of sub-path hashes. """ hashes = [] path_description = str(path[0]) for node in path[1:]: path_description += ' -> %s' % (node) current_hash = hashlib.sha3_256(path_description.encode('utf-8')).hexdigest() hashes.append(current_hash) return (path_description, hashes) def save_object(self, data, name): """Saves given object to the object backup directory. Args: data: object that needs to be saved. name: string value representing the name of the object. """ with open(self.current_path / Storage.DIR["OBJECT"] / name, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) def load_object(self, name): """Load given object from the object backup directory. Args: name: string value representing the name of the object. Returns: object which has the same name as the given argument. """ with open(self.current_path / Storage.DIR["OBJECT"] / name, 'rb') as f: data = pickle.load(f) return data
37.07489
89
0.617277
abe27a28993d80adf65798e82876526da69c6a03
3,478
py
Python
analyzr/settings.py
Rakib1508/django-analyzr
2d62c896755b1422cbcc6e95ee6da45bc05f6384
[ "MIT" ]
null
null
null
analyzr/settings.py
Rakib1508/django-analyzr
2d62c896755b1422cbcc6e95ee6da45bc05f6384
[ "MIT" ]
null
null
null
analyzr/settings.py
Rakib1508/django-analyzr
2d62c896755b1422cbcc6e95ee6da45bc05f6384
[ "MIT" ]
null
null
null
""" Django settings for analyzr project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '******************************************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'csvs', 'customer', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'analyzr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'analyzr.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR / 'static_cdn' / 'static_root' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media_cnd' / 'media_root' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
25.762963
91
0.684589
b1a497dff483ceff136f1199a11aa070443b5378
5,684
py
Python
rasa/core/policies/policy.py
ntent/rasa
a7df9c1ecddb8cd03b090b4cd3e0229e78fd6f98
[ "Apache-2.0" ]
5
2019-06-06T08:59:15.000Z
2020-01-19T10:56:45.000Z
rasa/core/policies/policy.py
RakibulAsheeque/rasa
7d3804cd081c73d78ab5e973f95a55845eed1e89
[ "Apache-2.0" ]
21
2019-12-16T17:37:54.000Z
2020-07-06T06:19:04.000Z
rasa/core/policies/policy.py
RakibulAsheeque/rasa
7d3804cd081c73d78ab5e973f95a55845eed1e89
[ "Apache-2.0" ]
4
2019-05-19T21:19:32.000Z
2021-01-06T14:26:37.000Z
import copy import logging import tensorflow as tf from typing import Any, List, Optional, Text, Dict, Callable import rasa.utils.common from rasa.core.domain import Domain from rasa.core.featurizers import ( MaxHistoryTrackerFeaturizer, BinarySingleStateFeaturizer, ) from rasa.core.featurizers import TrackerFeaturizer from rasa.core.trackers import DialogueStateTracker from rasa.core.training.data import DialogueTrainingData logger = logging.getLogger(__name__) class Policy(object): SUPPORTS_ONLINE_TRAINING = False @staticmethod def _standard_featurizer(): return MaxHistoryTrackerFeaturizer(BinarySingleStateFeaturizer()) @classmethod def _create_featurizer(cls, featurizer=None): if featurizer: return copy.deepcopy(featurizer) else: return cls._standard_featurizer() @staticmethod def _load_tf_config(config: Dict[Text, Any]) -> Optional[tf.ConfigProto]: """Prepare tf.ConfigProto for training""" if config.get("tf_config") is not None: return tf.ConfigProto(**config.pop("tf_config")) else: return None def __init__( self, featurizer: Optional[TrackerFeaturizer] = None, priority: Optional[int] = 1, ) -> None: self.__featurizer = self._create_featurizer(featurizer) self.priority = priority @property def featurizer(self): return self.__featurizer @staticmethod def _get_valid_params(func: Callable, **kwargs: Any) -> Dict: # filter out kwargs that cannot be passed to func valid_keys = rasa.utils.common.arguments_of(func) params = {key: kwargs.get(key) for key in valid_keys if kwargs.get(key)} ignored_params = { key: kwargs.get(key) for key in kwargs.keys() if not params.get(key) } logger.debug( "Parameters ignored by `model.fit(...)`: {}".format(ignored_params) ) return params def featurize_for_training( self, training_trackers: List[DialogueStateTracker], domain: Domain, **kwargs: Any ) -> DialogueTrainingData: """Transform training trackers into a vector representation. The trackers, consisting of multiple turns, will be transformed into a float vector which can be used by a ML model.""" training_data = self.featurizer.featurize_trackers(training_trackers, domain) max_training_samples = kwargs.get("max_training_samples") if max_training_samples is not None: logger.debug( "Limit training data to {} training samples." "".format(max_training_samples) ) training_data.limit_training_data_to(max_training_samples) return training_data def train( self, training_trackers: List[DialogueStateTracker], domain: Domain, **kwargs: Any ) -> None: """Trains the policy on given training trackers.""" raise NotImplementedError("Policy must have the capacity to train.") def _training_data_for_continue_training( self, batch_size: int, training_trackers: List[DialogueStateTracker], domain: Domain, ) -> DialogueTrainingData: """Creates training_data for `continue_training` by taking the new labelled example training_trackers[-1:] and inserting it in batch_size-1 parts of the old training data, """ import numpy as np num_samples = batch_size - 1 num_prev_examples = len(training_trackers) - 1 sampled_idx = np.random.choice( range(num_prev_examples), replace=False, size=min(num_samples, num_prev_examples), ) trackers = [training_trackers[i] for i in sampled_idx] + training_trackers[-1:] return self.featurize_for_training(trackers, domain) def continue_training( self, training_trackers: List[DialogueStateTracker], domain: Domain, **kwargs: Any ) -> None: """Continues training an already trained policy. This doesn't need to be supported by every policy. If it is supported, the policy can be used for online training and the implementation for the continued training should be put into this function.""" pass def predict_action_probabilities( self, tracker: DialogueStateTracker, domain: Domain ) -> List[float]: """Predicts the next action the bot should take after seeing the tracker. Returns the list of probabilities for the next actions""" raise NotImplementedError("Policy must have the capacity to predict.") def persist(self, path: Text) -> None: """Persists the policy to a storage.""" raise NotImplementedError("Policy must have the capacity to persist itself.") @classmethod def load(cls, path: Text) -> "Policy": """Loads a policy from the storage. Needs to load its featurizer""" raise NotImplementedError("Policy must have the capacity to load itself.") def confidence_scores_for(action_name, value, domain): """Returns confidence scores if a single action is predicted. Args: action_name: Name of action for which the score should be set. value: Confidence for `action_name`. domain: Domain which contains all actions. Returns: List of length `len(nr_actions)`. """ results = [0.0] * domain.num_actions idx = domain.index_for_action(action_name) results[idx] = value return results
32.666667
87
0.66045
b55f0898bedb1e6879fff8c664628ff16a865646
1,194
py
Python
dsp/half_filt.py
FelixVi/Bedrock
82072341902048e5b37022512909d209efb243d6
[ "RSA-MD" ]
17
2019-09-29T14:52:18.000Z
2022-03-28T21:16:25.000Z
dsp/half_filt.py
FelixVi/Bedrock
82072341902048e5b37022512909d209efb243d6
[ "RSA-MD" ]
null
null
null
dsp/half_filt.py
FelixVi/Bedrock
82072341902048e5b37022512909d209efb243d6
[ "RSA-MD" ]
4
2019-12-04T17:30:38.000Z
2021-11-01T01:52:13.000Z
import argparse import numpy from numpy import sqrt, mean def make_check(): y = numpy.loadtxt("half_filt.dat") npt = len(y) print('read %d points, expected 245' % npt) ix = numpy.arange(npt) s = numpy.sin((ix+3.0)*.0081*2*16) lf1 = numpy.polyfit(s, y, 1) oamp = abs(lf1[0]) print('actual amplitude %8.1f, expected about 200000' % oamp) erry = y-lf1[0]*s err = numpy.std(erry, ddof=1) print('DC offset %.4f bits, expected about 0' % mean(erry)) nom_err = sqrt(1.0**2+1/12)*0.66787 tst_err = sqrt(nom_err**2 + 0.3**2) print('std deviation %.4f bits, expected about %.4f' % (err, nom_err)) print('excess noise %.4f bits' % sqrt(err**2-nom_err**2)) if (npt > 230 and oamp > 199800 and oamp < 200000 and abs(mean(erry)) < 0.01 and err < tst_err): print("PASS") else: print("FAIL") exit(1) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Test a_compress') parser.add_argument('-c', '--check', action='store_true', default=True, help='Purely run the check') args = parser.parse_args() make_check()
29.85
75
0.586265
5e12986f17c229acc51a1088d0c0f79b694489cd
3,375
py
Python
predictor.py
Shirhe-Lyh/deep_image_matting
7fa84f94a21ab7e95df78f9f7fb5c46adf98cc2c
[ "Apache-2.0" ]
23
2018-11-22T09:33:04.000Z
2021-03-26T08:42:08.000Z
predictor.py
Shirhe-Lyh/deep_image_matting
7fa84f94a21ab7e95df78f9f7fb5c46adf98cc2c
[ "Apache-2.0" ]
3
2019-01-02T08:35:14.000Z
2019-03-29T11:17:19.000Z
predictor.py
Shirhe-Lyh/deep_image_matting
7fa84f94a21ab7e95df78f9f7fb5c46adf98cc2c
[ "Apache-2.0" ]
10
2019-02-16T03:21:48.000Z
2022-02-09T03:02:20.000Z
# -*- coding: utf-8 -*- """ Created on Thu Oct 11 11:49:09 2018 @author: shirhe-lyh """ import os import tensorflow as tf class Predictor(object): """Classify images to predifined classes.""" def __init__(self, frozen_inference_graph_path, gpu_index=None, gpu_memory_fraction=None): """Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used. Default None. """ self._gpu_index = gpu_index self._gpu_memory_fraction = gpu_memory_fraction self._graph, self._sess = self._load_model(frozen_inference_graph_path) self._images = self._graph.get_tensor_by_name('image_tensor:0') self._trimaps = self._graph.get_tensor_by_name('trimap_tensor:0') self._alpha_mattes = self._graph.get_tensor_by_name('alpha_matte:0') self._refined_alpha_mattes = self._graph.get_tensor_by_name( 'refined_alpha_matte:0') def _load_model(self, frozen_inference_graph_path): """Load a (frozen) Tensorflow model into memory. Args: frozen_inference_graph_path: Path to frozen inference graph. Returns: graph: A tensorflow Graph object. sess: A tensorflow Session object. Raises: ValueError: If frozen_inference_graph_path does not exist. """ if not tf.gfile.Exists(frozen_inference_graph_path): raise ValueError('`frozen_inference_graph_path` does not exist.') # Specify which gpu to be used. if self._gpu_index is not None: if not isinstance(self._gpu_index, str): self._gpu_index = str(self._gpu_index) os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_index if self._gpu_memory_fraction is None: self._gpu_memory_fraction = 1.0 graph = tf.Graph() with graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(frozen_inference_graph_path, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') config = tf.ConfigProto(allow_soft_placement = True) config.gpu_options.per_process_gpu_memory_fraction = ( self._gpu_memory_fraction) sess = tf.Session(graph=graph, config=config) return graph, sess def predict(self, images, trimaps): """Predict prediction tensors from inputs tensor. Args: preprocessed_inputs: A 4D float32 tensor with shape [batch_size, height, width, channels] representing a batch of images. Returns: classes: A 1D integer tensor with shape [batch_size]. """ feed_dict = {self._images: images, self._trimaps: trimaps} [alpha_mattes, refined_alpha_mattes] = self._sess.run( [self._alpha_mattes, self._refined_alpha_mattes], feed_dict=feed_dict) return alpha_mattes, refined_alpha_mattes
38.352273
80
0.599407
f8c0dc603472f4bf1ee4ce4eeeb2609c5d41f70d
3,916
py
Python
model/customized_similarity_model.py
RayTzeng/s3m-membership-inference
ec1ed9438afc4fd3d7a55fd10e6065d2ecc861c4
[ "MIT" ]
9
2021-11-03T11:27:50.000Z
2022-03-14T00:25:45.000Z
model/customized_similarity_model.py
RayTzeng/s3m-membership-inference
ec1ed9438afc4fd3d7a55fd10e6065d2ecc861c4
[ "MIT" ]
null
null
null
model/customized_similarity_model.py
RayTzeng/s3m-membership-inference
ec1ed9438afc4fd3d7a55fd10e6065d2ecc861c4
[ "MIT" ]
null
null
null
import torch import torch.nn as nn from torch.nn.utils.rnn import pad_sequence class SelfAttentionPooling(nn.Module): """ Implementation of SelfAttentionPooling Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition https://arxiv.org/pdf/2008.01077v1.pdf """ def __init__(self, input_dim): super(SelfAttentionPooling, self).__init__() self.W = nn.Linear(input_dim, 1) def forward(self, batch_rep, att_mask): """ input: batch_rep : size (N, T, H), N: batch size, T: sequence length, H: Hidden dimension attention_weight: att_w : size (N, T, 1) return: utter_rep: size (N, H) """ softmax = nn.functional.softmax att_logits = self.W(batch_rep).squeeze(-1) att_logits = att_mask + att_logits att_w = softmax(att_logits, dim=-1).unsqueeze(-1) utter_rep = torch.sum(batch_rep * att_w, dim=1) return utter_rep class SpeakerLevelModel(nn.Module): def __init__(self, input_dim): super(SpeakerLevelModel, self).__init__() self.pooling = SelfAttentionPooling(input_dim) self.linear = nn.Linear(input_dim, input_dim) self.dropout = nn.Dropout(p=0.2) def forward(self, features_x, features_y): """ input: features_x : size (N, T, H), N: batch size, T: sequence length, H: Hidden dimension features_y : size (N, T, H), N: batch size, T: sequence length, H: Hidden dimension attention_weight: att_w : size (N, T, 1) return: sim : scalar """ device = features_x[0].device lengths_x = torch.LongTensor([len(feature) for feature in features_x]).to( device ) features_x_padding_mask = ~torch.lt( torch.arange(max(lengths_x)).unsqueeze(0).to(device), lengths_x.unsqueeze(1), ) padded_features_x = pad_sequence(features_x, batch_first=True) x = self.pooling(padded_features_x, features_x_padding_mask) x = self.linear(x) x = self.dropout(x) x = x.unsqueeze(1) lengths_y = torch.LongTensor([len(feature) for feature in features_y]).to( device ) features_y_padding_mask = ~torch.lt( torch.arange(max(lengths_y)).unsqueeze(0).to(device), lengths_y.unsqueeze(1), ) padded_features_y = pad_sequence(features_y, batch_first=True) y = self.pooling(padded_features_y, features_y_padding_mask) y = self.linear(y) y = self.dropout(y) y = y.unsqueeze(2) sim = torch.matmul(x, y).squeeze().view(-1) return sim class UtteranceLevelModel(nn.Module): def __init__(self, input_dim): super(UtteranceLevelModel, self).__init__() self.pooling = SelfAttentionPooling(input_dim) self.linear = nn.Linear(input_dim, input_dim) self.output = nn.Linear(input_dim, 1) self.relu = nn.ReLU() self.dropout = nn.Dropout(p=0.2) def forward(self, features): """ input: features : size (N, T, H), N: batch size, T: sequence length, H: Hidden dimension attention_weight: att_w : size (N, T, 1) return: sim : scalar """ device = features[0].device lengths = torch.LongTensor([len(feature) for feature in features]).to(device) features_padding_mask = ~torch.lt( torch.arange(max(lengths)).unsqueeze(0).to(device), lengths.unsqueeze(1), ) padded_features = pad_sequence(features, batch_first=True) feature = self.pooling(padded_features, features_padding_mask) feature = self.linear(feature) feature = self.relu(self.dropout(feature)) sim = self.output(feature) sim = sim.squeeze().view(-1) return sim
31.837398
91
0.61236
7225083df9a8e6bd642f8b20386109fdcd499050
1,538
py
Python
img_metadata_lib/metadata.py
Austin-Schmidli/Image-Metadata-API
73e7f9cbcd397d6aefe53a75dbb9ff4e6a924f7d
[ "MIT" ]
null
null
null
img_metadata_lib/metadata.py
Austin-Schmidli/Image-Metadata-API
73e7f9cbcd397d6aefe53a75dbb9ff4e6a924f7d
[ "MIT" ]
null
null
null
img_metadata_lib/metadata.py
Austin-Schmidli/Image-Metadata-API
73e7f9cbcd397d6aefe53a75dbb9ff4e6a924f7d
[ "MIT" ]
null
null
null
import json import exifread def restructure(metadata: dict) -> dict: """Restructures a flat metadata dictionary into one composed of objects by Image File Directory (IFD) Uses the first word of each key to form the IFD objects """ new_metadata = {} for (key, value) in metadata.items(): # Custom logic for certain fields if key == "JPEGThumbnail": add_IFD(new_metadata, "Thumbnail") new_metadata["Thumbnail"].update({key: value}) continue split_key = key.split() if len(split_key) == 1: # If key has no IFD, just append to top level new_metadata.update({key: value}) elif len(split_key) > 1: # Create a new IFD then add the data to that IFD add_IFD(new_metadata, split_key[0]) new_metadata[split_key[0]].update({" ".join(split_key[1:]): value}) return new_metadata def add_IFD(metadata: dict, ifd: str) -> dict: """Adds an empty object to a dictionary if one does not already exist""" if ifd not in metadata: metadata.update({ifd: {}}) return metadata def to_json(metadata: dict) -> str: """Creates a valid json string out of a metadata dictionary""" def serialize(value): """Custom serializer to handle exifread classes""" if isinstance(value, exifread.classes.IfdTag): return value.printable else: return str(value) return json.dumps(metadata, default=serialize, sort_keys=True)
30.76
105
0.626138
7e7f8df5327611fdd74f89fc9b2f0bd2d3fb3a56
2,443
py
Python
code/venv/lib/python3.8/site-packages/datadog_api_client/v2/model/incident_team_included_items.py
Valisback/hiring-engineers
7196915dd5a429ae27c21fa43d527f0332e662ed
[ "Apache-2.0" ]
null
null
null
code/venv/lib/python3.8/site-packages/datadog_api_client/v2/model/incident_team_included_items.py
Valisback/hiring-engineers
7196915dd5a429ae27c21fa43d527f0332e662ed
[ "Apache-2.0" ]
null
null
null
code/venv/lib/python3.8/site-packages/datadog_api_client/v2/model/incident_team_included_items.py
Valisback/hiring-engineers
7196915dd5a429ae27c21fa43d527f0332e662ed
[ "Apache-2.0" ]
null
null
null
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( ModelComposed, cached_property, ) def lazy_import(): from datadog_api_client.v2.model.user import User from datadog_api_client.v2.model.user_attributes import UserAttributes from datadog_api_client.v2.model.user_response_relationships import UserResponseRelationships from datadog_api_client.v2.model.users_type import UsersType globals()["User"] = User globals()["UserAttributes"] = UserAttributes globals()["UserResponseRelationships"] = UserResponseRelationships globals()["UsersType"] = UsersType class IncidentTeamIncludedItems(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ validations = {} @cached_property def openapi_types(): return {} def __init__(self, *args, **kwargs): """IncidentTeamIncludedItems - a model defined in OpenAPI Keyword Args: attributes (UserAttributes): [optional] id (str): [optional] ID of the user. relationships (UserResponseRelationships): [optional] type (UsersType): [optional] """ super().__init__(kwargs) self._check_pos_args(args) @classmethod def _from_openapi_data(cls, *args, **kwargs): """Helper creating a new instance from a response.""" self = super(IncidentTeamIncludedItems, cls)._from_openapi_data(kwargs) self._check_pos_args(args) return self @cached_property def _composed_schemas(): # we need this here to make our import statements work # we must store _composed_schemas in here so the code is only run # when we invoke this method. If we kept this at the class # level we would get an error because the class level # code would be run when this module is imported, and these composed # classes don't exist yet because their module has not finished # loading lazy_import() return { "anyOf": [], "allOf": [], "oneOf": [ User, ], }
31.727273
108
0.665984
6699edb5964530e7e352497de43ff1e154b52a1d
425
py
Python
tools/wptserve/wptserve/sslutils/__init__.py
caub/wpt
ee2e69bfb1d44c4013a8ce94ca6932f86d63aa31
[ "BSD-3-Clause" ]
1
2022-03-19T09:43:35.000Z
2022-03-19T09:43:35.000Z
tools/wptserve/wptserve/sslutils/__init__.py
caub/wpt
ee2e69bfb1d44c4013a8ce94ca6932f86d63aa31
[ "BSD-3-Clause" ]
1
2021-12-13T19:49:45.000Z
2021-12-13T19:49:45.000Z
tools/wptserve/wptserve/sslutils/__init__.py
caub/wpt
ee2e69bfb1d44c4013a8ce94ca6932f86d63aa31
[ "BSD-3-Clause" ]
null
null
null
from .base import NoSSLEnvironment from .openssl import OpenSSLEnvironment from .pregenerated import PregeneratedSSLEnvironment environments = {"none": NoSSLEnvironment, "openssl": OpenSSLEnvironment, "pregenerated": PregeneratedSSLEnvironment} def get_cls(name): try: return environments[name] except KeyError: raise ValueError("%s is not a vaid ssl type." % name)
28.333333
61
0.701176
24fb84e5b76038ff47f51bdd55bb0ea10db6fa76
963
py
Python
tests/test_data/test_dataset/test_cocodataset.py
riskycheng/pytorch.nanodet
8e14a7f89e484f6b462a83e24afa1047c02cd80c
[ "Apache-2.0" ]
1
2021-07-30T03:29:23.000Z
2021-07-30T03:29:23.000Z
tests/test_data/test_dataset/test_cocodataset.py
wealook/nanodet
359d3f9c95eefbad759308e1f57520d25a98055a
[ "Apache-2.0" ]
null
null
null
tests/test_data/test_dataset/test_cocodataset.py
wealook/nanodet
359d3f9c95eefbad759308e1f57520d25a98055a
[ "Apache-2.0" ]
null
null
null
import pytest from nanodet.data.dataset import CocoDataset, build_dataset def test_cocodataset(): cfg = dict( name="CocoDataset", img_path="./tests/data", ann_path="./tests/data/dummy_coco.json", input_size=[320, 320], # [w,h] keep_ratio=True, use_instance_mask=True, pipeline=dict(normalize=[[103.53, 116.28, 123.675], [57.375, 57.12, 58.395]]), ) dataset = build_dataset(cfg, "train") assert isinstance(dataset, CocoDataset) for i, data in enumerate(dataset): assert data["img"].shape == (3, 320, 320) for mask in data["gt_masks"]: assert mask.shape == (320, 320) dataset = build_dataset(cfg, "val") for i, data in enumerate(dataset): assert data["img"].shape == (3, 320, 320) for mask in data["gt_masks"]: assert mask.shape == (320, 320) with pytest.raises(AssertionError): build_dataset(cfg, "2333")
30.09375
86
0.603323
f3d2bee05132ef78f8553d583955151709f98e72
11,793
py
Python
superset/views/base.py
raghul-selsoft/incubator-superset
92abe2e4b0efacb4bcc21e8bb6823cb095896a2b
[ "Apache-2.0" ]
null
null
null
superset/views/base.py
raghul-selsoft/incubator-superset
92abe2e4b0efacb4bcc21e8bb6823cb095896a2b
[ "Apache-2.0" ]
null
null
null
superset/views/base.py
raghul-selsoft/incubator-superset
92abe2e4b0efacb4bcc21e8bb6823cb095896a2b
[ "Apache-2.0" ]
null
null
null
# pylint: disable=C,R,W from datetime import datetime import functools import logging import traceback from flask import abort, flash, g, get_flashed_messages, redirect, Response from flask_appbuilder import BaseView, ModelView from flask_appbuilder.actions import action from flask_appbuilder.models.sqla.filters import BaseFilter from flask_appbuilder.widgets import ListWidget from flask_babel import get_locale from flask_babel import gettext as __ from flask_babel import lazy_gettext as _ import simplejson as json import yaml from superset import conf, db, security_manager from superset.exceptions import SupersetException, SupersetSecurityException from superset.translations.utils import get_language_pack from superset.utils import core as utils FRONTEND_CONF_KEYS = ( 'SUPERSET_WEBSERVER_TIMEOUT', 'SUPERSET_DASHBOARD_POSITION_DATA_LIMIT', 'ENABLE_JAVASCRIPT_CONTROLS', 'DEFAULT_SQLLAB_LIMIT', 'SQL_MAX_ROW', 'SUPERSET_WEBSERVER_DOMAINS', ) def get_error_msg(): if conf.get('SHOW_STACKTRACE'): error_msg = traceback.format_exc() else: error_msg = 'FATAL ERROR \n' error_msg += ( 'Stacktrace is hidden. Change the SHOW_STACKTRACE ' 'configuration setting to enable it') return error_msg def json_error_response(msg=None, status=500, stacktrace=None, payload=None, link=None): if not payload: payload = {'error': '{}'.format(msg)} if stacktrace: payload['stacktrace'] = stacktrace if link: payload['link'] = link return Response( json.dumps(payload, default=utils.json_iso_dttm_ser, ignore_nan=True), status=status, mimetype='application/json') def json_success(json_msg, status=200): return Response(json_msg, status=status, mimetype='application/json') def data_payload_response(payload_json, has_error=False): status = 400 if has_error else 200 return json_success(payload_json, status=status) def generate_download_headers(extension, filename=None): filename = filename if filename else datetime.now().strftime('%Y%m%d_%H%M%S') content_disp = 'attachment; filename={}.{}'.format(filename, extension) headers = { 'Content-Disposition': content_disp, } return headers def api(f): """ A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as e: logging.exception(e) return json_error_response(get_error_msg()) return functools.update_wrapper(wraps, f) def handle_api_exception(f): """ A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions. """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except SupersetSecurityException as e: logging.exception(e) return json_error_response(utils.error_msg_from_exception(e), status=e.status, stacktrace=traceback.format_exc(), link=e.link) except SupersetException as e: logging.exception(e) return json_error_response(utils.error_msg_from_exception(e), stacktrace=traceback.format_exc(), status=e.status) except Exception as e: logging.exception(e) return json_error_response(utils.error_msg_from_exception(e), stacktrace=traceback.format_exc()) return functools.update_wrapper(wraps, f) def get_datasource_exist_error_msg(full_name): return __('Datasource %(name)s already exists', name=full_name) def get_user_roles(): if g.user.is_anonymous: public_role = conf.get('AUTH_ROLE_PUBLIC') return [security_manager.find_role(public_role)] if public_role else [] return g.user.roles class BaseSupersetView(BaseView): def json_response(self, obj, status=200): return Response( json.dumps(obj, default=utils.json_int_dttm_ser, ignore_nan=True), status=status, mimetype='application/json') def common_bootsrap_payload(self): """Common data always sent to the client""" messages = get_flashed_messages(with_categories=True) locale = str(get_locale()) return { 'flash_messages': messages, 'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS}, 'locale': locale, 'language_pack': get_language_pack(locale), 'feature_flags': conf.get('FEATURE_FLAGS'), } class SupersetListWidget(ListWidget): template = 'superset/fab_overrides/list.html' class SupersetModelView(ModelView): page_size = 100 list_widget = SupersetListWidget class ListWidgetWithCheckboxes(ListWidget): """An alternative to list view that renders Boolean fields as checkboxes Works in conjunction with the `checkbox` view.""" template = 'superset/fab_overrides/list_with_checkboxes.html' def validate_json(form, field): # noqa try: json.loads(field.data) except Exception as e: logging.exception(e) raise Exception(_("json isn't valid")) class YamlExportMixin(object): @action('yaml_export', __('Export to YAML'), __('Export to YAML?'), 'fa-download') def yaml_export(self, items): if not isinstance(items, list): items = [items] data = [t.export_to_dict() for t in items] return Response( yaml.safe_dump(data), headers=generate_download_headers('yaml'), mimetype='application/text') class DeleteMixin(object): def _delete(self, pk): """ Delete function logic, override to implement diferent logic deletes the record with primary_key = pk :param pk: record primary key to delete """ item = self.datamodel.get(pk, self._base_filters) if not item: abort(404) try: self.pre_delete(item) except Exception as e: flash(str(e), 'danger') else: view_menu = security_manager.find_view_menu(item.get_perm()) pvs = security_manager.get_session.query( security_manager.permissionview_model).filter_by( view_menu=view_menu).all() schema_view_menu = None if hasattr(item, 'schema_perm'): schema_view_menu = security_manager.find_view_menu(item.schema_perm) pvs.extend(security_manager.get_session.query( security_manager.permissionview_model).filter_by( view_menu=schema_view_menu).all()) if self.datamodel.delete(item): self.post_delete(item) for pv in pvs: security_manager.get_session.delete(pv) if view_menu: security_manager.get_session.delete(view_menu) if schema_view_menu: security_manager.get_session.delete(schema_view_menu) security_manager.get_session.commit() flash(*self.datamodel.message) self.update_redirect() @action( 'muldelete', __('Delete'), __('Delete all Really?'), 'fa-trash', single=False, ) def muldelete(self, items): if not items: abort(404) for item in items: try: self.pre_delete(item) except Exception as e: flash(str(e), 'danger') else: self._delete(item.id) self.update_redirect() return redirect(self.get_redirect()) class SupersetFilter(BaseFilter): """Add utility function to make BaseFilter easy and fast These utility function exist in the SecurityManager, but would do a database round trip at every check. Here we cache the role objects to be able to make multiple checks but query the db only once """ def get_user_roles(self): return get_user_roles() def get_all_permissions(self): """Returns a set of tuples with the perm name and view menu name""" perms = set() for role in self.get_user_roles(): for perm_view in role.permissions: t = (perm_view.permission.name, perm_view.view_menu.name) perms.add(t) return perms def has_role(self, role_name_or_list): """Whether the user has this role name""" if not isinstance(role_name_or_list, list): role_name_or_list = [role_name_or_list] return any( [r.name in role_name_or_list for r in self.get_user_roles()]) def has_perm(self, permission_name, view_menu_name): """Whether the user has this perm""" return (permission_name, view_menu_name) in self.get_all_permissions() def get_view_menus(self, permission_name): """Returns the details of view_menus for a perm name""" vm = set() for perm_name, vm_name in self.get_all_permissions(): if perm_name == permission_name: vm.add(vm_name) return vm class DatasourceFilter(SupersetFilter): def apply(self, query, func): # noqa if security_manager.all_datasource_access(): return query perms = self.get_view_menus('datasource_access') # TODO(bogdan): add `schema_access` support here return query.filter(self.model.perm.in_(perms)) class CsvResponse(Response): """ Override Response to take into account csv encoding from config.py """ charset = conf.get('CSV_EXPORT').get('encoding', 'utf-8') class XlsxResponse(Response): """ Override Response to take into account xlsx encoding from config.py """ charset = conf.get('XLSX_EXPORT').get('encoding', 'utf-8') def check_ownership(obj, raise_if_false=True): """Meant to be used in `pre_update` hooks on models to enforce ownership Admin have all access, and other users need to be referenced on either the created_by field that comes with the ``AuditMixin``, or in a field named ``owners`` which is expected to be a one-to-many with the User model. It is meant to be used in the ModelView's pre_update hook in which raising will abort the update. """ if not obj: return False security_exception = SupersetSecurityException( "You don't have the rights to alter [{}]".format(obj)) if g.user.is_anonymous: if raise_if_false: raise security_exception return False roles = [r.name for r in get_user_roles()] if 'Admin' in roles: return True session = db.create_scoped_session() orig_obj = session.query(obj.__class__).filter_by(id=obj.id).first() # Making a list of owners that works across ORM models owners = [] if hasattr(orig_obj, 'owners'): owners += orig_obj.owners if hasattr(orig_obj, 'owner'): owners += [orig_obj.owner] if hasattr(orig_obj, 'created_by'): owners += [orig_obj.created_by] owner_names = [o.username for o in owners if o] if ( g.user and hasattr(g.user, 'username') and g.user.username in owner_names): return True if raise_if_false: raise security_exception else: return False
32.577348
89
0.641143
bdda36bc7306b2083c1f4648222655ec39ad7244
1,668
py
Python
currencyconverter/sign.py
yueow/cryptoconverter-microservice
a76ee419239e20f9940350f81993b2aecdb4139a
[ "MIT" ]
null
null
null
currencyconverter/sign.py
yueow/cryptoconverter-microservice
a76ee419239e20f9940350f81993b2aecdb4139a
[ "MIT" ]
null
null
null
currencyconverter/sign.py
yueow/cryptoconverter-microservice
a76ee419239e20f9940350f81993b2aecdb4139a
[ "MIT" ]
null
null
null
import hmac from functools import wraps from django.conf import settings class SignVerifyError(Exception): pass # Request does not have 'Sign' in headers class SignRequestEmpty(SignVerifyError): pass # 'Sign' does not match class SignDoesNotMatch(SignVerifyError): pass # Generate HMAC 'Sign' def generate_sign(msg): msg = msg.encode('utf-8') return hmac.new(bytes(settings.API_KEY, encoding='utf-8'), msg, digestmod=settings.SIGN_DIGESTMOD).hexdigest() # Formating a message(e.g. ’2BTCUSDT’) # 'obj' could be a dict or request.POST def comb_sign_string(obj): data = {key: value for key, value in obj.items()} msg = ''.join(sorted(data.values())) return msg # Verify 'Sign' in Request def verify_sign_request(request): # Checks an existing 'sign' header in request # If 'sign' does not exist, it raises exception request_sign = request.headers.get('Sign', None) if not request_sign: raise SignRequestEmpty('The request unsigned') msg = comb_sign_string(request.POST) # print(generate_sign(msg)) # Verifying request # If request 'Sign' does not match to generated sign, it raises exception if hmac.compare_digest(request_sign, generate_sign(msg)): return request else: raise SignDoesNotMatch('Request sign is not verified!') # Assign 'Sign' to Response def sign_reponse(response, msg): # If we use JsonResponse it raise AttributeError Exception # and it passes 'Sign' into response object try: response.headers['Sign'] = generate_sign(msg) except AttributeError: response['Sign'] = generate_sign(msg) return response
30.327273
114
0.705036
1021eb881b7f50fa0e3f8b22947bedc9e3416673
15,355
py
Python
pyscf/cc/eom_gccsd.py
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
2
2019-05-28T05:25:56.000Z
2019-11-09T02:16:43.000Z
pyscf/cc/eom_gccsd.py
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
2
2019-09-16T17:58:31.000Z
2019-09-22T17:26:01.000Z
pyscf/cc/eom_gccsd.py
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
1
2019-11-09T02:13:16.000Z
2019-11-09T02:13:16.000Z
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 time import numpy as np from pyscf import lib from pyscf.lib import logger from pyscf.cc import ccsd from pyscf.cc import eom_rccsd from pyscf.cc import gintermediates as imd ######################################## # EOM-IP-CCSD ######################################## def vector_to_amplitudes_ip(vector, nmo, nocc): nvir = nmo - nocc r1 = vector[:nocc].copy() r2 = np.zeros((nocc,nocc,nvir), dtype=vector.dtype) idx, idy = np.tril_indices(nocc, -1) r2[idx,idy] = vector[nocc:].reshape(nocc*(nocc-1)//2,nvir) r2[idy,idx] =-vector[nocc:].reshape(nocc*(nocc-1)//2,nvir) return r1, r2 def amplitudes_to_vector_ip(r1, r2): nocc = r1.size return np.hstack((r1, r2[np.tril_indices(nocc, -1)].ravel())) def ipccsd_matvec(eom, vector, imds=None, diag=None): # Ref: Tu, Wang, and Li, J. Chem. Phys. 136, 174102 (2012) Eqs.(8)-(9) if imds is None: imds = eom.make_imds() nocc = eom.nocc nmo = eom.nmo r1, r2 = vector_to_amplitudes_ip(vector, nmo, nocc) # Eq. (8) Hr1 = -np.einsum('mi,m->i', imds.Foo, r1) Hr1 += np.einsum('me,mie->i', imds.Fov, r2) Hr1 += -0.5*np.einsum('nmie,mne->i', imds.Wooov, r2) # Eq. (9) Hr2 = lib.einsum('ae,ije->ija', imds.Fvv, r2) tmp1 = lib.einsum('mi,mja->ija', imds.Foo, r2) Hr2 -= tmp1 - tmp1.transpose(1,0,2) Hr2 -= np.einsum('maji,m->ija', imds.Wovoo, r1) Hr2 += 0.5*lib.einsum('mnij,mna->ija', imds.Woooo, r2) tmp2 = lib.einsum('maei,mje->ija', imds.Wovvo, r2) Hr2 += tmp2 - tmp2.transpose(1,0,2) Hr2 += 0.5*lib.einsum('mnef,mnf,ijae->ija', imds.Woovv, r2, imds.t2) vector = amplitudes_to_vector_ip(Hr1, Hr2) return vector def ipccsd_diag(eom, imds=None): if imds is None: imds = eom.make_imds() t1, t2 = imds.t1, imds.t2 nocc, nvir = t1.shape Hr1 = -np.diag(imds.Foo) Hr2 = np.zeros((nocc,nocc,nvir), dtype=t1.dtype) for i in range(nocc): for j in range(nocc): for a in range(nvir): Hr2[i,j,a] += imds.Fvv[a,a] Hr2[i,j,a] += -imds.Foo[i,i] Hr2[i,j,a] += -imds.Foo[j,j] Hr2[i,j,a] += 0.5*(imds.Woooo[i,j,i,j]-imds.Woooo[j,i,i,j]) Hr2[i,j,a] += imds.Wovvo[i,a,a,i] Hr2[i,j,a] += imds.Wovvo[j,a,a,j] Hr2[i,j,a] += 0.5*(np.dot(imds.Woovv[i,j,:,a], t2[i,j,a,:]) -np.dot(imds.Woovv[j,i,:,a], t2[i,j,a,:])) vector = amplitudes_to_vector_ip(Hr1, Hr2) return vector class EOMIP(eom_rccsd.EOMIP): matvec = ipccsd_matvec l_matvec = None get_diag = ipccsd_diag ipccsd_star = None def vector_to_amplitudes(self, vector, nmo=None, nocc=None): if nmo is None: nmo = self.nmo if nocc is None: nocc = self.nocc return vector_to_amplitudes_ip(vector, nmo, nocc) def amplitudes_to_vector(self, r1, r2): return amplitudes_to_vector_ip(r1, r2) def vector_size(self): nocc = self.nocc nvir = self.nmo - nocc return nocc + nocc*(nocc-1)/2*nvir def make_imds(self, eris=None): imds = _IMDS(self._cc, eris) imds.make_ip() return imds ######################################## # EOM-EA-CCSD ######################################## def vector_to_amplitudes_ea(vector, nmo, nocc): nvir = nmo - nocc r1 = vector[:nvir].copy() r2 = np.zeros((nocc,nvir,nvir), vector.dtype) idx, idy = np.tril_indices(nvir, -1) r2[:,idx,idy] = vector[nvir:].reshape(nocc,-1) r2[:,idy,idx] =-vector[nvir:].reshape(nocc,-1) return r1, r2 def amplitudes_to_vector_ea(r1, r2): nvir = r1.size idx, idy = np.tril_indices(nvir, -1) return np.hstack((r1, r2[:,idx,idy].ravel())) def eaccsd_matvec(eom, vector, imds=None, diag=None): # Ref: Nooijen and Bartlett, J. Chem. Phys. 102, 3629 (1994) Eqs.(30)-(31) if imds is None: imds = eom.make_imds() nocc = eom.nocc nmo = eom.nmo r1, r2 = vector_to_amplitudes_ea(vector, nmo, nocc) # Eq. (30) Hr1 = np.einsum('ac,c->a', imds.Fvv, r1) Hr1 += np.einsum('ld,lad->a', imds.Fov, r2) Hr1 += 0.5*np.einsum('alcd,lcd->a', imds.Wvovv, r2) # Eq. (31) Hr2 = np.einsum('abcj,c->jab', imds.Wvvvo, r1) tmp1 = lib.einsum('ac,jcb->jab', imds.Fvv, r2) Hr2 += tmp1 - tmp1.transpose(0,2,1) Hr2 -= lib.einsum('lj,lab->jab', imds.Foo, r2) tmp2 = lib.einsum('lbdj,lad->jab', imds.Wovvo, r2) Hr2 += tmp2 - tmp2.transpose(0,2,1) Hr2 += 0.5*lib.einsum('abcd,jcd->jab', imds.Wvvvv, r2) Hr2 -= 0.5*lib.einsum('klcd,lcd,kjab->jab', imds.Woovv, r2, imds.t2) vector = amplitudes_to_vector_ea(Hr1, Hr2) return vector def eaccsd_diag(eom, imds=None): if imds is None: imds = eom.make_imds() t1, t2 = imds.t1, imds.t2 nocc, nvir = t1.shape Hr1 = np.diag(imds.Fvv) Hr2 = np.zeros((nocc,nvir,nvir),dtype=t1.dtype) for a in range(nvir): _Wvvvva = np.array(imds.Wvvvv[a]) for b in range(a): for j in range(nocc): Hr2[j,a,b] += imds.Fvv[a,a] Hr2[j,a,b] += imds.Fvv[b,b] Hr2[j,a,b] += -imds.Foo[j,j] Hr2[j,a,b] += imds.Wovvo[j,b,b,j] Hr2[j,a,b] += imds.Wovvo[j,a,a,j] Hr2[j,a,b] += 0.5*(_Wvvvva[b,a,b]-_Wvvvva[b,b,a]) Hr2[j,a,b] += -0.5*(np.dot(imds.Woovv[:,j,a,b], t2[:,j,a,b]) -np.dot(imds.Woovv[:,j,b,a], t2[:,j,a,b])) vector = amplitudes_to_vector_ea(Hr1, Hr2) return vector class EOMEA(eom_rccsd.EOMEA): matvec = eaccsd_matvec l_matvec = None get_diag = eaccsd_diag eaccsd_star = None def vector_to_amplitudes(self, vector, nmo=None, nocc=None): if nmo is None: nmo = self.nmo if nocc is None: nocc = self.nocc return vector_to_amplitudes_ea(vector, nmo, nocc) def amplitudes_to_vector(self, r1, r2): return amplitudes_to_vector_ea(r1, r2) def vector_size(self): nocc = self.nocc nvir = self.nmo - nocc return nvir + nocc*nvir*(nvir-1)//2 def make_imds(self, eris=None): imds = _IMDS(self._cc, eris) imds.make_ea() return imds ######################################## # EOM-EE-CCSD ######################################## vector_to_amplitudes_ee = ccsd.vector_to_amplitudes_s4 amplitudes_to_vector_ee = ccsd.amplitudes_to_vector_s4 def eeccsd_matvec(eom, vector, imds=None, diag=None): # Ref: Wang, Tu, and Wang, J. Chem. Theory Comput. 10, 5567 (2014) Eqs.(9)-(10) # Note: Last line in Eq. (10) is superfluous. # See, e.g. Gwaltney, Nooijen, and Barlett, Chem. Phys. Lett. 248, 189 (1996) if imds is None: imds = eom.make_imds() nocc = eom.nocc nmo = eom.nmo r1, r2 = vector_to_amplitudes_ee(vector, nmo, nocc) # Eq. (9) Hr1 = lib.einsum('ae,ie->ia', imds.Fvv, r1) Hr1 -= lib.einsum('mi,ma->ia', imds.Foo, r1) Hr1 += lib.einsum('me,imae->ia', imds.Fov, r2) Hr1 += lib.einsum('maei,me->ia', imds.Wovvo, r1) Hr1 -= 0.5*lib.einsum('mnie,mnae->ia', imds.Wooov, r2) Hr1 += 0.5*lib.einsum('amef,imef->ia', imds.Wvovv, r2) # Eq. (10) tmpab = lib.einsum('be,ijae->ijab', imds.Fvv, r2) tmpab -= 0.5*lib.einsum('mnef,ijae,mnbf->ijab', imds.Woovv, imds.t2, r2) tmpab -= lib.einsum('mbij,ma->ijab', imds.Wovoo, r1) tmpab -= lib.einsum('amef,ijfb,me->ijab', imds.Wvovv, imds.t2, r1) tmpij = lib.einsum('mj,imab->ijab', -imds.Foo, r2) tmpij -= 0.5*lib.einsum('mnef,imab,jnef->ijab', imds.Woovv, imds.t2, r2) tmpij += lib.einsum('abej,ie->ijab', imds.Wvvvo, r1) tmpij += lib.einsum('mnie,njab,me->ijab', imds.Wooov, imds.t2, r1) tmpabij = lib.einsum('mbej,imae->ijab', imds.Wovvo, r2) tmpabij = tmpabij - tmpabij.transpose(1,0,2,3) tmpabij = tmpabij - tmpabij.transpose(0,1,3,2) Hr2 = tmpabij Hr2 += tmpab - tmpab.transpose(0,1,3,2) Hr2 += tmpij - tmpij.transpose(1,0,2,3) Hr2 += 0.5*lib.einsum('mnij,mnab->ijab', imds.Woooo, r2) Hr2 += 0.5*lib.einsum('abef,ijef->ijab', imds.Wvvvv, r2) vector = amplitudes_to_vector_ee(Hr1, Hr2) return vector def eeccsd_diag(eom, imds=None): if imds is None: imds = eom.make_imds() t1, t2 = imds.t1, imds.t2 nocc, nvir = t1.shape Hr1 = np.zeros((nocc,nvir), dtype=t1.dtype) Hr2 = np.zeros((nocc,nocc,nvir,nvir), dtype=t1.dtype) for i in range(nocc): for a in range(nvir): Hr1[i,a] = imds.Fvv[a,a] - imds.Foo[i,i] + imds.Wovvo[i,a,a,i] for a in range(nvir): tmp = 0.5*(np.einsum('ijeb,ijbe->ijb', imds.Woovv, t2) -np.einsum('jieb,ijbe->ijb', imds.Woovv, t2)) Hr2[:,:,:,a] += imds.Fvv[a,a] + tmp Hr2[:,:,a,:] += imds.Fvv[a,a] + tmp _Wvvvva = np.array(imds.Wvvvv[a]) for b in range(a): Hr2[:,:,a,b] += 0.5*(_Wvvvva[b,a,b]-_Wvvvva[b,b,a]) for i in range(nocc): tmp = imds.Wovvo[i,a,a,i] Hr2[:,i,:,a] += tmp Hr2[i,:,:,a] += tmp Hr2[:,i,a,:] += tmp Hr2[i,:,a,:] += tmp for i in range(nocc): tmp = 0.5*(np.einsum('kjab,jkab->jab', imds.Woovv, t2) -np.einsum('kjba,jkab->jab', imds.Woovv, t2)) Hr2[:,i,:,:] += -imds.Foo[i,i] + tmp Hr2[i,:,:,:] += -imds.Foo[i,i] + tmp for j in range(i): Hr2[i,j,:,:] += 0.5*(imds.Woooo[i,j,i,j]-imds.Woooo[j,i,i,j]) vector = amplitudes_to_vector_ee(Hr1, Hr2) return vector def eeccsd(eom, nroots=1, koopmans=False, guess=None, eris=None, imds=None): '''Calculate N-electron neutral excitations via EOM-EE-CCSD. Kwargs: nroots : int Number of roots (eigenvalues) requested koopmans : bool Calculate Koopmans'-like (1p1h) excitations only, targeting via overlap. guess : list of ndarray List of guess vectors to use for targeting via overlap. ''' return eom_rccsd.eomee_ccsd_singlet(eom, nroots, koopmans, guess, eris, imds) class EOMEE(eom_rccsd.EOMEE): kernel = eeccsd eeccsd = eeccsd matvec = eeccsd_matvec get_diag = eeccsd_diag def gen_matvec(self, imds=None, **kwargs): if imds is None: imds = self.make_imds() diag = self.get_diag(imds) matvec = lambda xs: [self.matvec(x, imds) for x in xs] return matvec, diag def vector_to_amplitudes(self, vector, nmo=None, nocc=None): if nmo is None: nmo = self.nmo if nocc is None: nocc = self.nocc return vector_to_amplitudes_ee(vector, nmo, nocc) def amplitudes_to_vector(self, r1, r2): return amplitudes_to_vector_ee(r1, r2) def vector_size(self): '''size of the vector based on spin-orbital basis''' nocc = self.nocc nvir = self.nmo - nocc return nocc*nvir + nocc*(nocc-1)//2*nvir*(nvir-1)//2 def make_imds(self, eris=None): imds = _IMDS(self._cc, eris) imds.make_ee() return imds class _IMDS: # Exactly the same as RCCSD IMDS except # -- rintermediates --> gintermediates # -- Loo, Lvv, cc_Fov --> Foo, Fvv, Fov # -- One less 2-virtual intermediate def __init__(self, cc, eris=None): self.verbose = cc.verbose self.stdout = cc.stdout self.t1 = cc.t1 self.t2 = cc.t2 if eris is None: eris = cc.ao2mo() self.eris = eris self._made_shared = False self.made_ip_imds = False self.made_ea_imds = False self.made_ee_imds = False def _make_shared(self): cput0 = (time.clock(), time.time()) t1, t2, eris = self.t1, self.t2, self.eris self.Foo = imd.Foo(t1, t2, eris) self.Fvv = imd.Fvv(t1, t2, eris) self.Fov = imd.Fov(t1, t2, eris) # 2 virtuals self.Wovvo = imd.Wovvo(t1, t2, eris) self.Woovv = eris.oovv self._made_shared = True logger.timer_debug1(self, 'EOM-CCSD shared intermediates', *cput0) return self def make_ip(self): if not self._made_shared: self._make_shared() cput0 = (time.clock(), time.time()) t1, t2, eris = self.t1, self.t2, self.eris # 0 or 1 virtuals self.Woooo = imd.Woooo(t1, t2, eris) self.Wooov = imd.Wooov(t1, t2, eris) self.Wovoo = imd.Wovoo(t1, t2, eris) self.made_ip_imds = True logger.timer_debug1(self, 'EOM-CCSD IP intermediates', *cput0) return self def make_ea(self): if not self._made_shared: self._make_shared() cput0 = (time.clock(), time.time()) t1, t2, eris = self.t1, self.t2, self.eris # 3 or 4 virtuals self.Wvovv = imd.Wvovv(t1, t2, eris) self.Wvvvv = imd.Wvvvv(t1, t2, eris) self.Wvvvo = imd.Wvvvo(t1, t2, eris,self.Wvvvv) self.made_ea_imds = True logger.timer_debug1(self, 'EOM-CCSD EA intermediates', *cput0) return self def make_ee(self): if not self._made_shared: self._make_shared() cput0 = (time.clock(), time.time()) t1, t2, eris = self.t1, self.t2, self.eris if not self.made_ip_imds: # 0 or 1 virtuals self.Woooo = imd.Woooo(t1, t2, eris) self.Wooov = imd.Wooov(t1, t2, eris) self.Wovoo = imd.Wovoo(t1, t2, eris) if not self.made_ea_imds: # 3 or 4 virtuals self.Wvovv = imd.Wvovv(t1, t2, eris) self.Wvvvv = imd.Wvvvv(t1, t2, eris) self.Wvvvo = imd.Wvvvo(t1, t2, eris,self.Wvvvv) self.made_ee_imds = True logger.timer(self, 'EOM-CCSD EE intermediates', *cput0) return self if __name__ == '__main__': from pyscf import scf from pyscf import gto from pyscf.cc import gccsd mol = gto.Mole() mol.atom = [ [8 , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)]] mol.basis = 'cc-pvdz' mol.spin = 0 mol.build() mf = scf.UHF(mol).run() mf = scf.addons.convert_to_ghf(mf) mycc = gccsd.GCCSD(mf) ecc, t1, t2 = mycc.kernel() print(ecc - -0.2133432712431435) e,v = mycc.ipccsd(nroots=8) print(e[0] - 0.4335604332073799) print(e[2] - 0.5187659896045407) print(e[4] - 0.6782876002229172) #mycc.verbose = 5 e,v = mycc.eaccsd(nroots=8) print(e[0] - 0.16737886338859731) print(e[2] - 0.24027613852009164) print(e[4] - 0.51006797826488071) e,v = mycc.eeccsd(nroots=4) print(e[0] - 0.2757159395886167) print(e[1] - 0.2757159395886167) print(e[2] - 0.2757159395886167) print(e[3] - 0.3005716731825082)
33.380435
83
0.577727
f9a26b42fed82c1543f4b81c16d5bc8f43f911d9
12,033
py
Python
deutschland/jobsuche/model/job_search_response_auswahl.py
kiranmusze/deutschland
86d8ead3f38ad88ad66bb338b9f5a8db06992344
[ "Apache-2.0" ]
null
null
null
deutschland/jobsuche/model/job_search_response_auswahl.py
kiranmusze/deutschland
86d8ead3f38ad88ad66bb338b9f5a8db06992344
[ "Apache-2.0" ]
null
null
null
deutschland/jobsuche/model/job_search_response_auswahl.py
kiranmusze/deutschland
86d8ead3f38ad88ad66bb338b9f5a8db06992344
[ "Apache-2.0" ]
null
null
null
""" Bundesagentur für Arbeit: Jobsuche API Die größte Stellendatenbank Deutschlands durchsuchen, Details zu Stellenanzeigen und Informationen über Arbeitgeber abrufen. <br><br> Die Authentifizierung funktioniert per OAuth 2 Client Credentials mit JWTs. Folgende Client-Credentials können dafür verwendet werden:<br><br> **ClientID:** c003a37f-024f-462a-b36d-b001be4cd24a <br> **ClientSecret:** 32a39620-32b3-4307-9aa1-511e3d7f48a8 # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from deutschland.jobsuche.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) from ..model_utils import OpenApiModel from deutschland.jobsuche.exceptions import ApiAttributeError class JobSearchResponseAuswahl(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = {} validations = {} @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return ( bool, date, datetime, dict, float, int, list, str, none_type, ) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { "treffer_anzahl": (int,), # noqa: E501 "preset": (bool,), # noqa: E501 "name": (str,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { "treffer_anzahl": "trefferAnzahl", # noqa: E501 "preset": "preset", # noqa: E501 "name": "name", # noqa: E501 } read_only_vars = {} _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """JobSearchResponseAuswahl - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) treffer_anzahl (int): [optional] # noqa: E501 preset (bool): [optional] # noqa: E501 name (str): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) self = super(OpenApiModel, cls).__new__(cls) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set( [ "_data_store", "_check_type", "_spec_property_naming", "_path_to_item", "_configuration", "_visited_composed_classes", ] ) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """JobSearchResponseAuswahl - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) treffer_anzahl (int): [optional] # noqa: E501 preset (bool): [optional] # noqa: E501 name (str): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError( f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes." )
43.129032
405
0.566608
5e29e942c96d5e06c4b2519ea670fd7829d775a4
40,566
py
Python
sdk/python/pulumi_aws/alb/listener.py
rapzo/pulumi-aws
390a098221315d98a54ba97d1559e750dc3053b7
[ "ECL-2.0", "Apache-2.0" ]
260
2018-06-18T14:57:00.000Z
2022-03-29T11:41:03.000Z
sdk/python/pulumi_aws/alb/listener.py
rapzo/pulumi-aws
390a098221315d98a54ba97d1559e750dc3053b7
[ "ECL-2.0", "Apache-2.0" ]
1,154
2018-06-19T20:38:20.000Z
2022-03-31T19:48:16.000Z
sdk/python/pulumi_aws/alb/listener.py
rapzo/pulumi-aws
390a098221315d98a54ba97d1559e750dc3053b7
[ "ECL-2.0", "Apache-2.0" ]
115
2018-06-28T03:20:27.000Z
2022-03-29T11:41:06.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['ListenerArgs', 'Listener'] @pulumi.input_type class ListenerArgs: def __init__(__self__, *, default_actions: pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]], load_balancer_arn: pulumi.Input[str], alpn_policy: Optional[pulumi.Input[str]] = None, certificate_arn: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, protocol: Optional[pulumi.Input[str]] = None, ssl_policy: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a Listener resource. :param pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]] default_actions: Configuration block for default actions. Detailed below. :param pulumi.Input[str] load_balancer_arn: ARN of the load balancer. :param pulumi.Input[str] alpn_policy: Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. :param pulumi.Input[str] certificate_arn: ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. :param pulumi.Input[int] port: Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. :param pulumi.Input[str] protocol: Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. :param pulumi.Input[str] ssl_policy: Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. """ pulumi.set(__self__, "default_actions", default_actions) pulumi.set(__self__, "load_balancer_arn", load_balancer_arn) if alpn_policy is not None: pulumi.set(__self__, "alpn_policy", alpn_policy) if certificate_arn is not None: pulumi.set(__self__, "certificate_arn", certificate_arn) if port is not None: pulumi.set(__self__, "port", port) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if ssl_policy is not None: pulumi.set(__self__, "ssl_policy", ssl_policy) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="defaultActions") def default_actions(self) -> pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]: """ Configuration block for default actions. Detailed below. """ return pulumi.get(self, "default_actions") @default_actions.setter def default_actions(self, value: pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]): pulumi.set(self, "default_actions", value) @property @pulumi.getter(name="loadBalancerArn") def load_balancer_arn(self) -> pulumi.Input[str]: """ ARN of the load balancer. """ return pulumi.get(self, "load_balancer_arn") @load_balancer_arn.setter def load_balancer_arn(self, value: pulumi.Input[str]): pulumi.set(self, "load_balancer_arn", value) @property @pulumi.getter(name="alpnPolicy") def alpn_policy(self) -> Optional[pulumi.Input[str]]: """ Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. """ return pulumi.get(self, "alpn_policy") @alpn_policy.setter def alpn_policy(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "alpn_policy", value) @property @pulumi.getter(name="certificateArn") def certificate_arn(self) -> Optional[pulumi.Input[str]]: """ ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. """ return pulumi.get(self, "certificate_arn") @certificate_arn.setter def certificate_arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "certificate_arn", value) @property @pulumi.getter def port(self) -> Optional[pulumi.Input[int]]: """ Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. """ return pulumi.get(self, "port") @port.setter def port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "port", value) @property @pulumi.getter def protocol(self) -> Optional[pulumi.Input[str]]: """ Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. """ return pulumi.get(self, "protocol") @protocol.setter def protocol(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "protocol", value) @property @pulumi.getter(name="sslPolicy") def ssl_policy(self) -> Optional[pulumi.Input[str]]: """ Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. """ return pulumi.get(self, "ssl_policy") @ssl_policy.setter def ssl_policy(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ssl_policy", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @pulumi.input_type class _ListenerState: def __init__(__self__, *, alpn_policy: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, certificate_arn: Optional[pulumi.Input[str]] = None, default_actions: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]] = None, load_balancer_arn: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, protocol: Optional[pulumi.Input[str]] = None, ssl_policy: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ Input properties used for looking up and filtering Listener resources. :param pulumi.Input[str] alpn_policy: Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. :param pulumi.Input[str] arn: ARN of the target group. :param pulumi.Input[str] certificate_arn: ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. :param pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]] default_actions: Configuration block for default actions. Detailed below. :param pulumi.Input[str] load_balancer_arn: ARN of the load balancer. :param pulumi.Input[int] port: Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. :param pulumi.Input[str] protocol: Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. :param pulumi.Input[str] ssl_policy: Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags_all: A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. """ if alpn_policy is not None: pulumi.set(__self__, "alpn_policy", alpn_policy) if arn is not None: pulumi.set(__self__, "arn", arn) if certificate_arn is not None: pulumi.set(__self__, "certificate_arn", certificate_arn) if default_actions is not None: pulumi.set(__self__, "default_actions", default_actions) if load_balancer_arn is not None: pulumi.set(__self__, "load_balancer_arn", load_balancer_arn) if port is not None: pulumi.set(__self__, "port", port) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if ssl_policy is not None: pulumi.set(__self__, "ssl_policy", ssl_policy) if tags is not None: pulumi.set(__self__, "tags", tags) if tags_all is not None: pulumi.set(__self__, "tags_all", tags_all) @property @pulumi.getter(name="alpnPolicy") def alpn_policy(self) -> Optional[pulumi.Input[str]]: """ Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. """ return pulumi.get(self, "alpn_policy") @alpn_policy.setter def alpn_policy(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "alpn_policy", value) @property @pulumi.getter def arn(self) -> Optional[pulumi.Input[str]]: """ ARN of the target group. """ return pulumi.get(self, "arn") @arn.setter def arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "arn", value) @property @pulumi.getter(name="certificateArn") def certificate_arn(self) -> Optional[pulumi.Input[str]]: """ ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. """ return pulumi.get(self, "certificate_arn") @certificate_arn.setter def certificate_arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "certificate_arn", value) @property @pulumi.getter(name="defaultActions") def default_actions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]: """ Configuration block for default actions. Detailed below. """ return pulumi.get(self, "default_actions") @default_actions.setter def default_actions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]): pulumi.set(self, "default_actions", value) @property @pulumi.getter(name="loadBalancerArn") def load_balancer_arn(self) -> Optional[pulumi.Input[str]]: """ ARN of the load balancer. """ return pulumi.get(self, "load_balancer_arn") @load_balancer_arn.setter def load_balancer_arn(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "load_balancer_arn", value) @property @pulumi.getter def port(self) -> Optional[pulumi.Input[int]]: """ Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. """ return pulumi.get(self, "port") @port.setter def port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "port", value) @property @pulumi.getter def protocol(self) -> Optional[pulumi.Input[str]]: """ Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. """ return pulumi.get(self, "protocol") @protocol.setter def protocol(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "protocol", value) @property @pulumi.getter(name="sslPolicy") def ssl_policy(self) -> Optional[pulumi.Input[str]]: """ Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. """ return pulumi.get(self, "ssl_policy") @ssl_policy.setter def ssl_policy(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ssl_policy", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter(name="tagsAll") def tags_all(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. """ return pulumi.get(self, "tags_all") @tags_all.setter def tags_all(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags_all", value) class Listener(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, alpn_policy: Optional[pulumi.Input[str]] = None, certificate_arn: Optional[pulumi.Input[str]] = None, default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None, load_balancer_arn: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, protocol: Optional[pulumi.Input[str]] = None, ssl_policy: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ Provides a Load Balancer Listener resource. > **Note:** `alb.Listener` is known as `lb.Listener`. The functionality is identical. ## Example Usage ### Forward Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=443, protocol="HTTPS", ssl_policy="ELBSecurityPolicy-2016-08", certificate_arn="arn:aws:iam::187416307283:server-certificate/test_cert_rab3wuqwgja25ct3n4jdj2tzu4", default_actions=[aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, )]) ``` To a NLB: ```python import pulumi import pulumi_aws as aws front_end = aws.lb.Listener("frontEnd", load_balancer_arn=aws_lb["front_end"]["arn"], port=443, protocol="TLS", certificate_arn="arn:aws:iam::187416307283:server-certificate/test_cert_rab3wuqwgja25ct3n4jdj2tzu4", alpn_policy="HTTP2Preferred", default_actions=[aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=aws_lb_target_group["front_end"]["arn"], )]) ``` ### Redirect Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[aws.lb.ListenerDefaultActionArgs( type="redirect", redirect=aws.lb.ListenerDefaultActionRedirectArgs( port="443", protocol="HTTPS", status_code="HTTP_301", ), )]) ``` ### Fixed-response Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[aws.lb.ListenerDefaultActionArgs( type="fixed-response", fixed_response=aws.lb.ListenerDefaultActionFixedResponseArgs( content_type="text/plain", message_body="Fixed response content", status_code="200", ), )]) ``` ### Authenticate-cognito Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... pool = aws.cognito.UserPool("pool") # ... client = aws.cognito.UserPoolClient("client") # ... domain = aws.cognito.UserPoolDomain("domain") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[ aws.lb.ListenerDefaultActionArgs( type="authenticate-cognito", authenticate_cognito=aws.lb.ListenerDefaultActionAuthenticateCognitoArgs( user_pool_arn=pool.arn, user_pool_client_id=client.id, user_pool_domain=domain.domain, ), ), aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, ), ]) ``` ### Authenticate-OIDC Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[ aws.lb.ListenerDefaultActionArgs( type="authenticate-oidc", authenticate_oidc=aws.lb.ListenerDefaultActionAuthenticateOidcArgs( authorization_endpoint="https://example.com/authorization_endpoint", client_id="client_id", client_secret="client_secret", issuer="https://example.com", token_endpoint="https://example.com/token_endpoint", user_info_endpoint="https://example.com/user_info_endpoint", ), ), aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, ), ]) ``` ### Gateway Load Balancer Listener ```python import pulumi import pulumi_aws as aws example_load_balancer = aws.lb.LoadBalancer("exampleLoadBalancer", load_balancer_type="gateway", subnet_mappings=[aws.lb.LoadBalancerSubnetMappingArgs( subnet_id=aws_subnet["example"]["id"], )]) example_target_group = aws.lb.TargetGroup("exampleTargetGroup", port=6081, protocol="GENEVE", vpc_id=aws_vpc["example"]["id"], health_check=aws.lb.TargetGroupHealthCheckArgs( port="80", protocol="HTTP", )) example_listener = aws.lb.Listener("exampleListener", load_balancer_arn=example_load_balancer.id, default_actions=[aws.lb.ListenerDefaultActionArgs( target_group_arn=example_target_group.id, type="forward", )]) ``` ## Import Listeners can be imported using their ARN, e.g. ```sh $ pulumi import aws:alb/listener:Listener front_end arn:aws:elasticloadbalancing:us-west-2:187416307283:listener/app/front-end-alb/8e4497da625e2d8a/9ab28ade35828f96 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] alpn_policy: Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. :param pulumi.Input[str] certificate_arn: ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]] default_actions: Configuration block for default actions. Detailed below. :param pulumi.Input[str] load_balancer_arn: ARN of the load balancer. :param pulumi.Input[int] port: Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. :param pulumi.Input[str] protocol: Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. :param pulumi.Input[str] ssl_policy: Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. """ ... @overload def __init__(__self__, resource_name: str, args: ListenerArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Provides a Load Balancer Listener resource. > **Note:** `alb.Listener` is known as `lb.Listener`. The functionality is identical. ## Example Usage ### Forward Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=443, protocol="HTTPS", ssl_policy="ELBSecurityPolicy-2016-08", certificate_arn="arn:aws:iam::187416307283:server-certificate/test_cert_rab3wuqwgja25ct3n4jdj2tzu4", default_actions=[aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, )]) ``` To a NLB: ```python import pulumi import pulumi_aws as aws front_end = aws.lb.Listener("frontEnd", load_balancer_arn=aws_lb["front_end"]["arn"], port=443, protocol="TLS", certificate_arn="arn:aws:iam::187416307283:server-certificate/test_cert_rab3wuqwgja25ct3n4jdj2tzu4", alpn_policy="HTTP2Preferred", default_actions=[aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=aws_lb_target_group["front_end"]["arn"], )]) ``` ### Redirect Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[aws.lb.ListenerDefaultActionArgs( type="redirect", redirect=aws.lb.ListenerDefaultActionRedirectArgs( port="443", protocol="HTTPS", status_code="HTTP_301", ), )]) ``` ### Fixed-response Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[aws.lb.ListenerDefaultActionArgs( type="fixed-response", fixed_response=aws.lb.ListenerDefaultActionFixedResponseArgs( content_type="text/plain", message_body="Fixed response content", status_code="200", ), )]) ``` ### Authenticate-cognito Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... pool = aws.cognito.UserPool("pool") # ... client = aws.cognito.UserPoolClient("client") # ... domain = aws.cognito.UserPoolDomain("domain") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[ aws.lb.ListenerDefaultActionArgs( type="authenticate-cognito", authenticate_cognito=aws.lb.ListenerDefaultActionAuthenticateCognitoArgs( user_pool_arn=pool.arn, user_pool_client_id=client.id, user_pool_domain=domain.domain, ), ), aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, ), ]) ``` ### Authenticate-OIDC Action ```python import pulumi import pulumi_aws as aws front_end_load_balancer = aws.lb.LoadBalancer("frontEndLoadBalancer") # ... front_end_target_group = aws.lb.TargetGroup("frontEndTargetGroup") # ... front_end_listener = aws.lb.Listener("frontEndListener", load_balancer_arn=front_end_load_balancer.arn, port=80, protocol="HTTP", default_actions=[ aws.lb.ListenerDefaultActionArgs( type="authenticate-oidc", authenticate_oidc=aws.lb.ListenerDefaultActionAuthenticateOidcArgs( authorization_endpoint="https://example.com/authorization_endpoint", client_id="client_id", client_secret="client_secret", issuer="https://example.com", token_endpoint="https://example.com/token_endpoint", user_info_endpoint="https://example.com/user_info_endpoint", ), ), aws.lb.ListenerDefaultActionArgs( type="forward", target_group_arn=front_end_target_group.arn, ), ]) ``` ### Gateway Load Balancer Listener ```python import pulumi import pulumi_aws as aws example_load_balancer = aws.lb.LoadBalancer("exampleLoadBalancer", load_balancer_type="gateway", subnet_mappings=[aws.lb.LoadBalancerSubnetMappingArgs( subnet_id=aws_subnet["example"]["id"], )]) example_target_group = aws.lb.TargetGroup("exampleTargetGroup", port=6081, protocol="GENEVE", vpc_id=aws_vpc["example"]["id"], health_check=aws.lb.TargetGroupHealthCheckArgs( port="80", protocol="HTTP", )) example_listener = aws.lb.Listener("exampleListener", load_balancer_arn=example_load_balancer.id, default_actions=[aws.lb.ListenerDefaultActionArgs( target_group_arn=example_target_group.id, type="forward", )]) ``` ## Import Listeners can be imported using their ARN, e.g. ```sh $ pulumi import aws:alb/listener:Listener front_end arn:aws:elasticloadbalancing:us-west-2:187416307283:listener/app/front-end-alb/8e4497da625e2d8a/9ab28ade35828f96 ``` :param str resource_name: The name of the resource. :param ListenerArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ListenerArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, alpn_policy: Optional[pulumi.Input[str]] = None, certificate_arn: Optional[pulumi.Input[str]] = None, default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None, load_balancer_arn: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, protocol: Optional[pulumi.Input[str]] = None, ssl_policy: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ListenerArgs.__new__(ListenerArgs) __props__.__dict__["alpn_policy"] = alpn_policy __props__.__dict__["certificate_arn"] = certificate_arn if default_actions is None and not opts.urn: raise TypeError("Missing required property 'default_actions'") __props__.__dict__["default_actions"] = default_actions if load_balancer_arn is None and not opts.urn: raise TypeError("Missing required property 'load_balancer_arn'") __props__.__dict__["load_balancer_arn"] = load_balancer_arn __props__.__dict__["port"] = port __props__.__dict__["protocol"] = protocol __props__.__dict__["ssl_policy"] = ssl_policy __props__.__dict__["tags"] = tags __props__.__dict__["arn"] = None __props__.__dict__["tags_all"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="aws:applicationloadbalancing/listener:Listener")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Listener, __self__).__init__( 'aws:alb/listener:Listener', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, alpn_policy: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, certificate_arn: Optional[pulumi.Input[str]] = None, default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None, load_balancer_arn: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, protocol: Optional[pulumi.Input[str]] = None, ssl_policy: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None) -> 'Listener': """ Get an existing Listener resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] alpn_policy: Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. :param pulumi.Input[str] arn: ARN of the target group. :param pulumi.Input[str] certificate_arn: ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]] default_actions: Configuration block for default actions. Detailed below. :param pulumi.Input[str] load_balancer_arn: ARN of the load balancer. :param pulumi.Input[int] port: Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. :param pulumi.Input[str] protocol: Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. :param pulumi.Input[str] ssl_policy: Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags_all: A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _ListenerState.__new__(_ListenerState) __props__.__dict__["alpn_policy"] = alpn_policy __props__.__dict__["arn"] = arn __props__.__dict__["certificate_arn"] = certificate_arn __props__.__dict__["default_actions"] = default_actions __props__.__dict__["load_balancer_arn"] = load_balancer_arn __props__.__dict__["port"] = port __props__.__dict__["protocol"] = protocol __props__.__dict__["ssl_policy"] = ssl_policy __props__.__dict__["tags"] = tags __props__.__dict__["tags_all"] = tags_all return Listener(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="alpnPolicy") def alpn_policy(self) -> pulumi.Output[Optional[str]]: """ Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if `protocol` is `TLS`. Valid values are `HTTP1Only`, `HTTP2Only`, `HTTP2Optional`, `HTTP2Preferred`, and `None`. """ return pulumi.get(self, "alpn_policy") @property @pulumi.getter def arn(self) -> pulumi.Output[str]: """ ARN of the target group. """ return pulumi.get(self, "arn") @property @pulumi.getter(name="certificateArn") def certificate_arn(self) -> pulumi.Output[Optional[str]]: """ ARN of the default SSL server certificate. Exactly one certificate is required if the protocol is HTTPS. For adding additional SSL certificates, see the `lb.ListenerCertificate` resource. """ return pulumi.get(self, "certificate_arn") @property @pulumi.getter(name="defaultActions") def default_actions(self) -> pulumi.Output[Sequence['outputs.ListenerDefaultAction']]: """ Configuration block for default actions. Detailed below. """ return pulumi.get(self, "default_actions") @property @pulumi.getter(name="loadBalancerArn") def load_balancer_arn(self) -> pulumi.Output[str]: """ ARN of the load balancer. """ return pulumi.get(self, "load_balancer_arn") @property @pulumi.getter def port(self) -> pulumi.Output[Optional[int]]: """ Port. Specify a value from `1` to `65535` or `#{port}`. Defaults to `#{port}`. """ return pulumi.get(self, "port") @property @pulumi.getter def protocol(self) -> pulumi.Output[str]: """ Protocol. Valid values are `HTTP`, `HTTPS`, or `#{protocol}`. Defaults to `#{protocol}`. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="sslPolicy") def ssl_policy(self) -> pulumi.Output[str]: """ Name of the SSL Policy for the listener. Required if `protocol` is `HTTPS` or `TLS`. """ return pulumi.get(self, "ssl_policy") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ A map of tags to assign to the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. """ return pulumi.get(self, "tags") @property @pulumi.getter(name="tagsAll") def tags_all(self) -> pulumi.Output[Mapping[str, str]]: """ A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. """ return pulumi.get(self, "tags_all")
44.529089
258
0.6237
e1fb5cb431a5f274e61cd65b4964c085b1f6715e
2,502
py
Python
examples/issue_asset.py
Shaptic/py-stellar-base
f5fa47f4d96f215889d99249fb25c7be002f5cf3
[ "Apache-2.0" ]
null
null
null
examples/issue_asset.py
Shaptic/py-stellar-base
f5fa47f4d96f215889d99249fb25c7be002f5cf3
[ "Apache-2.0" ]
27
2022-01-12T10:55:38.000Z
2022-03-28T01:38:24.000Z
examples/issue_asset.py
Shaptic/py-stellar-base
f5fa47f4d96f215889d99249fb25c7be002f5cf3
[ "Apache-2.0" ]
null
null
null
""" This example shows how to issue assets on the Stellar network. # See: https://developers.stellar.org/docs/issuing-assets/ """ from stellar_sdk.asset import Asset from stellar_sdk.keypair import Keypair from stellar_sdk.network import Network from stellar_sdk.server import Server from stellar_sdk.transaction_builder import TransactionBuilder # Configure StellarSdk to talk to the horizon instance hosted by Stellar.org # To use the live network, set the hostname to 'horizon.stellar.org' server = Server(horizon_url="https://horizon-testnet.stellar.org") # Keys for accounts to issue and receive the new asset issuing_keypair = Keypair.from_secret( "SCBHQEGSNBTT4S7Y73YAF3M3JSVSTSNBGAVU5M4XVFGUF7664EUXQHFU" ) issuing_public = issuing_keypair.public_key distributor_keypair = Keypair.from_secret( "SB6MJ6M3BPJZUGFP2QCODUIKWQWF6AIN4Z6L3J6PWL3QGDW4L6YR3QIU" ) distributor_public = distributor_keypair.public_key # Transactions require a valid sequence number that is specific to this account. # We can fetch the current sequence number for the source account from Horizon. distributor_account = server.load_account(distributor_public) # Create an object to represent the new asset hello_asset = Asset("Hello", issuing_public) # First, the receiving account must trust the asset trust_transaction = ( TransactionBuilder( source_account=distributor_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100, ) .append_change_trust_op(asset=hello_asset) .set_timeout(30) .build() ) trust_transaction.sign(distributor_keypair) resp = server.submit_transaction(trust_transaction) print(f"Change Trust Op Resp:\n{resp}") print("-" * 32) issuing_account = server.load_account(issuing_public) # Second, the issuing account actually sends a payment using the asset. # We recommend that you use the distribution account to distribute assets and # add more security measures to the issue account. Other acceptances should also # add a trust line to accept assets like the distribution account. payment_transaction = ( TransactionBuilder( source_account=issuing_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100, ) .append_payment_op(destination=distributor_public, amount="1000", asset=hello_asset) .set_timeout(30) .build() ) payment_transaction.sign(issuing_keypair) resp = server.submit_transaction(payment_transaction) print(f"Payment Op Resp:\n{resp}")
35.742857
88
0.792566
21c5d89c63d7a0a6d605058bcfb5a6dfa42f3298
29
py
Python
public/assets/pythonscript.py
meiningerj/FoundationLearning
45170408c041b1f41902eefde07b6493a6e337e1
[ "Apache-2.0" ]
null
null
null
public/assets/pythonscript.py
meiningerj/FoundationLearning
45170408c041b1f41902eefde07b6493a6e337e1
[ "Apache-2.0" ]
null
null
null
public/assets/pythonscript.py
meiningerj/FoundationLearning
45170408c041b1f41902eefde07b6493a6e337e1
[ "Apache-2.0" ]
null
null
null
import sys exec(sys.argv[1])
9.666667
17
0.724138
98853e5c7a15b881c9223305e874379f3945b318
2,064
py
Python
bin/githubapi.py
eddo888/Steppenwolf
71a00515e1a8cc21a0a402977bacf20e7929c7cc
[ "MIT" ]
null
null
null
bin/githubapi.py
eddo888/Steppenwolf
71a00515e1a8cc21a0a402977bacf20e7929c7cc
[ "MIT" ]
null
null
null
bin/githubapi.py
eddo888/Steppenwolf
71a00515e1a8cc21a0a402977bacf20e7929c7cc
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK import os, re, sys from github import Github from Argumental.Argue import Argue from Spanners.Squirrel import Squirrel args=Argue() squirrel=Squirrel() @args.command(single=True) class GitHubAPI(object): @args.property(default='github.com') def hostname(self): return @args.property(default='pypi') def tokename(self): return def __init__(self): token=squirrel.get('%s:%s'%(self.hostname, self.tokename)) self.github = Github(token) @args.operation def list(self): for repo in self.github.get_user().get_repos(): print(repo.full_name) @args.operation @args.parameter(name='new_tag', short='t', help='tag label') @args.parameter(name='repo_name', short='r', help='select repository') @args.parameter(name='tag_message', short='m', help='tag message') def release(self, new_tag=None, repo_name=None, tag_message=None): if not new_tag: pattern = re.compile('^version\s*=\s*[\'\"]([0-9\.]*)[\'\"].*$') with open('setup.py') as input: for line in input.readlines(): match = pattern.match(line) if match: new_tag = match.group(1) break print('requested tag = %s'%new_tag) repo_name = repo_name or os.path.basename(os.getcwd()) print('requested repo = %s'%repo_name) repo = self.github.get_user().get_repo(repo_name) print('repository found = %s'%repo.name) found = None for tag in repo.get_tags(): if tag.name == new_tag: found = tag break if found: tag = found print('existing tag = %s'%tag.name) sha = tag.commit.sha else: head = repo.get_commits()[0] print('using commit sha = %s'%head.sha) tag = repo.create_git_tag(new_tag, tag_message or new_tag, head.sha, 'commit') print('created tag = %s'%tag.tag) sha = tag.sha ref = repo.create_git_ref('refs/tags/%s'%tag.tag, tag.sha) release = repo.create_git_release(new_tag, new_tag, tag_message or new_tag,) print('release created = %s'%release.title) if __name__ == '__main__': args.execute()
24.282353
81
0.667636
46d23587683846f898e87b5fa2f97d6d2c9778e2
19,685
py
Python
pandas/core/nanops.py
nipunreddevil/pandas
08b1b3edf9d470e804226927701954a39a73ab98
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
1
2021-07-06T23:36:28.000Z
2021-07-06T23:36:28.000Z
pandas/core/nanops.py
thorwhalen/pandas
bfd5348d824a721dd0d896bb06e63e4ad801ba51
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
pandas/core/nanops.py
thorwhalen/pandas
bfd5348d824a721dd0d896bb06e63e4ad801ba51
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
from pandas import compat import sys import itertools import functools import numpy as np from pandas.core.common import isnull, notnull, _values_from_object, is_float import pandas.core.common as com import pandas.lib as lib import pandas.algos as algos import pandas.hashtable as _hash import pandas.tslib as tslib from pandas.compat import builtins try: import bottleneck as bn _USE_BOTTLENECK = True except ImportError: # pragma: no cover _USE_BOTTLENECK = False class disallow(object): def __init__(self, *dtypes): super(disallow, self).__init__() self.dtypes = tuple(np.dtype(dtype).type for dtype in dtypes) def check(self, obj): return hasattr(obj, 'dtype') and issubclass(obj.dtype.type, self.dtypes) def __call__(self, f): @functools.wraps(f) def _f(*args, **kwargs): obj_iter = itertools.chain(args, compat.itervalues(kwargs)) if any(self.check(obj) for obj in obj_iter): raise TypeError('reduction operation {0!r} not allowed for ' 'this dtype'.format(f.__name__.replace('nan', ''))) return f(*args, **kwargs) return _f class bottleneck_switch(object): def __init__(self, zero_value=None, **kwargs): self.zero_value = zero_value self.kwargs = kwargs def __call__(self, alt): bn_name = alt.__name__ try: bn_func = getattr(bn, bn_name) except (AttributeError, NameError): # pragma: no cover bn_func = None @functools.wraps(alt) def f(values, axis=None, skipna=True, **kwds): if len(self.kwargs) > 0: for k, v in compat.iteritems(self.kwargs): if k not in kwds: kwds[k] = v try: if self.zero_value is not None and values.size == 0: if values.ndim == 1: return 0 else: result_shape = (values.shape[:axis] + values.shape[axis + 1:]) result = np.empty(result_shape) result.fill(0) return result if _USE_BOTTLENECK and skipna and _bn_ok_dtype(values.dtype, bn_name): result = bn_func(values, axis=axis, **kwds) # prefer to treat inf/-inf as NA, but must compute the func # twice :( if _has_infs(result): result = alt(values, axis=axis, skipna=skipna, **kwds) else: result = alt(values, axis=axis, skipna=skipna, **kwds) except Exception: result = alt(values, axis=axis, skipna=skipna, **kwds) return result return f def _bn_ok_dtype(dt, name): # Bottleneck chokes on datetime64 if dt != np.object_ and not issubclass(dt.type, (np.datetime64, np.timedelta64)): # bottleneck does not properly upcast during the sum # so can overflow if name == 'nansum': if dt.itemsize < 8: return False return True return False def _has_infs(result): if isinstance(result, np.ndarray): if result.dtype == 'f8': return lib.has_infs_f8(result) elif result.dtype == 'f4': return lib.has_infs_f4(result) return False return np.isinf(result) or np.isneginf(result) def _get_fill_value(dtype, fill_value=None, fill_value_typ=None): """ return the correct fill value for the dtype of the values """ if fill_value is not None: return fill_value if _na_ok_dtype(dtype): if fill_value_typ is None: return np.nan else: if fill_value_typ == '+inf': return np.inf else: return -np.inf else: if fill_value_typ is None: return tslib.iNaT else: if fill_value_typ == '+inf': # need the max int here return np.iinfo(np.int64).max else: return tslib.iNaT def _get_values(values, skipna, fill_value=None, fill_value_typ=None, isfinite=False, copy=True): """ utility to get the values view, mask, dtype if necessary copy and mask using the specified fill_value copy = True will force the copy """ values = _values_from_object(values) if isfinite: mask = _isfinite(values) else: mask = isnull(values) dtype = values.dtype dtype_ok = _na_ok_dtype(dtype) # get our fill value (in case we need to provide an alternative # dtype for it) fill_value = _get_fill_value(dtype, fill_value=fill_value, fill_value_typ=fill_value_typ) if skipna: if copy: values = values.copy() if dtype_ok: np.putmask(values, mask, fill_value) # promote if needed else: values, changed = com._maybe_upcast_putmask(values, mask, fill_value) elif copy: values = values.copy() values = _view_if_needed(values) # return a platform independent precision dtype dtype_max = dtype if dtype.kind == 'i' and not issubclass( dtype.type, (np.bool, np.datetime64, np.timedelta64)): dtype_max = np.int64 elif dtype.kind in ['b'] or issubclass(dtype.type, np.bool): dtype_max = np.int64 elif dtype.kind in ['f']: dtype_max = np.float64 return values, mask, dtype, dtype_max def _isfinite(values): if issubclass(values.dtype.type, (np.timedelta64, np.datetime64)): return isnull(values) elif isinstance(values.dtype, object): return ~np.isfinite(values.astype('float64')) return ~np.isfinite(values) def _na_ok_dtype(dtype): return not issubclass(dtype.type, (np.integer, np.datetime64, np.timedelta64)) def _view_if_needed(values): if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): return values.view(np.int64) return values def _wrap_results(result, dtype): """ wrap our results if needed """ if issubclass(dtype.type, np.datetime64): if not isinstance(result, np.ndarray): result = lib.Timestamp(result) else: result = result.view(dtype) elif issubclass(dtype.type, np.timedelta64): if not isinstance(result, np.ndarray): # this is a scalar timedelta result! # we have series convert then take the element (scalar) # as series will do the right thing in py3 (and deal with numpy # 1.6.2 bug in that it results dtype of timedelta64[us] from pandas import Series # coerce float to results if is_float(result): result = int(result) result = Series([result], dtype='timedelta64[ns]') else: result = result.view(dtype) return result def nanany(values, axis=None, skipna=True): values, mask, dtype, _ = _get_values(values, skipna, False, copy=skipna) return values.any(axis) def nanall(values, axis=None, skipna=True): values, mask, dtype, _ = _get_values(values, skipna, True, copy=skipna) return values.all(axis) @disallow('M8') @bottleneck_switch(zero_value=0) def nansum(values, axis=None, skipna=True): values, mask, dtype, dtype_max = _get_values(values, skipna, 0) the_sum = values.sum(axis,dtype=dtype_max) the_sum = _maybe_null_out(the_sum, axis, mask) return _wrap_results(the_sum, dtype) @disallow('M8') @bottleneck_switch() def nanmean(values, axis=None, skipna=True): values, mask, dtype, dtype_max = _get_values(values, skipna, 0) the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_max)) count = _get_counts(mask, axis) if axis is not None: the_mean = the_sum / count ct_mask = count == 0 if ct_mask.any(): the_mean[ct_mask] = np.nan else: the_mean = the_sum / count if count > 0 else np.nan return _wrap_results(the_mean, dtype) @disallow('M8') @bottleneck_switch() def nanmedian(values, axis=None, skipna=True): values, mask, dtype, dtype_max = _get_values(values, skipna) def get_median(x): mask = notnull(x) if not skipna and not mask.all(): return np.nan return algos.median(_values_from_object(x[mask])) if values.dtype != np.float64: values = values.astype('f8') notempty = values.size # an array from a frame if values.ndim > 1: # there's a non-empty array to apply over otherwise numpy raises if notempty: return np.apply_along_axis(get_median, axis, values) # must return the correct shape, but median is not defined for the # empty set so return nans of shape "everything but the passed axis" # since "axis" is where the reduction would occur if we had a nonempty # array shp = np.array(values.shape) dims = np.arange(values.ndim) ret = np.empty(shp[dims != axis]) ret.fill(np.nan) return ret # otherwise return a scalar value return _wrap_results(get_median(values), dtype) if notempty else np.nan @disallow('M8') @bottleneck_switch(ddof=1) def nanvar(values, axis=None, skipna=True, ddof=1): if not isinstance(values.dtype.type, np.floating): values = values.astype('f8') mask = isnull(values) if axis is not None: count = (values.shape[axis] - mask.sum(axis)).astype(float) else: count = float(values.size - mask.sum()) d = count-ddof if skipna: values = values.copy() np.putmask(values, mask, 0) # always return NaN, never inf if np.isscalar(count): if count <= ddof: count = np.nan d = np.nan else: mask = count <= ddof if mask.any(): np.putmask(d, mask, np.nan) np.putmask(count, mask, np.nan) X = _ensure_numeric(values.sum(axis)) XX = _ensure_numeric((values ** 2).sum(axis)) return np.fabs((XX - X ** 2 / count) / d) @bottleneck_switch() def nanmin(values, axis=None, skipna=True): values, mask, dtype, dtype_max = _get_values(values, skipna, fill_value_typ='+inf') # numpy 1.6.1 workaround in Python 3.x if (values.dtype == np.object_ and compat.PY3): if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(builtins.min, apply_ax, values) else: try: result = builtins.min(values) except: result = np.nan else: if ((axis is not None and values.shape[axis] == 0) or values.size == 0): try: result = com.ensure_float(values.sum(axis,dtype=dtype_max)) result.fill(np.nan) except: result = np.nan else: result = values.min(axis) result = _wrap_results(result, dtype) return _maybe_null_out(result, axis, mask) @bottleneck_switch() def nanmax(values, axis=None, skipna=True): values, mask, dtype, dtype_max = _get_values(values, skipna, fill_value_typ='-inf') # numpy 1.6.1 workaround in Python 3.x if (values.dtype == np.object_ and compat.PY3): if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(builtins.max, apply_ax, values) else: try: result = builtins.max(values) except: result = np.nan else: if ((axis is not None and values.shape[axis] == 0) or values.size == 0): try: result = com.ensure_float(values.sum(axis, dtype=dtype_max)) result.fill(np.nan) except: result = np.nan else: result = values.max(axis) result = _wrap_results(result, dtype) return _maybe_null_out(result, axis, mask) def nanargmax(values, axis=None, skipna=True): """ Returns -1 in the NA case """ values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='-inf', isfinite=True) result = values.argmax(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return result def nanargmin(values, axis=None, skipna=True): """ Returns -1 in the NA case """ values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='+inf', isfinite=True) result = values.argmin(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return result @disallow('M8') def nanskew(values, axis=None, skipna=True): if not isinstance(values.dtype.type, np.floating): values = values.astype('f8') mask = isnull(values) count = _get_counts(mask, axis) if skipna: values = values.copy() np.putmask(values, mask, 0) A = values.sum(axis) / count B = (values ** 2).sum(axis) / count - A ** 2 C = (values ** 3).sum(axis) / count - A ** 3 - 3 * A * B # floating point error B = _zero_out_fperr(B) C = _zero_out_fperr(C) result = ((np.sqrt((count ** 2 - count)) * C) / ((count - 2) * np.sqrt(B) ** 3)) if isinstance(result, np.ndarray): result = np.where(B == 0, 0, result) result[count < 3] = np.nan return result else: result = 0 if B == 0 else result if count < 3: return np.nan return result @disallow('M8') def nankurt(values, axis=None, skipna=True): if not isinstance(values.dtype.type, np.floating): values = values.astype('f8') mask = isnull(values) count = _get_counts(mask, axis) if skipna: values = values.copy() np.putmask(values, mask, 0) A = values.sum(axis) / count B = (values ** 2).sum(axis) / count - A ** 2 C = (values ** 3).sum(axis) / count - A ** 3 - 3 * A * B D = (values ** 4).sum(axis) / count - A ** 4 - 6 * B * A * A - 4 * C * A B = _zero_out_fperr(B) C = _zero_out_fperr(C) D = _zero_out_fperr(D) result = (((count * count - 1.) * D / (B * B) - 3 * ((count - 1.) ** 2)) / ((count - 2.) * (count - 3.))) if isinstance(result, np.ndarray): result = np.where(B == 0, 0, result) result[count < 4] = np.nan return result else: result = 0 if B == 0 else result if count < 4: return np.nan return result @disallow('M8') def nanprod(values, axis=None, skipna=True): mask = isnull(values) if skipna and not issubclass(values.dtype.type, np.integer): values = values.copy() values[mask] = 1 result = values.prod(axis) return _maybe_null_out(result, axis, mask) def _maybe_arg_null_out(result, axis, mask, skipna): # helper function for nanargmin/nanargmax if axis is None: if skipna: if mask.all(): result = -1 else: if mask.any(): result = -1 else: if skipna: na_mask = mask.all(axis) else: na_mask = mask.any(axis) if na_mask.any(): result[na_mask] = -1 return result def _get_counts(mask, axis): if axis is not None: count = (mask.shape[axis] - mask.sum(axis)).astype(float) else: count = float(mask.size - mask.sum()) return count def _maybe_null_out(result, axis, mask): if axis is not None: null_mask = (mask.shape[axis] - mask.sum(axis)) == 0 if null_mask.any(): result = result.astype('f8') result[null_mask] = np.nan else: null_mask = mask.size - mask.sum() if null_mask == 0: result = np.nan return result def _zero_out_fperr(arg): if isinstance(arg, np.ndarray): return np.where(np.abs(arg) < 1e-14, 0, arg) else: return 0 if np.abs(arg) < 1e-14 else arg @disallow('M8') def nancorr(a, b, method='pearson', min_periods=None): """ a, b: ndarrays """ if len(a) != len(b): raise AssertionError('Operands to nancorr must have same size') if min_periods is None: min_periods = 1 valid = notnull(a) & notnull(b) if not valid.all(): a = a[valid] b = b[valid] if len(a) < min_periods: return np.nan f = get_corr_func(method) return f(a, b) def get_corr_func(method): if method in ['kendall', 'spearman']: from scipy.stats import kendalltau, spearmanr def _pearson(a, b): return np.corrcoef(a, b)[0, 1] def _kendall(a, b): rs = kendalltau(a, b) if isinstance(rs, tuple): return rs[0] return rs def _spearman(a, b): return spearmanr(a, b)[0] _cor_methods = { 'pearson': _pearson, 'kendall': _kendall, 'spearman': _spearman } return _cor_methods[method] @disallow('M8') def nancov(a, b, min_periods=None): if len(a) != len(b): raise AssertionError('Operands to nancov must have same size') if min_periods is None: min_periods = 1 valid = notnull(a) & notnull(b) if not valid.all(): a = a[valid] b = b[valid] if len(a) < min_periods: return np.nan return np.cov(a, b)[0, 1] def _ensure_numeric(x): if isinstance(x, np.ndarray): if x.dtype == np.object_: x = x.astype(np.float64) elif not (com.is_float(x) or com.is_integer(x) or com.is_complex(x)): try: x = float(x) except Exception: try: x = complex(x) except Exception: raise TypeError('Could not convert %s to numeric' % str(x)) return x # NA-friendly array comparisons import operator def make_nancomp(op): def f(x, y): xmask = isnull(x) ymask = isnull(y) mask = xmask | ymask result = op(x, y) if mask.any(): if result.dtype == np.bool_: result = result.astype('O') np.putmask(result, mask, np.nan) return result return f nangt = make_nancomp(operator.gt) nange = make_nancomp(operator.ge) nanlt = make_nancomp(operator.lt) nanle = make_nancomp(operator.le) naneq = make_nancomp(operator.eq) nanne = make_nancomp(operator.ne) def unique1d(values): """ Hash table-based unique """ if np.issubdtype(values.dtype, np.floating): table = _hash.Float64HashTable(len(values)) uniques = np.array(table.unique(com._ensure_float64(values)), dtype=np.float64) elif np.issubdtype(values.dtype, np.datetime64): table = _hash.Int64HashTable(len(values)) uniques = table.unique(com._ensure_int64(values)) uniques = uniques.view('M8[ns]') elif np.issubdtype(values.dtype, np.integer): table = _hash.Int64HashTable(len(values)) uniques = table.unique(com._ensure_int64(values)) else: table = _hash.PyObjectHashTable(len(values)) uniques = table.unique(com._ensure_object(values)) return uniques
28.948529
87
0.576988
0c362cc89037e609498fbae05681c48872b002c0
1,460
py
Python
Module03/assignment3-1.py
kholt90/DataStruct
acc42358f27ec4bac15b87e2bfd53b5843d592b6
[ "Unlicense" ]
null
null
null
Module03/assignment3-1.py
kholt90/DataStruct
acc42358f27ec4bac15b87e2bfd53b5843d592b6
[ "Unlicense" ]
null
null
null
Module03/assignment3-1.py
kholt90/DataStruct
acc42358f27ec4bac15b87e2bfd53b5843d592b6
[ "Unlicense" ]
null
null
null
# You want to build a word cloud, an infographic where the size of a word corresponds to how often it appears in the body of text. # To do this, you'll need data. # Write code that takes a long string and builds its word cloud data in a dictionary, where the keys are words and the values are the number of times the words occurred. # Think about capitalized words. # For example, look at these sentences: # 'After beating the eggs, Dana read the next step:' # 'Add milk and eggs, then add flour and sugar.' # What do we want to do with "After", "Dana", and "add"? # In this example, your final dictionary should include one "Add" or "add" with a value of 2. # Make reasonable (not necessarily perfect) decisions about cases like "After" and "Dana". # Assume the input will only contain words and standard punctuation. # You could make a reasonable argument to use regex in your solution. # We won't, mainly because performance is difficult to measure and can get pretty bad. print("\n-----===== Start =====-----\n") def WordCloud(the_string): the_data = {} the_string = the_string.lower().split() for i in the_string: if i in the_data: the_data[i] = the_data[i] + 1 else: the_data[i] = 1 return the_data long_string = "After beating the eggs, Dana read the next step: Add milk and eggs, then add flour and sugar." print(f"The String: {WordCloud(long_string)}") print("\n-----===== End =====-----")
45.625
169
0.693151
bd01ca3d3196075d44c2f616b3497fe4eace31f9
27,678
py
Python
magenta/music/melodies_lib_test.py
vaipatel/magenta
8a828116c2a73c26724204987d2b5bddaab31a7e
[ "Apache-2.0" ]
16
2016-09-02T04:59:30.000Z
2022-01-11T10:38:29.000Z
magenta/music/melodies_lib_test.py
Kiku-git/magenta
b36c65466745ff1e056dca40179ae71306a0ca5b
[ "Apache-2.0" ]
2
2016-09-25T16:39:59.000Z
2016-11-18T17:43:41.000Z
magenta/music/melodies_lib_test.py
Kiku-git/magenta
b36c65466745ff1e056dca40179ae71306a0ca5b
[ "Apache-2.0" ]
10
2016-09-02T04:59:32.000Z
2021-09-29T06:57:24.000Z
# Copyright 2019 The Magenta 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. """Tests for melodies_lib.""" import os from magenta.common import testing_lib as common_testing_lib from magenta.music import constants from magenta.music import melodies_lib from magenta.music import sequences_lib from magenta.music import testing_lib from magenta.protobuf import music_pb2 import tensorflow as tf NOTE_OFF = constants.MELODY_NOTE_OFF NO_EVENT = constants.MELODY_NO_EVENT class MelodiesLibTest(tf.test.TestCase): def setUp(self): self.steps_per_quarter = 4 self.note_sequence = common_testing_lib.parse_test_proto( music_pb2.NoteSequence, """ time_signatures: { numerator: 4 denominator: 4 } tempos: { qpm: 60 } """) def testGetNoteHistogram(self): events = [NO_EVENT, NOTE_OFF, 12 * 2 + 1, 12 * 3, 12 * 5 + 11, 12 * 6 + 3, 12 * 4 + 11] melody = melodies_lib.Melody(events) expected = [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2] self.assertEqual(expected, list(melody.get_note_histogram())) events = [0, 1, NO_EVENT, NOTE_OFF, 12 * 2 + 1, 12 * 3, 12 * 6 + 3, 12 * 5 + 11, NO_EVENT, 12 * 4 + 11, 12 * 7 + 1] melody = melodies_lib.Melody(events) expected = [2, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2] self.assertEqual(expected, list(melody.get_note_histogram())) melody = melodies_lib.Melody() expected = [0] * 12 self.assertEqual(expected, list(melody.get_note_histogram())) def testGetKeyHistogram(self): # One C. events = [NO_EVENT, 12 * 5, NOTE_OFF] melody = melodies_lib.Melody(events) expected = [1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0] self.assertListEqual(expected, list(melody.get_major_key_histogram())) # One C and one C#. events = [NO_EVENT, 12 * 5, NOTE_OFF, 12 * 7 + 1, NOTE_OFF] melody = melodies_lib.Melody(events) expected = [1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1] self.assertListEqual(expected, list(melody.get_major_key_histogram())) # One C, one C#, and one D. events = [NO_EVENT, 12 * 5, NOTE_OFF, 12 * 7 + 1, NO_EVENT, 12 * 9 + 2] melody = melodies_lib.Melody(events) expected = [2, 2, 2, 2, 1, 2, 1, 2, 2, 2, 2, 1] self.assertListEqual(expected, list(melody.get_major_key_histogram())) def testGetMajorKey(self): # D Major. events = [NO_EVENT, 12 * 2 + 2, 12 * 3 + 4, 12 * 5 + 1, 12 * 6 + 6, 12 * 4 + 11, 12 * 3 + 9, 12 * 5 + 7, NOTE_OFF] melody = melodies_lib.Melody(events) self.assertEqual(2, melody.get_major_key()) # C# Major with accidentals. events = [NO_EVENT, 12 * 2 + 1, 12 * 4 + 8, 12 * 5 + 5, 12 * 6 + 6, 12 * 3 + 3, 12 * 2 + 11, 12 * 3 + 10, 12 * 5, 12 * 2 + 8, 12 * 4 + 1, 12 * 3 + 5, 12 * 5 + 9, 12 * 4 + 3, NOTE_OFF] melody = melodies_lib.Melody(events) self.assertEqual(1, melody.get_major_key()) # One note in C Major. events = [NO_EVENT, 12 * 2 + 11, NOTE_OFF] melody = melodies_lib.Melody(events) self.assertEqual(0, melody.get_major_key()) def testTranspose(self): # Melody transposed down 5 half steps. 2 octave range. events = [12 * 5 + 4, NO_EVENT, 12 * 5 + 5, NOTE_OFF, 12 * 6, NO_EVENT] melody = melodies_lib.Melody(events) melody.transpose(transpose_amount=-5, min_note=12 * 5, max_note=12 * 7) expected = [12 * 5 + 11, NO_EVENT, 12 * 5, NOTE_OFF, 12 * 5 + 7, NO_EVENT] self.assertEqual(expected, list(melody)) # Melody transposed up 19 half steps. 2 octave range. events = [12 * 5 + 4, NO_EVENT, 12 * 5 + 5, NOTE_OFF, 12 * 6, NO_EVENT] melody = melodies_lib.Melody(events) melody.transpose(transpose_amount=19, min_note=12 * 5, max_note=12 * 7) expected = [12 * 6 + 11, NO_EVENT, 12 * 6, NOTE_OFF, 12 * 6 + 7, NO_EVENT] self.assertEqual(expected, list(melody)) # Melody transposed zero half steps. 1 octave range. events = [12 * 4 + 11, 12 * 5, 12 * 5 + 11, NOTE_OFF, 12 * 6, NO_EVENT] melody = melodies_lib.Melody(events) melody.transpose(transpose_amount=0, min_note=12 * 5, max_note=12 * 6) expected = [12 * 5 + 11, 12 * 5, 12 * 5 + 11, NOTE_OFF, 12 * 5, NO_EVENT] self.assertEqual(expected, list(melody)) def testSquash(self): # Melody in C, transposed to C, and squashed to 1 octave. events = [12 * 5, NO_EVENT, 12 * 5 + 2, NOTE_OFF, 12 * 6 + 4, NO_EVENT] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 5, max_note=12 * 6, transpose_to_key=0) expected = [12 * 5, NO_EVENT, 12 * 5 + 2, NOTE_OFF, 12 * 5 + 4, NO_EVENT] self.assertEqual(expected, list(melody)) # Melody in D, transposed to C, and squashed to 1 octave. events = [12 * 5 + 2, 12 * 5 + 4, 12 * 6 + 7, 12 * 6 + 6, 12 * 5 + 1] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 5, max_note=12 * 6, transpose_to_key=0) expected = [12 * 5, 12 * 5 + 2, 12 * 5 + 5, 12 * 5 + 4, 12 * 5 + 11] self.assertEqual(expected, list(melody)) # Melody in D, transposed to E, and squashed to 1 octave. events = [12 * 5 + 2, 12 * 5 + 4, 12 * 6 + 7, 12 * 6 + 6, 12 * 4 + 11] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 5, max_note=12 * 6, transpose_to_key=4) expected = [12 * 5 + 4, 12 * 5 + 6, 12 * 5 + 9, 12 * 5 + 8, 12 * 5 + 1] self.assertEqual(expected, list(melody)) def testSquashCenterOctaves(self): # Move up an octave. events = [12 * 4, NO_EVENT, 12 * 4 + 2, NOTE_OFF, 12 * 4 + 4, NO_EVENT, 12 * 4 + 5, 12 * 5 + 2, 12 * 4 - 1, NOTE_OFF] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 4, max_note=12 * 7, transpose_to_key=0) expected = [12 * 5, NO_EVENT, 12 * 5 + 2, NOTE_OFF, 12 * 5 + 4, NO_EVENT, 12 * 5 + 5, 12 * 6 + 2, 12 * 5 - 1, NOTE_OFF] self.assertEqual(expected, list(melody)) # Move down an octave. events = [12 * 6, NO_EVENT, 12 * 6 + 2, NOTE_OFF, 12 * 6 + 4, NO_EVENT, 12 * 6 + 5, 12 * 7 + 2, 12 * 6 - 1, NOTE_OFF] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 4, max_note=12 * 7, transpose_to_key=0) expected = [12 * 5, NO_EVENT, 12 * 5 + 2, NOTE_OFF, 12 * 5 + 4, NO_EVENT, 12 * 5 + 5, 12 * 6 + 2, 12 * 5 - 1, NOTE_OFF] self.assertEqual(expected, list(melody)) def testSquashMaxNote(self): events = [12 * 5, 12 * 5 + 2, 12 * 5 + 4, 12 * 5 + 5, 12 * 5 + 11, 12 * 6, 12 * 6 + 1] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 5, max_note=12 * 6, transpose_to_key=0) expected = [12 * 5, 12 * 5 + 2, 12 * 5 + 4, 12 * 5 + 5, 12 * 5 + 11, 12 * 5, 12 * 5 + 1] self.assertEqual(expected, list(melody)) def testSquashAllNotesOff(self): events = [NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT] melody = melodies_lib.Melody(events) melody.squash(min_note=12 * 4, max_note=12 * 7, transpose_to_key=0) self.assertEqual(events, list(melody)) def testFromQuantizedNoteSequence(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 0.01, 10.0), (11, 55, 0.22, 0.50), (40, 45, 2.50, 3.50), (55, 120, 4.0, 4.01), (52, 99, 4.75, 5.0)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0) expected = ([12, 11, NOTE_OFF, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 40, NO_EVENT, NO_EVENT, NO_EVENT, NOTE_OFF, NO_EVENT, 55, NOTE_OFF, NO_EVENT, 52]) self.assertEqual(expected, list(melody)) self.assertEqual(16, melody.steps_per_bar) def testFromQuantizedNoteSequenceNotCommonTimeSig(self): self.note_sequence.time_signatures[0].numerator = 7 self.note_sequence.time_signatures[0].denominator = 8 testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 0.01, 10.0), (11, 55, 0.22, 0.50), (40, 45, 2.50, 3.50), (55, 120, 4.0, 4.01), (52, 99, 4.75, 5.0)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0) expected = ([12, 11, NOTE_OFF, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 40, NO_EVENT, NO_EVENT, NO_EVENT, NOTE_OFF, NO_EVENT, 55, NOTE_OFF, NO_EVENT, 52]) self.assertEqual(expected, list(melody)) self.assertEqual(14, melody.steps_per_bar) def testFromNotesPolyphonic(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 0.0, 10.0), (11, 55, 0.0, 0.50)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() with self.assertRaises(melodies_lib.PolyphonicMelodyError): melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) self.assertFalse(list(melody)) def testFromNotesPolyphonicWithIgnorePolyphonicNotes(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 0.0, 2.0), (19, 100, 0.0, 3.0), (12, 100, 1.0, 3.0), (19, 100, 1.0, 4.0)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=True) expected = ([19] + [NO_EVENT] * 3 + [19] + [NO_EVENT] * 11) self.assertEqual(expected, list(melody)) self.assertEqual(16, melody.steps_per_bar) def testFromNotesChord(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 1, 1.25), (19, 100, 1, 1.25), (20, 100, 1, 1.25), (25, 100, 1, 1.25)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() with self.assertRaises(melodies_lib.PolyphonicMelodyError): melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) self.assertFalse(list(melody)) def testFromNotesTrimEmptyMeasures(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 1.5, 1.75), (11, 100, 2, 2.25)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) expected = [NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 12, NOTE_OFF, 11] self.assertEqual(expected, list(melody)) self.assertEqual(16, melody.steps_per_bar) def testFromNotesTimeOverlap(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 1, 2), (11, 100, 3.25, 3.75), (13, 100, 2, 4)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) expected = [NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 12, NO_EVENT, NO_EVENT, NO_EVENT, 13, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 11, NO_EVENT] self.assertEqual(expected, list(melody)) def testFromNotesStepsPerBar(self): self.note_sequence.time_signatures[0].numerator = 7 self.note_sequence.time_signatures[0].denominator = 8 quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=12) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) self.assertEqual(42, melody.steps_per_bar) def testFromNotesStartAndEndStep(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 1, 2), (11, 100, 2.25, 2.5), (13, 100, 3.25, 3.75), (14, 100, 8.75, 9), (15, 100, 9.25, 10.75)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, self.steps_per_quarter) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=18, instrument=0, ignore_polyphonic_notes=False) expected = [NO_EVENT, 14, NOTE_OFF, 15, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT] self.assertEqual(expected, list(melody)) self.assertEqual(34, melody.start_step) self.assertEqual(43, melody.end_step) def testSetLength(self): events = [60] melody = melodies_lib.Melody(events, start_step=9) melody.set_length(5) self.assertListEqual([60, NOTE_OFF, NO_EVENT, NO_EVENT, NO_EVENT], list(melody)) self.assertEqual(9, melody.start_step) self.assertEqual(14, melody.end_step) melody = melodies_lib.Melody(events, start_step=9) melody.set_length(5, from_left=True) self.assertListEqual([NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, 60], list(melody)) self.assertEqual(5, melody.start_step) self.assertEqual(10, melody.end_step) events = [60, NO_EVENT, NO_EVENT, NOTE_OFF] melody = melodies_lib.Melody(events) melody.set_length(3) self.assertListEqual([60, NO_EVENT, NO_EVENT], list(melody)) self.assertEqual(0, melody.start_step) self.assertEqual(3, melody.end_step) melody = melodies_lib.Melody(events) melody.set_length(3, from_left=True) self.assertListEqual([NO_EVENT, NO_EVENT, NOTE_OFF], list(melody)) self.assertEqual(1, melody.start_step) self.assertEqual(4, melody.end_step) def testToSequenceSimple(self): melody = melodies_lib.Melody( [NO_EVENT, 1, NO_EVENT, NOTE_OFF, NO_EVENT, 2, 3, NOTE_OFF, NO_EVENT]) sequence = melody.to_sequence( velocity=10, instrument=1, sequence_start_time=2, qpm=60.0) self.assertProtoEquals( 'ticks_per_quarter: 220 ' 'tempos < qpm: 60.0 > ' 'total_time: 3.75 ' 'notes < ' ' pitch: 1 velocity: 10 instrument: 1 start_time: 2.25 end_time: 2.75 ' '> ' 'notes < ' ' pitch: 2 velocity: 10 instrument: 1 start_time: 3.25 end_time: 3.5 ' '> ' 'notes < ' ' pitch: 3 velocity: 10 instrument: 1 start_time: 3.5 end_time: 3.75 ' '> ', sequence) def testToSequenceEndsWithSustainedNote(self): melody = melodies_lib.Melody( [NO_EVENT, 1, NO_EVENT, NOTE_OFF, NO_EVENT, 2, 3, NO_EVENT, NO_EVENT]) sequence = melody.to_sequence( velocity=100, instrument=0, sequence_start_time=0, qpm=60.0) self.assertProtoEquals( 'ticks_per_quarter: 220 ' 'tempos < qpm: 60.0 > ' 'total_time: 2.25 ' 'notes < pitch: 1 velocity: 100 start_time: 0.25 end_time: 0.75 > ' 'notes < pitch: 2 velocity: 100 start_time: 1.25 end_time: 1.5 > ' 'notes < pitch: 3 velocity: 100 start_time: 1.5 end_time: 2.25 > ', sequence) def testToSequenceEndsWithNonzeroStart(self): melody = melodies_lib.Melody([NO_EVENT, 1, NO_EVENT], start_step=4) sequence = melody.to_sequence( velocity=100, instrument=0, sequence_start_time=0.5, qpm=60.0) self.assertProtoEquals( 'ticks_per_quarter: 220 ' 'tempos < qpm: 60.0 > ' 'total_time: 2.25 ' 'notes < pitch: 1 velocity: 100 start_time: 1.75 end_time: 2.25 > ', sequence) def testToSequenceEmpty(self): melody = melodies_lib.Melody() sequence = melody.to_sequence( velocity=10, instrument=1, sequence_start_time=2, qpm=60.0) self.assertProtoEquals( 'ticks_per_quarter: 220 ' 'tempos < qpm: 60.0 > ', sequence) def testExtractMelodiesSimple(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 2, 4), (11, 1, 6, 7)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 9)]) testing_lib.add_track_to_sequence( self.note_sequence, 9, [(13, 100, 2, 4), (15, 25, 6, 8)], is_drum=True) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 11], [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True) self.assertEqual(2, len(melodies)) self.assertTrue(isinstance(melodies[0], melodies_lib.Melody)) self.assertTrue(isinstance(melodies[1], melodies_lib.Melody)) melodies = sorted([list(melody) for melody in melodies]) self.assertEqual(expected, melodies) def testExtractMultipleMelodiesFromSameTrack(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 2, 4), (11, 1, 6, 11)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 8), (50, 100, 33, 37), (52, 100, 34, 37)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 11, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT], [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT], [NO_EVENT, 50, 52, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=2, min_unique_pitches=2, ignore_polyphonic_notes=True) melodies = sorted([list(melody) for melody in melodies]) self.assertEqual(expected, melodies) def testExtractMelodiesMelodyTooShort(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 127, 2, 4), (14, 50, 6, 7)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 8)]) testing_lib.add_track_to_sequence( self.note_sequence, 2, [(12, 127, 2, 4), (14, 50, 6, 9)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT], [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=2, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True) melodies = [list(melody) for melody in melodies] self.assertEqual(expected, melodies) def testExtractMelodiesPadEnd(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 127, 2, 4), (14, 50, 6, 7)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 8)]) testing_lib.add_track_to_sequence( self.note_sequence, 2, [(12, 127, 2, 4), (14, 50, 6, 9)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NOTE_OFF], [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT], [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT, NO_EVENT, NOTE_OFF, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True, pad_end=True) melodies = [list(melody) for melody in melodies] self.assertEqual(expected, melodies) def testExtractMelodiesMelodyTooLong(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 127, 2, 4), (14, 50, 6, 15)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 18)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14] + [NO_EVENT] * 7, [NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14] + [NO_EVENT] * 7] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, max_steps_truncate=14, max_steps_discard=18, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True) melodies = [list(melody) for melody in melodies] self.assertEqual(expected, melodies) def testExtractMelodiesMelodyTooLongWithPad(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 127, 2, 4), (14, 50, 6, 15)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 6, 18)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 14, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, max_steps_truncate=14, max_steps_discard=18, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True, pad_end=True) melodies = [list(melody) for melody in melodies] self.assertEqual(expected, melodies) def testExtractMelodiesTooFewPitches(self): # Test that extract_melodies discards melodies with too few pitches where # pitches are equivalent by octave. testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 0, 1), (13, 100, 1, 2), (18, 100, 2, 3), (24, 100, 3, 4), (25, 100, 4, 5)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 100, 0, 1), (13, 100, 1, 2), (18, 100, 2, 3), (25, 100, 3, 4), (26, 100, 4, 5)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[12, 13, 18, 25, 26]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=1, min_unique_pitches=4, ignore_polyphonic_notes=True) melodies = [list(melody) for melody in melodies] self.assertEqual(expected, melodies) def testExtractMelodiesLateStart(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 102, 103), (13, 100, 104, 106)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 100, 100, 101), (13, 100, 102, 105)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) expected = [[NO_EVENT, NO_EVENT, 12, NOTE_OFF, 13, NO_EVENT], [12, NOTE_OFF, 13, NO_EVENT, NO_EVENT]] melodies, _ = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=True) melodies = sorted([list(melody) for melody in melodies]) self.assertEqual(expected, melodies) def testExtractMelodiesStatistics(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 2, 4), (11, 1, 6, 7), (10, 100, 8, 10), (9, 100, 11, 14), (8, 100, 16, 40), (7, 100, 41, 42)]) testing_lib.add_track_to_sequence( self.note_sequence, 1, [(12, 127, 2, 4), (14, 50, 2, 8)]) testing_lib.add_track_to_sequence( self.note_sequence, 2, [(12, 127, 0, 1)]) testing_lib.add_track_to_sequence( self.note_sequence, 3, [(12, 127, 2, 4), (12, 50, 6, 8)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) _, stats = melodies_lib.extract_melodies( quantized_sequence, min_bars=1, gap_bars=1, min_unique_pitches=2, ignore_polyphonic_notes=False) stats_dict = dict((stat.name, stat) for stat in stats) self.assertEqual(stats_dict['polyphonic_tracks_discarded'].count, 1) self.assertEqual(stats_dict['melodies_discarded_too_short'].count, 1) self.assertEqual(stats_dict['melodies_discarded_too_few_pitches'].count, 1) self.assertEqual( stats_dict['melody_lengths_in_bars'].counters, {float('-inf'): 0, 0: 0, 1: 0, 2: 0, 10: 1, 20: 0, 30: 0, 40: 0, 50: 0, 100: 0, 200: 0, 500: 0}) def testMidiFileToMelody(self): filename = os.path.join(tf.resource_loader.get_data_files_path(), 'testdata', 'melody.mid') melody = melodies_lib.midi_file_to_melody(filename) expected = melodies_lib.Melody([60, 62, 64, 66, 68, 70, 72, 70, 68, 66, 64, 62]) self.assertEqual(expected, melody) def testSlice(self): testing_lib.add_track_to_sequence( self.note_sequence, 0, [(12, 100, 1, 3), (11, 100, 5, 7), (13, 100, 9, 10)]) quantized_sequence = sequences_lib.quantize_note_sequence( self.note_sequence, steps_per_quarter=1) melody = melodies_lib.Melody() melody.from_quantized_sequence(quantized_sequence, search_start_step=0, instrument=0, ignore_polyphonic_notes=False) expected = [NO_EVENT, 12, NO_EVENT, NOTE_OFF, NO_EVENT, 11, NO_EVENT, NOTE_OFF, NO_EVENT, 13] self.assertEqual(expected, list(melody)) expected_slice = [NO_EVENT, NO_EVENT, NO_EVENT, 11, NO_EVENT, NOTE_OFF, NO_EVENT] self.assertEqual(expected_slice, list(melody[2:-1])) if __name__ == '__main__': tf.test.main()
41.248882
80
0.634511
960f3168928b50ed433178470fce854faacc15dc
118
py
Python
{{cookiecutter.project_package}}/{{cookiecutter.project_package}}/settings/dev.py
madelyneriksen/react-django-goodstuff-cookiecutter
daa8960a762c59ebbdc940ebb08f3784853e4ccf
[ "MIT" ]
17
2019-11-05T20:29:11.000Z
2022-03-09T09:25:10.000Z
{{cookiecutter.project_package}}/{{cookiecutter.project_package}}/settings/dev.py
madelyneriksen/react-django-goodstuff-cookiecutter
daa8960a762c59ebbdc940ebb08f3784853e4ccf
[ "MIT" ]
49
2019-12-02T13:27:23.000Z
2021-08-03T13:32:25.000Z
{{cookiecutter.project_package}}/{{cookiecutter.project_package}}/settings/dev.py
madelyneriksen/react-django-goodstuff-cookiecutter
daa8960a762c59ebbdc940ebb08f3784853e4ccf
[ "MIT" ]
2
2020-10-11T18:38:39.000Z
2021-03-16T13:16:00.000Z
"""Settings for development.""" from .base import * EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
14.75
61
0.737288
c41954ff06589f7a5e1e2e71a74ec8beeb02eae3
1,759
py
Python
App/migrations/0002_auto_20200116_0401.py
Bchizi/Web_Awaards
2889147501cc83a1ce672664f33688c26678ac44
[ "MIT" ]
null
null
null
App/migrations/0002_auto_20200116_0401.py
Bchizi/Web_Awaards
2889147501cc83a1ce672664f33688c26678ac44
[ "MIT" ]
7
2020-06-06T01:15:08.000Z
2021-09-08T01:34:59.000Z
App/migrations/0002_auto_20200116_0401.py
leon-bi/Web_Awaards
2889147501cc83a1ce672664f33688c26678ac44
[ "MIT" ]
null
null
null
# Generated by Django 2.2.8 on 2020-01-16 04:01 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('App', '0001_initial'), ] operations = [ migrations.AlterField( model_name='project', name='live_site', field=models.URLField(blank=True, max_length=300), ), migrations.AlterField( model_name='project', name='project_pic', field=models.ImageField(null=True, upload_to='project/'), ), migrations.CreateModel( name='review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment', models.TextField()), ('design_score', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10)])), ('usability_score', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10)])), ('content_score', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10)])), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to=settings.AUTH_USER_MODEL)), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='App.Project')), ], ), ]
43.975
161
0.652075
3caf0b22fbc4ea0ec376ef9dc7b88945212a149c
7,005
py
Python
lib/sqlalchemy/orm/identity.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
null
null
null
lib/sqlalchemy/orm/identity.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
null
null
null
lib/sqlalchemy/orm/identity.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
null
null
null
# orm/identity.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php from __future__ import annotations import weakref from . import util as orm_util from .. import exc as sa_exc class IdentityMap: def __init__(self): self._dict = {} self._modified = set() self._wr = weakref.ref(self) def _kill(self): self._add_unpresent = _killed def keys(self): return self._dict.keys() def replace(self, state): raise NotImplementedError() def add(self, state): raise NotImplementedError() def _add_unpresent(self, state, key): """optional inlined form of add() which can assume item isn't present in the map""" self.add(state) def update(self, dict_): raise NotImplementedError("IdentityMap uses add() to insert data") def clear(self): raise NotImplementedError("IdentityMap uses remove() to remove data") def _manage_incoming_state(self, state): state._instance_dict = self._wr if state.modified: self._modified.add(state) def _manage_removed_state(self, state): del state._instance_dict if state.modified: self._modified.discard(state) def _dirty_states(self): return self._modified def check_modified(self): """return True if any InstanceStates present have been marked as 'modified'. """ return bool(self._modified) def has_key(self, key): return key in self def popitem(self): raise NotImplementedError("IdentityMap uses remove() to remove data") def pop(self, key, *args): raise NotImplementedError("IdentityMap uses remove() to remove data") def setdefault(self, key, default=None): raise NotImplementedError("IdentityMap uses add() to insert data") def __len__(self): return len(self._dict) def copy(self): raise NotImplementedError() def __setitem__(self, key, value): raise NotImplementedError("IdentityMap uses add() to insert data") def __delitem__(self, key): raise NotImplementedError("IdentityMap uses remove() to remove data") class WeakInstanceDict(IdentityMap): def __getitem__(self, key): state = self._dict[key] o = state.obj() if o is None: raise KeyError(key) return o def __contains__(self, key): try: if key in self._dict: state = self._dict[key] o = state.obj() else: return False except KeyError: return False else: return o is not None def contains_state(self, state): if state.key in self._dict: try: return self._dict[state.key] is state except KeyError: return False else: return False def replace(self, state): if state.key in self._dict: try: existing = self._dict[state.key] except KeyError: # catch gc removed the key after we just checked for it pass else: if existing is not state: self._manage_removed_state(existing) else: return None else: existing = None self._dict[state.key] = state self._manage_incoming_state(state) return existing def add(self, state): key = state.key # inline of self.__contains__ if key in self._dict: try: existing_state = self._dict[key] except KeyError: # catch gc removed the key after we just checked for it pass else: if existing_state is not state: o = existing_state.obj() if o is not None: raise sa_exc.InvalidRequestError( "Can't attach instance " "%s; another instance with key %s is already " "present in this session." % (orm_util.state_str(state), state.key) ) else: return False self._dict[key] = state self._manage_incoming_state(state) return True def _add_unpresent(self, state, key): # inlined form of add() called by loading.py self._dict[key] = state state._instance_dict = self._wr def get(self, key, default=None): if key not in self._dict: return default try: state = self._dict[key] except KeyError: # catch gc removed the key after we just checked for it return default else: o = state.obj() if o is None: return default return o def items(self): values = self.all_states() result = [] for state in values: value = state.obj() if value is not None: result.append((state.key, value)) return result def values(self): values = self.all_states() result = [] for state in values: value = state.obj() if value is not None: result.append(value) return result def __iter__(self): return iter(self.keys()) def all_states(self): return list(self._dict.values()) def _fast_discard(self, state): # used by InstanceState for state being # GC'ed, inlines _managed_removed_state try: st = self._dict[state.key] except KeyError: # catch gc removed the key after we just checked for it pass else: if st is state: self._dict.pop(state.key, None) def discard(self, state): self.safe_discard(state) def safe_discard(self, state): if state.key in self._dict: try: st = self._dict[state.key] except KeyError: # catch gc removed the key after we just checked for it pass else: if st is state: self._dict.pop(state.key, None) self._manage_removed_state(state) def _killed(state, key): # external function to avoid creating cycles when assigned to # the IdentityMap raise sa_exc.InvalidRequestError( "Object %s cannot be converted to 'persistent' state, as this " "identity map is no longer valid. Has the owning Session " "been closed?" % orm_util.state_str(state), code="lkrp", )
28.591837
77
0.559029
a9b12868b995ad9715ddda5f93908099ac622fdf
18,910
py
Python
ahyper/observables.py
PhilChodrow/annotated_hypergraphs
e5fcaaa4196631460d188ab8d4dfc2ba4c3a2e4e
[ "MIT" ]
3
2019-11-09T21:39:23.000Z
2021-01-25T13:35:07.000Z
ahyper/observables.py
PhilChodrow/annotated_hypergraphs
e5fcaaa4196631460d188ab8d4dfc2ba4c3a2e4e
[ "MIT" ]
null
null
null
ahyper/observables.py
PhilChodrow/annotated_hypergraphs
e5fcaaa4196631460d188ab8d4dfc2ba4c3a2e4e
[ "MIT" ]
1
2021-05-18T19:19:05.000Z
2021-05-18T19:19:05.000Z
from itertools import groupby, chain from collections import Counter import networkx as nx from .utils import normalise_counters import numpy as np from itertools import combinations, permutations from collections import defaultdict import pandas as pd from scipy.linalg import eigh def local_role_density( annotated_hypergraph, include_focus=False, absolute_values=False, as_array=False ): """ Calculates the density of each role within a 1-step neighbourhood of a node, for all nodes. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. include_focus [Bool]: If True, includes the roles of the focal node in th calculation. absolute_values [Bool]: If True, returns role counts rather than densities. as_array [Bool]: If True, return an array rather than a Counter. Returns: role_densities []: An array of dimension (# nodes x # roles) describing the density of each role. """ A = annotated_hypergraph def get_counts(group): return Counter([x.role for x in group]) by_edge = { eid: get_counts(v) for eid, v in groupby( sorted(A.IL, key=lambda x: x.eid, reverse=True), lambda x: x.eid ) } densities = {} for incidence in A.IL: densities[incidence.nid] = ( densities.get(incidence.nid, Counter()) + by_edge[incidence.eid] ) if not include_focus: densities[incidence.nid] = densities.get( incidence.nid, Counter() ) - Counter([incidence.role]) keys = set(chain.from_iterable(densities.values())) for item in densities.values(): item.update({key: 0 for key in keys if key not in item}) if not absolute_values: normalise_counters(densities) if as_array: densities = to_matrix(densities, A) return densities def node_role_participation( annotated_hypergraph, absolute_values=False, as_array=False ): """ Calculates the proportion of instances where each node is in each role. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. absolute_values [Bool]: If True, returns role counts rather than densities. as_array [Bool]: If True, return an array rather than a Counter. Returns: role_densities []: An array of dimension (# nodes x # roles) describing the participation of each role. """ A = annotated_hypergraph def get_counts(group): return Counter([x.role for x in group]) densities = { nid: get_counts(v) for nid, v in groupby(sorted(A.IL, key=lambda x: x.nid), lambda x: x.nid) } keys = set(chain.from_iterable(densities.values())) for item in densities.values(): item.update({key: 0 for key in keys if key not in item}) if not absolute_values: normalise_counters(densities) if as_array: densities = to_matrix(densities, A) return densities def _degree_centrality(weighted_projection): if isinstance(weighted_projection, nx.DiGraph): degrees = { node: weighted_projection.out_degree(node, weight="weight") for node in weighted_projection.nodes() } return degrees elif isinstance(weighted_projection, dict): return NotImplementedError("Specify one of 'use_networkx' or 'use_graphtool'") else: # graphtool G = weighted_projection degrees = G.degree_property_map("out", weight=G.ep.weights) degrees = {G.vp.node_labels[v]: degrees[v] for v in G.vertices()} return degrees def degree_centrality(annotated_hypergraph, **kwargs): """ Returns the weighted degree centrality for each node in an annotated hypergraph with a defined role-interaction matrix. Note: For stylistic purposes we recreate the weighted adjacency graph for each centrality. This can easily be factored out. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. Output: degrees (dict): A dictionary of {node:degree} pairs. """ weighted_projection = annotated_hypergraph.to_weighted_projection(**kwargs) return _degree_centrality(weighted_projection) def _eigenvector_centrality(weighted_projection, **kwargs): if isinstance(weighted_projection, nx.DiGraph): return nx.eigenvector_centrality(weighted_projection, **kwargs) else: from graph_tool.centrality import eigenvector G = weighted_projection _, eigenv = eigenvector(G, weight=G.ep.weights) ev = {G.vp.node_labels[v]: eigenv[v] for v in G.vertices()} return ev def eigenvector_centrality(annotated_hypergraph, **kwargs): """ Returns the weighted eigenvector centrality for each node in an annotated hypergraph with a defined role-interaction matrix. Note: For stylistic purposes we recreate the weighted adjacency graph for each centrality, and create a NetworkX DiGraph. This can easily be factored out. Note: Using networkx for simplicity at the moment but can migrate to more efficient library if needed. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. Output: eigenvector (dict): A dictionary of {node:eigenvector_centrality} pairs. """ weighted_projection = annotated_hypergraph.to_weighted_projection(use_networkx=True) return _eigenvector_centrality(weighted_projection, **kwargs) def _pagerank_centrality(weighted_projection, **kwargs): if isinstance(weighted_projection, nx.DiGraph): return nx.pagerank(weighted_projection, **kwargs) else: from graph_tool.centrality import pagerank G = weighted_projection pr = pagerank(G, weight=G.ep.weights) pr = {G.vp.node_labels[v]: pr[v] for v in G.vertices()} return pr def pagerank_centrality(annotated_hypergraph, **kwargs): """ Returns the weighted PageRank centrality for each node in an annotated hypergraph with a defined role-interaction matrix. Note: For stylistic purposes we recreate the weighted adjacency graph for each centrality, and create a NetworkX DiGraph. This can easily be factored out. Note: Using networkx for simplicity at the moment but can migrate to more efficient library if needed. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. Output: pagerank (dict): A dictionary of {node:pagerank_centrality} pairs. """ weighted_projection = annotated_hypergraph.to_weighted_projection(use_networkx=True) return _pagerank_centrality(weighted_projection, **kwargs) def _connected_components(weighted_projection): if isinstance(weighted_projection, nx.DiGraph): return nx.number_weakly_connected_components(weighted_projection) else: from graph_tool.topology import label_components G = weighted_projection G.set_directed(False) _, comps = label_components(G) G.set_directed(True) return len(comps) def connected_components(annotated_hypergraph): """ Returns the number of connected components of an annotated hypergraph. Note: For stylistic purposes we recreate the weighted adjacency graph for each centrality. This can easily be factored out. Input: annotated_hypergraph [AnnotatedHypergraph]: An annotated hypergraph. Output: connected_components (int): The number of connected components. """ weighted_projection = annotated_hypergraph.to_weighted_projection(use_networkx=True) return _connected_components(weighted_projection) def random_walk( G, n_steps, alpha=0, nonbacktracking=False, alpha_ve=None, alpha_ev=None ): """ Conduct a random walk on a network G, optionally with teleportation parameter alpha and nonbacktracking. Note: Assumes a randomly chosen starting node. Input: G (nx.Graph/nx.DiGraph): A graph to conduct the random walk. n_steps (int): The number of steps the random walk should take. alpha (float): nonbacktracking (bool): alpha_ve (float): alpha_ev (float): Output: V (np.array): TODO: Check this works (test) and make it clear differences between alphas. """ V = np.zeros(n_steps) nodes = np.array(list(G.nodes())) nodes = nodes[nodes >= 0] n = len(nodes) v = np.random.choice(nodes) # v2 eventually holds where we went last time. v2 = v for i in range(n_steps): N = G[v] v_ = np.random.choice(list(N)) if nonbacktracking: while v_ == v2: v_ = np.random.choice(list(N)) role = G[v][v_]["role"] if v < 0: alpha = alpha_ev else: alpha = alpha_ve if np.random.rand() < alpha[role]: i_ = np.random.randint(n) v_ = nodes[i_] v2 = v v = v_ V[i] = v return V def random_walk_pagerank( annotated_hypergraph, n_steps, nonbacktracking=False, alpha_1=None, alpha_2=None, return_path=False, ): """ Calculate the random walk PageRank for each node in the network by sampling. Input: annotated_hypergraph (AnnotatedHypergraph): The hypergraph to apply PageRank to. n_steps (int): The number of steps to take in the random walk. nonbacktracking (bool): If True, the random walk is non-backtracking. alpha_1 (float): alpha_2 (float): return_path (bool): If True, returns also the path of the random walk. Output: pagerank (dict): A dictionary of node:pagerank pairs. V (np.array) [optional]: The random walk trajectory. """ A = annotated_hypergraph G = A.to_bipartite_graph() V = random_walk( G, n_steps, nonbacktracking=nonbacktracking, alpha_ve=alpha_1, alpha_ev=alpha_2 ) counts = np.unique(V, return_counts=True) ix = counts[0] >= 0 v = counts[1][ix] v = v / v.sum() labels = counts[0][ix] d = {labels[i]: v[i] for i in range(len(v))} if return_path: return d, V else: return d def _assortativity(annotated_hypergraph, n_samples, by_role=True, spearman=True): """Helper function.""" assort = assortativity(annotated_hypergraph, n_samples, by_role=True, spearman=True) assort_dict = {} role_map = dict(annotated_hypergraph.role_map) for ix, row in assort.iterrows(): key = f"{role_map[int(ix[0])]}_{role_map[int(ix[1])]}" assort_dict[key] = row.deg_2 return assort_dict def assortativity(annotated_hypergraph, n_samples, by_role=True, spearman=True): """ Return a stochastic approximation of the assortativity between nodes, optionally by roles. Notes: Not quite the same thing as the standard degree-assortativity coefficient for dyadic graphs due to the role of hyperedges. Generalizes the uniform measure in the "Configuration Models of Random Hypergraphs" Input: annotated_hypergraph (AnnotatedHypergraph): The annotated hypergraph on which to measure n_samples (int): The number of hyperedges to sample by_role (bool): If True, break out all the correlations by pairs of node roles. spearman (bool): If True, replace degrees by their ranks (within each pair of node_roles if by_role) Output: A pd.DataFrame containing degree-correlation coefficients. """ A = annotated_hypergraph # first, construct a lookup giving the number of edges incident to each pair of nodes, by role if specified. def discount_lookup(role_1, role_2, by_role=by_role): weighted_edges = defaultdict(lambda: defaultdict(lambda: 0.0)) for eid, edge in groupby(A.get_IL(), lambda x: x.eid): edge = list(edge) for a, b in combinations(edge, 2): if by_role: if ( (a.role == role_1) and (b.role == role_2) or (a.role == role_2) and (b.role == role_1) ): weighted_edges[a.nid][b.nid] += 1 else: weighted_edges[a.nid][b.nid] += 1 return weighted_edges D = { (role_1, role_2): discount_lookup(role_1, role_2) for role_1, role_2 in permutations(A.roles, 2) } D = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0.0)), D) # next, construct the degree lookup, again by role if specified. degs = A.node_degrees(by_role=by_role) # containers for the data generated in the loop if isinstance(A.roles[0], int): max_len = max(len(str(role)) for role in A.roles) else: max_len = max(len(role) for role in A.roles) dtype = "S" + str(max_len) role_1 = np.empty(2 * n_samples, dtype=dtype) role_2 = np.empty(2 * n_samples, dtype=dtype) deg_1 = np.zeros(2 * n_samples) deg_2 = np.zeros(2 * n_samples) # generate a dict which for each eid gives the list of NodeEdgeIncidences in that edge. IL = A.get_IL() IL.sort(key=lambda e: (e.eid, e.role)) edges = groupby(IL, lambda e: (e.eid)) edges = {k: list(v) for k, v in edges} # main loop for k in 2 * np.arange(n_samples): # choose a random edge and two nodes on it. # i = np.random.randint(1, A.m+1) i = np.random.randint(0, A.m) edge = edges[i] i_ = np.random.randint(len(edge)) j_ = np.random.randint(len(edge)) while i_ == j_: i_ = np.random.randint(len(edge)) j_ = np.random.randint(len(edge)) u = edges[i][i_].nid v = edges[i][j_].nid u_role = edges[i][i_].role v_role = edges[i][j_].role # compute the discount -- this is the number of edges between u and v themselves. discount = D[(u_role, v_role)][u][v] role_1[k] = u_role role_2[k] = v_role role_1[k + 1] = v_role role_2[k + 1] = u_role if by_role: deg_1[k] = degs[u][u_role] - discount deg_2[k] = degs[v][v_role] - discount deg_1[k + 1] = degs[u][u_role] - discount deg_2[k + 1] = degs[v][v_role] - discount else: deg_1[k] = degs[u] - discount deg_2[k] = degs[v] - discount deg_1[k + 1] = degs[u] - discount deg_2[k + 1] = degs[v] - discount # construct a DataFrame with the results. role_1 = role_1.astype("U" + str(max_len)) role_2 = role_2.astype("U" + str(max_len)) df = pd.DataFrame( {"role_1": role_1, "role_2": role_2, "deg_1": deg_1, "deg_2": deg_2} ) df = df.astype({"deg_1": "int32", "deg_2": "int32"}) if by_role: grouped = df.groupby(["role_1", "role_2"]) if spearman: df["deg_1"] = grouped["deg_1"].rank() df["deg_2"] = grouped["deg_2"].rank() df = df.groupby(["role_1", "role_2"]) corrs = df.corr().iloc[0::2, -1] else: if spearman: df["deg_1"] = df["deg_1"].rank() df["deg_2"] = df["deg_2"].rank() corrs = df.corr().iloc[0::2, -1] return pd.DataFrame(corrs) def multiway_spectral(A, A0, k): # implementation(?) of Zhang + Newman on multiway spectral partitioning B = A - A0 n = B.shape[0] m = A.sum() / 2 eigen = eigh(B, eigvals=(n - k, n - 1)) lam = eigen[0] U = eigen[1] # vertex vectors (eq (10)) r = np.sqrt(lam) * U ix = np.random.randint(0, n, k) # initialize community vectors R = r[ix, :] # random assignments ix = np.random.randint(0, k, n) L = np.zeros((n, k)) L[np.arange(n), ix] = 1 L_old = L.copy() ell_old = np.zeros(n) for j in range(100): # # until convergence Rr = np.dot(r, R.T) # current assignment ell = np.argmax(Rr, axis=1) L = np.zeros((n, k)) L[np.arange(n), ell] = 1 ell = L.argmax(axis=1) R = np.dot(L.T, r) obj = (1 / (2 * m)) * (R ** 2).sum() if (ell == ell_old).mean() == 1: break ell_old = ell.copy() return (ell, obj) def mutual_information_of_roles(annotated_hypergraph): """ Calculates the mutual information between an individuals' roles and the roles of their neighbours. """ with np.errstate(divide="ignore", invalid="ignore"): M = local_role_density(annotated_hypergraph, as_array=True) p_ = M.mean(axis=0) return 1 / annotated_hypergraph.n * np.nansum((np.log(M / p_) * M)) def MI(X, Y, normalize=False, return_joint=False): # assumes X and Y are vectors of integer labels of the same length and on the same alphabet space n = len(X) k = max(X.max(), Y.max()) joint = np.zeros((k + 1, k + 1)) p_x = np.zeros(k + 1) p_y = np.zeros(k + 1) for i in range(n): joint[X[i], Y[i]] += 1 p_x[X[i]] += 1 p_y[Y[i]] += 1 joint = joint / joint.sum() p_x = p_x / p_x.sum() p_y = p_y / p_y.sum() mat = joint * np.log(joint / np.outer(p_x, p_y)) mat[np.isnan(mat)] = 0 I_XY = mat.sum() if normalize: H_x = -p_x * np.log(p_x) H_x[np.isnan(H_x)] = 0 H_x = H_x.sum() H_y = -p_y * np.log(p_y) H_y[np.isnan(H_y)] = 0 H_y = H_y.sum() NMI = I_XY / (0.5 * (H_x + H_y)) out = NMI else: out = I_XY if return_joint: return (out, joint) else: return out def to_matrix(C, A): """ Convert a counter, such as that returned by local_role_densities(), to a matrix in which each column corresponds to a role of A. """ M = np.zeros((len(C), len(A.roles))) k = list(C.keys()) for i in range(len(k)): for j in range(len(A.roles)): M[k[i], j] = C[i][A.roles[j]] return M
31
138
0.600423
ce7d72ec0b2574daec90dd9d48d1fb0aa7c423bf
335
py
Python
plugins/flytekit-sqlalchemy/flytekitplugins/sqlalchemy/__init__.py
bstadlbauer/flytekit
12ef34d7b6d777088ab87f9cf0d5c32355895852
[ "Apache-2.0" ]
null
null
null
plugins/flytekit-sqlalchemy/flytekitplugins/sqlalchemy/__init__.py
bstadlbauer/flytekit
12ef34d7b6d777088ab87f9cf0d5c32355895852
[ "Apache-2.0" ]
null
null
null
plugins/flytekit-sqlalchemy/flytekitplugins/sqlalchemy/__init__.py
bstadlbauer/flytekit
12ef34d7b6d777088ab87f9cf0d5c32355895852
[ "Apache-2.0" ]
null
null
null
""" .. currentmodule:: flytekitplugins.sqlalchemy This package contains things that are useful when extending Flytekit. .. autosummary:: :template: custom.rst :toctree: generated/ SQLAlchemyConfig SQLAlchemyDefaultImages SQLAlchemyTask """ from .task import SQLAlchemyConfig, SQLAlchemyDefaultImages, SQLAlchemyTask
20.9375
75
0.779104
7f9886a5409845b625ad7ada9b8e346eaac4e811
8,941
py
Python
vut/lib/python3.8/site-packages/pipenv/patched/notpip/_internal/utils/compat.py
dan-mutua/djangowk1
1e5dcb6443ef21451e21845ec639198719e11b10
[ "MIT" ]
18,636
2017-12-06T14:53:18.000Z
2022-03-31T13:12:34.000Z
vut/lib/python3.8/site-packages/pipenv/patched/notpip/_internal/utils/compat.py
dan-mutua/djangowk1
1e5dcb6443ef21451e21845ec639198719e11b10
[ "MIT" ]
3,640
2017-12-06T16:58:35.000Z
2022-03-31T22:20:57.000Z
vut/lib/python3.8/site-packages/pipenv/patched/notpip/_internal/utils/compat.py
dan-mutua/djangowk1
1e5dcb6443ef21451e21845ec639198719e11b10
[ "MIT" ]
1,987
2017-12-06T15:04:51.000Z
2022-03-26T10:05:15.000Z
"""Stuff that differs in different Python versions and platform distributions.""" # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import, division import codecs import locale import logging import os import shutil import sys from pipenv.patched.notpip._vendor.six import PY2, text_type from pipenv.patched.notpip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Text, Tuple, Union try: import ipaddress except ImportError: try: from pipenv.patched.notpip._vendor import ipaddress # type: ignore except ImportError: import ipaddr as ipaddress # type: ignore ipaddress.ip_address = ipaddress.IPAddress # type: ignore ipaddress.ip_network = ipaddress.IPNetwork # type: ignore __all__ = [ "ipaddress", "uses_pycache", "console_to_str", "get_path_uid", "stdlib_pkgs", "WINDOWS", "samefile", "get_terminal_size", ] logger = logging.getLogger(__name__) if PY2: import imp try: cache_from_source = imp.cache_from_source # type: ignore except AttributeError: # does not use __pycache__ cache_from_source = None uses_pycache = cache_from_source is not None else: uses_pycache = True from importlib.util import cache_from_source if PY2: # In Python 2.7, backslashreplace exists # but does not support use for decoding. # We implement our own replace handler for this # situation, so that we can consistently use # backslash replacement for all versions. def backslashreplace_decode_fn(err): raw_bytes = (err.object[i] for i in range(err.start, err.end)) # Python 2 gave us characters - convert to numeric bytes raw_bytes = (ord(b) for b in raw_bytes) return u"".join(u"\\x%x" % c for c in raw_bytes), err.end codecs.register_error( "backslashreplace_decode", backslashreplace_decode_fn, ) backslashreplace_decode = "backslashreplace_decode" else: backslashreplace_decode = "backslashreplace" def has_tls(): # type: () -> bool try: import _ssl # noqa: F401 # ignore unused return True except ImportError: pass from pipenv.patched.notpip._vendor.urllib3.util import IS_PYOPENSSL return IS_PYOPENSSL def str_to_display(data, desc=None): # type: (Union[bytes, Text], Optional[str]) -> Text """ For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ if isinstance(data, text_type): return data # Otherwise, data is a bytes object (str in Python 2). # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: if desc is None: desc = 'Bytes object' msg_format = '{} does not appear to be encoded as %s'.format(desc) logger.warning(msg_format, encoding) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. """ return str_to_display(data, desc='Subprocess output') def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded # packages in the stdlib that may have installation metadata, but should not be # considered 'installed'. this theoretically could be determined based on # dist.location (py27:`sysconfig.get_paths()['stdlib']`, # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may # make this ineffective, so hard-coding stdlib_pkgs = {"python", "wsgiref", "argparse"} # windows detection, covers cpython and ironpython WINDOWS = (sys.platform.startswith("win") or (sys.platform == 'cli' and os.name == 'nt')) def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2 if hasattr(shutil, 'get_terminal_size'): def get_terminal_size(): # type: () -> Tuple[int, int] """ Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. """ return tuple(shutil.get_terminal_size()) # type: ignore else: def get_terminal_size(): # type: () -> Tuple[int, int] """ Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. """ def ioctl_GWINSZ(fd): try: import fcntl import termios import struct cr = struct.unpack_from( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678') ) except Exception: return None if cr == (0, 0): return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: if sys.platform != "win32": try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except Exception: pass if not cr: cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80)) return int(cr[1]), int(cr[0])
33.114815
79
0.645006
5179cf093c14959323244e2fa28b2eeba2b14089
512
py
Python
quesans/migrations/0004_auto_20210223_1700.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
3
2021-03-22T10:39:18.000Z
2021-04-30T10:29:37.000Z
quesans/migrations/0004_auto_20210223_1700.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
1
2021-04-16T06:54:10.000Z
2021-04-16T06:54:10.000Z
quesans/migrations/0004_auto_20210223_1700.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
3
2021-03-11T10:02:37.000Z
2021-04-23T07:34:10.000Z
# Generated by Django 3.1.6 on 2021-02-23 11:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quesans', '0003_question_slug'), ] operations = [ migrations.RemoveField( model_name='question', name='updated_on', ), migrations.AddField( model_name='answer', name='date', field=models.DateTimeField(auto_now=True), ), ]
22.26087
55
0.544922
f5e544c95308e86c4e9a4f95c0fd2fba8f39b51c
7,220
py
Python
transitfeed/trip_capacity.py
brendannee/transitfeed-ride
78cfd664eeedc8e41324750ff8c23d5095837039
[ "Apache-2.0" ]
null
null
null
transitfeed/trip_capacity.py
brendannee/transitfeed-ride
78cfd664eeedc8e41324750ff8c23d5095837039
[ "Apache-2.0" ]
null
null
null
transitfeed/trip_capacity.py
brendannee/transitfeed-ride
78cfd664eeedc8e41324750ff8c23d5095837039
[ "Apache-2.0" ]
2
2017-08-09T18:17:51.000Z
2017-08-09T19:31:41.000Z
# Copyright (C) 2017 Oregon Department of Transportation (ODOT) # # 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. from problems import default_problem_reporter from gtfsobjectbase import GtfsObjectBase import util from loader import Loader import gtfsfactory as gtfsfactory_module class Trip_capacity(GtfsObjectBase): """This class represents a rule that determines which itineraries a fare rule applies to.""" _REQUIRED_FIELD_NAMES = [] _FIELD_NAMES = _REQUIRED_FIELD_NAMES + [ 'agency_id', 'trip_id', 'service_date', 'vehicle_description', 'seated_capacity', 'standing_capacity', 'wheelchair_capacity', 'bike_capacity' ] _TABLE_NAME = "trip_capacity" def __init__(self,agency_id = None, trip_id = None, service_date = None, vehicle_description = None, seated_capacity = None, standing_capacity = None, wheelchair_capacity = None, bike_capacity = None, field_dict=None,**kwargs): self._schedule = None self.boardTimeMin = None self.boardTimeMax = None if not field_dict: if agency_id: kwargs['agency_id'] = agency_id if trip_id: kwargs['trip_id'] = trip_id if service_date: kwargs['service_date'] = service_date if vehicle_description: kwargs['vehicle_description'] = vehicle_description if seated_capacity: kwargs['seated_capacity'] = seated_capacity if standing_capacity: kwargs['standing_capacity'] = standing_capacity if wheelchair_capacity: kwargs['wheelchair_capacity'] = wheelchair_capacity if bike_capacity: kwargs['bike_capacity'] = bike_capacity field_dict = kwargs self.__dict__.update(field_dict) def validateServiceDate(self,problems): if util.IsEmpty(self.service_date): return valid_date = util.ValidateDate(self.service_date, 'service_date', problems) if self._schedule.validRideDates == 0: return if valid_date: if self.service_date > self._schedule.ride_feed_date[1] or self.service_date < self._schedule.ride_feed_date[0]: problems.InvalidValue('service_date',self.service_date,'Service date does not fall in valid range') def validateTripID(self,problems): if util.IsEmpty(self.trip_id): return if self.trip_id not in self._schedule.trips.keys(): problems.InvalidValue('trip_id',self.trip_id,'Did not find a matching trip_id in trips.txt') def validateVehicleDescription(self,problems): #a description can be very unique so any format is really appropriate if util.IsEmpty(self.vehicle_description): return def ValidateSeatedCapacity(self,problems): if util.IsEmpty(self.seated_capacity): self.seated_capacity = 0 return try: self.seated_capacity = int(self.seated_capacity) except (ValueError, TypeError): problems.InvalidValue('seated_capacity', self.seated_capacity, 'Value must be non negative integer') del self.seated_capacity return if self.seated_capacity < 0: problems.InvalidValue('seated_capacity', self.seated_capacity, 'Value must be non negative integer') def ValidateStandingCapacity(self,problems): if util.IsEmpty(self.standing_capacity): self.standing_capacity = 0 return try: self.standing_capacity = int(self.standing_capacity) except (ValueError, TypeError): problems.InvalidValue('standing_capacity', self.standing_capacity, 'Value must be non negative integer') del self.standing_capacity return if self.standing_capacity < 0: problems.InvalidValue('standing_capacity', self.standing_capacity, 'Value must be non negative integer') def ValidateWheelChairCapacity(self,problems): if util.IsEmpty(self.wheelchair_capacity): self.wheelchair_capacity = 0 return try: self.wheelchair_capacity = int(self.wheelchair_capacity) except (ValueError, TypeError): problems.InvalidValue('wheelchair_capacity', self.wheelchair_capacity, 'Value must be non negative integer') del self.wheelchair_capacity return if self.wheelchair_capacity < 0: problems.InvalidValue('wheelchair_capacity', self.wheelchair_capacity, 'Value must be non negative integer') def ValidateBikeCapacity(self,problems): if util.IsEmpty(self.bike_capacity): self.bike_capacity = 0 return try: self.bike_capacity = int(self.bike_capacity) except (ValueError, TypeError): problems.InvalidValue('bike_capacity', self.bike_capacity, 'Value must be non negative integer') del self.bike_capacity return if self.bike_capacity < 0: problems.InvalidValue('bike_capacity', self.bike_capacity, 'Value must be non negative integer') def validateagencieID(self,problems): if util.IsEmpty(self.agency_id): return if self.agency_id not in self._schedule._agencies.keys(): problems.InvalidValue('agency_id',self.agency_id,'Did not find a matching agency_id in agencies.txt') def Validate(self, problems=default_problem_reporter): """Validate attribute values and this object's internal consistency. Returns: True iff all validation checks passed. """ found_problem = False found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty( self, self._REQUIRED_FIELD_NAMES, problems)) or found_problem) #found_problem = self.validateServiceDate(problems) found_problem = self.validateVehicleDescription(problems) found_problem = self.ValidateSeatedCapacity(problems) found_problem = self.ValidateStandingCapacity(problems) found_problem = self.ValidateWheelChairCapacity(problems) found_problem = self.ValidateBikeCapacity(problems) found_problem = self.validateagencieID(problems) found_problem = self.validateTripID(problems) found_problem = self.validateServiceDate(problems) return not found_problem def ValidateBeforeAdd(self, problems): return True def ValidateAfterAdd(self, problems): self.Validate(problems) #def AddToSchedule(self, schedule, problems): #schedule.AddBoardAlightObject(self, problems)
38
142
0.677285
4719fbc4f6022da0d87f39757fec1e67b5117d70
12,991
py
Python
src/lib/opts.py
pranshumittal08/FairMOT
5881dfa02973b442a11c4e84186ff3ec860d1681
[ "MIT" ]
null
null
null
src/lib/opts.py
pranshumittal08/FairMOT
5881dfa02973b442a11c4e84186ff3ec860d1681
[ "MIT" ]
null
null
null
src/lib/opts.py
pranshumittal08/FairMOT
5881dfa02973b442a11c4e84186ff3ec860d1681
[ "MIT" ]
null
null
null
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys class opts(object): def __init__(self): self.parser = argparse.ArgumentParser() # basic experiment setting self.parser.add_argument('task', default='mot', help='mot') self.parser.add_argument('--dataset', default='jde', help='jde') self.parser.add_argument('--exp_id', default='default') self.parser.add_argument('--test', action='store_true') #self.parser.add_argument('--load_model', default='../models/ctdet_coco_dla_2x.pth', #help='path to pretrained model') self.parser.add_argument('--load_model', default='', help='path to pretrained model') self.parser.add_argument('--resume', action='store_true', help='resume an experiment. ' 'Reloaded the optimizer parameter and ' 'set load_model to model_last.pth ' 'in the exp dir if load_model is empty.') # system self.parser.add_argument('--gpus', default='2, 3', help='-1 for CPU, use comma for multiple gpus') self.parser.add_argument('--num_workers', type=int, default=8, help='dataloader threads. 0 for single-thread.') self.parser.add_argument('--not_cuda_benchmark', action='store_true', help='disable when the input size is not fixed.') self.parser.add_argument('--seed', type=int, default=317, help='random seed') # from CornerNet # log self.parser.add_argument('--print_iter', type=int, default=0, help='disable progress bar and print to screen.') self.parser.add_argument('--hide_data_time', action='store_true', help='not display time during training.') self.parser.add_argument('--save_all', action='store_true', help='save model to disk every 5 epochs.') self.parser.add_argument('--metric', default='loss', help='main metric to save best model') self.parser.add_argument('--vis_thresh', type=float, default=0.5, help='visualization threshold.') # model self.parser.add_argument('--arch', default='dla_34', help='model architecture. Currently tested' 'resdcn_34 | resdcn_50 | resfpndcn_34 |' 'dla_34 | hrnet_18') self.parser.add_argument('--head_conv', type=int, default=-1, help='conv layer channels for output head' '0 for no conv layer' '-1 for default setting: ' '256 for resnets and 256 for dla.') self.parser.add_argument('--down_ratio', type=int, default=4, help='output stride. Currently only supports 4.') # input self.parser.add_argument('--input_res', type=int, default=-1, help='input height and width. -1 for default from ' 'dataset. Will be overriden by input_h | input_w') self.parser.add_argument('--input_h', type=int, default=-1, help='input height. -1 for default from dataset.') self.parser.add_argument('--input_w', type=int, default=-1, help='input width. -1 for default from dataset.') # train self.parser.add_argument('--lr', type=float, default=1e-4, help='learning rate for batch size 12.') self.parser.add_argument('--lr_step', type=str, default='20', help='drop learning rate by 10.') self.parser.add_argument('--num_epochs', type=int, default=30, help='total training epochs.') self.parser.add_argument('--batch_size', type=int, default=12, help='batch size') self.parser.add_argument('--master_batch_size', type=int, default=-1, help='batch size on the master gpu.') self.parser.add_argument('--num_iters', type=int, default=-1, help='default: #samples / batch_size.') self.parser.add_argument('--val_intervals', type=int, default=5, help='number of epochs to run validation.') self.parser.add_argument('--trainval', action='store_true', help='include validation in training and ' 'test on test set') # test self.parser.add_argument('--K', type=int, default=500, help='max number of output objects.') self.parser.add_argument('--not_prefetch_test', action='store_true', help='not use parallal data pre-processing.') self.parser.add_argument('--fix_res', action='store_true', help='fix testing resolution or keep ' 'the original resolution') self.parser.add_argument('--keep_res', action='store_true', help='keep the original resolution' ' during validation.') # tracking self.parser.add_argument('--test_mot16', default=False, help='test mot16') self.parser.add_argument('--val_mot15', default=False, help='val mot15') self.parser.add_argument('--test_mot15', default=False, help='test mot15') self.parser.add_argument('--val_mot16', default=False, help='val mot16 or mot15') self.parser.add_argument('--test_mot17', default=False, help='test mot17') self.parser.add_argument('--val_mot17', default=True, help='val mot17') self.parser.add_argument('--val_mot20', default=False, help='val mot20') self.parser.add_argument('--test_mot20', default=False, help='test mot20') self.parser.add_argument('--val_hie', default=False, help='val hie') self.parser.add_argument('--test_hie', default=False, help='test hie') self.parser.add_argument('--conf_thres', type=float, default=0.4, help='confidence thresh for tracking') self.parser.add_argument('--match_thres', type=float, default=0.4, help='match thresh for byte tracking') self.parser.add_argument('--det_thres', type=float, default=0.3, help='confidence thresh for detection') self.parser.add_argument('--nms_thres', type=float, default=0.4, help='iou thresh for nms') self.parser.add_argument('--track_buffer', type=int, default=30, help='tracking buffer') self.parser.add_argument('--min-box-area', type=float, default=0, help='filter out tiny boxes') self.parser.add_argument('--input-video', type=str, default='../videos/MOT16-03.mp4', help='path to the input video') self.parser.add_argument('--output-format', type=str, default='video', help='video or text') self.parser.add_argument('--output-root', type=str, default='../demos', help='expected output root path') # mot self.parser.add_argument('--data_cfg', type=str, default='../src/lib/cfg/data.json', help='load data from cfg') self.parser.add_argument('--data_dir', type=str, default='/home/zyf/dataset') self.parser.add_argument('--result_dir', type=str, default='/content/drive/MyDrive/NFL_FaitMOT') # loss self.parser.add_argument('--mse_loss', action='store_true', help='use mse loss or focal loss to train ' 'keypoint heatmaps.') self.parser.add_argument('--reg_loss', default='l1', help='regression loss: sl1 | l1 | l2') self.parser.add_argument('--hm_weight', type=float, default=1, help='loss weight for keypoint heatmaps.') self.parser.add_argument('--off_weight', type=float, default=1, help='loss weight for keypoint local offsets.') self.parser.add_argument('--wh_weight', type=float, default=0.1, help='loss weight for bounding box size.') self.parser.add_argument('--id_loss', default='ce', help='reid loss: ce | focal') self.parser.add_argument('--id_weight', type=float, default=1, help='loss weight for id') self.parser.add_argument('--reid_dim', type=int, default=128, help='feature dim for reid') self.parser.add_argument('--ltrb', default=True, help='regress left, top, right, bottom of bbox') self.parser.add_argument('--multi_loss', default='uncertainty', help='multi_task loss: uncertainty | fix') self.parser.add_argument('--norm_wh', action='store_true', help='L1(\hat(y) / y, 1) or L1(\hat(y), y)') self.parser.add_argument('--dense_wh', action='store_true', help='apply weighted regression near center or ' 'just apply regression on center point.') self.parser.add_argument('--cat_spec_wh', action='store_true', help='category specific bounding box size.') self.parser.add_argument('--not_reg_offset', action='store_true', help='not regress local offset.') def parse(self, args=''): if args == '': opt = self.parser.parse_args() else: opt = self.parser.parse_args(args) opt.gpus_str = opt.gpus opt.gpus = [int(gpu) for gpu in opt.gpus.split(',')] opt.lr_step = [int(i) for i in opt.lr_step.split(',')] opt.fix_res = not opt.keep_res print('Fix size testing.' if opt.fix_res else 'Keep resolution testing.') opt.reg_offset = not opt.not_reg_offset if opt.head_conv == -1: # init default head_conv opt.head_conv = 256 if 'dla' in opt.arch else 256 opt.pad = 31 opt.num_stacks = 1 if opt.trainval: opt.val_intervals = 100000000 if opt.master_batch_size == -1: opt.master_batch_size = opt.batch_size // len(opt.gpus) rest_batch_size = (opt.batch_size - opt.master_batch_size) opt.chunk_sizes = [opt.master_batch_size] for i in range(len(opt.gpus) - 1): slave_chunk_size = rest_batch_size // (len(opt.gpus) - 1) if i < rest_batch_size % (len(opt.gpus) - 1): slave_chunk_size += 1 opt.chunk_sizes.append(slave_chunk_size) print('training chunk_sizes:', opt.chunk_sizes) opt.exp_dir = os.path.join(opt.result_dir, 'exp', opt.task) opt.save_dir = os.path.join(opt.exp_dir, opt.exp_id) opt.debug_dir = os.path.join(opt.save_dir, 'debug') print('The output will be saved to ', opt.save_dir) if opt.resume and opt.load_model == '': model_path = opt.save_dir[:-4] if opt.save_dir.endswith('TEST') \ else opt.save_dir opt.load_model = os.path.join(model_path, 'model_last.pth') return opt def update_dataset_info_and_set_heads(self, opt, dataset): input_h, input_w = dataset.default_resolution opt.mean, opt.std = dataset.mean, dataset.std opt.num_classes = dataset.num_classes # input_h(w): opt.input_h overrides opt.input_res overrides dataset default input_h = opt.input_res if opt.input_res > 0 else input_h input_w = opt.input_res if opt.input_res > 0 else input_w opt.input_h = opt.input_h if opt.input_h > 0 else input_h opt.input_w = opt.input_w if opt.input_w > 0 else input_w opt.output_h = opt.input_h // opt.down_ratio opt.output_w = opt.input_w // opt.down_ratio opt.input_res = max(opt.input_h, opt.input_w) opt.output_res = max(opt.output_h, opt.output_w) if opt.task == 'mot': opt.heads = {'hm': opt.num_classes, 'wh': 2 if not opt.ltrb else 4, 'id': opt.reid_dim} if opt.reg_offset: opt.heads.update({'reg': 2}) opt.nID = dataset.nID opt.img_size = (input_w, input_h) #opt.img_size = (864, 480) #opt.img_size = (576, 320) else: assert 0, 'task not defined!' print('heads', opt.heads) return opt def init(self, args=''): default_dataset_info = { 'mot': {'default_resolution': [608, 1088], 'num_classes': 1, 'mean': [0.408, 0.447, 0.470], 'std': [0.289, 0.274, 0.278], 'dataset': 'jde', 'nID': 14455}, } class Struct: def __init__(self, entries): for k, v in entries.items(): self.__setattr__(k, v) opt = self.parse(args) dataset = Struct(default_dataset_info[opt.task]) opt.dataset = dataset.dataset opt = self.update_dataset_info_and_set_heads(opt, dataset) return opt
51.347826
110
0.59318
ab09e4f69cec53addaef78b3a323e53b95a9e1b6
195
py
Python
ch09_movement_detector.py
jeffreycoen/prog_mb
739e9869b51dc861a57da697d49406b1394ade6d
[ "MIT" ]
13
2017-12-05T16:28:14.000Z
2022-02-21T22:05:00.000Z
ch09_movement_detector.py
jeffreycoen/prog_mb
739e9869b51dc861a57da697d49406b1394ade6d
[ "MIT" ]
null
null
null
ch09_movement_detector.py
jeffreycoen/prog_mb
739e9869b51dc861a57da697d49406b1394ade6d
[ "MIT" ]
5
2018-03-23T20:14:18.000Z
2021-03-15T06:37:58.000Z
from microbit import * THRESHOLD = 100 old_x = accelerometer.get_x() while True: x = accelerometer.get_x() if abs(x - old_x) > THRESHOLD: display.scroll("ALARM!") old_x = x
17.727273
34
0.641026
87b36acaeccd9fecffba48a7b0c6c61a3ff782b2
3,249
py
Python
deepspeech/training/gradclip.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
deepspeech/training/gradclip.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
deepspeech/training/gradclip.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
# 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 paddle from paddle.fluid import core from paddle.fluid import layers from paddle.fluid.dygraph import base as imperative_base from deepspeech.utils.log import Log __all__ = ["ClipGradByGlobalNormWithLog"] logger = Log(__name__).getlog() class ClipGradByGlobalNormWithLog(paddle.nn.ClipGradByGlobalNorm): def __init__(self, clip_norm): super().__init__(clip_norm) def __repr__(self): return f"{self.__class__.__name__}(global_clip_norm={self.clip_norm})" @imperative_base.no_grad def _dygraph_clip(self, params_grads): params_and_grads = [] sum_square_list = [] for i, (p, g) in enumerate(params_grads): if g is None: continue if getattr(p, 'need_clip', True) is False: continue merge_grad = g if g.type == core.VarDesc.VarType.SELECTED_ROWS: merge_grad = layers.merge_selected_rows(g) merge_grad = layers.get_tensor_from_selected_rows(merge_grad) square = layers.square(merge_grad) sum_square = layers.reduce_sum(square) sum_square_list.append(sum_square) # debug log, not dump all since slow down train process if i < 10: logger.debug( f"Grad Before Clip: {p.name}: {float(sum_square.sqrt()) }") # all parameters have been filterd out if len(sum_square_list) == 0: return params_grads global_norm_var = layers.concat(sum_square_list) global_norm_var = layers.reduce_sum(global_norm_var) global_norm_var = layers.sqrt(global_norm_var) # debug log logger.debug(f"Grad Global Norm: {float(global_norm_var)}!!!!") max_global_norm = layers.fill_constant( shape=[1], dtype=global_norm_var.dtype, value=self.clip_norm) clip_var = layers.elementwise_div( x=max_global_norm, y=layers.elementwise_max(x=global_norm_var, y=max_global_norm)) for i, (p, g) in enumerate(params_grads): if g is None: continue if getattr(p, 'need_clip', True) is False: params_and_grads.append((p, g)) continue new_grad = layers.elementwise_mul(x=g, y=clip_var) params_and_grads.append((p, new_grad)) # debug log, not dump all since slow down train process if i < 10: logger.debug( f"Grad After Clip: {p.name}: {float(new_grad.square().sum().sqrt())}" ) return params_and_grads
37.77907
89
0.640813
99a5b030816cf3054135d570219e4f15f9460451
3,350
py
Python
conopy/dbpool.py
sshmakov/conopy
6187297b3cd26faa7e6279dd184a7657b32914e7
[ "MIT" ]
5
2017-08-28T10:59:53.000Z
2021-12-16T07:06:45.000Z
conopy/dbpool.py
sshmakov/conopy
6187297b3cd26faa7e6279dd184a7657b32914e7
[ "MIT" ]
null
null
null
conopy/dbpool.py
sshmakov/conopy
6187297b3cd26faa7e6279dd184a7657b32914e7
[ "MIT" ]
12
2017-08-28T06:57:30.000Z
2021-04-28T12:09:19.000Z
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys, os from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtSql import * class DBLoginDlg(QDialog): def __init__(self, parent=None): super().__init__(parent) self.lay = QFormLayout() self.setWindowTitle("Login to DB") self.topLay = QVBoxLayout(self) self.topLay.setContentsMargins(6,6,6,6) self.lay = QFormLayout() self.topLay.addLayout(self.lay) self.btnLay = QHBoxLayout() self.topLay.addLayout(self.btnLay) self.userEdit = QLineEdit(self) self.passEdit = QLineEdit(self) self.passEdit.setEchoMode(QLineEdit.Password) self.lay.addRow("Пользователь",self.userEdit) self.lay.addRow("Пароль",self.passEdit) self.okBtn = QPushButton('Ok') self.okBtn.setDefault(True) self.cancelBtn = QPushButton('Отмена') self.btnLay.addWidget(self.okBtn) self.btnLay.addWidget(self.cancelBtn) self.okBtn.clicked.connect(self.accept) self.cancelBtn.clicked.connect(self.reject) def __getattr__(self, name): if name == 'user': return self.userEdit.text() if name == 'password': return self.passEdit.text() raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == 'user': self.userEdit.setText(value) return if name == 'password': self.passEdit.setText(value) return if name == 'dbname': self.setWindowTitle(value) return super().__setattr__(name,value) def openDatabase(dbini): db = QSqlDatabase.database(dbini) if not db.isValid(): ini = QSettings(dbini, QSettings.IniFormat) ini.setIniCodec("utf-8") ini.beginGroup("DB") dbdriver = ini.value("Driver") dbname = str(ini.value("DBName")) inipath = os.path.split(os.path.abspath(dbini))[0] dbname = dbname.format(inipath=inipath) dbuser = ini.value("DBUser") dbpass = ini.value("DBPass") needPrompt = ini.value("PromptLogin") if needPrompt: dlg = DBLoginDlg() dlg.user = dbuser dlg.password = dbpass dlg.dbname = os.path.basename(dbini) if not dlg.exec(): return None dbuser = dlg.user dbpass = dlg.password startSql = ini.value("StartSQL","") ini.endGroup() db = QSqlDatabase.addDatabase(dbdriver,dbini) db.setDatabaseName(dbname); db.setUserName(dbuser) db.setPassword(dbpass) if not db.open(): print("Error ({0}) on open DB '{2}'\n{1}".format( db.lastError().nativeErrorCode(), db.lastError().text(), dbini)) db = None QSqlDatabase.removeDatabase(dbini) return None if startSql != None and startSql != "": QSqlQuery(startSql, db).exec_() return db if __name__ == '__main__': app = QApplication(sys.argv) ex = DBLoginDlg() ex.user = 'abc' ex.password = 'abc' ex.exec() print(ex.user, ex.password) #sys.exit(app.exec_())
32.843137
99
0.58
2d2c7270fc7a5126fc9829a6f787a2b89c2d18a5
1,243
py
Python
src/app/externalOutages/checkIfOutageIsPresent.py
nagasudhirpulla/wrldc_codebook
8fbc795074e16e2012b29ae875b99aa721a7f021
[ "MIT" ]
null
null
null
src/app/externalOutages/checkIfOutageIsPresent.py
nagasudhirpulla/wrldc_codebook
8fbc795074e16e2012b29ae875b99aa721a7f021
[ "MIT" ]
21
2021-01-08T18:03:32.000Z
2021-02-02T16:17:34.000Z
src/app/externalOutages/checkIfOutageIsPresent.py
nagasudhirpulla/wrldc_codebook
8fbc795074e16e2012b29ae875b99aa721a7f021
[ "MIT" ]
null
null
null
import cx_Oracle def checkIfOutageIsPresent(pwcDbConnStr: str, rtoId: int) -> bool: """check if outage is present in pwc db Args: pwcDbConnStr (str): [description] rtoId (int): [description] Returns: bool: True if outage is present in pwc db """ outageCount = 0 countFetchSql = """ SELECT count(*) FROM REPORTING_WEB_UI_UAT.REAL_TIME_OUTAGE RTO WHERE RTO.ID = :1 """ dbConn = None dbCur = None try: # get connection with raw data table dbConn = cx_Oracle.connect(pwcDbConnStr) # get cursor and execute fetch sql dbCur = dbConn.cursor() dbCur.execute(countFetchSql, (rtoId,)) colNames = [row[0] for row in dbCur.description] dbRows = dbCur.fetchall() except Exception as err: dbRows = [] print('Error while fetching the count of rows by id from pwc rto table') print(err) finally: # closing database cursor and connection if dbCur is not None: dbCur.close() if dbConn is not None: dbConn.close() if not len(dbRows) == 0: outageCount = dbRows[0][0] return True if outageCount > 0 else False
24.372549
80
0.595334
51ffc5d79c9b9bd0007a24471247f29e24360141
4,927
py
Python
project_redss/auto_code_surveys.py
AfricasVoices/Project-REDSS
64999c5240fe8f1c839ccafccfa1e75b155c4787
[ "MIT" ]
null
null
null
project_redss/auto_code_surveys.py
AfricasVoices/Project-REDSS
64999c5240fe8f1c839ccafccfa1e75b155c4787
[ "MIT" ]
20
2018-11-21T15:58:36.000Z
2019-03-12T11:19:59.000Z
project_redss/auto_code_surveys.py
AfricasVoices/Project-REDSS
64999c5240fe8f1c839ccafccfa1e75b155c4787
[ "MIT" ]
null
null
null
import time from os import path from core_data_modules.cleaners import Codes, PhoneCleaner from core_data_modules.cleaners.cleaning_utils import CleaningUtils from core_data_modules.traced_data import Metadata from core_data_modules.traced_data.io import TracedDataCodaV2IO from core_data_modules.util import IOUtils from project_redss.lib.pipeline_configuration import PipelineConfiguration from project_redss.lib.redss_schemes import CodeSchemes class AutoCodeSurveys(object): SENT_ON_KEY = "sent_on" @classmethod def auto_code_surveys(cls, user, data, phone_uuid_table, coda_output_dir): # Label missing data for td in data: missing_dict = dict() for plan in PipelineConfiguration.SURVEY_CODING_PLANS: if td.get(plan.raw_field, "") == "": na_label = CleaningUtils.make_label_from_cleaner_code( plan.code_scheme, plan.code_scheme.get_code_with_control_code(Codes.TRUE_MISSING), Metadata.get_call_location() ) missing_dict[plan.coded_field] = na_label.to_dict() td.append_data(missing_dict, Metadata(user, Metadata.get_call_location(), time.time())) # Auto-code remaining data for plan in PipelineConfiguration.SURVEY_CODING_PLANS: if plan.cleaner is not None: CleaningUtils.apply_cleaner_to_traced_data_iterable(user, data, plan.raw_field, plan.coded_field, plan.cleaner, plan.code_scheme) # For any locations where the cleaners assigned a code to a sub district, set the district code to NC # (this is because only one column should have a value set in Coda) for td in data: if "mogadishu_sub_district_coded" in td: mogadishu_code_id = td["mogadishu_sub_district_coded"]["CodeID"] if CodeSchemes.MOGADISHU_SUB_DISTRICT.get_code_with_id(mogadishu_code_id).code_type == "Normal": nc_label = CleaningUtils.make_label_from_cleaner_code( CodeSchemes.MOGADISHU_SUB_DISTRICT, CodeSchemes.MOGADISHU_SUB_DISTRICT.get_code_with_control_code(Codes.NOT_CODED), Metadata.get_call_location(), ) td.append_data({"district_coded": nc_label.to_dict()}, Metadata(user, Metadata.get_call_location(), time.time())) # Set operator from phone number for td in data: operator_clean = PhoneCleaner.clean_operator(phone_uuid_table.get_phone(td["uid"])) if operator_clean == Codes.NOT_CODED: label = CleaningUtils.make_label_from_cleaner_code( CodeSchemes.OPERATOR, CodeSchemes.OPERATOR.get_code_with_control_code(Codes.NOT_CODED), Metadata.get_call_location() ) else: label = CleaningUtils.make_label_from_cleaner_code( CodeSchemes.OPERATOR, CodeSchemes.OPERATOR.get_code_with_match_value(operator_clean), Metadata.get_call_location() ) td.append_data({"operator_coded": label.to_dict()}, Metadata(user, Metadata.get_call_location(), time.time())) # Output single-scheme answers to coda for manual verification + coding IOUtils.ensure_dirs_exist(coda_output_dir) for plan in PipelineConfiguration.SURVEY_CODING_PLANS: if plan.raw_field == "mogadishu_sub_district_raw": continue TracedDataCodaV2IO.compute_message_ids(user, data, plan.raw_field, plan.id_field) coda_output_path = path.join(coda_output_dir, plan.coda_filename) with open(coda_output_path, "w") as f: TracedDataCodaV2IO.export_traced_data_iterable_to_coda_2( data, plan.raw_field, plan.time_field, plan.id_field, {plan.coded_field: plan.code_scheme}, f ) # Output location scheme to coda for manual verification + coding output_path = path.join(coda_output_dir, "location.json") TracedDataCodaV2IO.compute_message_ids(user, data, "mogadishu_sub_district_raw", "mogadishu_sub_district_raw_id") with open(output_path, "w") as f: TracedDataCodaV2IO.export_traced_data_iterable_to_coda_2( data, "mogadishu_sub_district_raw", "mogadishu_sub_district_time", "mogadishu_sub_district_raw_id", {"mogadishu_sub_district_coded": CodeSchemes.MOGADISHU_SUB_DISTRICT, "district_coded": CodeSchemes.DISTRICT, "region_coded": CodeSchemes.REGION, "state_coded": CodeSchemes.STATE, "zone_coded": CodeSchemes.ZONE}, f ) return data
52.414894
122
0.653745
8f92fa891ab471b245398d6ee766bcbbc9f60d43
4,245
py
Python
examples/AsyncProgressBar/progress_bar.py
rperesy/aioflask
446c34671fe2d7084815e2639cf416534ac1a5e8
[ "MIT" ]
189
2020-07-16T18:03:05.000Z
2022-03-31T02:07:12.000Z
examples/AsyncProgressBar/progress_bar.py
rperesy/aioflask
446c34671fe2d7084815e2639cf416534ac1a5e8
[ "MIT" ]
9
2020-07-17T01:23:57.000Z
2022-03-11T12:48:30.000Z
examples/AsyncProgressBar/progress_bar.py
rperesy/aioflask
446c34671fe2d7084815e2639cf416534ac1a5e8
[ "MIT" ]
8
2020-10-01T20:36:28.000Z
2021-08-12T05:25:59.000Z
import asyncio import random import aioredis import redis from aioflask import Flask, request, url_for, jsonify app = Flask(__name__) sr = redis.StrictRedis(host='localhost', port=6379) sr.execute_command('FLUSHDB') async def some_work(): global aredis await aredis.set('state', 'running') work_to_do = range(1, 26) await aredis.set('length_of_work', len(work_to_do)) for i in work_to_do: await aredis.set('processed', i) await asyncio.sleep(random.random()) await aredis.set('state', 'ready') await aredis.set('percent', 100) @app.route('/check_status/') async def check_status(): global aredis, sr status = dict() try: if await aredis.get('state') == b'running': if await aredis.get('processed') != await aredis.get('lastProcessed'): await aredis.set('percent', round( int(await aredis.get('processed')) / int(await aredis.get('length_of_work')) * 100, 2)) await aredis.set('lastProcessed', str(await aredis.get('processed'))) except: pass try: status['state'] = sr.get('state').decode() status['processed'] = sr.get('processed').decode() status['length_of_work'] = sr.get('length_of_work').decode() status['percent_complete'] = sr.get('percent').decode() except: status['state'] = sr.get('state') status['processed'] = sr.get('processed') status['length_of_work'] = sr.get('length_of_work') status['percent_complete'] = sr.get('percent') status['hint'] = 'refresh me.' return jsonify(status) @app.route('/progress/') async def progress(): return """ <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Asyncio Progress Bar Demo</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> var percent; function checkStatus() { $.getJSON('""" + url_for('check_status') + """', function (data) { console.log(data); percent = parseFloat(data.percent_complete); update_bar(percent); update_text(percent); }); if (percent != 100) { setTimeout(checkStatus, 1000); } } function update_bar(val) { if (val.length <= 0) { val = 0; } $( "#progressBar" ).progressbar({ value: val }); }; function update_text(val) { if (val != 100) { document.getElementById("progressData").innerHTML = "&nbsp;<center>"+percent+"%</center>"; } else { document.getElementById("progressData").innerHTML = "&nbsp;<center>Done!</center>"; } } checkStatus(); </script> </head> <body> <center><h2>Progress of work is shown below</h2></center> <div id="progressBar"></div> <div id="progressData" name="progressData"><center></center></div> </body> </html>""" @app.route('/') async def index(): return 'This is the index page. Try the following to <a href="' + url_for( 'start_work') + '">start some test work</a> with a progress indicator.' @app.route('/start_work/') async def start_work(): global aredis loop = asyncio.get_event_loop() aredis = await aioredis.create_redis('redis://localhost', loop=loop) if await aredis.get('state') == b'running': return "<center>Please wait for current work to finish.</center>" else: await aredis.set('state', 'ready') if await aredis.get('state') == b'ready': loop.create_task(some_work()) body = ''' <center> work started! </center> <script type="text/javascript"> window.location = "''' + url_for('progress') + '''"; </script>''' return body if __name__ == "__main__": app.run('localhost', port=5000, debug=True)
30.106383
107
0.589164
679ac71c782b54a88da4272cb69e2af6bfeb279b
3,122
py
Python
contrib/testgen/base58.py
thothd/unit-e
44cd02af44592ebfa99f276e20775ed7d2182d02
[ "MIT" ]
36
2019-04-17T18:58:51.000Z
2022-01-18T12:16:27.000Z
contrib/testgen/base58.py
Danpetersen448/unit-e
4ca86fc55a41e0daeb4409de2719a5523b6007c6
[ "MIT" ]
109
2019-04-17T17:19:45.000Z
2019-06-19T15:16:37.000Z
contrib/testgen/base58.py
Danpetersen448/unit-e
4ca86fc55a41e0daeb4409de2719a5523b6007c6
[ "MIT" ]
16
2019-04-17T17:35:42.000Z
2020-01-09T17:51:05.000Z
# Copyright (c) 2012-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Unit-e base58 encoding and decoding. Based on https://bitcointalk.org/index.php?topic=1026.0 (public domain) ''' import hashlib # for compatibility with following code... class SHA256: new = hashlib.sha256 if str != bytes: # Python 3.x def ord(c): return c def chr(n): return bytes( (n,) ) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) b58chars = __b58chars def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): if isinstance(c, str): c = ord(c) long_value += (256**i) * c result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Unit-e does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == 0: nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length = None): """ decode v into a string of len bytes """ long_value = 0 for i, c in enumerate(v[::-1]): pos = __b58chars.find(c) assert pos != -1 long_value += pos * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 continue break result = bytes(nPad) + result if length is not None and len(result) != length: return None return result def checksum(v): """Return 32-bit checksum based on SHA256""" return SHA256.new(SHA256.new(v).digest()).digest()[0:4] def b58encode_chk(v): """b58encode a string, with 32-bit checksum""" return b58encode(v + checksum(v)) def b58decode_chk(v): """decode a base58 string, check and remove checksum""" result = b58decode(v) if result is None: return None if result[-4:] == checksum(result[:-4]): return result[:-4] else: return None def get_bcaddress_version(strAddress): """ Returns None if strAddress is invalid. Otherwise returns integer version of address. """ addr = b58decode_chk(strAddress) if addr is None or len(addr)!=21: return None version = addr[0] return ord(version) if __name__ == '__main__': # Test case (from http://gitorious.org/bitcoin/python-base58.git) assert get_bcaddress_version('15VjRaDX9zpbA8LVnbrCAFzrVzN7ixHNsC') is 0 _ohai = 'o hai'.encode('ascii') _tmp = b58encode(_ohai) assert _tmp == 'DYB3oMS' assert b58decode(_tmp, 5) == _ohai print("Tests passed")
26.913793
97
0.620756
fd979c354eccf34c83fdeb82f8333428c1a6d40f
2,412
py
Python
packages/blueking/component/apis/bk_login.py
gangh/bk-sops
29f4b4915be42650c2eeee637e0cf798e4066f09
[ "Apache-2.0" ]
1
2019-12-23T07:23:35.000Z
2019-12-23T07:23:35.000Z
packages/blueking/component/apis/bk_login.py
bk-sops/bk-sops
9f5950b13473bf7b5032528b20016b7a571bb3cd
[ "Apache-2.0" ]
9
2020-02-12T03:15:49.000Z
2021-06-10T22:04:51.000Z
packages/blueking/component/apis/bk_login.py
tanghaiyong1989/bk-sops-ce
7388914acc4004469982d6b5bf9cd7641bdf82f7
[ "Apache-2.0" ]
1
2022-01-17T11:32:05.000Z
2022-01-17T11:32:05.000Z
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ from ..base import ComponentAPI class CollectionsBkLogin(object): """Collections of BK_LOGIN APIS""" def __init__(self, client): self.client = client self.get_all_users = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi{bk_api_ver}/bk_login/get_all_users/', description=u'获取所有用户信息' ) self.get_batch_users = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi{bk_api_ver}/bk_login/get_batch_users/', description=u'批量获取用户信息' ) self.get_batch_users_platform_role = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi{bk_api_ver}/bk_login/get_batch_users_platform_role/', description=u'批量获取用户各平台角色信息' ) self.get_user = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi{bk_api_ver}/bk_login/get_user/', description=u'获取用户信息' ) self.get_all_user = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi{bk_api_ver}/bk_login/get_all_user/', description=u'获取所有用户信息' ) self.get_batch_user = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi{bk_api_ver}/bk_login/get_batch_user/', description=u'获取多个用户信息' ) self.get_batch_user_platform_role = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi{bk_api_ver}/bk_login/get_batch_user_platform_role/', description=u'获取多个用户在平台应用的角色' )
41.586207
115
0.663765
5fb28d78525455b2ac2c9b2ee7fa6413ddb52d4c
1,591
py
Python
src/cogs/helpers/config.py
nsde-archive/novalix-1
7a521fd7d7662b3db49ef34e01b2508d9c4b9b2a
[ "MIT" ]
null
null
null
src/cogs/helpers/config.py
nsde-archive/novalix-1
7a521fd7d7662b3db49ef34e01b2508d9c4b9b2a
[ "MIT" ]
null
null
null
src/cogs/helpers/config.py
nsde-archive/novalix-1
7a521fd7d7662b3db49ef34e01b2508d9c4b9b2a
[ "MIT" ]
null
null
null
import yaml from typing import Union CONFIG_NAME = 'config' def load(filename: str=CONFIG_NAME): """Parses the config. Args: filename (str): A .yml-file name. Returns: dict: The parsed YAML Data from src/config.yml """ parsed_config_data = yaml.safe_load(open(f'src/{filename}.yml').read()) return parsed_config_data if parsed_config_data else {} def save(source, filename): yaml.dump(data=source, stream=open(f'src/{filename}.yml', 'w'), indent=2) def nested_set(dic: dict, keys: list, value) -> None: """Helps with editing a nested dictionary, credit: https://stackoverflow.com/a/13688108/14345173 Args: dic (dict): Input dictionary keys (list): List of keys for the path value (any): Value to set """ create_missing = True d = dic for key in keys[:-1]: if key in d: d = d[key] elif create_missing: d = d.setdefault(key, {}) else: return dic if keys[-1] in d or create_missing: d[keys[-1]] = value return dic def edit(path: Union[str, list], to: str, filename: str=CONFIG_NAME) -> None: """Edits the config Args: path (str/list): path for the keys to access/edit to (str): Value to edit it to """ if isinstance(path, str): path = [path] source = load(filename=filename) nested_set(source, path, to) save(source=source, filename=filename) if __name__ == '__main__': print(load('join_channels')) save({'t': 1, 5: {'yes': False}}, 'join_channels')
24.859375
100
0.607794
2a3dd8ce1ecdc4ab27ef69a0d5cab82afc1135de
618
py
Python
blog/migrations/0008_auto_20160217_0315.py
StratoBallooning/website
dad8db401279674d03355fdf5557c73074ff851f
[ "MIT" ]
null
null
null
blog/migrations/0008_auto_20160217_0315.py
StratoBallooning/website
dad8db401279674d03355fdf5557c73074ff851f
[ "MIT" ]
19
2016-02-17T03:41:17.000Z
2016-02-24T03:01:18.000Z
blog/migrations/0008_auto_20160217_0315.py
StratoBallooning/website
dad8db401279674d03355fdf5557c73074ff851f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-17 03:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20160217_0247'), ] operations = [ migrations.AlterModelOptions( name='blogpageauthor', options={'ordering': ['sort_order']}, ), migrations.AddField( model_name='blogpageauthor', name='sort_order', field=models.IntegerField(blank=True, editable=False, null=True), ), ]
24.72
77
0.606796
b17458c523ab9c97caaf983994c36b4854c7b249
20,743
py
Python
electrum/exchange_rate.py
tzarebczan/electrum
11b95709aa3c17736ab7c957c87ad33cddaa12f3
[ "MIT" ]
2
2019-10-04T23:57:13.000Z
2020-05-19T23:24:29.000Z
electrum/exchange_rate.py
tzarebczan/electrum
11b95709aa3c17736ab7c957c87ad33cddaa12f3
[ "MIT" ]
1
2018-12-12T18:06:31.000Z
2018-12-12T18:06:31.000Z
electrum/exchange_rate.py
tzarebczan/electrum
11b95709aa3c17736ab7c957c87ad33cddaa12f3
[ "MIT" ]
3
2018-11-29T20:46:49.000Z
2020-02-14T14:00:43.000Z
import asyncio from datetime import datetime import inspect import sys import os import json import time import csv import decimal from decimal import Decimal import concurrent.futures import traceback from typing import Sequence from .bitcoin import COIN from .i18n import _ from .util import PrintError, ThreadJob, make_dir, log_exceptions from .util import make_aiohttp_session from .network import Network from .simple_config import SimpleConfig # See https://en.wikipedia.org/wiki/ISO_4217 CCY_PRECISIONS = {'BHD': 3, 'BIF': 0, 'BYR': 0, 'CLF': 4, 'CLP': 0, 'CVE': 0, 'DJF': 0, 'GNF': 0, 'IQD': 3, 'ISK': 0, 'JOD': 3, 'JPY': 0, 'KMF': 0, 'KRW': 0, 'KWD': 3, 'LYD': 3, 'MGA': 1, 'MRO': 1, 'OMR': 3, 'PYG': 0, 'RWF': 0, 'TND': 3, 'UGX': 0, 'UYI': 0, 'VND': 0, 'VUV': 0, 'XAF': 0, 'XAU': 4, 'XOF': 0, 'XPF': 0} class ExchangeBase(PrintError): def __init__(self, on_quotes, on_history): self.history = {} self.quotes = {} self.on_quotes = on_quotes self.on_history = on_history async def get_raw(self, site, get_string): # APIs must have https url = ''.join(['https://', site, get_string]) async with make_aiohttp_session(Network.get_instance().proxy) as session: async with session.get(url) as response: return await response.text() async def get_json(self, site, get_string): # APIs must have https url = ''.join(['https://', site, get_string]) async with make_aiohttp_session(Network.get_instance().proxy) as session: async with session.get(url) as response: # set content_type to None to disable checking MIME type return await response.json(content_type=None) async def get_csv(self, site, get_string): raw = await self.get_raw(site, get_string) reader = csv.DictReader(raw.split('\n')) return list(reader) def name(self): return self.__class__.__name__ @log_exceptions async def update_safe(self, ccy): try: self.print_error("getting fx quotes for", ccy) self.quotes = await self.get_rates(ccy) self.print_error("received fx quotes") except BaseException as e: self.print_error("failed fx quotes:", repr(e)) self.quotes = {} self.on_quotes() def update(self, ccy): asyncio.get_event_loop().create_task(self.update_safe(ccy)) def read_historical_rates(self, ccy, cache_dir): filename = os.path.join(cache_dir, self.name() + '_'+ ccy) if os.path.exists(filename): timestamp = os.stat(filename).st_mtime try: with open(filename, 'r', encoding='utf-8') as f: h = json.loads(f.read()) h['timestamp'] = timestamp except: h = None else: h = None if h: self.history[ccy] = h self.on_history() return h @log_exceptions async def get_historical_rates_safe(self, ccy, cache_dir): try: self.print_error("requesting fx history for", ccy) h = await self.request_history(ccy) self.print_error("received fx history for", ccy) except BaseException as e: self.print_error("failed fx history:", e) #traceback.print_exc() return filename = os.path.join(cache_dir, self.name() + '_' + ccy) with open(filename, 'w', encoding='utf-8') as f: f.write(json.dumps(h)) h['timestamp'] = time.time() self.history[ccy] = h self.on_history() def get_historical_rates(self, ccy, cache_dir): if ccy not in self.history_ccys(): return h = self.history.get(ccy) if h is None: h = self.read_historical_rates(ccy, cache_dir) if h is None or h['timestamp'] < time.time() - 24*3600: asyncio.get_event_loop().create_task(self.get_historical_rates_safe(ccy, cache_dir)) def history_ccys(self): return [] def historical_rate(self, ccy, d_t): return self.history.get(ccy, {}).get(d_t.strftime('%Y-%m-%d'), 'NaN') def get_currencies(self): rates = self.get_rates('') return sorted([str(a) for (a, b) in rates.items() if b is not None and len(a)==3]) class BitcoinAverage(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('apiv2.bitcoinaverage.com', '/indices/global/ticker/short') return dict([(r.replace("LBC", ""), Decimal(json[r]['last'])) for r in json if r != 'timestamp']) def history_ccys(self): return ['AUD', 'BRL', 'CAD', 'CHF', 'CNY', 'EUR', 'GBP', 'IDR', 'ILS', 'MXN', 'NOK', 'NZD', 'PLN', 'RON', 'RUB', 'SEK', 'SGD', 'USD', 'ZAR'] async def request_history(self, ccy): history = await self.get_csv('apiv2.bitcoinaverage.com', "/indices/global/history/BTC%s?period=alltime&format=csv" % ccy) return dict([(h['DateTime'][:10], h['Average']) for h in history]) class Bitcointoyou(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('bitcointoyou.com', "/API/ticker.aspx") return {'BRL': Decimal(json['ticker']['last'])} def history_ccys(self): return ['BRL'] class BitcoinVenezuela(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.bitcoinvenezuela.com', '/') rates = [(r, json['LBC'][r]) for r in json['LBC'] if json['LBC'][r] is not None] # Giving NULL for LTC return dict(rates) def history_ccys(self): return ['ARS', 'EUR', 'USD', 'VEF'] async def request_history(self, ccy): json = await self.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=LBC") return json[ccy +'_LBC'] class Bitbank(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('public.bitbank.cc', '/btc_jpy/ticker') return {'JPY': Decimal(json['data']['last'])} class BitFlyer(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('bitflyer.jp', '/api/echo/price') return {'JPY': Decimal(json['mid'])} class Bitmarket(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('www.bitmarket.pl', '/json/BTCPLN/ticker.json') return {'PLN': Decimal(json['last'])} class BitPay(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('bitpay.com', '/api/rates') return dict([(r['code'], Decimal(r['rate'])) for r in json]) class Bitso(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.bitso.com', '/v2/ticker') return {'MXN': Decimal(json['last'])} class BitStamp(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('www.bitstamp.net', '/api/ticker/') return {'USD': Decimal(json['last'])} class Bitvalor(ExchangeBase): async def get_rates(self,ccy): json = await self.get_json('api.bitvalor.com', '/v1/ticker.json') return {'BRL': Decimal(json['ticker_1h']['total']['last'])} class BlockchainInfo(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('blockchain.info', '/ticker') return dict([(r, Decimal(json[r]['15m'])) for r in json]) class BTCChina(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('data.btcchina.com', '/data/ticker') return {'CNY': Decimal(json['ticker']['last'])} class BTCParalelo(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('btcparalelo.com', '/api/price') return {'VEF': Decimal(json['price'])} class Coinbase(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('coinbase.com', '/api/v1/currencies/exchange_rates') return dict([(r[7:].upper(), Decimal(json[r])) for r in json if r.startswith('btc_to_')]) class CoinDesk(ExchangeBase): async def get_currencies(self): dicts = await self.get_json('api.coindesk.com', '/v1/bpi/supported-currencies.json') return [d['currency'] for d in dicts] async def get_rates(self, ccy): json = await self.get_json('api.coindesk.com', '/v1/bpi/currentprice/%s.json' % ccy) result = {ccy: Decimal(json['bpi'][ccy]['rate_float'])} return result def history_starts(self): return { 'USD': '2012-11-30', 'EUR': '2013-09-01' } def history_ccys(self): return self.history_starts().keys() async def request_history(self, ccy): start = self.history_starts()[ccy] end = datetime.today().strftime('%Y-%m-%d') # Note ?currency and ?index don't work as documented. Sigh. query = ('/v1/bpi/historical/close.json?start=%s&end=%s' % (start, end)) json = await self.get_json('api.coindesk.com', query) return json['bpi'] class Coinsecure(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.coinsecure.in', '/v0/noauth/newticker') return {'INR': Decimal(json['lastprice'] / 100.0 )} class CoinMarketCap(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.coinmarketcap.com', '/v2/ticker/1298/?convert=%s' % ccy) result = {ccy: Decimal(json['data']['quotes'][ccy]['price'])} return result class Foxbit(ExchangeBase): async def get_rates(self,ccy): json = await self.get_json('api.bitvalor.com', '/v1/ticker.json') return {'BRL': Decimal(json['ticker_1h']['exchanges']['FOX']['last'])} class itBit(ExchangeBase): async def get_rates(self, ccy): ccys = ['USD', 'EUR', 'SGD'] json = await self.get_json('api.itbit.com', '/v1/markets/XBT%s/ticker' % ccy) result = dict.fromkeys(ccys) if ccy in ccys: result[ccy] = Decimal(json['lastPrice']) return result class Kraken(ExchangeBase): async def get_rates(self, ccy): ccys = ['EUR', 'USD', 'CAD', 'GBP', 'JPY'] pairs = ['XBT%s' % c for c in ccys] json = await self.get_json('api.kraken.com', '/0/public/Ticker?pair=%s' % ','.join(pairs)) return dict((k[-3:], Decimal(float(v['c'][0]))) for k, v in json['result'].items()) class LocalBitcoins(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('localbitcoins.com', '/bitcoinaverage/ticker-all-currencies/') return dict([(r, Decimal(json[r]['rates']['last'])) for r in json]) class MercadoBitcoin(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.bitvalor.com', '/v1/ticker.json') return {'BRL': Decimal(json['ticker_1h']['exchanges']['MBT']['last'])} class NegocieCoins(ExchangeBase): async def get_rates(self,ccy): json = await self.get_json('api.bitvalor.com', '/v1/ticker.json') return {'BRL': Decimal(json['ticker_1h']['exchanges']['NEG']['last'])} class TheRockTrading(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.therocktrading.com', '/v1/funds/BTCEUR/ticker') return {'EUR': Decimal(json['last'])} class Unocoin(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('www.unocoin.com', 'trade?buy') return {'INR': Decimal(json)} class WEX(ExchangeBase): async def get_rates(self, ccy): json_eur = await self.get_json('wex.nz', '/api/3/ticker/btc_eur') json_rub = await self.get_json('wex.nz', '/api/3/ticker/btc_rur') json_usd = await self.get_json('wex.nz', '/api/3/ticker/btc_usd') return {'EUR': Decimal(json_eur['btc_eur']['last']), 'RUB': Decimal(json_rub['btc_rur']['last']), 'USD': Decimal(json_usd['btc_usd']['last'])} class Winkdex(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('winkdex.com', '/api/v0/price') return {'USD': Decimal(json['price'] / 100.0)} def history_ccys(self): return ['USD'] async def request_history(self, ccy): json = await self.get_json('winkdex.com', "/api/v0/series?start_time=1342915200") history = json['series'][0]['results'] return dict([(h['timestamp'][:10], h['price'] / 100.0) for h in history]) class Zaif(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.zaif.jp', '/api/1/last_price/btc_jpy') return {'JPY': Decimal(json['last_price'])} def dictinvert(d): inv = {} for k, vlist in d.items(): for v in vlist: keys = inv.setdefault(v, []) keys.append(k) return inv def get_exchanges_and_currencies(): path = os.path.join(os.path.dirname(__file__), 'currencies.json') try: with open(path, 'r', encoding='utf-8') as f: return json.loads(f.read()) except: pass d = {} is_exchange = lambda obj: (inspect.isclass(obj) and issubclass(obj, ExchangeBase) and obj != ExchangeBase) exchanges = dict(inspect.getmembers(sys.modules[__name__], is_exchange)) for name, klass in exchanges.items(): exchange = klass(None, None) try: d[name] = exchange.get_currencies() print(name, "ok") except: print(name, "error") continue with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(d, indent=4, sort_keys=True)) return d CURRENCIES = get_exchanges_and_currencies() def get_exchanges_by_ccy(history=True): if not history: return dictinvert(CURRENCIES) d = {} exchanges = CURRENCIES.keys() for name in exchanges: klass = globals()[name] exchange = klass(None, None) d[name] = exchange.history_ccys() return dictinvert(d) class FxThread(ThreadJob): def __init__(self, config: SimpleConfig, network: Network): self.config = config self.network = network if self.network: self.network.register_callback(self.set_proxy, ['proxy_set']) self.ccy = self.get_currency() self.history_used_spot = False self.ccy_combo = None self.hist_checkbox = None self.cache_dir = os.path.join(config.path, 'cache') self._trigger = asyncio.Event() self._trigger.set() self.set_exchange(self.config_exchange()) make_dir(self.cache_dir) def set_proxy(self, trigger_name, *args): self._trigger.set() @staticmethod def get_currencies(history: bool) -> Sequence[str]: d = get_exchanges_by_ccy(history) return sorted(d.keys()) @staticmethod def get_exchanges_by_ccy(ccy: str, history: bool) -> Sequence[str]: d = get_exchanges_by_ccy(history) return d.get(ccy, []) def ccy_amount_str(self, amount, commas): prec = CCY_PRECISIONS.get(self.ccy, 2) fmt_str = "{:%s.%df}" % ("," if commas else "", max(0, prec)) try: rounded_amount = round(amount, prec) except decimal.InvalidOperation: rounded_amount = amount return fmt_str.format(rounded_amount) async def run(self): while True: try: await asyncio.wait_for(self._trigger.wait(), 150) except concurrent.futures.TimeoutError: pass else: self._trigger.clear() if self.is_enabled(): if self.show_history(): self.exchange.get_historical_rates(self.ccy, self.cache_dir) if self.is_enabled(): self.exchange.update(self.ccy) def is_enabled(self): return bool(self.config.get('use_exchange_rate', True)) def set_enabled(self, b): self.config.set_key('use_exchange_rate', bool(b)) self.trigger_update() def get_history_config(self): return bool(self.config.get('history_rates')) def set_history_config(self, b): self.config.set_key('history_rates', bool(b)) def get_history_capital_gains_config(self): return bool(self.config.get('history_rates_capital_gains', False)) def set_history_capital_gains_config(self, b): self.config.set_key('history_rates_capital_gains', bool(b)) def get_fiat_address_config(self): return bool(self.config.get('fiat_address')) def set_fiat_address_config(self, b): self.config.set_key('fiat_address', bool(b)) def get_currency(self): '''Use when dynamic fetching is needed''' return self.config.get("currency", "USD") def config_exchange(self): return self.config.get('use_exchange', 'CoinMarketCap') def show_history(self): return self.is_enabled() and self.get_history_config() and self.ccy in self.exchange.history_ccys() def set_currency(self, ccy): self.ccy = ccy self.config.set_key('currency', ccy, True) self.trigger_update() self.on_quotes() def trigger_update(self): if self.network: self.network.asyncio_loop.call_soon_threadsafe(self._trigger.set) def set_exchange(self, name): class_ = globals().get(name, BitcoinAverage) self.print_error("using exchange", name) if self.config_exchange() != name: self.config.set_key('use_exchange', name, True) self.exchange = class_(self.on_quotes, self.on_history) # A new exchange means new fx quotes, initially empty. Force # a quote refresh self.trigger_update() self.exchange.read_historical_rates(self.ccy, self.cache_dir) def on_quotes(self): if self.network: self.network.trigger_callback('on_quotes') def on_history(self): if self.network: self.network.trigger_callback('on_history') def exchange_rate(self) -> Decimal: """Returns the exchange rate as a Decimal""" rate = self.exchange.quotes.get(self.ccy) if rate is None: return Decimal('NaN') return Decimal(rate) def format_amount(self, btc_balance): rate = self.exchange_rate() return '' if rate.is_nan() else "%s" % self.value_str(btc_balance, rate) def format_amount_and_units(self, btc_balance): rate = self.exchange_rate() return '' if rate.is_nan() else "%s %s" % (self.value_str(btc_balance, rate), self.ccy) def get_fiat_status_text(self, btc_balance, base_unit, decimal_point): rate = self.exchange_rate() return _(" (No FX rate available)") if rate.is_nan() else " 1 %s~%s %s" % (base_unit, self.value_str(COIN / (10**(8 - decimal_point)), rate), self.ccy) def fiat_value(self, satoshis, rate): return Decimal('NaN') if satoshis is None else Decimal(satoshis) / COIN * Decimal(rate) def value_str(self, satoshis, rate): return self.format_fiat(self.fiat_value(satoshis, rate)) def format_fiat(self, value): if value.is_nan(): return _("No data") return "%s" % (self.ccy_amount_str(value, True)) def history_rate(self, d_t): if d_t is None: return Decimal('NaN') rate = self.exchange.historical_rate(self.ccy, d_t) # Frequently there is no rate for today, until tomorrow :) # Use spot quotes in that case if rate == 'NaN' and (datetime.today().date() - d_t.date()).days <= 2: rate = self.exchange.quotes.get(self.ccy, 'NaN') self.history_used_spot = True return Decimal(rate) def historical_value_str(self, satoshis, d_t): return self.format_fiat(self.historical_value(satoshis, d_t)) def historical_value(self, satoshis, d_t): return self.fiat_value(satoshis, self.history_rate(d_t)) def timestamp_rate(self, timestamp): from .util import timestamp_to_datetime date = timestamp_to_datetime(timestamp) return self.history_rate(date)
33.893791
107
0.602372
b0aaa69e60cfabe4e163edaf9800b0b87f498b75
3,101
py
Python
Window.py
BrunoMartins11/UPT_Protocol
4daf74df61ce3694d414e0d1518d33cbe738ecff
[ "MIT" ]
null
null
null
Window.py
BrunoMartins11/UPT_Protocol
4daf74df61ce3694d414e0d1518d33cbe738ecff
[ "MIT" ]
null
null
null
Window.py
BrunoMartins11/UPT_Protocol
4daf74df61ce3694d414e0d1518d33cbe738ecff
[ "MIT" ]
null
null
null
import utils as CC from random import randint class Window: def __init__(self, ws): self.msg_window = [] self.initial_sn = randint(0, 65535) self.current_sn = self.initial_sn self.ws = ws self.cwnd = 1 self.dup_ack = 0 self.ssthresh = 64 self.state = CC.SLOW_START self.action = CC.TRANS def push(self, data): self.msg_window.append(data) def ack(self, seqno): if self.state == CC.SLOW_START: self.slow_start(seqno) elif self.state == CC.AVOID_CONGEST: self.avoid(seqno) else: self.quick_r(seqno) temp_packet = [] temp_index = 0 for index in list(range(len(self.msg_window))): if seqno == self.msg_window[index][0]: temp_packet = self.msg_window[index] temp_index = index break if len(temp_packet) > 0: if self.msg_window[temp_index][2]: del self.msg_window[temp_index] return True return False def slow_start(self, seqno): if self.cwnd >= self.ssthresh: self.state = CC.AVOID_CONGEST self.avoid(seqno) elif list(filter(lambda x: x[2] and x[0] == seqno, self.msg_window)): self.cwnd += 1 self.dup_ack = 0 self.action = CC.TRANS else: self.dup_ack += 1 if self.dup_ack == 3: self.to_quick_r() def avoid(self, seqno): if list(filter(lambda x: x[2] and x[0] == seqno, self.msg_window)): self.cwnd += (1 / self.cwnd) self.dup_ack = 0 self.action = CC.TRANS else: self.dup_ack += 1 if self.dup_ack == 3: self.to_quick_r() def quick_r(self, seqno): old_ack = list(filter(lambda x: x[2] and x[0] == seqno, self.msg_window)) if not old_ack: self.cwnd += 1 self.action = CC.TRANS elif old_ack: self.state = CC.AVOID_CONGEST self.cwnd = self.ssthresh self.dup_ack = 0 def to_quick_r(self): self.state = CC.QUICK_RECOVER self.action = CC.RETRANS self.ssthresh = self.cwnd / 2 self.cwnd = self.ssthresh + 3 def can_send(self, rwnd): return len(self.msg_window) < min([self.cwnd, self.ws, rwnd]) def timeout(self): self.ssthresh = self.cwnd / 2 self.cwnd = 1 self.dup_ack = 0 self.state = CC.SLOW_START self.action = CC.RETRANS def to_send(self): packets = [] i = 0 while i < len(self.msg_window): if not self.msg_window[i][2]: packets.append((self.msg_window[i], i)) i += 1 return packets def to_ack(self): packets = [] i = 0 while i < len(self.msg_window): if self.msg_window[i][2]: packets.append((self.msg_window[i], i)) i += 1 return packets
28.449541
81
0.521445
8cd2b5266219c5f678f2d38388ff430efc79e6ef
4,748
py
Python
vtrace.py
seungwoos/minimalRL
7597b9af94ee64536dfd261446d795854f34171b
[ "MIT" ]
2,259
2019-05-03T23:33:01.000Z
2022-03-30T09:50:00.000Z
vtrace.py
Olegnv47/minimalRL
7597b9af94ee64536dfd261446d795854f34171b
[ "MIT" ]
47
2019-05-26T20:52:51.000Z
2021-11-16T05:55:32.000Z
vtrace.py
Olegnv47/minimalRL
7597b9af94ee64536dfd261446d795854f34171b
[ "MIT" ]
375
2019-05-17T12:22:36.000Z
2022-03-22T18:48:39.000Z
import gym import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Categorical import numpy as np #Hyperparameters learning_rate = 0.0005 gamma = 0.98 T_horizon = 20 clip_rho_threshold = 1.0 clip_c_threshold = 1.0 print_interval = 20 class Vtrace(nn.Module): def __init__(self): super(Vtrace, self).__init__() self.data = [] self.fc1 = nn.Linear(4,256) self.fc_pi = nn.Linear(256,2) self.fc_v = nn.Linear(256,1) self.optimizer = optim.Adam(self.parameters(), lr=learning_rate) self.clip_rho_threshold = torch.tensor(clip_rho_threshold, dtype=torch.float) self.clip_c_threshold = torch.tensor(clip_c_threshold, dtype=torch.float) def pi(self, x, softmax_dim = 0): x = F.relu(self.fc1(x)) x = self.fc_pi(x) prob = F.softmax(x, dim=softmax_dim) return prob def v(self, x): x = F.relu(self.fc1(x)) v = self.fc_v(x) return v def put_data(self, transition): self.data.append(transition) def make_batch(self): s_lst, a_lst, r_lst, s_prime_lst, mu_a_lst, done_lst = [], [], [], [], [], [] for transition in self.data: s, a, r, s_prime, mu_a, done = transition s_lst.append(s) a_lst.append([a]) r_lst.append([r]) s_prime_lst.append(s_prime) mu_a_lst.append([mu_a]) done_mask = 0 if done else 1 done_lst.append([done_mask]) s,a,r,s_prime,done_mask, mu_a = torch.tensor(s_lst, dtype=torch.float), torch.tensor(a_lst), \ torch.tensor(r_lst), torch.tensor(s_prime_lst, dtype=torch.float), \ torch.tensor(done_lst, dtype=torch.float), torch.tensor(mu_a_lst) self.data = [] return s, a, r, s_prime, done_mask, mu_a def vtrace(self, s, a, r, s_prime, done_mask, mu_a): with torch.no_grad(): pi = self.pi(s, softmax_dim=1) pi_a = pi.gather(1,a) v, v_prime = self.v(s), self.v(s_prime) ratio = torch.exp(torch.log(pi_a) - torch.log(mu_a)) # a/b == exp(log(a)-log(b)) rhos = torch.min(self.clip_rho_threshold, ratio) cs = torch.min(self.clip_c_threshold, ratio).numpy() td_target = r + gamma * v_prime * done_mask delta = rhos*(td_target - v).numpy() vs_minus_v_xs_lst = [] vs_minus_v_xs = 0.0 vs_minus_v_xs_lst.append([vs_minus_v_xs]) for i in range(len(delta)-1, -1, -1): vs_minus_v_xs = gamma * cs[i][0] * vs_minus_v_xs + delta[i][0] vs_minus_v_xs_lst.append([vs_minus_v_xs]) vs_minus_v_xs_lst.reverse() vs_minus_v_xs = torch.tensor(vs_minus_v_xs_lst, dtype=torch.float) vs = vs_minus_v_xs[:-1] + v.numpy() vs_prime = vs_minus_v_xs[1:] + v_prime.numpy() advantage = r + gamma * vs_prime - v.numpy() return vs, advantage, rhos def train_net(self): s, a, r, s_prime, done_mask, mu_a = self.make_batch() vs, advantage, rhos = self.vtrace(s, a, r, s_prime, done_mask, mu_a) pi = self.pi(s, softmax_dim=1) pi_a = pi.gather(1,a) val_loss = F.smooth_l1_loss(self.v(s) , vs) pi_loss = -rhos * torch.log(pi_a) * advantage loss = pi_loss + val_loss self.optimizer.zero_grad() loss.mean().backward() self.optimizer.step() def main(): env = gym.make('CartPole-v1') model = Vtrace() score = 0.0 for n_epi in range(10000): s = env.reset() done = False while not done: for t in range(T_horizon): prob = model.pi(torch.from_numpy(s).float()) m = Categorical(prob) a = m.sample().item() s_prime, r, done, info = env.step(a) model.put_data((s, a, r/100.0, s_prime, prob[a].item(), done)) s = s_prime score += r if done: break model.train_net() if n_epi%print_interval==0 and n_epi!=0: print("# of episode :{}, avg score : {:.1f}".format(n_epi, score/print_interval)) score = 0.0 env.close() if __name__ == '__main__': main()
34.656934
109
0.524853
26d1033928e5dc7e6131b5b0ba4aced5f95ad7d9
7,893
py
Python
COMP9418_Assignment_2/example_test.py
usama-sadiq/COMP9418_20T3
af5561c146f463da838a621d1adf0fad8b7777fa
[ "MIT" ]
null
null
null
COMP9418_Assignment_2/example_test.py
usama-sadiq/COMP9418_20T3
af5561c146f463da838a621d1adf0fad8b7777fa
[ "MIT" ]
null
null
null
COMP9418_Assignment_2/example_test.py
usama-sadiq/COMP9418_20T3
af5561c146f463da838a621d1adf0fad8b7777fa
[ "MIT" ]
null
null
null
''' COMP9418 Assignment 2 This file is similar to the file that will be used to test your assignment It should be used to make sure you code will work during testing ''' # Make division default to floating-point, saving confusion from __future__ import division # Allowed libraries import numpy as np import pandas as pd import datetime import time # import the function written by the student #from example_solution import get_action from example_solution_latest import get_action # simulator code class Person: def __init__(self, name, office=None): self.name = name def timestep(self, building_simulator): pass class ReliableSensor: def __init__(self, name, room): self.room = room self.name = name def get_output(self, room_occupancy): pass class UnreliableSensor: def __init__(self, name, room): self.room = room self.name = name def get_output(self, room_occupancy): pass class DoorSensor: def __init__(self, name, rooms): self.rooms = rooms #pair of rooms self.name = name def get_output(self, building_simulator): pass class Robot: def __init__(self, name, start_room): self.name = name self.current_location = start_room def timestep(self, building_simulator): pass off_cost = 0 wastage = 0 zero_count = 0 one_count = 0 start = time.time() # part of the code from the building simulator. class SmartBuildingSimulatorExample: def __init__(self): self.data = pd.read_csv('data.csv') self.num_lights = 35 self.num_people = 20 self.start_time = datetime.time(hour=8,minute=0) self.end_time = datetime.time(18,0) self.time_step = datetime.timedelta(seconds=15) # 15 second self.current_time = self.start_time self.current_electricity_price = 1.0 self.productivity_cost = 4 # cumulative cost so far today self.cost = 0 self.people = [Person(i) for i in range(1,self.num_people+1)] self.room_occupancy = dict([(room, 0) for room in ['r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15', 'r16', 'r17', 'r18', 'r19', 'r20', 'r21', 'r22', 'r23', 'r24', 'r25', 'r26', 'r27', 'r28', 'r29', 'r30', 'r31', 'r32', 'r33', 'r34', 'r35', 'c1', 'c2', 'c3', 'c4', 'o1', 'outside']]) self.room_occupancy['outside'] = self.num_people # current state of lights lights = {} for i in range(1,self.num_lights+1): lights["lights"+str(i)] = "off" self.lights = lights # set up of all sensors self.reliable_motion_sensors = [ReliableSensor('reliable_sensor1','r16'), ReliableSensor('reliable_sensor2','r5'), ReliableSensor('reliable_sensor3','r25'), ReliableSensor('reliable_sensor4','r31'), ] self.unreliable_motion_sensors = [UnreliableSensor('unreliable_sensor1','o1'), UnreliableSensor('unreliable_sensor2','c3'), UnreliableSensor('unreliable_sensor3','r1'), UnreliableSensor('unreliable_sensor4','r24'), ] self.door_sensors = [DoorSensor('door_sensor1',('r8','r9')), DoorSensor('door_sensor2',('c1','c2')), DoorSensor('door_sensor3',('r26','r27')), DoorSensor('door_sensor4',('c4','r35')) ] # the robot starts in room 1, and randomly wanders self.robot_sensors = [Robot('robot1','r1'), Robot('robot2', 'r19')] self.curr_step = 0 def timestep(self, actions_dict=None): ''' actions_dict is a dictionary that maps from action strings to either 'on' or 'off' ''' # do actions if actions_dict is not None: for key in actions_dict: self.lights[key] # test that that action exists self.lights[key] = actions_dict[key] # get data for current timestep (only for example) current_data = self.data.iloc[self.curr_step] # move people for room in self.room_occupancy: self.room_occupancy[room] = current_data.loc[room] # increment time self.current_time = (datetime.datetime.combine(datetime.date.today(), self.current_time) + self.time_step).time() # calculate cost self.cost += self.cost_of_prev_timestep(self.current_electricity_price) # update electricity price self.current_electricity_price *= np.random.choice([0.98,1/0.98,1.0]) # simple martingale #self.current_electricity_price = 1 # work out sensor data sensor_data = {} for sensor in self.reliable_motion_sensors + self.unreliable_motion_sensors: sensor_data[sensor.name] = current_data[sensor.name] for robot in self.robot_sensors: sensor_data[robot.name] = current_data[robot.name] for sensor in self.door_sensors: sensor_data[sensor.name] = current_data[sensor.name] # To make sure your code can handle this case, # set one random sensor to None broken_sensor = np.random.choice(list(sensor_data.keys())) sensor_data[broken_sensor] = None sensor_data['time'] = self.current_time sensor_data['electricity_price'] = self.current_electricity_price self.curr_step += 1 return sensor_data def cost_of_prev_timestep(self, electricity_price): ''' calculates the cost incurred in the previous 2 minutes ''' global off_cost global wastage global zero_count global one_count cost = 0 #off_cost = 0 #wastage = 0 #zero_count = 0 #one_count = 0 for light, state in self.lights.items(): room_num = 'r' + (light[6:]) # extract number from string if state == 'on': waste = self.current_electricity_price cost += waste if self.room_occupancy[room_num] == 0: wastage+=waste #zero_count+=1 elif state == 'off': temp = self.productivity_cost*self.room_occupancy[room_num] cost += temp off_cost+=temp #one_count+=1 # if temp > 0: # print("off_cost->" + str(off_cost)) else: raise Exception("Invalid light state") return cost simulator = SmartBuildingSimulatorExample() sensor_data = simulator.timestep() for i in range(len(simulator.data)-1): actions_dict = get_action(sensor_data) sensor_data = simulator.timestep(actions_dict) print("################################################################") print(f"Total cost for the day: {simulator.cost} cents") print("Off Cost ->" + str(off_cost)) print("################################################################") print("Wastage -> " + str(wastage)) print("##################################################################") #print("zero erro -> " + str(zero_count)) #print("############################################################") #print("one error -> " + str(one_count)) #print("#########################################################") print("Time -> " + str(time.time() - start)) print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
34.021552
337
0.548461
33e48151fdf8a382fd286e9f5474577e395ee953
3,338
py
Python
tests/table_popup_test.py
surfaceanalytics/inelasticscattering
da549dde788a55084c565bbc5f89ebf9cbae4263
[ "MIT" ]
null
null
null
tests/table_popup_test.py
surfaceanalytics/inelasticscattering
da549dde788a55084c565bbc5f89ebf9cbae4263
[ "MIT" ]
3
2021-09-08T03:02:25.000Z
2022-03-12T01:00:06.000Z
tests/table_popup_test.py
surfaceanalytics/inelasticscattering
da549dde788a55084c565bbc5f89ebf9cbae4263
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 22:31:45 2020 @author: Mark """ import tkinter as tk import tkinter.ttk as ttk import functools class Controller(): def __init__(self): self.root = tk.Tk() self.table_values = [(0,'A','1'),(1,'A','2'),(2,'B','3')] self.table1_values = [(0,'D','4'),(1,'D','5'),(2,'E','6')] self.table_choices = {1:['A','B','C'],2:['1','2','3']} self.table1_choices = {1:['D','E','F'],2:['4','5','6']} self.view = View(self, self.root) self.fillTable(self.view.table,self.table_values) self.fillTable(self.view.table1,self.table1_values) def fillTable(self, table, values): for i,j in enumerate(values): table.insert('',i,values=j) def tablePopup(self, event, table, table_choices): row = table.identify_row(event.y) col = table.identify_column(event.x) col = int(col.lstrip('#'))-1 def setChoice(choice): table.set(row,column=col,value=choice) popup = tk.Menu(self.view.root, tearoff=0) if col > 0: choices = table_choices[col] for i,j in enumerate(choices): # This line below is crazy. Needs to be done this way because the i in the loop is only scoped for the loop, and does not persist popup.add_command(command = lambda choice = choices[i]: setChoice(choice), label=j) try: popup.tk_popup(event.x_root, event.y_root, 0) finally: popup.grab_release() class View(): def __init__(self, controller, root): self.root = root self.controller = controller columns = ('ID','Col1', 'Col2') self.table = ttk.Treeview(self.root, height=4,show='headings',columns=columns, selectmode='browse') self.table.column('ID',width=50,anchor=tk.W) self.table.heading('ID', text='ID', anchor=tk.W) self.table.column('Col1',width=150,anchor=tk.W) self.table.heading('Col1', text='Col1', anchor=tk.W) #self.table.bind('<<TreeviewSelect>>',self.controller.tableSelection) self.table.column('Col2',width=200,anchor=tk.W) self.table.heading('Col2', text='Col2', anchor=tk.W) self.table.pack(side=tk.TOP, anchor="center") self.table.bind('<Button-3>',functools.partial(self.controller.tablePopup, table=self.table, table_choices = self.controller.table_choices)) columns = ('ID','Col3', 'Col4') self.table1 = ttk.Treeview(self.root, height=4,show='headings',columns=columns, selectmode='browse') self.table1.column('ID',width=50,anchor=tk.W) self.table1.heading('ID', text='ID', anchor=tk.W) self.table1.column('Col3',width=150,anchor=tk.W) self.table1.heading('Col3', text='Col3', anchor=tk.W) #self.table.bind('<<TreeviewSelect>>',self.controller.tableSelection) self.table1.column('Col4',width=200,anchor=tk.W) self.table1.heading('Col4', text='Col4', anchor=tk.W) self.table1.pack(side=tk.TOP, anchor="center") self.table1.bind('<Button-3>',functools.partial(self.controller.tablePopup, table=self.table1, table_choices = self.controller.table1_choices)) if __name__ == "__main__": app = Controller() app.root.mainloop()
43.350649
151
0.611144
b423c0b7dd7b9d5226488760c727835a61dd1092
614
py
Python
bl4zzer/bl4zzer.py
s0wr0b1ndef/security-tools
865682ba958c4138261863af27243d1da35e13e5
[ "MIT" ]
3
2020-04-24T13:54:31.000Z
2021-05-30T08:12:58.000Z
bl4zzer/bl4zzer.py
FingerLeakers/security-tools
7537294b17abc5ff219d745c0829aa10d945c5ca
[ "MIT" ]
null
null
null
bl4zzer/bl4zzer.py
FingerLeakers/security-tools
7537294b17abc5ff219d745c0829aa10d945c5ca
[ "MIT" ]
4
2019-08-30T16:42:07.000Z
2021-10-30T16:17:15.000Z
#!/usr/bin/env python """Web Application Fuzzer """ import requests import os url = "http://us.rd.yahoo.com/200/*http://google.ie*FUZZ" fuzzString = "FUZZ" counter = 0 separator = "#" * 80 os.system('clear') print '[+] working, please be patient...' for p in open('xss_vectors.txt', 'r').readlines(): currentUrl = url.replace(fuzzString, p.strip()).strip() counter = counter + 1 resp = requests.get(currentUrl) # print resp if resp.status_code in [200, 403, 500, 301, 302]: print '[+] {} {}\n\n{}\n{}'.format(currentUrl, resp.status_code, resp.text, separator) print '[+] Done'
22.740741
95
0.636808
4f1a02b8b9c67c872f2b02993faf8775e8c4993c
5,434
py
Python
src/backoff_simulator.py
randomvariable/aws-arch-backoff-simulator
caf4f123bd96aee900aa1f5b50becb2d8bb22b0f
[ "Apache-2.0" ]
null
null
null
src/backoff_simulator.py
randomvariable/aws-arch-backoff-simulator
caf4f123bd96aee900aa1f5b50becb2d8bb22b0f
[ "Apache-2.0" ]
null
null
null
src/backoff_simulator.py
randomvariable/aws-arch-backoff-simulator
caf4f123bd96aee900aa1f5b50becb2d8bb22b0f
[ "Apache-2.0" ]
null
null
null
# Simulator for the effects of backoff and jitter on a remote OCC system. # This code was used for the post on backoff on the AWS architecture blog # at http://www.awsarchitectureblog.com/ import heapq import random # Net models the natural delay and variance of the network class Net: def __init__(self, mean, sd): self.mean = mean self.sd = sd def delay(self): # We use a normal distribution model. Networks are more likely to be a Weibull model # in reality, but this is close enough for the model comparison. return abs(random.normalvariate(self.mean, self.sd)) # Base class for all the backoff implementations class Backoff: def __init__(self, base, cap): self.base = base self.cap = cap def expo(self, n): return min(self.cap, pow(2, n)*self.base) class NoBackoff(Backoff): def backoff(self, n): return 0 class ExpoBackoff(Backoff): def backoff(self, n): return self.expo(n) class ExpoBackoffEqualJitter(Backoff): def backoff(self, n): v = self.expo(n) return v/2 + random.uniform(0, v/2) class KubeJitter(Backoff): def expo(self, n): return min(self.cap, pow(1.71, n)*self.base) def backoff(self, n): v = self.expo(n) * 0.4 return random.uniform(0, v) + v class ExpoBackoffFullJitter(Backoff): def backoff(self, n): v = self.expo(n) return random.uniform(0, v) class ExpoBackoffDecorr(Backoff): def __init__(self, base, cap): Backoff.__init__(self, base, cap) self.sleep = self.base def backoff(self, n): self.sleep = min(self.cap, random.uniform(self.base, self.sleep * 3)) return self.sleep # Small class to track two counters class Stats: def __init__(self): self.failures = 0 self.calls = 0 # Build a message to be added to the simulated network def msg(tm, send_to, reply_to, payload): assert tm >= 0 assert send_to is not None return (tm, send_to, reply_to, payload) # The OCC server. It models a single "row" with a single version. class OccServer: def __init__(self, net, stats, ts_f): self.version = 0 self.net = net self.stats = stats self.ts_f = ts_f # Try to write the row. If you provide the right version number (obtained from a read), # the write will succeed. def write(self, tm, request): self.ts_f.write("%d\n"%(tm)) success = False self.stats.calls += 1 if request[3] == self.version: self.version += 1 success = True else: self.stats.failures += 1 return msg(tm + self.net.delay(), request[2], None, success) # Read the current version number of the row. def read(self, tm, request): return msg(tm + self.net.delay(), request[2], None, self.version) # The OCC client. It models a client that tries to update the row exactly once, # then stops. class OccClient: def __init__(self, server, net, backoff): self.server = server self.net = net self.attempt = 0 self.backoff = backoff def start(self, tm): return msg(tm + self.net.delay(), self.server.read, self.read_rsp, None) def read_rsp(self, tm, request): return msg(tm + self.net.delay(), self.server.write, self.write_rsp, request[3]) def write_rsp(self, tm, request): if not request[3]: self.attempt += 1 return msg(tm + self.net.delay() + self.backoff.backoff(self.attempt), self.server.read, self.read_rsp, None) else: return None # The main loop of the simulation. def run_sim(queue): tm = 0 while len(queue) > 0: # Pull an event off the priority queue msg = heapq.heappop(queue) assert msg[0] >= tm # TIme must move forward tm = msg[0] next_msg = msg[1](tm, msg) if next_msg is not None: # If it cause another event to be generated, enqueue it heapq.heappush(queue, next_msg) return tm # Setup the simulation, creating the clients and server def setup_sim(clients, backoff_cls, ts_f, stats): net = Net(10, 2) queue = [] server = OccServer(net, stats, ts_f) for i in xrange(0, clients): client = OccClient(server, net, backoff_cls(1, 150)) heapq.heappush(queue, client.start(0)) return (queue, stats) # The list of backoff types that we simulate over. The tuples are a class # name and a friendly name for the output. backoff_types = ((ExpoBackoffDecorr,"Decorr"), (ExpoBackoffFullJitter, "FullJitter"), (KubeJitter, "KubeJitter")) def run(): with open("backoff_results.csv", "w") as f: f.write("clients,time,calls,Algorithm\n") for i in xrange(1, 20): clients = i * 10 for backoff in backoff_types: with open("ts_" + backoff[1], "w") as ts_f: stats = Stats() tm = 0 for t in xrange(0, 100): queue, stats = setup_sim(clients, backoff[0], ts_f, stats) tm += run_sim(queue) f.write("%d,%d,%d,%s\n"%(clients, tm/100, stats.calls/100, backoff[1])) run()
32.73494
121
0.595142
461f98c028adac03ecfe063149804347e4090f6f
1,314
py
Python
tests/view_tests/models.py
webjunkie/django
5dbca13f3baa2e1bafd77e84a80ad6d8a074712e
[ "BSD-3-Clause" ]
790
2015-01-03T02:13:39.000Z
2020-05-10T19:53:57.000Z
AppServer/lib/django-1.5/tests/regressiontests/views/models.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
1,361
2015-01-08T23:09:40.000Z
2020-04-14T00:03:04.000Z
AppServer/lib/django-1.5/tests/regressiontests/views/models.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
155
2015-01-08T22:59:31.000Z
2020-04-08T08:01:53.000Z
""" Regression tests for Django built-in views. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return '/views/authors/%s/' % self.id @python_2_unicode_compatible class BaseArticle(models.Model): """ An abstract article Model so that we can create article models with and without a get_absolute_url method (for create_update generic views tests). """ title = models.CharField(max_length=100) slug = models.SlugField() author = models.ForeignKey(Author) class Meta: abstract = True def __str__(self): return self.title class Article(BaseArticle): date_created = models.DateTimeField() class UrlArticle(BaseArticle): """ An Article class with a get_absolute_url defined. """ date_created = models.DateTimeField() def get_absolute_url(self): return '/urlarticles/%s/' % self.slug get_absolute_url.purge = True class DateArticle(BaseArticle): """ An article Model with a DateField instead of DateTimeField, for testing #7602 """ date_created = models.DateField()
24.792453
78
0.703196
d5f825fd49aa7bae2f23e2ab9ddc676d7f159915
2,361
py
Python
src/etl/tasks/song_transform.py
vatdaell/spotify-analysis
030239ba16cfc4a80d4f870686450c1ababc62c2
[ "MIT" ]
1
2020-10-14T10:01:37.000Z
2020-10-14T10:01:37.000Z
src/etl/tasks/song_transform.py
vatdaell/spotify-analysis
030239ba16cfc4a80d4f870686450c1ababc62c2
[ "MIT" ]
null
null
null
src/etl/tasks/song_transform.py
vatdaell/spotify-analysis
030239ba16cfc4a80d4f870686450c1ababc62c2
[ "MIT" ]
null
null
null
from common.store import Store from common.timehelpers import extractDate from common.apiauth import spotify_authenticate from dotenv import load_dotenv, find_dotenv from os import getenv from io import StringIO from datetime import datetime import pandas as pd FEATURE_PREFIX = "audio_features" LYRICS_PREFIX = "lyrics" RECENTLY_PREFIX = "weekly_reports" FOLDER = "songs" def validateData(dataframe, primary_key): return pd.Series(dataframe[primary_key]).is_unique def getLatestCSVFile(store, prefix): files = store.getFiles(prefix) file_names = list( filter( lambda x: ".csv" in x, map(lambda x: x.key, files) ) ) latest = max( list( map(lambda x: extractDate(x, prefix, ".csv"), file_names) ) ) filename = "{}/{}.{}".format(prefix, latest, "csv") # Get File body = store.getFile(filename) csv = pd.read_csv(StringIO(body), low_memory=False) # Remove weird index col return csv.loc[:, csv.columns != "Unnamed: 0"] def main(): load_dotenv(find_dotenv()) store = Store(getenv("S3_BUCKET")) csv_features = getLatestCSVFile(store, FEATURE_PREFIX) csv_features = csv_features.loc[:, csv_features.columns != "Unnamed: 0"] csv_features = csv_features.drop_duplicates(subset=["track_id"]) csv_lyrics = getLatestCSVFile(store, LYRICS_PREFIX)[["track_id", "lyrics"]] csv_lyrics = csv_lyrics.drop_duplicates(subset=["track_id"]) csv_recently = getLatestCSVFile(store, RECENTLY_PREFIX)[ [ "track_id", "popularity", "explicit" ] ] csv_recently = csv_recently.drop_duplicates(subset=["track_id"]) joined_data = csv_features.join( csv_lyrics.set_index("track_id"), on="track_id" ) joined_data = joined_data.join( csv_recently.set_index("track_id"), on="track_id" ) joined_data = joined_data.drop_duplicates(subset=["track_id"]) if(validateData(joined_data, "track_id")): # load to buffer csv_buffer = StringIO() joined_data.to_csv(csv_buffer, index=False) body = csv_buffer.getvalue() # save file store.saveFile(datetime.now(), FOLDER, body, "", "csv") if __name__ == "__main__": main()
25.663043
79
0.63956
46d392b3a241f2da7b31bf75f6e1694c4caed155
4,864
py
Python
tests/integration_tests/test_mlflow.py
iamshnoo/optuna
d809aacd0384a17d06dcab03cf99d5c4c86abc92
[ "MIT" ]
1
2019-05-28T07:29:49.000Z
2019-05-28T07:29:49.000Z
tests/integration_tests/test_mlflow.py
nabenabe0928/optuna
aa505125de8515518fe19ba227edf7a1d3f8ebda
[ "MIT" ]
null
null
null
tests/integration_tests/test_mlflow.py
nabenabe0928/optuna
aa505125de8515518fe19ba227edf7a1d3f8ebda
[ "MIT" ]
2
2020-03-03T00:40:28.000Z
2021-01-28T11:54:32.000Z
from mlflow.tracking import MlflowClient import py import optuna from optuna.integration.mlflow import MLflowCallback def _objective_func(trial: optuna.trial.Trial) -> float: x = trial.suggest_uniform("x", -1.0, 1.0) y = trial.suggest_loguniform("y", 20, 30) z = trial.suggest_categorical("z", (-1.0, 1.0)) assert isinstance(z, float) trial.set_user_attr("my_user_attr", "my_user_attr_value") return (x - 2) ** 2 + (y - 25) ** 2 + z # This is tool function for a temporary fix on Optuna side. It avoids an error with user # attributes that are too long. It should be fixed on MLflow side later. # When it is fixed on MLflow side this test can be removed. # see https://github.com/optuna/optuna/issues/1340 # see https://github.com/mlflow/mlflow/issues/2931 def _objective_func_long_user_attr(trial: optuna.trial.Trial) -> float: x = trial.suggest_uniform("x", -1.0, 1.0) y = trial.suggest_loguniform("y", 20, 30) z = trial.suggest_categorical("z", (-1.0, 1.0)) assert isinstance(z, float) long_str = str(list(range(5000))) trial.set_user_attr("my_user_attr", long_str) return (x - 2) ** 2 + (y - 25) ** 2 + z def test_study_name(tmpdir: py.path.local) -> None: tracking_file_name = "file:{}".format(tmpdir) study_name = "my_study" n_trials = 3 mlflc = MLflowCallback(tracking_uri=tracking_file_name) study = optuna.create_study(study_name=study_name) study.optimize(_objective_func, n_trials=n_trials, callbacks=[mlflc]) mlfl_client = MlflowClient(tracking_file_name) experiments = mlfl_client.list_experiments() assert len(experiments) == 1 experiment = experiments[0] assert experiment.name == study_name experiment_id = experiment.experiment_id run_infos = mlfl_client.list_run_infos(experiment_id) assert len(run_infos) == n_trials first_run_id = run_infos[0].run_id first_run = mlfl_client.get_run(first_run_id) first_run_dict = first_run.to_dictionary() assert "value" in first_run_dict["data"]["metrics"] assert "x" in first_run_dict["data"]["params"] assert "y" in first_run_dict["data"]["params"] assert "z" in first_run_dict["data"]["params"] assert first_run_dict["data"]["tags"]["direction"] == "MINIMIZE" assert first_run_dict["data"]["tags"]["state"] == "COMPLETE" assert ( first_run_dict["data"]["tags"]["x_distribution"] == "UniformDistribution(high=1.0, low=-1.0)" ) assert ( first_run_dict["data"]["tags"]["y_distribution"] == "LogUniformDistribution(high=30, low=20)" ) assert ( first_run_dict["data"]["tags"]["z_distribution"] == "CategoricalDistribution(choices=(-1.0, 1.0))" ) assert first_run_dict["data"]["tags"]["my_user_attr"] == "my_user_attr_value" def test_metric_name(tmpdir: py.path.local) -> None: tracking_file_name = "file:{}".format(tmpdir) metric_name = "my_metric_name" mlflc = MLflowCallback(tracking_uri=tracking_file_name, metric_name=metric_name) study = optuna.create_study(study_name="my_study") study.optimize(_objective_func, n_trials=3, callbacks=[mlflc]) mlfl_client = MlflowClient(tracking_file_name) experiments = mlfl_client.list_experiments() experiment = experiments[0] experiment_id = experiment.experiment_id run_infos = mlfl_client.list_run_infos(experiment_id) first_run_id = run_infos[0].run_id first_run = mlfl_client.get_run(first_run_id) first_run_dict = first_run.to_dictionary() assert metric_name in first_run_dict["data"]["metrics"] # This is a test for a temporary fix on Optuna side. It avoids an error with user # attributes that are too long. It should be fixed on MLflow side later. # When it is fixed on MLflow side this test can be removed. # see https://github.com/optuna/optuna/issues/1340 # see https://github.com/mlflow/mlflow/issues/2931 def test_tag_truncation(tmpdir: py.path.local) -> None: tracking_file_name = "file:{}".format(tmpdir) study_name = "my_study" n_trials = 3 mlflc = MLflowCallback(tracking_uri=tracking_file_name) study = optuna.create_study(study_name=study_name) study.optimize(_objective_func_long_user_attr, n_trials=n_trials, callbacks=[mlflc]) mlfl_client = MlflowClient(tracking_file_name) experiments = mlfl_client.list_experiments() assert len(experiments) == 1 experiment = experiments[0] assert experiment.name == study_name experiment_id = experiment.experiment_id run_infos = mlfl_client.list_run_infos(experiment_id) assert len(run_infos) == n_trials first_run_id = run_infos[0].run_id first_run = mlfl_client.get_run(first_run_id) first_run_dict = first_run.to_dictionary() my_user_attr = first_run_dict["data"]["tags"]["my_user_attr"] assert len(my_user_attr) <= 5000
36.02963
88
0.71176
00013651dedd34f35d71f09c33c91c0c937425cc
732
py
Python
setup.py
cutec-chris/gitlab-timetracking
8f96fadb5baee8a80bb309ca61a7d06ba4f5a2be
[ "MIT" ]
null
null
null
setup.py
cutec-chris/gitlab-timetracking
8f96fadb5baee8a80bb309ca61a7d06ba4f5a2be
[ "MIT" ]
null
null
null
setup.py
cutec-chris/gitlab-timetracking
8f96fadb5baee8a80bb309ca61a7d06ba4f5a2be
[ "MIT" ]
null
null
null
from setuptools import setup with open("README.md", 'r') as f: long_description = f.read() setup(name='gitlab-timetracking', version='0.0.1', description='simple timetracking commandline application that uses the Gitlab api to get / store times in gitlab directly in the project/repository', long_description=long_description, url='https://github.com/cutec-chris/gitlab-timetracking', author='Christian Ulrich', author_email='pypi@chris.ullihome.de', license='MIT', python_requires='>=3.6', packages=['gitlab_timetracking'], scripts=['bin/tt'], zip_safe=False, include_package_data=True, install_requires=['python-gitlab','timesheet-gitlab'] )
38.526316
155
0.685792
400846cc4ca1de7433eaf982551bc22797428464
11,831
py
Python
crabageprediction/venv/Lib/site-packages/pandas/tests/arrays/interval/test_interval.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
3
2021-11-23T05:35:28.000Z
2022-02-10T08:05:53.000Z
crabageprediction/venv/Lib/site-packages/pandas/tests/arrays/interval/test_interval.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
5
2022-02-13T14:38:04.000Z
2022-02-15T00:13:07.000Z
crabageprediction/venv/Lib/site-packages/pandas/tests/arrays/interval/test_interval.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
5
2018-04-24T13:31:56.000Z
2021-10-21T05:06:23.000Z
import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import ( Index, Interval, IntervalIndex, Timedelta, Timestamp, date_range, timedelta_range, ) import pandas._testing as tm from pandas.core.arrays import IntervalArray @pytest.fixture( params=[ (Index([0, 2, 4]), Index([1, 3, 5])), (Index([0.0, 1.0, 2.0]), Index([1.0, 2.0, 3.0])), (timedelta_range("0 days", periods=3), timedelta_range("1 day", periods=3)), (date_range("20170101", periods=3), date_range("20170102", periods=3)), ( date_range("20170101", periods=3, tz="US/Eastern"), date_range("20170102", periods=3, tz="US/Eastern"), ), ], ids=lambda x: str(x[0].dtype), ) def left_right_dtypes(request): """ Fixture for building an IntervalArray from various dtypes """ return request.param class TestAttributes: @pytest.mark.parametrize( "left, right", [ (0, 1), (Timedelta("0 days"), Timedelta("1 day")), (Timestamp("2018-01-01"), Timestamp("2018-01-02")), ( Timestamp("2018-01-01", tz="US/Eastern"), Timestamp("2018-01-02", tz="US/Eastern"), ), ], ) @pytest.mark.parametrize("constructor", [IntervalArray, IntervalIndex]) def test_is_empty(self, constructor, left, right, closed): # GH27219 tuples = [(left, left), (left, right), np.nan] expected = np.array([closed != "both", False, False]) result = constructor.from_tuples(tuples, closed=closed).is_empty tm.assert_numpy_array_equal(result, expected) class TestMethods: @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"]) def test_set_closed(self, closed, new_closed): # GH 21670 array = IntervalArray.from_breaks(range(10), closed=closed) result = array.set_closed(new_closed) expected = IntervalArray.from_breaks(range(10), closed=new_closed) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize( "other", [ Interval(0, 1, closed="right"), IntervalArray.from_breaks([1, 2, 3, 4], closed="right"), ], ) def test_where_raises(self, other): ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left")) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.where([True, False, True], other=other) def test_shift(self): # https://github.com/pandas-dev/pandas/issues/31495 a = IntervalArray.from_breaks([1, 2, 3]) result = a.shift() # int -> float expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)]) tm.assert_interval_array_equal(result, expected) def test_shift_datetime(self): a = IntervalArray.from_breaks(date_range("2000", periods=4)) result = a.shift(2) expected = a.take([-1, -1, 0], allow_fill=True) tm.assert_interval_array_equal(result, expected) result = a.shift(-1) expected = a.take([1, 2, -1], allow_fill=True) tm.assert_interval_array_equal(result, expected) class TestSetitem: def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) result = IntervalArray.from_arrays(left, right) if result.dtype.subtype.kind not in ["m", "M"]: msg = "'value' should be an interval type, got <.*NaTType'> instead." with pytest.raises(TypeError, match=msg): result[0] = pd.NaT if result.dtype.subtype.kind in ["i", "u"]: msg = "Cannot set float NaN to integer-backed IntervalArray" with pytest.raises(ValueError, match=msg): result[0] = np.NaN return result[0] = np.nan expected_left = Index([left._na_value] + list(left[1:])) expected_right = Index([right._na_value] + list(right[1:])) expected = IntervalArray.from_arrays(expected_left, expected_right) tm.assert_extension_array_equal(result, expected) def test_setitem_mismatched_closed(self): arr = IntervalArray.from_breaks(range(4)) orig = arr.copy() other = arr.set_closed("both") msg = "'value.closed' is 'both', expected 'right'" with pytest.raises(ValueError, match=msg): arr[0] = other[0] with pytest.raises(ValueError, match=msg): arr[:1] = other[:1] with pytest.raises(ValueError, match=msg): arr[:0] = other[:0] with pytest.raises(ValueError, match=msg): arr[:] = other[::-1] with pytest.raises(ValueError, match=msg): arr[:] = list(other[::-1]) with pytest.raises(ValueError, match=msg): arr[:] = other[::-1].astype(object) with pytest.raises(ValueError, match=msg): arr[:] = other[::-1].astype("category") # empty list should be no-op arr[:0] = [] tm.assert_interval_array_equal(arr, orig) def test_repr(): # GH 25022 arr = IntervalArray.from_tuples([(0, 1), (1, 2)]) result = repr(arr) expected = ( "<IntervalArray>\n" "[(0, 1], (1, 2]]\n" "Length: 2, dtype: interval[int64, right]" ) assert result == expected class TestReductions: def test_min_max_invalid_axis(self, left_right_dtypes): left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) arr = IntervalArray.from_arrays(left, right) msg = "`axis` must be fewer than the number of dimensions" for axis in [-2, 1]: with pytest.raises(ValueError, match=msg): arr.min(axis=axis) with pytest.raises(ValueError, match=msg): arr.max(axis=axis) msg = "'>=' not supported between" with pytest.raises(TypeError, match=msg): arr.min(axis="foo") with pytest.raises(TypeError, match=msg): arr.max(axis="foo") def test_min_max(self, left_right_dtypes, index_or_series_or_array): # GH#44746 left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) arr = IntervalArray.from_arrays(left, right) # The expected results below are only valid if monotonic assert left.is_monotonic_increasing assert Index(arr).is_monotonic_increasing MIN = arr[0] MAX = arr[-1] indexer = np.arange(len(arr)) np.random.shuffle(indexer) arr = arr.take(indexer) arr_na = arr.insert(2, np.nan) arr = index_or_series_or_array(arr) arr_na = index_or_series_or_array(arr_na) for skipna in [True, False]: res = arr.min(skipna=skipna) assert res == MIN assert type(res) == type(MIN) res = arr.max(skipna=skipna) assert res == MAX assert type(res) == type(MAX) res = arr_na.min(skipna=False) assert np.isnan(res) res = arr_na.max(skipna=False) assert np.isnan(res) res = arr_na.min(skipna=True) assert res == MIN assert type(res) == type(MIN) res = arr_na.max(skipna=True) assert res == MAX assert type(res) == type(MAX) # ---------------------------------------------------------------------------- # Arrow interaction pyarrow_skip = td.skip_if_no("pyarrow") @pyarrow_skip def test_arrow_extension_type(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType p1 = ArrowIntervalType(pa.int64(), "left") p2 = ArrowIntervalType(pa.int64(), "left") p3 = ArrowIntervalType(pa.int64(), "right") assert p1.closed == "left" assert p1 == p2 assert not p1 == p3 assert hash(p1) == hash(p2) assert not hash(p1) == hash(p3) @pyarrow_skip def test_arrow_array(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType intervals = pd.interval_range(1, 5, freq=1).array result = pa.array(intervals) assert isinstance(result.type, ArrowIntervalType) assert result.type.closed == intervals.closed assert result.type.subtype == pa.int64() assert result.storage.field("left").equals(pa.array([1, 2, 3, 4], type="int64")) assert result.storage.field("right").equals(pa.array([2, 3, 4, 5], type="int64")) expected = pa.array([{"left": i, "right": i + 1} for i in range(1, 5)]) assert result.storage.equals(expected) # convert to its storage type result = pa.array(intervals, type=expected.type) assert result.equals(expected) # unsupported conversions with pytest.raises(TypeError, match="Not supported to convert IntervalArray"): pa.array(intervals, type="float64") with pytest.raises(TypeError, match="different 'subtype'"): pa.array(intervals, type=ArrowIntervalType(pa.float64(), "left")) @pyarrow_skip def test_arrow_array_missing(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0]) arr[1] = None result = pa.array(arr) assert isinstance(result.type, ArrowIntervalType) assert result.type.closed == arr.closed assert result.type.subtype == pa.float64() # fields have missing values (not NaN) left = pa.array([0.0, None, 2.0], type="float64") right = pa.array([1.0, None, 3.0], type="float64") assert result.storage.field("left").equals(left) assert result.storage.field("right").equals(right) # structarray itself also has missing values on the array level vals = [ {"left": 0.0, "right": 1.0}, {"left": None, "right": None}, {"left": 2.0, "right": 3.0}, ] expected = pa.StructArray.from_pandas(vals, mask=np.array([False, True, False])) assert result.storage.equals(expected) @pyarrow_skip @pytest.mark.parametrize( "breaks", [[0.0, 1.0, 2.0, 3.0], date_range("2017", periods=4, freq="D")], ids=["float", "datetime64[ns]"], ) def test_arrow_table_roundtrip(breaks): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks(breaks) arr[1] = None df = pd.DataFrame({"a": arr}) table = pa.table(df) assert isinstance(table.field("a").type, ArrowIntervalType) result = table.to_pandas() assert isinstance(result["a"].dtype, pd.IntervalDtype) tm.assert_frame_equal(result, df) table2 = pa.concat_tables([table, table]) result = table2.to_pandas() expected = pd.concat([df, df], ignore_index=True) tm.assert_frame_equal(result, expected) # GH-41040 table = pa.table( [pa.chunked_array([], type=table.column(0).type)], schema=table.schema ) result = table.to_pandas() tm.assert_frame_equal(result, expected[0:0]) @pyarrow_skip @pytest.mark.parametrize( "breaks", [[0.0, 1.0, 2.0, 3.0], date_range("2017", periods=4, freq="D")], ids=["float", "datetime64[ns]"], ) def test_arrow_table_roundtrip_without_metadata(breaks): import pyarrow as pa arr = IntervalArray.from_breaks(breaks) arr[1] = None df = pd.DataFrame({"a": arr}) table = pa.table(df) # remove the metadata table = table.replace_schema_metadata() assert table.schema.metadata is None result = table.to_pandas() assert isinstance(result["a"].dtype, pd.IntervalDtype) tm.assert_frame_equal(result, df)
31.975676
85
0.614487
b36b251b6ac0bd83ba2e3de45203605c70e81927
119,573
py
Python
electrumx/lib/coins.py
magnumwallet/electrumx
b732283de717a5cfa4215582d03dc43f1542dac6
[ "MIT" ]
null
null
null
electrumx/lib/coins.py
magnumwallet/electrumx
b732283de717a5cfa4215582d03dc43f1542dac6
[ "MIT" ]
null
null
null
electrumx/lib/coins.py
magnumwallet/electrumx
b732283de717a5cfa4215582d03dc43f1542dac6
[ "MIT" ]
null
null
null
# Copyright (c) 2016-2017, Neil Booth # Copyright (c) 2017, the ElectrumX authors # # All rights reserved. # # The MIT License (MIT) # # 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. '''Module providing coin abstraction. Anything coin-specific should go in this file and be subclassed where necessary for appropriate handling. ''' from collections import namedtuple import re import struct from decimal import Decimal from hashlib import sha256 from functools import partial import electrumx.lib.util as util from electrumx.lib.hash import Base58, hash160, double_sha256, hash_to_hex_str, blake2b_hash from electrumx.lib.hash import HASHX_LEN, hex_str_to_hash from electrumx.lib.script import (_match_ops, Script, ScriptError, ScriptPubKey, OpCodes) import electrumx.lib.tx as lib_tx import electrumx.lib.tx_dash as lib_tx_dash import electrumx.lib.tx_axe as lib_tx_axe import electrumx.server.block_processor as block_proc import electrumx.server.daemon as daemon from electrumx.server.session import (ElectrumX, DashElectrumX, SmartCashElectrumX, AuxPoWElectrumX, SyscoinElectrumX) Block = namedtuple("Block", "raw header transactions") class CoinError(Exception): '''Exception raised for coin-related errors.''' class Coin(object): '''Base class of coin hierarchy.''' REORG_LIMIT = 200 # Not sure if these are coin-specific RPC_URL_REGEX = re.compile('.+@(\\[[0-9a-fA-F:]+\\]|[^:]+)(:[0-9]+)?') VALUE_PER_COIN = 100000000 CHUNK_SIZE = 2016 BASIC_HEADER_SIZE = 80 STATIC_BLOCK_HEADERS = True SESSIONCLS = ElectrumX DEFAULT_MAX_SEND = 1000000 DESERIALIZER = lib_tx.Deserializer DAEMON = daemon.Daemon BLOCK_PROCESSOR = block_proc.BlockProcessor HEADER_VALUES = ('version', 'prev_block_hash', 'merkle_root', 'timestamp', 'bits', 'nonce') HEADER_UNPACK = struct.Struct('< I 32s 32s I I I').unpack_from MEMPOOL_HISTOGRAM_REFRESH_SECS = 500 P2PKH_VERBYTE = bytes.fromhex("00") P2SH_VERBYTES = [bytes.fromhex("05")] XPUB_VERBYTES = bytes('????', 'utf-8') XPRV_VERBYTES = bytes('????', 'utf-8') WIF_BYTE = bytes.fromhex("80") ENCODE_CHECK = Base58.encode_check DECODE_CHECK = Base58.decode_check GENESIS_HASH = ('000000000019d6689c085ae165831e93' '4ff763ae46a2a6c172b3f1b60a8ce26f') GENESIS_ACTIVATION = 100_000_000 # Peer discovery PEER_DEFAULT_PORTS = {'t': '50001', 's': '50002'} PEERS = [] CRASH_CLIENT_VER = None BLACKLIST_URL = None @classmethod def lookup_coin_class(cls, name, net): '''Return a coin class given name and network. Raise an exception if unrecognised.''' req_attrs = ['TX_COUNT', 'TX_COUNT_HEIGHT', 'TX_PER_BLOCK'] for coin in util.subclasses(Coin): if (coin.NAME.lower() == name.lower() and coin.NET.lower() == net.lower()): coin_req_attrs = req_attrs.copy() missing = [attr for attr in coin_req_attrs if not hasattr(coin, attr)] if missing: raise CoinError('coin {} missing {} attributes' .format(name, missing)) return coin raise CoinError('unknown coin {} and network {} combination' .format(name, net)) @classmethod def sanitize_url(cls, url): # Remove surrounding ws and trailing /s url = url.strip().rstrip('/') match = cls.RPC_URL_REGEX.match(url) if not match: raise CoinError('invalid daemon URL: "{}"'.format(url)) if match.groups()[1] is None: url += ':{:d}'.format(cls.RPC_PORT) if not url.startswith('http://') and not url.startswith('https://'): url = 'http://' + url return url + '/' @classmethod def max_fetch_blocks(cls, height): if height < 130000: return 1000 return 100 @classmethod def genesis_block(cls, block): '''Check the Genesis block is the right one for this coin. Return the block less its unspendable coinbase. ''' header = cls.block_header(block, 0) header_hex_hash = hash_to_hex_str(cls.header_hash(header)) if header_hex_hash != cls.GENESIS_HASH: raise CoinError('genesis block has hash {} expected {}' .format(header_hex_hash, cls.GENESIS_HASH)) return header + bytes(1) @classmethod def hashX_from_script(cls, script): '''Returns a hashX from a script.''' return sha256(script).digest()[:HASHX_LEN] @staticmethod def lookup_xverbytes(verbytes): '''Return a (is_xpub, coin_class) pair given xpub/xprv verbytes.''' # Order means BTC testnet will override NMC testnet for coin in util.subclasses(Coin): if verbytes == coin.XPUB_VERBYTES: return True, coin if verbytes == coin.XPRV_VERBYTES: return False, coin raise CoinError('version bytes unrecognised') @classmethod def address_to_hashX(cls, address): '''Return a hashX given a coin address.''' return cls.hashX_from_script(cls.pay_to_address_script(address)) @classmethod def P2PKH_address_from_hash160(cls, hash160): '''Return a P2PKH address given a public key.''' assert len(hash160) == 20 return cls.ENCODE_CHECK(cls.P2PKH_VERBYTE + hash160) @classmethod def P2PKH_address_from_pubkey(cls, pubkey): '''Return a coin address given a public key.''' return cls.P2PKH_address_from_hash160(hash160(pubkey)) @classmethod def P2SH_address_from_hash160(cls, hash160): '''Return a coin address given a hash160.''' assert len(hash160) == 20 return cls.ENCODE_CHECK(cls.P2SH_VERBYTES[0] + hash160) @classmethod def hash160_to_P2PKH_script(cls, hash160): return ScriptPubKey.P2PKH_script(hash160) @classmethod def hash160_to_P2PKH_hashX(cls, hash160): return cls.hashX_from_script(cls.hash160_to_P2PKH_script(hash160)) @classmethod def pay_to_address_script(cls, address): '''Return a pubkey script that pays to a pubkey hash. Pass the address (either P2PKH or P2SH) in base58 form. ''' raw = cls.DECODE_CHECK(address) # Require version byte(s) plus hash160. verbyte = -1 verlen = len(raw) - 20 if verlen > 0: verbyte, hash160 = raw[:verlen], raw[verlen:] if verbyte == cls.P2PKH_VERBYTE: return cls.hash160_to_P2PKH_script(hash160) if verbyte in cls.P2SH_VERBYTES: return ScriptPubKey.P2SH_script(hash160) raise CoinError('invalid address: {}'.format(address)) @classmethod def privkey_WIF(cls, privkey_bytes, compressed): '''Return the private key encoded in Wallet Import Format.''' payload = bytearray(cls.WIF_BYTE) + privkey_bytes if compressed: payload.append(0x01) return cls.ENCODE_CHECK(payload) @classmethod def header_hash(cls, header): '''Given a header return hash''' return double_sha256(header) @classmethod def header_prevhash(cls, header): '''Given a header return previous hash''' return header[4:36] @classmethod def static_header_offset(cls, height): '''Given a header height return its offset in the headers file. If header sizes change at some point, this is the only code that needs updating.''' assert cls.STATIC_BLOCK_HEADERS return height * cls.BASIC_HEADER_SIZE @classmethod def static_header_len(cls, height): '''Given a header height return its length.''' return (cls.static_header_offset(height + 1) - cls.static_header_offset(height)) @classmethod def block_header(cls, block, height): '''Returns the block header given a block and its height.''' return block[:cls.static_header_len(height)] @classmethod def block(cls, raw_block, height): '''Return a Block namedtuple given a raw block and its height.''' header = cls.block_header(raw_block, height) txs = cls.DESERIALIZER(raw_block, start=len(header)).read_tx_block() return Block(raw_block, header, txs) @classmethod def decimal_value(cls, value): '''Return the number of standard coin units as a Decimal given a quantity of smallest units. For example 1 BTC is returned for 100 million satoshis. ''' return Decimal(value) / cls.VALUE_PER_COIN @classmethod def warn_old_client_on_tx_broadcast(cls, _client_ver): return False class AuxPowMixin(object): STATIC_BLOCK_HEADERS = False DESERIALIZER = lib_tx.DeserializerAuxPow SESSIONCLS = AuxPoWElectrumX TRUNCATED_HEADER_SIZE = 80 # AuxPoW headers are significantly larger, so the DEFAULT_MAX_SEND from # Bitcoin is insufficient. In Namecoin mainnet, 5 MB wasn't enough to # sync, while 10 MB worked fine. DEFAULT_MAX_SEND = 10000000 @classmethod def header_hash(cls, header): '''Given a header return hash''' return double_sha256(header[:cls.BASIC_HEADER_SIZE]) @classmethod def block_header(cls, block, height): '''Return the AuxPow block header bytes''' deserializer = cls.DESERIALIZER(block) return deserializer.read_header(cls.BASIC_HEADER_SIZE) class EquihashMixin(object): STATIC_BLOCK_HEADERS = False BASIC_HEADER_SIZE = 140 # Excluding Equihash solution DESERIALIZER = lib_tx.DeserializerEquihash HEADER_VALUES = ('version', 'prev_block_hash', 'merkle_root', 'reserved', 'timestamp', 'bits', 'nonce') HEADER_UNPACK = struct.Struct('< I 32s 32s 32s I I 32s').unpack_from @classmethod def block_header(cls, block, height): '''Return the block header bytes''' deserializer = cls.DESERIALIZER(block) return deserializer.read_header(cls.BASIC_HEADER_SIZE) class ScryptMixin(object): DESERIALIZER = lib_tx.DeserializerTxTime HEADER_HASH = None @classmethod def header_hash(cls, header): '''Given a header return the hash.''' if cls.HEADER_HASH is None: import scrypt cls.HEADER_HASH = lambda x: scrypt.hash(x, x, 1024, 1, 1, 32) version, = util.unpack_le_uint32_from(header) if version > 6: return super().header_hash(header) else: return cls.HEADER_HASH(header) class KomodoMixin(object): P2PKH_VERBYTE = bytes.fromhex("3C") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("BC") GENESIS_HASH = ('027e3758c3a65b12aa1046462b486d0a' '63bfa1beae327897f56c5cfb7daaae71') DESERIALIZER = lib_tx.DeserializerZcash class BitcoinMixin(object): SHORTNAME = "BTC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") RPC_PORT = 8332 class NameMixin(object): DATA_PUSH_MULTIPLE = -2 @classmethod def interpret_name_prefix(cls, script, possible_ops): """Interprets a potential name prefix Checks if the given script has a name prefix. If it has, the name prefix is split off the actual address script, and its parsed fields (e.g. the name) returned. possible_ops must be an array of arrays, defining the structures of name prefixes to look out for. Each array can consist of actual opcodes, -1 for ignored data placeholders, -2 for multiple ignored data placeholders and strings for named placeholders. Whenever a data push matches a named placeholder, the corresponding value is put into a dictionary the placeholder name as key, and the dictionary of matches is returned.""" try: ops = Script.get_ops(script) except ScriptError: return None, script name_op_count = None for pops in possible_ops: # Start by translating named placeholders to -1 values, and # keeping track of which op they corresponded to. template = [] named_index = {} n = len(pops) offset = 0 for i, op in enumerate(pops): if op == cls.DATA_PUSH_MULTIPLE: # Emercoin stores value in multiple placeholders # Script structure: https://git.io/fjuRu added, template = cls._add_data_placeholders_to_template(ops[i:], template) offset += added - 1 # subtract the "DATA_PUSH_MULTIPLE" opcode elif type(op) == str: template.append(-1) named_index[op] = i + offset else: template.append(op) n += offset if not _match_ops(ops[:n], template): continue name_op_count = n named_values = {key: ops[named_index[key]] for key in named_index} break if name_op_count is None: return None, script name_end_pos = cls.find_end_position_of_name(script, name_op_count) address_script = script[name_end_pos:] return named_values, address_script @classmethod def _add_data_placeholders_to_template(cls, opcodes, template): num_dp = cls._read_data_placeholders_count(opcodes) num_2drop = num_dp // 2 num_drop = num_dp % 2 two_drops = [OpCodes.OP_2DROP for _ in range(num_2drop)] one_drops = [OpCodes.OP_DROP for _ in range(num_drop)] elements_added = num_dp + num_2drop + num_drop placeholders = [-1 for _ in range(num_dp)] drops = two_drops + one_drops return elements_added, template + placeholders + drops @classmethod def _read_data_placeholders_count(cls, opcodes): data_placeholders = 0 for opcode in opcodes: if type(opcode) == tuple: data_placeholders += 1 else: break return data_placeholders @staticmethod def find_end_position_of_name(script, length): """Finds the end position of the name data Given the number of opcodes in the name prefix (length), returns the index into the byte array of where the name prefix ends.""" n = 0 for _i in range(length): # Content of this loop is copied from Script.get_ops's loop op = script[n] n += 1 if op <= OpCodes.OP_PUSHDATA4: # Raw bytes follow if op < OpCodes.OP_PUSHDATA1: dlen = op elif op == OpCodes.OP_PUSHDATA1: dlen = script[n] n += 1 elif op == OpCodes.OP_PUSHDATA2: dlen, = struct.unpack('<H', script[n: n + 2]) n += 2 else: dlen, = struct.unpack('<I', script[n: n + 4]) n += 4 if n + dlen > len(script): raise IndexError n += dlen return n class NameIndexMixin(NameMixin): """Shared definitions for coins that have a name index This class defines common functions and logic for coins that have a name index in addition to the index by address / script.""" BLOCK_PROCESSOR = block_proc.NameIndexBlockProcessor @classmethod def build_name_index_script(cls, name): """Returns the script by which names are indexed""" from electrumx.lib.script import Script res = bytearray() res.append(cls.OP_NAME_UPDATE) res.extend(Script.push_data(name)) res.extend(Script.push_data(bytes([]))) res.append(OpCodes.OP_2DROP) res.append(OpCodes.OP_DROP) res.append(OpCodes.OP_RETURN) return bytes(res) @classmethod def split_name_script(cls, script): named_values, address_script = cls.interpret_name_prefix(script, cls.NAME_OPERATIONS) if named_values is None or "name" not in named_values: return None, address_script name_index_script = cls.build_name_index_script(named_values["name"][1]) return name_index_script, address_script @classmethod def hashX_from_script(cls, script): _, address_script = cls.split_name_script(script) return super().hashX_from_script(address_script) @classmethod def address_from_script(cls, script): _, address_script = cls.split_name_script(script) return super().address_from_script(address_script) @classmethod def name_hashX_from_script(cls, script): name_index_script, _ = cls.split_name_script(script) if name_index_script is None: return None return super().hashX_from_script(name_index_script) class HOdlcoin(Coin): NAME = "HOdlcoin" SHORTNAME = "HODLC" NET = "mainnet" BASIC_HEADER_SIZE = 88 P2PKH_VERBYTE = bytes.fromhex("28") WIF_BYTE = bytes.fromhex("a8") GENESIS_HASH = ('008872e5582924544e5c707ee4b839bb' '82c28a9e94e917c94b40538d5658c04b') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 258858 TX_COUNT_HEIGHT = 382138 TX_PER_BLOCK = 5 class BitcoinSV(BitcoinMixin, Coin): NAME = "BitcoinSV" SHORTNAME = "BSV" TX_COUNT = 267318795 TX_COUNT_HEIGHT = 557037 TX_PER_BLOCK = 400 PEERS = [ 'electrumx.bitcoinsv.io s', 'satoshi.vision.cash s', 'sv.usebsv.com s t', 'sv.jochen-hoenicke.de s t', 'sv.satoshi.io s t', ] GENESIS_ACTIVATION = 620_538 class BitcoinCash(BitcoinMixin, Coin): NAME = "BitcoinCashABC" # Some releases later remove the ABC suffix SHORTNAME = "BCH" TX_COUNT = 265479628 TX_COUNT_HEIGHT = 556592 TX_PER_BLOCK = 400 PEERS = [ 'bch.imaginary.cash s t', 'electroncash.dk s t', 'wallet.satoshiscoffeehouse.com s t', ] BLOCK_PROCESSOR = block_proc.LTORBlockProcessor @classmethod def warn_old_client_on_tx_broadcast(cls, client_ver): if client_ver < (3, 3, 4): return ('<br/><br/>' 'Your transaction was successfully broadcast.<br/><br/>' 'However, you are using a VULNERABLE version of Electron Cash.<br/>' 'Download the latest version from this web site ONLY:<br/>' 'https://electroncash.org/' '<br/><br/>') return False class BitcoinSegwit(BitcoinMixin, Coin): NAME = "BitcoinSegwit" DESERIALIZER = lib_tx.DeserializerSegWit MEMPOOL_HISTOGRAM_REFRESH_SECS = 120 TX_COUNT = 318337769 TX_COUNT_HEIGHT = 524213 TX_PER_BLOCK = 1400 CRASH_CLIENT_VER = (3, 2, 3) BLACKLIST_URL = 'https://electrum.org/blacklist.json' PEERS = [ 'E-X.not.fyi s t', 'electrum.vom-stausee.de s t', 'electrum.hsmiths.com s t', 'helicarrier.bauerj.eu s t', 'hsmiths4fyqlw5xw.onion s t', 'ozahtqwp25chjdjd.onion s t', 'electrum.hodlister.co s', 'electrum3.hodlister.co s', 'btc.usebsv.com s50006', 'fortress.qtornado.com s443 t', 'ecdsa.net s110 t', 'e2.keff.org s t', 'currentlane.lovebitco.in s t', 'electrum.jochen-hoenicke.de s50005 t50003', 'vps5.hsmiths.com s', ] @classmethod def warn_old_client_on_tx_broadcast(cls, client_ver): if client_ver < (3, 3, 3): return ('<br/><br/>' 'Your transaction was successfully broadcast.<br/><br/>' 'However, you are using a VULNERABLE version of Electrum.<br/>' 'Download the new version from the usual place:<br/>' 'https://electrum.org/' '<br/><br/>') return False class BitcoinGold(EquihashMixin, BitcoinMixin, Coin): CHUNK_SIZE = 252 NAME = "BitcoinGold" SHORTNAME = "BTG" FORK_HEIGHT = 491407 P2PKH_VERBYTE = bytes.fromhex("26") P2SH_VERBYTES = [bytes.fromhex("17")] DESERIALIZER = lib_tx.DeserializerEquihashSegWit TX_COUNT = 265026255 TX_COUNT_HEIGHT = 499923 TX_PER_BLOCK = 50 REORG_LIMIT = 1000 RPC_PORT = 8332 PEERS = [ 'electrumx-eu.bitcoingold.org s50002 t50001', 'electrumx-us.bitcoingold.org s50002 t50001' ] @classmethod def header_hash(cls, header): '''Given a header return hash''' height, = util.unpack_le_uint32_from(header, 68) if height >= cls.FORK_HEIGHT: return double_sha256(header) else: return double_sha256(header[:68] + header[100:112]) class BitcoinGoldTestnet(BitcoinGold): FORK_HEIGHT = 1 SHORTNAME = "TBTG" XPUB_VERBYTES = bytes.fromhex("043587CF") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6F") P2SH_VERBYTES = [bytes.fromhex("C4")] WIF_BYTE = bytes.fromhex("EF") TX_COUNT = 0 TX_COUNT_HEIGHT = 1 NET = 'testnet' RPC_PORT = 18332 GENESIS_HASH = ('00000000e0781ebe24b91eedc293adfe' 'a2f557b53ec379e78959de3853e6f9f6') PEERS = [ 'test-node1.bitcoingold.org s50002', 'test-node2.bitcoingold.org s50002', 'test-node3.bitcoingold.org s50002' ] class BitcoinGoldRegtest(BitcoinGold): FORK_HEIGHT = 2000 SHORTNAME = "TBTG" XPUB_VERBYTES = bytes.fromhex("043587CF") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6F") P2SH_VERBYTES = [bytes.fromhex("C4")] WIF_BYTE = bytes.fromhex("EF") TX_COUNT = 0 TX_COUNT_HEIGHT = 1 NET = 'regtest' RPC_PORT = 18444 GENESIS_HASH = ('0f9188f13cb7b2c71f2a335e3a4fc328' 'bf5beb436012afca590b1a11466e2206') PEERS = [] class BitcoinDiamond(BitcoinSegwit, Coin): NAME = "BitcoinDiamond" SHORTNAME = "BCD" TX_VERSION = 12 TX_COUNT = 274277819 TX_COUNT_HEIGHT = 498678 TX_PER_BLOCK = 50 REORG_LIMIT = 1000 PEERS = [] VALUE_PER_COIN = 10000000 DESERIALIZER = lib_tx.DeserializerBitcoinDiamondSegWit class Emercoin(NameMixin, Coin): NAME = "Emercoin" SHORTNAME = "EMC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("21") P2SH_VERBYTES = [bytes.fromhex("5c")] GENESIS_HASH = ('00000000bcccd459d036a588d1008fce' '8da3754b205736f32ddfd35350e84c2d') TX_COUNT = 217380620 TX_COUNT_HEIGHT = 464000 TX_PER_BLOCK = 1700 VALUE_PER_COIN = 1000000 RPC_PORT = 6662 DESERIALIZER = lib_tx.DeserializerEmercoin PEERS = [] # Name opcodes OP_NAME_NEW = OpCodes.OP_1 OP_NAME_UPDATE = OpCodes.OP_2 OP_NAME_DELETE = OpCodes.OP_3 # Valid name prefixes. NAME_NEW_OPS = [OP_NAME_NEW, OpCodes.OP_DROP, "name", "days", OpCodes.OP_2DROP, NameMixin.DATA_PUSH_MULTIPLE] NAME_UPDATE_OPS = [OP_NAME_UPDATE, OpCodes.OP_DROP, "name", "days", OpCodes.OP_2DROP, NameMixin.DATA_PUSH_MULTIPLE] NAME_DELETE_OPS = [OP_NAME_DELETE, OpCodes.OP_DROP, "name", OpCodes.OP_DROP] NAME_OPERATIONS = [ NAME_NEW_OPS, NAME_UPDATE_OPS, NAME_DELETE_OPS, ] @classmethod def block_header(cls, block, height): '''Returns the block header given a block and its height.''' deserializer = cls.DESERIALIZER(block) if deserializer.is_merged_block(): return deserializer.read_header(cls.BASIC_HEADER_SIZE) return block[:cls.static_header_len(height)] @classmethod def header_hash(cls, header): '''Given a header return hash''' return double_sha256(header[:cls.BASIC_HEADER_SIZE]) @classmethod def hashX_from_script(cls, script): _, address_script = cls.interpret_name_prefix(script, cls.NAME_OPERATIONS) return super().hashX_from_script(address_script) class BitcoinTestnetMixin(object): SHORTNAME = "XTN" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('000000000933ea01ad0ee984209779ba' 'aec3ced90fa3f408719526f8d77f4943') REORG_LIMIT = 8000 TX_COUNT = 12242438 TX_COUNT_HEIGHT = 1035428 TX_PER_BLOCK = 21 RPC_PORT = 18332 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} class BitcoinSVTestnet(BitcoinTestnetMixin, Coin): '''Bitcoin Testnet for Bitcoin SV daemons.''' NAME = "BitcoinSV" PEERS = [ 'electrontest.cascharia.com t51001 s51002', ] GENESIS_ACTIVATION = 1_344_302 class BitcoinSVScalingTestnet(BitcoinSVTestnet): NET = "scalingtest" PEERS = [ 'stn-server.electrumsv.io t51001 s51002', ] TX_COUNT = 2015 TX_COUNT_HEIGHT = 5711 TX_PER_BLOCK = 5000 GENESIS_ACTIVATION = 14_896 @classmethod def max_fetch_blocks(cls, height): if height <= 10: return 100 return 3 class BitcoinCashTestnet(BitcoinTestnetMixin, Coin): '''Bitcoin Testnet for Bitcoin Cash daemons.''' NAME = "BitcoinCashABC" PEERS = [ 'bch0.kister.net t s', 'testnet.imaginary.cash t50001 s50002', 'blackie.c3-soft.com t60001 s60002', ] BLOCK_PROCESSOR = block_proc.LTORBlockProcessor @classmethod def warn_old_client_on_tx_broadcast(cls, client_ver): if client_ver < (3, 3, 4): return ('<br/><br/>' 'Your transaction was successfully broadcast.<br/><br/>' 'However, you are using a VULNERABLE version of Electron Cash.<br/>' 'Download the latest version from this web site ONLY:<br/>' 'https://electroncash.org/' '<br/><br/>') return False class BitcoinSVRegtest(BitcoinSVTestnet): NET = "regtest" GENESIS_HASH = ('0f9188f13cb7b2c71f2a335e3a4fc328' 'bf5beb436012afca590b1a11466e2206') PEERS = [] TX_COUNT = 1 TX_COUNT_HEIGHT = 1 GENESIS_ACTIVATION = 10_000 class BitcoinSegwitTestnet(BitcoinTestnetMixin, Coin): '''Bitcoin Testnet for Core bitcoind >= 0.13.1.''' NAME = "BitcoinSegwit" DESERIALIZER = lib_tx.DeserializerSegWit CRASH_CLIENT_VER = (3, 2, 3) PEERS = [ 'testnet.hsmiths.com t53011 s53012', 'hsmithsxurybd7uh.onion t53011 s53012', 'testnet.qtornado.com s t', 'testnet1.bauerj.eu t50001 s50002', 'tn.not.fyi t55001 s55002', 'bitcoin.cluelessperson.com s t', ] @classmethod def warn_old_client_on_tx_broadcast(cls, client_ver): if client_ver < (3, 3, 3): return ('<br/><br/>' 'Your transaction was successfully broadcast.<br/><br/>' 'However, you are using a VULNERABLE version of Electrum.<br/>' 'Download the new version from the usual place:<br/>' 'https://electrum.org/' '<br/><br/>') return False class BitcoinSegwitRegtest(BitcoinSegwitTestnet): NAME = "BitcoinSegwit" NET = "regtest" GENESIS_HASH = ('0f9188f13cb7b2c71f2a335e3a4fc328' 'bf5beb436012afca590b1a11466e2206') PEERS = [] TX_COUNT = 1 TX_COUNT_HEIGHT = 1 class BitcoinNolnet(BitcoinCash): '''Bitcoin Unlimited nolimit testnet.''' NET = "nolnet" GENESIS_HASH = ('0000000057e31bd2066c939a63b7b862' '3bd0f10d8c001304bdfc1a7902ae6d35') PEERS = [] REORG_LIMIT = 8000 TX_COUNT = 583589 TX_COUNT_HEIGHT = 8617 TX_PER_BLOCK = 50 RPC_PORT = 28332 PEER_DEFAULT_PORTS = {'t': '52001', 's': '52002'} # Source: https://github.com/sumcoinlabs/sumcoin class Sumcoin(Coin): NAME = "Sumcoin" SHORTNAME = "SUM" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b41c") XPRV_VERBYTES = bytes.fromhex("0488abe6") P2PKH_VERBYTE = bytes.fromhex("3f") P2SH_VERBYTES = [bytes.fromhex("c8"), bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("bf") GENESIS_HASH = ('37d4696c5072cd012f3b7c651e5ce56a' '1383577e4edacc2d289ec9b25eebfd5e') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 976394 TX_COUNT_HEIGHT = 659520 TX_PER_BLOCK = 2 REORG_LIMIT = 800 RPC_PORT = 3332 PEER_DEFAULT_PORTS = {'t': '53332', 's': '53333'} PEERS = [] class Litecoin(Coin): NAME = "Litecoin" SHORTNAME = "LTC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("30") P2SH_VERBYTES = [bytes.fromhex("32"), bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("b0") GENESIS_HASH = ('12a765e31ffd4059bada1e25190f6e98' 'c99d9714d334efa41a195a7e7e04bfe2') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 8908766 TX_COUNT_HEIGHT = 1105256 TX_PER_BLOCK = 10 RPC_PORT = 9332 REORG_LIMIT = 800 PEERS = [ 'ex.lug.gs s444', 'electrum-ltc.bysh.me s t', 'electrum-ltc.ddns.net s t', 'electrum-ltc.wilv.in s t', 'electrum.cryptomachine.com p1000 s t', 'electrum.ltc.xurious.com s t', 'eywr5eubdbbe2laq.onion s50008 t50007', ] class LitecoinTestnet(Litecoin): SHORTNAME = "XLT" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("3a"), bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('4966625a4b2851d9fdee139e56211a0d' '88575f59ed816ff5e6a63deb4e3e29a0') TX_COUNT = 21772 TX_COUNT_HEIGHT = 20800 TX_PER_BLOCK = 2 RPC_PORT = 19332 REORG_LIMIT = 4000 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} PEERS = [ 'electrum-ltc.bysh.me s t', 'electrum.ltc.xurious.com s t', ] class LitecoinRegtest(LitecoinTestnet): NET = "regtest" GENESIS_HASH = ('530827f38f93b43ed12af0b3ad25a288' 'dc02ed74d6d7857862df51fc56c416f9') PEERS = [] TX_COUNT = 1 TX_COUNT_HEIGHT = 1 class BitcoinCashRegtest(BitcoinTestnetMixin, Coin): NAME = "BitcoinCashABC" # Some releases later remove the ABC suffix NET = "regtest" PEERS = [] GENESIS_HASH = ('0f9188f13cb7b2c71f2a335e3a4fc328' 'bf5beb436012afca590b1a11466e2206') TX_COUNT = 1 TX_COUNT_HEIGHT = 1 BLOCK_PROCESSOR = block_proc.LTORBlockProcessor class Viacoin(AuxPowMixin, Coin): NAME = "Viacoin" SHORTNAME = "VIA" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("47") P2SH_VERBYTES = [bytes.fromhex("21")] WIF_BYTE = bytes.fromhex("c7") GENESIS_HASH = ('4e9b54001f9976049830128ec0331515' 'eaabe35a70970d79971da1539a400ba1') TX_COUNT = 113638 TX_COUNT_HEIGHT = 3473674 TX_PER_BLOCK = 30 RPC_PORT = 5222 REORG_LIMIT = 5000 DESERIALIZER = lib_tx.DeserializerAuxPowSegWit PEERS = [ 'vialectrum.bitops.me s t', 'server.vialectrum.org s t', 'vialectrum.viacoin.net s t', 'viax1.bitops.me s t', ] class ViacoinTestnet(Viacoin): SHORTNAME = "TVI" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("7f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ff") GENESIS_HASH = ('00000007199508e34a9ff81e6ec0c477' 'a4cccff2a4767a8eee39c11db367b008') RPC_PORT = 25222 REORG_LIMIT = 2500 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} PEERS = [ 'vialectrum.bysh.me s t', ] class ViacoinTestnetSegWit(ViacoinTestnet): NET = "testnet-segwit" DESERIALIZER = lib_tx.DeserializerSegWit # Source: https://github.com/LIMXTEC/Bitcloud/blob/master/src/chainparams.cpp class Bitcloud(Coin): NAME = "Bitcloud" SHORTNAME = "BTDX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("99") GENESIS_HASH = ('000002d56463941c20eae5cb474cc805b646515d18bc7dc222a0885b206eadb0') TX_COUNT = 446050 TX_COUNT_HEIGHT = 547346 TX_PER_BLOCK = 2 PEER_DEFAULT_PORTS = {'t': '50001', 's': '50002'} RPC_PORT = 29200 REORG_LIMIT = 5000 PEERS = [] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import quark_hash return quark_hash.getPoWHash(header) # Source: https://github.com/GravityCoinOfficial/GravityCoin/ class GravityCoin(Coin): NAME = "GravityCoin" SHORTNAME = "GXX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("28") P2SH_VERBYTES = [bytes.fromhex("0a")] WIF_BYTE = bytes.fromhex("d2") GENESIS_HASH = ('322bad477efb4b33fa4b1f0b2861eaf543c61068da9898a95062fdb02ada486f') TX_COUNT = 446050 TX_COUNT_HEIGHT = 547346 TX_PER_BLOCK = 2 PEER_DEFAULT_PORTS = {'t': '50001', 's': '50002'} RPC_PORT = 29200 REORG_LIMIT = 5000 PEERS = [] # Source: https://github.com/BitcoinZeroOfficial/bitcoinzero class Bitcoinzero(Coin): NAME = "Bitcoinzero" SHORTNAME = "BZX" TX_COUNT = 43798 TX_COUNT_HEIGHT = 44 TX_PER_BLOCK = 576 NET = "mainnet" GENESIS_HASH = ('322bad477efb4b33fa4b1f0b2861eaf543c61068da9898a95062fdb02ada486f') XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("4b") P2SH_VERBYTES = [bytes.fromhex("22")] WIF_BYTE = bytes.fromhex("d2") RPC_PORT = 29202 REORG_LIMIT = 5000 PEERS = [] # Source: https://github.com/LIMXTEC/Megacoin/blob/0.15/src/chainparams.cpp class Megacoin(Coin): NAME = "Megacoin" SHORTNAME = "MEC" TX_COUNT = 43798 TX_COUNT_HEIGHT = 44 TX_PER_BLOCK = 576 NET = "mainnet" GENESIS_HASH = ('7520788e2d99eec7cf6cf7315577e1268e177fff94cb0a7caf6a458ceeea9ac2') XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("22")] WIF_BYTE = bytes.fromhex("b2") RPC_PORT = 29202 REORG_LIMIT = 5000 PEERS = [] class Unitus(Coin): NAME = "Unitus" SHORTNAME = "UIS" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("44") P2SH_VERBYTES = [bytes.fromhex("0A")] WIF_BYTE = bytes.fromhex("84") GENESIS_HASH = ('d8a2b2439d013a59f3bfc626a33487a3' 'd7d27e42a3c9e0b81af814cd8e592f31') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 3484561 TX_COUNT_HEIGHT = 1697605 TX_PER_BLOCK = 3 RPC_PORT = 50604 REORG_LIMIT = 2000 PEERS = [ 'electrumx.unituscurrency.com s t', ] # Source: namecoin.org class Namecoin(NameIndexMixin, AuxPowMixin, Coin): NAME = "Namecoin" SHORTNAME = "NMC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("d7dd6370") XPRV_VERBYTES = bytes.fromhex("d7dc6e31") P2PKH_VERBYTE = bytes.fromhex("34") P2SH_VERBYTES = [bytes.fromhex("0d")] WIF_BYTE = bytes.fromhex("e4") GENESIS_HASH = ('000000000062b72c5e2ceb45fbc8587e' '807c155b0da735e6483dfba2f0a9c770') DESERIALIZER = lib_tx.DeserializerAuxPowSegWit TX_COUNT = 4415768 TX_COUNT_HEIGHT = 329065 TX_PER_BLOCK = 10 RPC_PORT = 8336 PEERS = [ 'electrum-nmc.le-space.de s50002', 'ex.lug.gs s446', 'luggscoqbymhvnkp.onion t82', 'nmc.bitcoins.sk s50002', 'ulrichard.ch s50006 t50005', ] BLOCK_PROCESSOR = block_proc.NameIndexBlockProcessor # Name opcodes OP_NAME_NEW = OpCodes.OP_1 OP_NAME_FIRSTUPDATE = OpCodes.OP_2 OP_NAME_UPDATE = OpCodes.OP_3 # Valid name prefixes. NAME_NEW_OPS = [OP_NAME_NEW, -1, OpCodes.OP_2DROP] NAME_FIRSTUPDATE_OPS = [OP_NAME_FIRSTUPDATE, "name", -1, -1, OpCodes.OP_2DROP, OpCodes.OP_2DROP] NAME_UPDATE_OPS = [OP_NAME_UPDATE, "name", -1, OpCodes.OP_2DROP, OpCodes.OP_DROP] NAME_OPERATIONS = [ NAME_NEW_OPS, NAME_FIRSTUPDATE_OPS, NAME_UPDATE_OPS, ] class NamecoinTestnet(Namecoin): NAME = "Namecoin" SHORTNAME = "XNM" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('00000007199508e34a9ff81e6ec0c477' 'a4cccff2a4767a8eee39c11db367b008') class NamecoinRegtest(NamecoinTestnet): NAME = "Namecoin" NET = "regtest" GENESIS_HASH = ('0f9188f13cb7b2c71f2a335e3a4fc328' 'bf5beb436012afca590b1a11466e2206') PEERS = [] TX_COUNT = 1 TX_COUNT_HEIGHT = 1 class Dogecoin(AuxPowMixin, Coin): NAME = "Dogecoin" SHORTNAME = "DOGE" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("02facafd") XPRV_VERBYTES = bytes.fromhex("02fac398") P2PKH_VERBYTE = bytes.fromhex("1e") P2SH_VERBYTES = [bytes.fromhex("16")] WIF_BYTE = bytes.fromhex("9e") GENESIS_HASH = ('1a91e3dace36e2be3bf030a65679fe82' '1aa1d6ef92e7c9902eb318182c355691') TX_COUNT = 27583427 TX_COUNT_HEIGHT = 1604979 TX_PER_BLOCK = 20 REORG_LIMIT = 2000 class DogecoinTestnet(Dogecoin): NAME = "Dogecoin" SHORTNAME = "XDT" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("71") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("f1") GENESIS_HASH = ('bb0a78264637406b6360aad926284d54' '4d7049f45189db5664f3c4d07350559e') # Source: https://github.com/motioncrypto/motion class Motion(Coin): NAME = "Motion" SHORTNAME = "XMN" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('000001e9dc60dd2618e91f7b90141349' '22c374496b61c1a272519b1c39979d78') P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("12")] TX_COUNT_HEIGHT = 54353 TX_COUNT = 92701 TX_PER_BLOCK = 4 RPC_PORT = 3385 SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x16r_hash return x16r_hash.getPoWHash(header) # Source: https://github.com/dashpay/dash class Dash(Coin): NAME = "Dash" SHORTNAME = "DASH" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("02fe52cc") XPRV_VERBYTES = bytes.fromhex("02fe52f8") GENESIS_HASH = ('00000ffd590b1485b3caadc19b22e637' '9c733355108f107a430458cdf3407ab6') P2PKH_VERBYTE = bytes.fromhex("4c") P2SH_VERBYTES = [bytes.fromhex("10")] WIF_BYTE = bytes.fromhex("cc") TX_COUNT_HEIGHT = 569399 TX_COUNT = 2157510 TX_PER_BLOCK = 4 RPC_PORT = 9998 PEERS = [ 'electrum.dash.org s t', 'electrum.masternode.io s t', 'electrum-drk.club s t', 'dashcrypto.space s t', 'electrum.dash.siampm.com s t', 'wl4sfwq2hwxnodof.onion s t', ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon DESERIALIZER = lib_tx_dash.DeserializerDash @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x11_hash return x11_hash.getPoWHash(header) class DashTestnet(Dash): SHORTNAME = "tDASH" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("3a805837") XPRV_VERBYTES = bytes.fromhex("3a8061a0") GENESIS_HASH = ('00000bafbc94add76cb75e2ec9289483' '7288a481e5c005f6563d91623bf8bc2c') P2PKH_VERBYTE = bytes.fromhex("8c") P2SH_VERBYTES = [bytes.fromhex("13")] WIF_BYTE = bytes.fromhex("ef") TX_COUNT_HEIGHT = 101619 TX_COUNT = 132681 TX_PER_BLOCK = 1 RPC_PORT = 19998 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} PEERS = [ 'electrum.dash.siampm.com s t', 'dasht.random.re s54002 t54001', ] class Argentum(AuxPowMixin, Coin): NAME = "Argentum" SHORTNAME = "ARG" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("17") WIF_BYTE = bytes.fromhex("97") GENESIS_HASH = ('88c667bc63167685e4e4da058fffdfe8' 'e007e5abffd6855de52ad59df7bb0bb2') TX_COUNT = 2263089 TX_COUNT_HEIGHT = 2050260 TX_PER_BLOCK = 2000 RPC_PORT = 13581 class ArgentumTestnet(Argentum): SHORTNAME = "XRG" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") REORG_LIMIT = 2000 class DigiByte(Coin): NAME = "DigiByte" SHORTNAME = "DGB" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1E") GENESIS_HASH = ('7497ea1b465eb39f1c8f507bc877078f' 'e016d6fcb6dfad3a64c98dcc6e1e8496') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 1046018 TX_COUNT_HEIGHT = 1435000 TX_PER_BLOCK = 1000 RPC_PORT = 12022 class DigiByteTestnet(DigiByte): NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('b5dca8039e300198e5fe7cd23bdd1728' 'e2a444af34c447dbd0916fa3430a68c2') RPC_PORT = 15022 REORG_LIMIT = 2000 class FairCoin(Coin): NAME = "FairCoin" SHORTNAME = "FAIR" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("5f") P2SH_VERBYTES = [bytes.fromhex("24")] WIF_BYTE = bytes.fromhex("df") GENESIS_HASH = ('beed44fa5e96150d95d56ebd5d262578' '1825a9407a5215dd7eda723373a0a1d7') BASIC_HEADER_SIZE = 108 HEADER_VALUES = ('version', 'prev_block_hash', 'merkle_root', 'payload_hash', 'timestamp', 'creatorId') HEADER_UNPACK = struct.Struct('< I 32s 32s 32s I I').unpack_from TX_COUNT = 505 TX_COUNT_HEIGHT = 470 TX_PER_BLOCK = 1 RPC_PORT = 40405 PEER_DEFAULT_PORTS = {'t': '51811', 's': '51812'} PEERS = [ 'electrum.faircoin.world s', 'electrumfair.punto0.org s', ] @classmethod def block(cls, raw_block, height): '''Return a Block namedtuple given a raw block and its height.''' if height > 0: return super().block(raw_block, height) else: return Block(raw_block, cls.block_header(raw_block, height), []) class Zcash(EquihashMixin, Coin): NAME = "Zcash" SHORTNAME = "ZEC" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1CB8") P2SH_VERBYTES = [bytes.fromhex("1CBD")] GENESIS_HASH = ('00040fe8ec8471911baa1db1266ea15d' 'd06b4a8a5c453883c000b031973dce08') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 5 RPC_PORT = 8232 REORG_LIMIT = 800 class ZcashTestnet(Zcash): SHORTNAME = "TAZ" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("1D25") P2SH_VERBYTES = [bytes.fromhex("1CBA")] WIF_BYTE = bytes.fromhex("EF") GENESIS_HASH = ('05a60a92d99d85997cce3b87616c089f' '6124d7342af37106edc76126334a2c38') TX_COUNT = 242312 TX_COUNT_HEIGHT = 321685 TX_PER_BLOCK = 2 RPC_PORT = 18232 class SnowGem(EquihashMixin, Coin): NAME = "SnowGem" SHORTNAME = "XSG" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1C28") P2SH_VERBYTES = [bytes.fromhex("1C2D")] GENESIS_HASH = ('00068b35729d9d2b0c294ff1fe9af009' '4740524311a131de40e7f705e4c29a5b') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 1680878 TX_COUNT_HEIGHT = 627250 TX_PER_BLOCK = 2 RPC_PORT = 16112 REORG_LIMIT = 800 CHUNK_SIZE = 200 class BitcoinZ(EquihashMixin, Coin): NAME = "BitcoinZ" SHORTNAME = "BTCZ" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1CB8") P2SH_VERBYTES = [bytes.fromhex("1CBD")] GENESIS_HASH = ('f499ee3d498b4298ac6a64205b8addb7' 'c43197e2a660229be65db8a4534d75c1') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 171976 TX_COUNT_HEIGHT = 81323 TX_PER_BLOCK = 3 RPC_PORT = 1979 REORG_LIMIT = 800 class Hush(EquihashMixin, Coin): NAME = "Hush" SHORTNAME = "HUSH" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1CB8") P2SH_VERBYTES = [bytes.fromhex("1CBD")] GENESIS_HASH = ('0003a67bc26fe564b75daf11186d3606' '52eb435a35ba3d9d3e7e5d5f8e62dc17') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 5 RPC_PORT = 8822 REORG_LIMIT = 800 class ZelCash(EquihashMixin, Coin): NAME = "ZelCash" SHORTNAME = "ZEL" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1CB8") P2SH_VERBYTES = [bytes.fromhex("1CBD")] GENESIS_HASH = ('00052461a5006c2e3b74ce48992a0869' '5607912d5604c3eb8da25749b0900444') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 450539 TX_COUNT_HEIGHT = 167114 TX_PER_BLOCK = 3 RPC_PORT = 16124 REORG_LIMIT = 800 class Zclassic(EquihashMixin, Coin): NAME = "Zclassic" SHORTNAME = "ZCL" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1CB8") P2SH_VERBYTES = [bytes.fromhex("1CBD")] GENESIS_HASH = ('0007104ccda289427919efc39dc9e4d4' '99804b7bebc22df55f8b834301260602') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 5 RPC_PORT = 8023 REORG_LIMIT = 800 class Koto(Coin): NAME = "Koto" SHORTNAME = "KOTO" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1836") P2SH_VERBYTES = [bytes.fromhex("183B")] GENESIS_HASH = ('6d424c350729ae633275d51dc3496e16' 'cd1b1d195c164da00f39c499a2e9959e') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 158914 TX_COUNT_HEIGHT = 67574 TX_PER_BLOCK = 3 RPC_PORT = 8432 REORG_LIMIT = 800 PEERS = [ 'fr.kotocoin.info s t', 'electrum.kotocoin.info s t', ] class KotoTestnet(Koto): SHORTNAME = "TOKO" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("18A4") P2SH_VERBYTES = [bytes.fromhex("1839")] WIF_BYTE = bytes.fromhex("EF") GENESIS_HASH = ('bf84afbde20c2d213b68b231ddb585ab' '616ef7567226820f00d9b397d774d2f0') TX_COUNT = 91144 TX_COUNT_HEIGHT = 89662 TX_PER_BLOCK = 1 RPC_PORT = 18432 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} PEERS = [ 'testnet.kotocoin.info s t', ] class Komodo(KomodoMixin, EquihashMixin, Coin): NAME = "Komodo" SHORTNAME = "KMD" NET = "mainnet" TX_COUNT = 693629 TX_COUNT_HEIGHT = 491777 TX_PER_BLOCK = 2 RPC_PORT = 7771 REORG_LIMIT = 800 PEERS = [] class Monaize(KomodoMixin, EquihashMixin, Coin): NAME = "Monaize" SHORTNAME = "MNZ" NET = "mainnet" TX_COUNT = 256 TX_COUNT_HEIGHT = 128 TX_PER_BLOCK = 2 RPC_PORT = 14337 REORG_LIMIT = 800 PEERS = [] class Einsteinium(Coin): NAME = "Einsteinium" SHORTNAME = "EMC2" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("21") WIF_BYTE = bytes.fromhex("b0") GENESIS_HASH = ('4e56204bb7b8ac06f860ff1c845f03f9' '84303b5b97eb7b42868f714611aed94b') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 2087559 TX_COUNT_HEIGHT = 1358517 TX_PER_BLOCK = 2 RPC_PORT = 41879 REORG_LIMIT = 2000 class Blackcoin(ScryptMixin, Coin): NAME = "Blackcoin" SHORTNAME = "BLK" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("99") GENESIS_HASH = ('000001faef25dec4fbcf906e6242621d' 'f2c183bf232f263d0ba5b101911e4563') DAEMON = daemon.LegacyRPCDaemon TX_COUNT = 4594999 TX_COUNT_HEIGHT = 1667070 TX_PER_BLOCK = 3 RPC_PORT = 15715 REORG_LIMIT = 5000 class Bitbay(ScryptMixin, Coin): NAME = "Bitbay" SHORTNAME = "BAY" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("99") GENESIS_HASH = ('0000075685d3be1f253ce777174b1594' '354e79954d2a32a6f77fe9cba00e6467') TX_COUNT = 4594999 TX_COUNT_HEIGHT = 1667070 TX_PER_BLOCK = 3 RPC_PORT = 19914 REORG_LIMIT = 5000 class DeepOnion(Coin): NAME = "DeepOnion" SHORTNAME = "ONION" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1F") P2SH_VERBYTES = [bytes.fromhex("4E")] WIF_BYTE = bytes.fromhex("9f") GENESIS_HASH = ('000004e29458ef4f2e0abab544737b07' '344e6ff13718f7c2d12926166db07b5e') DESERIALIZER = lib_tx.DeserializerTxTime DAEMON = daemon.LegacyRPCDaemon TX_COUNT = 1194707 TX_COUNT_HEIGHT = 530000 TX_PER_BLOCK = 2 RPC_PORT = 18580 REORG_LIMIT = 200 XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") PEERS = [] @classmethod def header_hash(cls, header): ''' Given a header return the hash for DeepOnion. Need to download `x13_hash` module Source code: https://github.com/MaruCoinOfficial/x13-hash ''' import x13_hash return x13_hash.getPoWHash(header) class Peercoin(Coin): NAME = "Peercoin" SHORTNAME = "PPC" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("37") P2SH_VERBYTES = [bytes.fromhex("75")] WIF_BYTE = bytes.fromhex("b7") GENESIS_HASH = ('0000000032fe677166d54963b62a4677' 'd8957e87c508eaa4fd7eb1c880cd27e3') DESERIALIZER = lib_tx.DeserializerTxTimeSegWit DAEMON = daemon.FakeEstimateFeeDaemon ESTIMATE_FEE = 0.001 RELAY_FEE = 0.01 TX_COUNT = 1691771 TX_COUNT_HEIGHT = 455409 TX_PER_BLOCK = 4 RPC_PORT = 9902 REORG_LIMIT = 5000 PEERS = [ "electrum.peercoinexplorer.net s" ] VALUE_PER_COIN = 1000000 class PeercoinTestnet(Peercoin): NAME = "PeercoinTestnet" SHORTNAME = "tPPC" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('00000001f757bb737f6596503e17cd17' 'b0658ce630cc727c0cca81aec47c9f06') ESTIMATE_FEE = 0.001 class Trezarcoin(Coin): NAME = "Trezarcoin" SHORTNAME = "TZC" NET = "mainnet" VALUE_PER_COIN = 1000000 XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("42") P2SH_VERBYTES = [bytes.fromhex("08")] WIF_BYTE = bytes.fromhex("c2") GENESIS_HASH = ('24502ba55d673d2ee9170d83dae2d1ad' 'b3bfb4718e4f200db9951382cc4f6ee6') DESERIALIZER = lib_tx.DeserializerTrezarcoin HEADER_HASH = lib_tx.DeserializerTrezarcoin.blake2s HEADER_HASH_GEN = lib_tx.DeserializerTrezarcoin.blake2s_gen BASIC_HEADER_SIZE = 80 TX_COUNT = 742886 TX_COUNT_HEIGHT = 643128 TX_PER_BLOCK = 2 RPC_PORT = 17299 REORG_LIMIT = 2000 PEERS = [ 'electrumx1.trezarcoin.com s t', ] @classmethod def genesis_block(cls, block): '''Check the Genesis block is the right one for this coin. Return the block less its unspendable coinbase. ''' header = cls.block_header(block, 0) header_hex_hash = cls.HEADER_HASH_GEN(header) if header_hex_hash != cls.GENESIS_HASH: raise CoinError('genesis block has hash {} expected {}' .format(header_hex_hash, cls.GENESIS_HASH)) return header + bytes(1) @classmethod def header_hash(cls, header): '''Given a header return the hash.''' return cls.HEADER_HASH(header) class Reddcoin(Coin): NAME = "Reddcoin" SHORTNAME = "RDD" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("3d") WIF_BYTE = bytes.fromhex("bd") GENESIS_HASH = ('b868e0d95a3c3c0e0dadc67ee587aaf9' 'dc8acbf99e3b4b3110fad4eb74c1decc') DESERIALIZER = lib_tx.DeserializerReddcoin TX_COUNT = 5413508 TX_COUNT_HEIGHT = 1717382 TX_PER_BLOCK = 3 RPC_PORT = 45443 class TokenPay(ScryptMixin, Coin): NAME = "TokenPay" SHORTNAME = "TPAY" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("41") P2SH_VERBYTES = [bytes.fromhex("7e")] WIF_BYTE = bytes.fromhex("b3") GENESIS_HASH = ('000008b71ab32e585a23f0de642dc113' '740144e94c0ece047751e9781f953ae9') DESERIALIZER = lib_tx.DeserializerTokenPay DAEMON = daemon.LegacyRPCDaemon TX_COUNT = 147934 TX_COUNT_HEIGHT = 73967 TX_PER_BLOCK = 100 RPC_PORT = 8800 REORG_LIMIT = 500 XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") PEERS = [ "electrum-us.tpay.ai s", "electrum-eu.tpay.ai s", ] class Vertcoin(Coin): NAME = "Vertcoin" SHORTNAME = "VTC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("47") GENESIS_HASH = ('4d96a915f49d40b1e5c2844d1ee2dccb' '90013a990ccea12c492d22110489f0c4') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 2383423 TX_COUNT_HEIGHT = 759076 TX_PER_BLOCK = 3 RPC_PORT = 5888 REORG_LIMIT = 1000 class Monacoin(Coin): NAME = "Monacoin" SHORTNAME = "MONA" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("37"), bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("B0") GENESIS_HASH = ('ff9f1c0116d19de7c9963845e129f9ed' '1bfc0b376eb54fd7afa42e0d418c8bb6') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 2568580 TX_COUNT_HEIGHT = 1029766 TX_PER_BLOCK = 2 RPC_PORT = 9402 REORG_LIMIT = 1000 BLACKLIST_URL = 'https://electrum-mona.org/blacklist.json' PEERS = [ 'electrumx.tamami-foundation.org s t', 'electrumx3.monacoin.nl s t', 'electrumx1.monacoin.ninja s t', 'electrumx2.movsign.info s t', 'electrum-mona.bitbank.cc s t', 'ri7rzlmdaf4eqbza.onion s t', ] class MonacoinTestnet(Monacoin): SHORTNAME = "XMN" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587CF") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6F") P2SH_VERBYTES = [bytes.fromhex("75"), bytes.fromhex("C4")] WIF_BYTE = bytes.fromhex("EF") GENESIS_HASH = ('a2b106ceba3be0c6d097b2a6a6aacf9d' '638ba8258ae478158f449c321061e0b2') TX_COUNT = 83602 TX_COUNT_HEIGHT = 83252 TX_PER_BLOCK = 1 RPC_PORT = 19402 REORG_LIMIT = 1000 PEER_DEFAULT_PORTS = {'t': '51001', 's': '51002'} PEERS = [ 'electrumx1.testnet.monacoin.ninja s t', 'electrumx1.testnet.monacoin.nl s t', ] class MonacoinRegtest(MonacoinTestnet): NET = "regtest" GENESIS_HASH = ('7543a69d7c2fcdb29a5ebec2fc064c07' '4a35253b6f3072c8a749473aa590a29c') PEERS = [] TX_COUNT = 1 TX_COUNT_HEIGHT = 1 class Crown(AuxPowMixin, Coin): NAME = "Crown" SHORTNAME = "CRW" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2SH_VERBYTES = [bytes.fromhex("1c")] GENESIS_HASH = ('0000000085370d5e122f64f4ab19c686' '14ff3df78c8d13cb814fd7e69a1dc6da') TX_COUNT = 13336629 TX_COUNT_HEIGHT = 1268206 TX_PER_BLOCK = 10 RPC_PORT = 9341 REORG_LIMIT = 1000 PEERS = [ 'sgp-crwseed.crowndns.info s t', 'blr-crwseed.crowndns.info s t', 'sfo-crwseed.crowndns.info s t', 'nyc-crwseed.crowndns.info s t', 'ams-crwseed.crowndns.info s t', 'tor-crwseed.crowndns.info s t', 'lon-crwseed.crowndns.info s t', 'fra-crwseed.crowndns.info s t', ] class Fujicoin(Coin): NAME = "Fujicoin" SHORTNAME = "FJC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("24") P2SH_VERBYTES = [bytes.fromhex("10")] WIF_BYTE = bytes.fromhex("a4") GENESIS_HASH = ('adb6d9cfd74075e7f91608add4bd2a2e' 'a636f70856183086842667a1597714a0') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 170478 TX_COUNT_HEIGHT = 1521676 TX_PER_BLOCK = 1 RPC_PORT = 3776 REORG_LIMIT = 1000 class Neblio(ScryptMixin, Coin): NAME = "Neblio" SHORTNAME = "NEBL" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("35") P2SH_VERBYTES = [bytes.fromhex("70")] GENESIS_HASH = ('7286972be4dbc1463d256049b7471c25' '2e6557e222cab9be73181d359cd28bcc') TX_COUNT = 23675 TX_COUNT_HEIGHT = 22785 TX_PER_BLOCK = 1 RPC_PORT = 6326 REORG_LIMIT = 1000 class Bitzeny(Coin): NAME = "Bitzeny" SHORTNAME = "ZNY" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("51") GENESIS_HASH = ('000009f7e55e9e3b4781e22bd87a7cfa' '4acada9e4340d43ca738bf4e9fb8f5ce') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 1408733 TX_COUNT_HEIGHT = 1015115 TX_PER_BLOCK = 1 RPC_PORT = 9252 REORG_LIMIT = 1000 @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import zny_yespower_0_5 return zny_yespower_0_5.getPoWHash(header) class CanadaeCoin(AuxPowMixin, Coin): NAME = "CanadaeCoin" SHORTNAME = "CDN" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1C") WIF_BYTE = bytes.fromhex("9c") GENESIS_HASH = ('863626dadaef221e2e2f30ff3dacae44' 'cabdae9e0028058072181b3fb675d94a') ESTIMATE_FEE = 0.0001 RELAY_FEE = 0.0001 DAEMON = daemon.FakeEstimateFeeDaemon TX_COUNT = 3455905 TX_COUNT_HEIGHT = 3645419 TX_PER_BLOCK = 1 RPC_PORT = 34330 REORG_LIMIT = 1000 class Denarius(Coin): NAME = "Denarius" SHORTNAME = "DNR" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1E") # Address starts with a D P2SH_VERBYTES = [bytes.fromhex("5A")] WIF_BYTE = bytes.fromhex("9E") # WIF starts with a 6 GENESIS_HASH = ('00000d5dbbda01621cfc16bbc1f9bf32' '64d641a5dbf0de89fd0182c2c4828fcd') DESERIALIZER = lib_tx.DeserializerTxTime TX_COUNT = 4230 RPC_PORT = 32339 ESTIMATE_FEE = 0.00001 RELAY_FEE = 0.00001 DAEMON = daemon.FakeEstimateFeeDaemon TX_COUNT_HEIGHT = 306187 TX_PER_BLOCK = 4000 @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import tribus_hash return tribus_hash.getPoWHash(header) class DenariusTestnet(Denarius): NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("12") P2SH_VERBYTES = [bytes.fromhex("74")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('000086bfe8264d241f7f8e5393f74778' '4b8ca2aa98bdd066278d590462a4fdb4') RPC_PORT = 32338 REORG_LIMIT = 2000 class Sibcoin(Dash): NAME = "Sibcoin" SHORTNAME = "SIB" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("3F") P2SH_VERBYTES = [bytes.fromhex("28")] WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('00000c492bf73490420868bc577680bf' 'c4c60116e7e85343bc624787c21efa4c') DAEMON = daemon.DashDaemon TX_COUNT = 1000 TX_COUNT_HEIGHT = 10000 TX_PER_BLOCK = 1 RPC_PORT = 1944 REORG_LIMIT = 1000 PEERS = [] @classmethod def header_hash(cls, header): ''' Given a header return the hash for sibcoin. Need to download `x11_gost_hash` module Source code: https://github.com/ivansib/x11_gost_hash ''' import x11_gost_hash return x11_gost_hash.getPoWHash(header) class SibcoinTestnet(Sibcoin): SHORTNAME = "tSIB" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") GENESIS_HASH = ('00000617791d0e19f524387f67e558b2' 'a928b670b9a3b387ae003ad7f9093017') RPC_PORT = 11944 class Chips(Coin): NAME = "Chips" SHORTNAME = "CHIPS" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("3c") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("bc") GENESIS_HASH = ('0000006e75f6aa0efdbf7db03132aa4e' '4d0c84951537a6f5a7c39a0a9d30e1e7') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 145290 TX_COUNT_HEIGHT = 318637 TX_PER_BLOCK = 2 RPC_PORT = 57776 REORG_LIMIT = 800 class Feathercoin(Coin): NAME = "Feathercoin" SHORTNAME = "FTC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488BC26") XPRV_VERBYTES = bytes.fromhex("0488DAEE") P2PKH_VERBYTE = bytes.fromhex("0E") WIF_BYTE = bytes.fromhex("8E") GENESIS_HASH = ('12a765e31ffd4059bada1e25190f6e98' 'c99d9714d334efa41a195a7e7e04bfe2') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 3170843 TX_COUNT_HEIGHT = 1981777 TX_PER_BLOCK = 2 RPC_PORT = 9337 REORG_LIMIT = 2000 PEERS = [ 'electrumx-gb-1.feathercoin.network s t', 'electrumx-gb-2.feathercoin.network s t', 'electrumx-de-1.feathercoin.network s t', ] class UFO(Coin): NAME = "UniformFiscalObject" SHORTNAME = "UFO" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("1B") P2SH_VERBYTES = [bytes.fromhex("44")] WIF_BYTE = bytes.fromhex("9B") GENESIS_HASH = ('ba1d39b4928ab03d813d952daf65fb77' '97fcf538a9c1b8274f4edc8557722d13') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 1608926 TX_COUNT_HEIGHT = 1300154 TX_PER_BLOCK = 2 RPC_PORT = 9888 REORG_LIMIT = 2000 PEERS = [ 'electrumx1.ufobject.com s t', ] class Newyorkcoin(AuxPowMixin, Coin): NAME = "Newyorkcoin" SHORTNAME = "NYC" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("3c") P2SH_VERBYTES = [bytes.fromhex("16")] WIF_BYTE = bytes.fromhex("bc") GENESIS_HASH = ('5597f25c062a3038c7fd815fe46c67de' 'dfcb3c839fbc8e01ed4044540d08fe48') TX_COUNT = 5161944 TX_COUNT_HEIGHT = 3948743 TX_PER_BLOCK = 2 REORG_LIMIT = 2000 class NewyorkcoinTestnet(Newyorkcoin): SHORTNAME = "tNYC" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("71") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("f1") GENESIS_HASH = ('24463e4d3c625b0a9059f309044c2cf0' 'd7e196cf2a6ecce901f24f681be33c8f') TX_COUNT = 5161944 TX_COUNT_HEIGHT = 3948743 TX_PER_BLOCK = 2 REORG_LIMIT = 2000 class Bitcore(BitcoinMixin, Coin): NAME = "Bitcore" SHORTNAME = "BTX" P2PKH_VERBYTE = bytes.fromhex("03") P2SH_VERBYTES = [bytes.fromhex("7D")] DESERIALIZER = lib_tx.DeserializerSegWit GENESIS_HASH = ('604148281e5c4b7f2487e5d03cd60d8e' '6f69411d613f6448034508cea52e9574') TX_COUNT = 126979 TX_COUNT_HEIGHT = 126946 TX_PER_BLOCK = 2 RPC_PORT = 8556 PEERS = [ 'ele1.bitcore.cc s t', 'ele2.bitcore.cc s t', 'ele3.bitcore.cc s t', 'ele4.bitcore.cc s t' ] class GameCredits(Coin): NAME = "GameCredits" SHORTNAME = "GAME" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("26") WIF_BYTE = bytes.fromhex("a6") GENESIS_HASH = ('91ec5f25ee9a0ffa1af7d4da4db9a552' '228dd2dc77cdb15b738be4e1f55f30ee') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 316796 TX_COUNT_HEIGHT = 2040250 TX_PER_BLOCK = 2 RPC_PORT = 40001 REORG_LIMIT = 1000 class Machinecoin(Coin): NAME = "Machinecoin" SHORTNAME = "MAC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("26"), bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("b2") GENESIS_HASH = ('6a1f879bcea5471cbfdee1fd0cb2ddcc' '4fed569a500e352d41de967703e83172') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 137641 TX_COUNT_HEIGHT = 513020 TX_PER_BLOCK = 2 RPC_PORT = 40332 REORG_LIMIT = 800 class BitcoinAtom(Coin): NAME = "BitcoinAtom" SHORTNAME = "BCA" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("17") P2SH_VERBYTES = [bytes.fromhex("0a")] STATIC_BLOCK_HEADERS = False DESERIALIZER = lib_tx.DeserializerBitcoinAtom HEADER_SIZE_POST_FORK = 84 BLOCK_PROOF_OF_STAKE = 0x01 BLOCK_PROOF_OF_STAKE_FLAGS = b'\x01\x00\x00\x00' TX_COUNT = 295158744 TX_COUNT_HEIGHT = 589197 TX_PER_BLOCK = 10 RPC_PORT = 9136 REORG_LIMIT = 5000 @classmethod def header_hash(cls, header): '''Given a header return hash''' header_to_be_hashed = header[:cls.BASIC_HEADER_SIZE] # New block header format has some extra flags in the end if len(header) == cls.HEADER_SIZE_POST_FORK: flags, = util.unpack_le_uint32_from(header, len(header) - 4) # Proof of work blocks have special serialization if flags & cls.BLOCK_PROOF_OF_STAKE != 0: header_to_be_hashed += cls.BLOCK_PROOF_OF_STAKE_FLAGS return double_sha256(header_to_be_hashed) @classmethod def block_header(cls, block, height): '''Return the block header bytes''' deserializer = cls.DESERIALIZER(block) return deserializer.read_header(height, cls.BASIC_HEADER_SIZE) class Decred(Coin): NAME = "Decred" SHORTNAME = "DCR" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("02fda926") XPRV_VERBYTES = bytes.fromhex("02fda4e8") P2PKH_VERBYTE = bytes.fromhex("073f") P2SH_VERBYTES = [bytes.fromhex("071a")] WIF_BYTE = bytes.fromhex("22de") GENESIS_HASH = ('298e5cc3d985bfe7f81dc135f360abe0' '89edd4396b86d2de66b0cef42b21d980') BASIC_HEADER_SIZE = 180 HEADER_HASH = lib_tx.DeserializerDecred.blake256 DESERIALIZER = lib_tx.DeserializerDecred DAEMON = daemon.DecredDaemon BLOCK_PROCESSOR = block_proc.DecredBlockProcessor ENCODE_CHECK = partial(Base58.encode_check, hash_fn=lib_tx.DeserializerDecred.blake256d) DECODE_CHECK = partial(Base58.decode_check, hash_fn=lib_tx.DeserializerDecred.blake256d) HEADER_VALUES = ('version', 'prev_block_hash', 'merkle_root', 'stake_root', 'vote_bits', 'final_state', 'voters', 'fresh_stake', 'revocations', 'pool_size', 'bits', 'sbits', 'block_height', 'size', 'timestamp', 'nonce', 'extra_data', 'stake_version') HEADER_UNPACK = struct.Struct( '< i 32s 32s 32s H 6s H B B I I Q I I I I 32s I').unpack_from TX_COUNT = 4629388 TX_COUNT_HEIGHT = 260628 TX_PER_BLOCK = 17 REORG_LIMIT = 1000 RPC_PORT = 9109 @classmethod def header_hash(cls, header): '''Given a header return the hash.''' return cls.HEADER_HASH(header) @classmethod def block(cls, raw_block, height): '''Return a Block namedtuple given a raw block and its height.''' if height > 0: return super().block(raw_block, height) else: return Block(raw_block, cls.block_header(raw_block, height), []) class DecredTestnet(Decred): SHORTNAME = "tDCR" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587d1") XPRV_VERBYTES = bytes.fromhex("04358397") P2PKH_VERBYTE = bytes.fromhex("0f21") P2SH_VERBYTES = [bytes.fromhex("0efc")] WIF_BYTE = bytes.fromhex("230e") GENESIS_HASH = ( 'a649dce53918caf422e9c711c858837e08d626ecfcd198969b24f7b634a49bac') BASIC_HEADER_SIZE = 180 ALLOW_ADVANCING_ERRORS = True TX_COUNT = 217380620 TX_COUNT_HEIGHT = 464000 TX_PER_BLOCK = 1800 REORG_LIMIT = 1000 RPC_PORT = 19109 class Axe(Dash): NAME = "Axe" SHORTNAME = "AXE" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("02fe52cc") XPRV_VERBYTES = bytes.fromhex("02fe52f8") P2PKH_VERBYTE = bytes.fromhex("37") P2SH_VERBYTES = [bytes.fromhex("10")] WIF_BYTE = bytes.fromhex("cc") GENESIS_HASH = ('00000c33631ca6f2f61368991ce2dc03' '306b5bb50bf7cede5cfbba6db38e52e6') SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon DESERIALIZER = lib_tx_axe.DeserializerAxe TX_COUNT = 18405 TX_COUNT_HEIGHT = 30237 TX_PER_BLOCK = 1 RPC_PORT = 9337 REORG_LIMIT = 1000 PEERS = [] @classmethod def header_hash(cls, header): ''' Given a header return the hash for AXE. Need to download `axe_hash` module Source code: https://github.com/AXErunners/axe_hash ''' import x11_hash return x11_hash.getPoWHash(header) class Xuez(Coin): NAME = "Xuez" SHORTNAME = "XUEZ" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("022d2533") XPRV_VERBYTES = bytes.fromhex("0221312b") P2PKH_VERBYTE = bytes.fromhex("48") P2SH_VERBYTES = [bytes.fromhex("12")] WIF_BYTE = bytes.fromhex("d4") GENESIS_HASH = ('000000e1febc39965b055e8e0117179a' '4d18e24e7aaa0c69864c4054b4f29445') TX_COUNT = 30000 TX_COUNT_HEIGHT = 15000 TX_PER_BLOCK = 1 RPC_PORT = 41799 REORG_LIMIT = 1000 BASIC_HEADER_SIZE = 112 PEERS = [] @classmethod def header_hash(cls, header): ''' Given a header return the hash for Xuez. Need to download `xevan_hash` module Source code: https://github.com/xuez/xuez ''' version, = util.unpack_le_uint32_from(header) import xevan_hash if version == 1: return xevan_hash.getPoWHash(header[:80]) else: return xevan_hash.getPoWHash(header) # Source: https://github.com/odinblockchain/odin class Odin(Coin): NAME = "ODIN" SHORTNAME = "ODIN" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("27561872") XPRV_VERBYTES = bytes.fromhex("27256746") P2PKH_VERBYTE = bytes.fromhex("73") P2SH_VERBYTES = [bytes.fromhex("39")] WIF_BYTE = bytes.fromhex("8a") GENESIS_HASH = ('31ca29566549e444cf227a0e2e067aed' '847c2acc541d3bbf9ca1ae89f4fd57d7') TX_COUNT = 340000 TX_COUNT_HEIGHT = 340000 TX_PER_BLOCK = 2 RPC_PORT = 22101 REORG_LIMIT = 100 BASIC_HEADER_SIZE = 80 HDR_V4_SIZE = 112 HDR_V4_HEIGHT = 143447 HDR_V4_START_OFFSET = HDR_V4_HEIGHT * BASIC_HEADER_SIZE SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon DESERIALIZER = lib_tx.DeserializerSegWit @classmethod def static_header_offset(cls, height): assert cls.STATIC_BLOCK_HEADERS if height >= cls.HDR_V4_HEIGHT: relative_v4_offset = (height - cls.HDR_V4_HEIGHT) * cls.HDR_V4_SIZE return cls.HDR_V4_START_OFFSET + relative_v4_offset else: return height * cls.BASIC_HEADER_SIZE @classmethod def header_hash(cls, header): version, = util.unpack_le_uint32_from(header) if version >= 4: return super().header_hash(header) else: import quark_hash return quark_hash.getPoWHash(header) class Pac(Coin): NAME = "PAC" SHORTNAME = "PAC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('00000354655ff039a51273fe61d3b493' 'bd2897fe6c16f732dbc4ae19f04b789e') P2PKH_VERBYTE = bytes.fromhex("37") P2SH_VERBYTES = [bytes.fromhex("0A")] WIF_BYTE = bytes.fromhex("CC") TX_COUNT_HEIGHT = 14939 TX_COUNT = 23708 TX_PER_BLOCK = 2 RPC_PORT = 7111 PEERS = [ 'electrum.paccoin.io s t', 'electro-pac.paccoin.io s t' ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon ESTIMATE_FEE = 0.00001 RELAY_FEE = 0.00001 @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x11_hash return x11_hash.getPoWHash(header) class PacTestnet(Pac): SHORTNAME = "tPAC" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587CF") XPRV_VERBYTES = bytes.fromhex("04358394") GENESIS_HASH = ('00000da63bd9478b655ef6bf1bf76cd9' 'af05202ab68643f9091e049b2b5280ed') P2PKH_VERBYTE = bytes.fromhex("78") P2SH_VERBYTES = [bytes.fromhex("0E")] WIF_BYTE = bytes.fromhex("EF") TX_COUNT_HEIGHT = 16275 TX_COUNT = 16275 TX_PER_BLOCK = 1 RPC_PORT = 17111 class Zcoin(Coin): NAME = "Zcoin" SHORTNAME = "XZC" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("52") P2SH_VERBYTES = [bytes.fromhex("07")] WIF_BYTE = bytes.fromhex("d2") GENESIS_HASH = ('4381deb85b1b2c9843c222944b616d99' '7516dcbd6a964e1eaf0def0830695233') TX_COUNT = 667154 TX_COUNT_HEIGHT = 100266 TX_PER_BLOCK = 4000 # 2000 for 1MB block IRC_PREFIX = None RPC_PORT = 8888 REORG_LIMIT = 5000 PEER_DEFAULT_PORTS = {'t': '50001', 's': '50002'} MTP_HEADER_EXTRA_SIZE = 100 MTP_HEADER_DATA_SIZE = 198864 MTP_HEADER_DATA_START = Coin.BASIC_HEADER_SIZE + MTP_HEADER_EXTRA_SIZE MTP_HEADER_DATA_END = MTP_HEADER_DATA_START + MTP_HEADER_DATA_SIZE STATIC_BLOCK_HEADERS = False SESSIONCLS = DashElectrumX DAEMON = daemon.ZcoinMtpDaemon DESERIALIZER = lib_tx.DeserializerZcoin PEERS = [ 'electrum.polispay.com' ] @classmethod def is_mtp(cls, header): from electrumx.lib.util import unpack_le_uint32_from, hex_to_bytes if isinstance(header, str): nVersion, = unpack_le_uint32_from(hex_to_bytes(header[0:4*2])) elif isinstance(header, bytes): nVersion, = unpack_le_uint32_from(header[0:4]) else: raise "Cannot handle the passed type" return nVersion & 0x1000 @classmethod def block_header(cls, block, height): sz = cls.BASIC_HEADER_SIZE if cls.is_mtp(block): sz += cls.MTP_HEADER_EXTRA_SIZE return block[:sz] @classmethod def header_hash(cls, header): sz = cls.BASIC_HEADER_SIZE if cls.is_mtp(header): sz += cls.MTP_HEADER_EXTRA_SIZE return double_sha256(header[:sz]) class ZcoinTestnet(Zcoin): SHORTNAME = "tXZC" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("41") P2SH_VERBYTES = [bytes.fromhex("b2")] WIF_BYTE = bytes.fromhex("b9") GENESIS_HASH = '1e3487fdb1a7d46dac3e8f3e58339c6e' \ 'ff54abf6aef353485f3ed64250a35e89' REORG_LIMIT = 8000 RPC_PORT = 18888 class GINCoin(Coin): NAME = "GINCoin" SHORTNAME = "GIN" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('00000cd6bde619b2c3b23ad2e384328a' '450a37fa28731debf748c3b17f91f97d') P2PKH_VERBYTE = bytes.fromhex("37") P2SH_VERBYTES = [bytes.fromhex("38")] WIF_BYTE = bytes.fromhex("3c") TX_COUNT_HEIGHT = 225000 TX_COUNT = 470784 TX_PER_BLOCK = 4 RPC_PORT = 10211 PEERS = [ 'electrum.polispay.com' ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon # Seems that the main lyra2z_hash python package doesn't works. # Tested and working with: https://github.com/LapoLab/lyra2z-py @classmethod def header_hash(cls, header): timestamp = util.unpack_le_uint32_from(header, 68)[0] if timestamp > 1550246400: import x16rt_hash return x16rt_hash.getPoWHash(header) elif timestamp > 1525651200: import lyra2z_hash return lyra2z_hash.getPoWHash(header) import neoscrypt return neoscrypt.getPoWHash(header) class Polis(Coin): NAME = "Polis" SHORTNAME = "POLIS" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("03E25D7E") XPRV_VERBYTES = bytes.fromhex("03E25945") GENESIS_HASH = ('000009701eb781a8113b1af1d814e2f0' '60f6408a2c990db291bc5108a1345c1e') P2PKH_VERBYTE = bytes.fromhex("37") P2SH_VERBYTES = [bytes.fromhex("38")] WIF_BYTE = bytes.fromhex("3c") TX_COUNT_HEIGHT = 280600 TX_COUNT = 635415 TX_PER_BLOCK = 4 RPC_PORT = 24127 PEERS = [ 'electrum.polispay.com' ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x11_hash return x11_hash.getPoWHash(header) class MNPCoin(Coin): NAME = "MNPCoin" SHORTNAME = "MNP" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('00000924036c67d803ce606ded814312' '7e62fa2111dd3b063880a1067c69ccb1') P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("35")] WIF_BYTE = bytes.fromhex("37") TX_COUNT_HEIGHT = 248000 TX_COUNT = 506447 TX_PER_BLOCK = 4 RPC_PORT = 13373 PEERS = [ 'electrum.polispay.com' ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import quark_hash return quark_hash.getPoWHash(header) class ColossusXT(Coin): NAME = "ColossusXT" SHORTNAME = "COLX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('a0ce8206c908357008c1b9a8ba2813af' 'f0989ca7f72d62b14e652c55f02b4f5c') P2PKH_VERBYTE = bytes.fromhex("1E") P2SH_VERBYTES = [bytes.fromhex("0D")] WIF_BYTE = bytes.fromhex("D4") TX_COUNT_HEIGHT = 356500 BASIC_HEADER_SIZE = 80 HDR_V5_HEIGHT = 500000 HDR_V5_SIZE = 112 HDR_V5_START_OFFSET = HDR_V5_HEIGHT * BASIC_HEADER_SIZE TX_COUNT = 761041 TX_PER_BLOCK = 4 RPC_PORT = 51473 PEERS = [ 'electrum.polispay.com' ] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def static_header_offset(cls, height): assert cls.STATIC_BLOCK_HEADERS if height >= cls.HDR_V5_HEIGHT: relative_v4_offset = (height - cls.HDR_V5_HEIGHT) * cls.HDR_V5_SIZE return cls.HDR_V5_START_OFFSET + relative_v4_offset else: return height * cls.BASIC_HEADER_SIZE @classmethod def header_hash(cls, header): version, = util.unpack_le_uint32_from(header) if version >= 5: return super().header_hash(header) else: import quark_hash return quark_hash.getPoWHash(header) class Minexcoin(EquihashMixin, Coin): NAME = "Minexcoin" SHORTNAME = "MNX" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("4b") GENESIS_HASH = ('490a36d9451a55ed197e34aca7414b35' 'd775baa4a8e896f1c577f65ce2d214cb') STATIC_BLOCK_HEADERS = True BASIC_HEADER_SIZE = 209 HEADER_SIZE_NO_SOLUTION = 140 TX_COUNT = 327963 TX_COUNT_HEIGHT = 74495 TX_PER_BLOCK = 5 RPC_PORT = 8022 CHUNK_SIZE = 960 PEERS = [ 'electrumx.xpresit.net s t', 'elex01-ams.turinex.eu s t', 'eu.minexpool.nl s t' ] @classmethod def block_header(cls, block, height): '''Return the block header bytes''' deserializer = cls.DESERIALIZER(block) return deserializer.read_header(cls.HEADER_SIZE_NO_SOLUTION) class Groestlcoin(Coin): NAME = "Groestlcoin" SHORTNAME = "GRS" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("24") GENESIS_HASH = ('00000ac5927c594d49cc0bdb81759d0d' 'a8297eb614683d3acb62f0703b639023') DESERIALIZER = lib_tx.DeserializerGroestlcoin TX_COUNT = 115900 TX_COUNT_HEIGHT = 1601528 TX_PER_BLOCK = 5 RPC_PORT = 1441 BLACKLIST_URL = 'https://groestlcoin.org/blacklist.json' PEERS = [ 'electrum1.groestlcoin.org s t', 'electrum2.groestlcoin.org s t', '6brsrbiinpc32tfc.onion t', 'xkj42efxrcy6vbfw.onion t', ] def grshash(data): import groestlcoin_hash return groestlcoin_hash.getHash(data, len(data)) @classmethod def header_hash(cls, header): '''Given a header return the hash.''' return cls.grshash(header) ENCODE_CHECK = partial(Base58.encode_check, hash_fn=grshash) DECODE_CHECK = partial(Base58.decode_check, hash_fn=grshash) class GroestlcoinTestnet(Groestlcoin): SHORTNAME = "TGRS" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6f") P2SH_VERBYTES = [bytes.fromhex("c4")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('000000ffbb50fc9898cdd36ec163e6ba' '23230164c0052a28876255b7dcf2cd36') RPC_PORT = 17766 PEERS = [ 'electrum-test1.groestlcoin.org s t', 'electrum-test2.groestlcoin.org s t', '7frvhgofuf522b5i.onion t', 'aocojvqcybdoxekv.onion t', ] class Pivx(Coin): NAME = "PIVX" SHORTNAME = "PIVX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("022D2533") XPRV_VERBYTES = bytes.fromhex("0221312B") GENESIS_HASH = ('0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818') P2PKH_VERBYTE = bytes.fromhex("1e") P2SH_VERBYTE = bytes.fromhex("0d") WIF_BYTE = bytes.fromhex("d4") TX_COUNT_HEIGHT = 569399 TX_COUNT = 2157510 TX_PER_BLOCK = 1 STATIC_BLOCK_HEADERS = False RPC_PORT = 51470 ZEROCOIN_HEADER = 112 ZEROCOIN_START_HEIGHT = 863787 ZEROCOIN_BLOCK_VERSION = 4 @classmethod def static_header_len(cls, height): '''Given a header height return its length.''' if (height >= cls.ZEROCOIN_START_HEIGHT): return cls.ZEROCOIN_HEADER else: return cls.BASIC_HEADER_SIZE @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = struct.unpack('<I', header[:4]) if version >= cls.ZEROCOIN_BLOCK_VERSION: return super().header_hash(header) else: import quark_hash return quark_hash.getPoWHash(header) class PivxTestnet(Pivx): NET = "testnet" XPUB_VERBYTES = bytes.fromhex("3a8061a0") XPRV_VERBYTES = bytes.fromhex("3a805837") GENESIS_HASH = ('0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818') P2PKH_VERBYTE = bytes.fromhex("8B") P2SH_VERBYTE = bytes.fromhex("13") WIF_BYTE = bytes.fromhex("EF") TX_PER_BLOCK = 4 RPC_PORT = 51472 ZEROCOIN_START_HEIGHT = 201564 class Bitg(Coin): NAME = "BitcoinGreen" SHORTNAME = "BITG" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("26") P2SH_VERBYTES = [bytes.fromhex("06")] WIF_BYTE = bytes.fromhex("2e") GENESIS_HASH = ( '000008467c3a9c587533dea06ad9380cded3ed32f9742a6c0c1aebc21bf2bc9b') DAEMON = daemon.DashDaemon TX_COUNT = 1000 TX_COUNT_HEIGHT = 10000 TX_PER_BLOCK = 1 RPC_PORT = 9332 REORG_LIMIT = 1000 SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import quark_hash return quark_hash.getPoWHash(header) class tBitg(Bitg): SHORTNAME = "tBITG" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("62") P2SH_VERBYTES = [bytes.fromhex("0c")] WIF_BYTE = bytes.fromhex("6c") GENESIS_HASH = ( '000008467c3a9c587533dea06ad9380cded3ed32f9742a6c0c1aebc21bf2bc9b') RPC_PORT = 19332 class EXOS(Coin): NAME = "EXOS" SHORTNAME = "EXOS" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") GENESIS_HASH = ('00000036090a68c523471da7a4f0f958' 'c1b4403fef74a003be7f71877699cab7') P2PKH_VERBYTE = bytes.fromhex("1C") P2SH_VERBYTE = [bytes.fromhex("57")] WIF_BYTE = bytes.fromhex("9C") RPC_PORT = 4561 TX_COUNT = 1000 TX_COUNT_HEIGHT = 10000 TX_PER_BLOCK = 4 DAEMON = daemon.PreLegacyRPCDaemon DESERIALIZER = lib_tx.DeserializerTxTime @classmethod def header_hash(cls, header): version, = util.unpack_le_uint32_from(header) if version > 2: return double_sha256(header) else: return hex_str_to_hash(EXOS.GENESIS_HASH) class EXOSTestnet(EXOS): SHORTNAME = "tEXOS" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") GENESIS_HASH = ('0000059bb2c2048493efcb0f1a034972' 'b3ce4089d54c93b69aaab212fb369887') P2PKH_VERBYTE = bytes.fromhex("4B") P2SH_VERBYTE = [bytes.fromhex("CE")] WIF_BYTE = bytes.fromhex("CB") RPC_PORT = 14561 @classmethod def header_hash(cls, header): version, = util.unpack_le_uint32_from(header) if version > 2: return double_sha256(header) else: return hex_str_to_hash(EXOSTestnet.GENESIS_HASH) class SmartCash(Coin): NAME = "SmartCash" SHORTNAME = "SMART" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("3f") P2SH_VERBYTES = [bytes.fromhex("12")] WIF_BYTE = bytes.fromhex("bf") GENESIS_HASH = ('000007acc6970b812948d14ea5a0a13d' 'b0fdd07d5047c7e69101fa8b361e05a4') DESERIALIZER = lib_tx.DeserializerSmartCash RPC_PORT = 9679 REORG_LIMIT = 5000 TX_COUNT = 1115016 TX_COUNT_HEIGHT = 541656 TX_PER_BLOCK = 1 ENCODE_CHECK = partial(Base58.encode_check, hash_fn=lib_tx.DeserializerSmartCash.keccak) DECODE_CHECK = partial(Base58.decode_check, hash_fn=lib_tx.DeserializerSmartCash.keccak) HEADER_HASH = lib_tx.DeserializerSmartCash.keccak DAEMON = daemon.SmartCashDaemon SESSIONCLS = SmartCashElectrumX @classmethod def header_hash(cls, header): '''Given a header return the hash.''' return cls.HEADER_HASH(header) class NIX(Coin): NAME = "NIX" SHORTNAME = "NIX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("26") P2SH_VERBYTES = [bytes.fromhex("35")] GENESIS_HASH = ('dd28ad86def767c3cfc34267a950d871' 'fc7462bc57ea4a929fc3596d9b598e41') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 114240 TX_COUNT_HEIGHT = 87846 TX_PER_BLOCK = 3 RPC_PORT = 6215 REORG_LIMIT = 1000 class NIXTestnet(NIX): SHORTNAME = "tNIX" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") GENESIS_HASH = ('dd28ad86def767c3cfc34267a950d871' 'fc7462bc57ea4a929fc3596d9b598e41') P2PKH_VERBYTE = bytes.fromhex("01") P2SH_VERBYTE = [bytes.fromhex("03")] RPC_PORT = 16215 DESERIALIZER = lib_tx.DeserializerSegWit class Noir(Coin): NAME = "Noir" SHORTNAME = "NOR" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2SH_VERBYTES = [bytes.fromhex("07")] WIF_BYTE = bytes.fromhex("D0") GENESIS_HASH = ('23911212a525e3d149fcad6c559c8b17' 'f1e8326a272a75ff9bb315c8d96433ef') RPC_PORT = 8825 TX_COUNT = 586369 TX_COUNT_HEIGHT = 379290 TX_PER_BLOCK = 5 class BitcoinPlus(Coin): NAME = "BitcoinPlus" SHORTNAME = "XBC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("99") GENESIS_HASH = ('0000005f6a28e686f641c616e56182d1' 'b43afbe08a223f23bda23cdf9d55b882') DESERIALIZER = lib_tx.DeserializerTxTime DAEMON = daemon.LegacyRPCDaemon TX_COUNT = 1479247 TX_COUNT_HEIGHT = 749740 TX_PER_BLOCK = 2 RPC_PORT = 8885 REORG_LIMIT = 2000 @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x13_hash return x13_hash.getPoWHash(header) class Myriadcoin(AuxPowMixin, Coin): NAME = "Myriadcoin" SHORTNAME = "XMY" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("09")] WIF_BYTE = bytes.fromhex("b2") GENESIS_HASH = ('00000ffde4c020b5938441a0ea3d314b' 'f619eff0b38f32f78f7583cffa1ea485') DESERIALIZER = lib_tx.DeserializerAuxPowSegWit TX_COUNT = 1976629 TX_COUNT_HEIGHT = 2580356 TX_PER_BLOCK = 20 REORG_LIMIT = 2000 RPC_PORT = 10889 class MyriadcoinTestnet(Myriadcoin): NAME = "Myriadcoin" SHORTNAME = "XMT" NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587cf") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("58") P2SH_VERBYTES = [bytes.fromhex("bc")] WIF_BYTE = bytes.fromhex("ef") GENESIS_HASH = ('0000017ce2a79c8bddafbbe47c004aa9' '2b20678c354b34085f62b762084b9788') class Sparks(Coin): NAME = "Sparks" SHORTNAME = "SPK" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") GENESIS_HASH = ('00000a5c6ddfaac5097218560d5b92d4' '16931cfeba1abf10c81d1d6a232fc8ea') P2PKH_VERBYTE = bytes.fromhex("26") P2SH_VERBYTES = [bytes.fromhex("0A")] WIF_BYTE = bytes.fromhex("C6") TX_COUNT_HEIGHT = 117400 TX_COUNT = 162310 TX_PER_BLOCK = 4 RPC_PORT = 8818 SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): import neoscrypt return neoscrypt.getPoWHash(header) # Source: https://github.com/LIMXTEC/BitSend class Bitsend(Coin): NAME = "Bitsend" SHORTNAME = "BSD" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("66") WIF_BYTE = bytes.fromhex("cc") GENESIS_HASH = ('0000012e1b8843ac9ce8c18603658eaf' '8895f99d3f5e7e1b7b1686f35e3c087a') TX_COUNT = 974672 TX_COUNT_HEIGHT = 586022 TX_PER_BLOCK = 2 RPC_PORT = 8800 REORG_LIMIT = 1000 DESERIALIZER = lib_tx.DeserializerSegWit XEVAN_TIMESTAMP = 1477958400 PEERS = [ 'ele1.bitsend.cc s t', '51.15.121.233 s t' ] @classmethod def header_hash(cls, header): timestamp, = util.unpack_le_uint32_from(header, 68) if timestamp > cls.XEVAN_TIMESTAMP: import xevan_hash return xevan_hash.getPoWHash(header) else: import x11_hash return x11_hash.getPoWHash(header) @classmethod def genesis_block(cls, block): header = cls.block_header(block, 0) header_hex_hash = hash_to_hex_str(cls.header_hash(header)) if header_hex_hash != cls.GENESIS_HASH: raise CoinError('genesis block has hash {} expected {}' .format(header_hex_hash, cls.GENESIS_HASH)) return header + bytes(1) class Ritocoin(Coin): NAME = "Ritocoin" SHORTNAME = "RITO" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0534E7CA") XPRV_VERBYTES = bytes.fromhex("05347EAC") P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("69")] GENESIS_HASH = ('00000075e344bdf1c0e433f453764b18' '30a7aa19b2a5213e707502a22b779c1b') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 1188090 TX_COUNT_HEIGHT = 296030 TX_PER_BLOCK = 3 RPC_PORT = 8766 REORG_LIMIT = 55 PEERS = [ 'electrum-rito.minermore.com s t' ] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x21s_hash return x21s_hash.getPoWHash(header) class Ravencoin(Coin): NAME = "Ravencoin" SHORTNAME = "RVN" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("3C") P2SH_VERBYTES = [bytes.fromhex("7A")] GENESIS_HASH = ('0000006b444bc2f2ffe627be9d9e7e7a' '0730000870ef6eb6da46c8eae389df90') DESERIALIZER = lib_tx.DeserializerSegWit X16RV2_ACTIVATION_TIME = 1569945600 # algo switch to x16rv2 at this timestamp TX_COUNT = 5626682 TX_COUNT_HEIGHT = 887000 TX_PER_BLOCK = 6 RPC_PORT = 8766 REORG_LIMIT = 55 PEERS = [ ] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' timestamp = util.unpack_le_uint32_from(header, 68)[0] if timestamp >= cls.X16RV2_ACTIVATION_TIME: import x16rv2_hash return x16rv2_hash.getPoWHash(header) else: import x16r_hash return x16r_hash.getPoWHash(header) class RavencoinTestnet(Ravencoin): NET = "testnet" XPUB_VERBYTES = bytes.fromhex("043587CF") XPRV_VERBYTES = bytes.fromhex("04358394") P2PKH_VERBYTE = bytes.fromhex("6F") P2SH_VERBYTES = [bytes.fromhex("C4")] WIF_BYTE = bytes.fromhex("EF") GENESIS_HASH = ('000000ecfc5e6324a079542221d00e10' '362bdc894d56500c414060eea8a3ad5a') X16RV2_ACTIVATION_TIME = 1567533600 TX_COUNT = 496158 TX_COUNT_HEIGHT = 420500 TX_PER_BLOCK = 1 RPC_PORT = 18766 PEER_DEFAULT_PORTS = {'t': '50003', 's': '50004'} REORG_LIMIT = 55 PEERS = [ ] class Bolivarcoin(Coin): NAME = "Bolivarcoin" SHORTNAME = "BOLI" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("55") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("D5") GENESIS_HASH = ('00000e4fc293a1912b9d73cbb8d8f727' '0007a7d84382f1370661e65d5d57b1f6') TX_COUNT = 1082515 TX_COUNT_HEIGHT = 540410 TX_PER_BLOCK = 10 RPC_PORT = 3563 REORG_LIMIT = 800 PEERS = [] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x11_hash return x11_hash.getPoWHash(header) class Onixcoin(Coin): NAME = "Onixcoin" SHORTNAME = "ONX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488B21E") XPRV_VERBYTES = bytes.fromhex("0488ADE4") P2PKH_VERBYTE = bytes.fromhex("4B") GENESIS_HASH = ('000007140b7a6ca0b64965824f5731f6' 'e86daadf19eb299033530b1e61236e43') TX_COUNT = 431808 TX_COUNT_HEIGHT = 321132 TX_PER_BLOCK = 10 RPC_PORT = 41019 REORG_LIMIT = 800 PEERS = [] SESSIONCLS = DashElectrumX DAEMON = daemon.DashDaemon @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import x11_hash return x11_hash.getPoWHash(header) # Magnum coins start class LitecoinCash(Coin): NAME = "LitecoinCash" SHORTNAME = "LCC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1c") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("b0") GENESIS_HASH = ('12a765e31ffd4059bada1e25190f6e98' 'c99d9714d334efa41a195a7e7e04bfe2') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 8908766 TX_COUNT_HEIGHT = 1105256 TX_PER_BLOCK = 10 RPC_PORT = 9332 REORG_LIMIT = 800 VALUE_PER_COIN = 10000000 PEERS = [ 'hetzner01.fischl-online.de s50010', 'electrum.mgnm.rocks s3020', ] class BitcoinAir(Coin): NAME = "BitcoinAir" SHORTNAME = "XBA" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("4b") P2SH_VERBYTES = [bytes.fromhex("75")] WIF_BYTE = bytes.fromhex("cb") GENESIS_HASH = ('000003e8d6924aba5397cfa6d8ababe4' 'f89384b4334cca6f823565c3ccf7799b') DESERIALIZER = lib_tx.DeserializerTxTime DAEMON = daemon.FakeEstimateFeeDaemon ESTIMATE_FEE = 0.01 RELAY_FEE = 0.01 TX_COUNT = 1207356 TX_COUNT_HEIGHT = 306425 TX_PER_BLOCK = 4 RPC_PORT = 9902 REORG_LIMIT = 5000 PEERS = [ 'electrum.mgnm.rocks s3012', ] VALUE_PER_COIN = 1000000 class Myriadcoin(Coin): NAME = "Myriadcoin" SHORTNAME = "XMY" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTES = [bytes.fromhex("09")] WIF_BYTE = bytes.fromhex("b2") GENESIS_HASH = ('00000ffde4c020b5938441a0ea3d314bf619eff0b38f32f78f7583cffa1ea485') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 318337769 TX_COUNT_HEIGHT = 1697605 TX_PER_BLOCK = 4000 RPC_PORT = 9332 REORG_LIMIT = 800 PEERS = [ 'electrum.mgnm.rocks s3021', ] class Microbitcoin(Coin): NAME = "Microbitcoin" SHORTNAME = "MBC" NET = "mainnet" VALUE_PER_COIN = 10000 P2PKH_VERBYTE = bytes.fromhex("1a") P2SH_VERBYTES = [bytes.fromhex("33")] XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('14c03ecf20edc9887fb98bf34b53809f063fc491e73f588961f764fac88ecbae') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 318337769 TX_COUNT_HEIGHT = 1697605 TX_PER_BLOCK = 4000 RPC_PORT = 6501 REORG_LIMIT = 800 PEERS = [ 'electrum.mgnm.rocks s5023', '52.78.182.106 t7403', '13.57.248.201 t7403', ] @classmethod def electrum_header(cls, header, height): version, = struct.unpack('<I', header[:4]) timestamp, bits, nonce = struct.unpack('<III', header[68:80]) block_hash = bytes(reversed(cls.header_hash(header, height))).hex() return { 'block_height': height, 'version': version, 'block_hash': block_hash, 'prev_block_hash': hash_to_str(header[4:36]), 'merkle_root': hash_to_str(header[36:68]), 'timestamp': timestamp, 'bits': bits, 'nonce': nonce, } @classmethod def header_hash(cls, header, height=0): return blake2b_hash(header) class Anon(EquihashMixin, Coin): NAME = "ANON" SHORTNAME = "ANON" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("0582") P2SH_VERBYTES = [bytes.fromhex("5389")] GENESIS_HASH = ('053a237d7ad7106e341a403286604df55bfe6f301fc9fff03a06f81c8c565b34') DESERIALIZER = lib_tx.DeserializerZcash TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 800 PEERS = [ 'electrum.mgnm.rocks s3001', ] class Cream(Coin): NAME = "Cream" SHORTNAME = "CRM" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1c") P2SH_VERBYTES = [bytes.fromhex("06")] WIF_BYTE = bytes.fromhex("a6") GENESIS_HASH = ('00000091271e3e42d5d07587169a0a60a5028ec1ec401eb0827f7764dcd121c5') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 800 PEERS = [] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' from skein import skein512 h = skein512() h.update(header) return sha256(h.digest()).digest() class Slice(Coin): NAME = "Slice" SHORTNAME = "SLC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("7d") P2SH_VERBYTES = [bytes.fromhex("3f")] WIF_BYTE = bytes.fromhex("73") GENESIS_HASH = ('c4de0ff17658843e77a93586199aa2c7bb21f13728526f241cf873da6c2bb1af') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 800 PEERS = [] class Zerozed(Coin): NAME = "Zerozed" SHORTNAME = "x0z" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1c") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("9c") GENESIS_HASH = ('b345b68b4c08441d6b7f9f58f9fa83b0bce5b670afa7274e3f5725ea1be8fb03') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 800 PEERS = [] class Navcoin(Coin): NAME = "Navcoin" SHORTNAME = "NAV" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("35") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("96") GENESIS_HASH = ('00006a4e3e18c71c6d48ad6c261e2254fa764cf29607a4357c99b712dfbb8e6a') DESERIALIZER = lib_tx.DeserializerTxTime TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 8000 PEERS = [] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = util.unpack_le_uint32_from(header) import x13_hash if version > 6: return double_sha256(header) else: return x13_hash.getPoWHash(header) class Syscoin(AuxPowMixin, Coin): NAME = "Syscoin" SHORTNAME = "SYS" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("3f") P2SH_VERBYTES = bytes.fromhex("05") WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('1b4ab9f52fb1cfe8a20008b444ff3b11' 'bcf277c985f530941e7bcca92ca14473') TX_COUNT = 3350 TX_COUNT_HEIGHT = 3372 TX_PER_BLOCK = 333 RPC_PORT = 8368 REORG_LIMIT = 2000 DEFAULT_MAX_SEND = 25000000 PEER_DEFAULT_PORTS = {'t': '58881', 's': '58882'} PEERS = [] DAEMON = daemon.SyscoinDaemon SESSIONCLS = SyscoinElectrumX DESERIALIZER = lib_tx.DeserializerAuxPowSegWit class LightningBitcoin(BitcoinSegwit, Coin): NAME = "LightningBitcoin" SHORTNAME = "LBTC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("00") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('08a54bbf1a76ac6437d3d63159ced807' '2a484ba0c8539db5900c5df5a863ef4d') FORK_HEIGHT = 499999 TX_COUNT = 265026255 TX_COUNT_HEIGHT = 499923 TX_PER_BLOCK = 50 REORG_LIMIT = 1000 RPC_PORT = 9332 PEERS = [ '47.96.185.83 t50998 s50999', ] class Footballcoin(Coin): NAME = "Footballcoin" SHORTNAME = "XFC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("00") P2SH_VERBYTES = [bytes.fromhex("05")] WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('00e935cde5a4066da0ec69948424d502d106a5d74ac47d8ad492e83bc4aac9a8') TX_COUNT = 329196 TX_COUNT_HEIGHT = 68379 TX_PER_BLOCK = 4000 RPC_PORT = 8023 REORG_LIMIT = 800 PEERS = [] class Netbox(Coin): NAME = "Netbox" SHORTNAME = "NBX" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("35") P2SH_VERBYTES = [bytes.fromhex("26")] WIF_BYTE = bytes.fromhex("5c") GENESIS_HASH = ('000000077c8f4eabb532fdacc3eb56825d3bcf1401e4958b9a2317cc7d8b0496') TX_COUNT_HEIGHT = 569399 TX_COUNT = 2157510 TX_PER_BLOCK = 1 STATIC_BLOCK_HEADERS = False RPC_PORT = 51470 ZEROCOIN_HEADER = 112 ZEROCOIN_START_HEIGHT = 863787 ZEROCOIN_BLOCK_VERSION = 4 @classmethod def static_header_len(cls, height): '''Given a header height return its length.''' if (height >= cls.ZEROCOIN_START_HEIGHT): return cls.ZEROCOIN_HEADER else: return cls.BASIC_HEADER_SIZE @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = struct.unpack('<I', header[:4]) if version >= cls.ZEROCOIN_BLOCK_VERSION: return super().header_hash(header) else: import quark_hash return quark_hash.getPoWHash(header) @classmethod def electrum_header(cls, header, height): version, = struct.unpack('<I', header[:4]) timestamp, bits, nonce = struct.unpack('<III', header[68:80]) if (version >= cls.ZEROCOIN_BLOCK_VERSION): return { 'block_height': height, 'version': version, 'prev_block_hash': hash_to_str(header[4:36]), 'merkle_root': hash_to_str(header[36:68]), 'timestamp': timestamp, 'bits': bits, 'nonce': nonce, 'acc_checkpoint': hash_to_str(header[80:112]) } else: return { 'block_height': height, 'version': version, 'prev_block_hash': hash_to_str(header[4:36]), 'merkle_root': hash_to_str(header[36:68]), 'timestamp': timestamp, 'bits': bits, 'nonce': nonce, } class Netboxcopy(Coin): NAME = "Netboxcopy" SHORTNAME = "NBXC" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("35") P2SH_VERBYTES = [bytes.fromhex("26")] WIF_BYTE = bytes.fromhex("5c") GENESIS_HASH = ('000000077c8f4eabb532fdacc3eb56825d3bcf1401e4958b9a2317cc7d8b0496') TX_COUNT = 265026255 TX_COUNT_HEIGHT = 499923 REORG_LIMIT = 1000 TX_PER_BLOCK = 4000 RPC_PORT = 8023 PEERS = [] class Lynx(Coin): NAME = "Lynx" SHORTNAME = "LYNX" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("2d") P2SH_VERBYTES = [bytes.fromhex("16")] WIF_BYTE = bytes.fromhex("ad") GENESIS_HASH = ('984b30fc9bb5e5ff424ad7f4ec193053' '8a7b14a2d93e58ad7976c23154ea4a76') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 1 TX_COUNT_HEIGHT = 1 TX_PER_BLOCK = 1 RPC_PORT = 9139 REORG_LIMIT = 5000 class EcoDollar(Coin): NAME = "EcoDollar" SHORTNAME = "ECOS" VALUE_PER_COIN = 100000000 NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("022D2533") XPRV_VERBYTES = bytes.fromhex("0221312B") GENESIS_HASH = ('000006f09e91f502ed156ff4ae30106d56e5e435dc5abca4315655b0798a09b8') P2PKH_VERBYTE = bytes.fromhex("21") P2SH_VERBYTE = bytes.fromhex("0f") WIF_BYTE = bytes.fromhex("c9") TX_COUNT_HEIGHT = 569399 TX_COUNT = 2157510 TX_PER_BLOCK = 1 STATIC_BLOCK_HEADERS = False RPC_PORT = 39024 ZEROCOIN_HEADER = 112 ZEROCOIN_START_HEIGHT = 401 ZEROCOIN_BLOCK_VERSION = 4 @classmethod def static_header_len(cls, height): '''Given a header height return its length.''' if (height >= cls.ZEROCOIN_START_HEIGHT): return cls.ZEROCOIN_HEADER else: return cls.BASIC_HEADER_SIZE @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = struct.unpack('<I', header[:4]) if version >= cls.ZEROCOIN_BLOCK_VERSION: return super().header_hash(header) else: import quark_hash return quark_hash.getPoWHash(header) # Magnum coins finish class Electra(Coin): NAME = "Electra" SHORTNAME = "ECA" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("21") P2SH_VERBYTES = [bytes.fromhex("28")] WIF_BYTE = bytes.fromhex("A1") GENESIS_HASH = ('00000f98da995de0ef1665c7d3338687' '923c1199230a44ecbdb5cec9306e4f4e') RPC_PORT = 5788 TX_COUNT = 615729 TX_COUNT_HEIGHT = 205243 TX_PER_BLOCK = 3 REORG_LIMIT = 100 DESERIALIZER = lib_tx.DeserializerElectra @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = util.unpack_le_uint32_from(header) import nist5_hash if version != 8: return nist5_hash.getPoWHash(header) else: return double_sha256(header) class ECCoin(Coin): NAME = "ECCoin" SHORTNAME = "ECC" NET = "mainnet" DESERIALIZER = lib_tx.DeserializerECCoin XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("21") P2SH_VERBYTES = [bytes.fromhex("08")] GENESIS_HASH = ('a60ac43c88dbc44b826cf315352a8a7b373d2af8b6e1c4c4a0638859c5e9ecd1') TX_COUNT = 4661197 TX_COUNT_HEIGHT = 2114846 TX_PER_BLOCK = 10 VALUE_PER_COIN = 1000000 RPC_PORT = 19119 @classmethod def header_hash(cls, header): # you have to install scryp python module (pip install scrypt) import scrypt return scrypt.hash(header, header, 1024, 1, 1, 32) class Bellcoin(Coin): NAME = "Bellcoin" SHORTNAME = "BELL" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("19") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("80") GENESIS_HASH = ('000008f3b6bd10c2d03b06674a006b8d' '9731f6cb58179ef1eee008cee2209603') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 264129 TX_COUNT_HEIGHT = 219574 TX_PER_BLOCK = 5 RPC_PORT = 25252 REORG_LIMIT = 1000 PEERS = [ 'bell.electrumx.japanesecoin-pool.work s t', 'bell.streetcrypto7.com s t', ] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import bell_yespower return bell_yespower.getPoWHash(header) class CPUchain(Coin): NAME = "CPUchain" SHORTNAME = "CPU" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("1C") P2SH_VERBYTES = [bytes.fromhex("1E")] GENESIS_HASH = ('000024d8766043ea0e1c9ad42e7ea4b5' 'fdb459887bd80b8f9756f3d87e128f12') DESERIALIZER = lib_tx.DeserializerSegWit TX_COUNT = 4471 TX_COUNT_HEIGHT = 3491 TX_PER_BLOCK = 2 RPC_PORT = 19707 REORG_LIMIT = 1000 PEERS = [ 'electrumx.cpuchain.org s t', ] @classmethod def header_hash(cls, header): '''Given a header return the hash.''' import cpupower return cpupower.getPoWHash(header) class Xaya(NameIndexMixin, AuxPowMixin, Coin): NAME = "Xaya" SHORTNAME = "CHI" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("1c") P2SH_VERBYTES = [bytes.fromhex("1e")] WIF_BYTE = bytes.fromhex("82") GENESIS_HASH = ('e5062d76e5f50c42f493826ac9920b63' 'a8def2626fd70a5cec707ec47a4c4651') TX_COUNT = 1147749 TX_COUNT_HEIGHT = 1030000 TX_PER_BLOCK = 2 DESERIALIZER = lib_tx.DeserializerXaya TRUNCATED_HEADER_SIZE = 80 + 5 RPC_PORT = 8396 PEERS = [ 'seeder.xaya.io s50002', 'xaya.domob.eu s50002', ] # Op-codes for name operations OP_NAME_REGISTER = OpCodes.OP_1 OP_NAME_UPDATE = OpCodes.OP_2 # Valid name prefixes. NAME_REGISTER_OPS = [OP_NAME_REGISTER, "name", -1, OpCodes.OP_2DROP, OpCodes.OP_DROP] NAME_UPDATE_OPS = [OP_NAME_UPDATE, "name", -1, OpCodes.OP_2DROP, OpCodes.OP_DROP] NAME_OPERATIONS = [ NAME_REGISTER_OPS, NAME_UPDATE_OPS, ] @classmethod def genesis_block(cls, block): super().genesis_block(block) # In Xaya, the genesis block's coinbase is spendable. Thus unlike # the generic genesis_block() method, we return the full block here. return block class XayaTestnet(Xaya): SHORTNAME = "XCH" NET = "testnet" P2PKH_VERBYTE = bytes.fromhex("58") P2SH_VERBYTES = [bytes.fromhex("5a")] WIF_BYTE = bytes.fromhex("e6") GENESIS_HASH = ('5195fc01d0e23d70d1f929f21ec55f47' 'e1c6ea1e66fae98ee44cbbc994509bba') TX_COUNT = 51557 TX_COUNT_HEIGHT = 49000 TX_PER_BLOCK = 1 RPC_PORT = 18396 PEERS = [] class XayaRegtest(XayaTestnet): NET = "regtest" GENESIS_HASH = ('6f750b36d22f1dc3d0a6e483af453010' '22646dfc3b3ba2187865f5a7d6d83ab1') RPC_PORT = 18493 # Source: https://github.com/GZR0/GRZ0 class GravityZeroCoin(ScryptMixin, Coin): NAME = "GravityZeroCoin" SHORTNAME = "GZRO" NET = "mainnet" P2PKH_VERBYTE = bytes.fromhex("26") WIF_BYTE = bytes.fromhex("26") GENESIS_HASH = ('0000028bfbf9ccaed8f28b3ca6b3ffe6b65e29490ab0e4430679bf41cc7c164f') DAEMON = daemon.FakeEstimateLegacyRPCDaemon TX_COUNT = 100 TX_COUNT_HEIGHT = 747635 TX_PER_BLOCK = 2 RPC_PORT = 36442 ESTIMATE_FEE = 0.01 RELAY_FEE = 0.01 class Simplicity(Coin): NAME = "Simplicity" SHORTNAME = "SPL" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0444d5bc") XPRV_VERBYTES = bytes.fromhex("0444f0a3") P2PKH_VERBYTE = bytes.fromhex("12") P2SH_VERBYTE = bytes.fromhex("3b") WIF_BYTE = bytes.fromhex("5d") GENESIS_HASH = ('f4bbfc518aa3622dbeb8d2818a606b82c2b8b1ac2f28553ebdb6fc04d7abaccf') RPC_PORT = 11958 TX_COUNT = 1726548 TX_COUNT_HEIGHT = 1040000 TX_PER_BLOCK = 5 REORG_LIMIT = 100 DESERIALIZER = lib_tx.DeserializerSimplicity @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = util.unpack_le_uint32_from(header) if version < 2: import quark_hash return quark_hash.getPoWHash(header) else: return double_sha256(header) class Myce(Coin): NAME = "Myce" SHORTNAME = "YCE" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("32") P2SH_VERBYTE = bytes.fromhex("55") WIF_BYTE = bytes.fromhex("99") GENESIS_HASH = ('0000c74cc66c72cb1a327c5c1d4893ae5276aa50be49fb23cec21df1a2f20d87') RPC_PORT = 23512 TX_COUNT = 1568977 TX_COUNT_HEIGHT = 774450 TX_PER_BLOCK = 3 REORG_LIMIT = 100 DESERIALIZER = lib_tx.DeserializerSimplicity @classmethod def header_hash(cls, header): '''Given a header return the hash.''' version, = util.unpack_le_uint32_from(header) if version < 7: import scrypt return scrypt.hash(header, header, 1024, 1, 1, 32) else: return double_sha256(header) class Navcoin(Coin): NAME = "Navcoin" SHORTNAME = "NAV" NET = "mainnet" XPUB_VERBYTES = bytes.fromhex("0488b21e") XPRV_VERBYTES = bytes.fromhex("0488ade4") P2PKH_VERBYTE = bytes.fromhex("35") P2SH_VERBYTES = [bytes.fromhex("55")] WIF_BYTE = bytes.fromhex("96") GENESIS_HASH = ('00006a4e3e18c71c6d48ad6c261e2254' 'fa764cf29607a4357c99b712dfbb8e6a') DESERIALIZER = lib_tx.DeserializerTxTimeSegWitNavCoin TX_COUNT = 137641 TX_COUNT_HEIGHT = 3649662 TX_PER_BLOCK = 2 RPC_PORT = 44444 REORG_LIMIT = 1000 @classmethod def header_hash(cls, header): if int.from_bytes(header[:4], "little") > 6: return double_sha256(header) else: import x13_hash return x13_hash.getPoWHash(header)
30.778121
95
0.649879
5cf644f33d2775abb892eb1d62e6ba0bcebf2306
5,917
py
Python
examples/dependency_parsing/ddparser/model/encoder.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
examples/dependency_parsing/ddparser/model/encoder.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
examples/dependency_parsing/ddparser/model/encoder.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
# 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 paddle import paddle.nn as nn from utils import mask_fill, index_sample, pad_sequence_paddle from model.dropouts import SharedDropout, IndependentDropout class ErnieEncoder(nn.Layer): def __init__(self, pad_index, pretrained_model): super(ErnieEncoder, self).__init__() self.pad_index = pad_index self.ptm = pretrained_model self.mlp_input_size = self.ptm.config["hidden_size"] def forward(self, words, wp): x, _ = self.ptm(words) x = paddle.reshape( index_sample(x, wp), shape=[wp.shape[0], wp.shape[1], x.shape[2]], ) words = index_sample(words, wp) return words, x class LSTMByWPEncoder(nn.Layer): def __init__(self, n_words, pad_index, lstm_by_wp_embed_size=200, n_embed=300, n_lstm_hidden=300, n_lstm_layers=3, lstm_dropout=0.33): super(LSTMByWPEncoder, self).__init__() self.pad_index = pad_index self.word_embed = nn.Embedding(n_words, lstm_by_wp_embed_size) self.lstm = nn.LSTM(input_size=lstm_by_wp_embed_size, hidden_size=n_lstm_hidden, num_layers=n_lstm_layers, dropout=lstm_dropout, direction="bidirectional") self.lstm_dropout = SharedDropout(p=lstm_dropout) self.mlp_input_size = n_lstm_hidden * 2 def forward(self, words, wp): word_embed = self.word_embed(words) mask = words != self.pad_index seq_lens = paddle.sum(paddle.cast(mask, "int32"), axis=-1) x, _ = self.lstm(word_embed, sequence_length=seq_lens) x = paddle.reshape( index_sample(x, wp), shape=[wp.shape[0], wp.shape[1], x.shape[2]], ) words = paddle.index_sample(words, wp) x = self.lstm_dropout(x) return words, x class LSTMEncoder(nn.Layer): def __init__(self, feat, n_feats, n_words, pad_index=0, feat_pad_index=0, n_char_embed=50, n_feat_embed=60, n_lstm_char_embed=100, n_embed=300, embed_dropout=0.33, n_lstm_hidden=300, n_lstm_layers=3, lstm_dropout=0.33): super(LSTMEncoder, self).__init__() self.pad_index = pad_index if feat == "char": self.feat_embed = CharLSTMEncoder( n_chars=n_feats, n_embed=n_char_embed, n_out=n_lstm_char_embed, pad_index=feat_pad_index, ) feat_embed_size = n_lstm_char_embed else: self.feat_embed = nn.Embedding(num_embeddings=n_feats, embedding_dim=n_feat_embed) feat_embed_size = n_feat_embed self.word_embed = nn.Embedding(num_embeddings=n_words, embedding_dim=n_embed) self.embed_dropout = IndependentDropout(p=embed_dropout) self.lstm = nn.LSTM(input_size=n_embed + feat_embed_size, hidden_size=n_lstm_hidden, num_layers=n_lstm_layers, dropout=lstm_dropout, direction="bidirectional") self.lstm_dropout = SharedDropout(p=lstm_dropout) self.mlp_input_size = n_lstm_hidden * 2 def forward(self, words, feats): word_embed = self.word_embed(words) feat_embed = self.feat_embed(feats) word_embed, feat_embed = self.embed_dropout(word_embed, feat_embed) embed = paddle.concat([word_embed, feat_embed], axis=-1) mask = words != self.pad_index seq_lens = paddle.sum(paddle.cast(mask, 'int32'), axis=-1) x, _ = self.lstm(embed, sequence_length=seq_lens) x = self.lstm_dropout(x) return words, x class CharLSTMEncoder(nn.Layer): def __init__(self, n_chars, n_embed, n_out, pad_index=0): super(CharLSTMEncoder, self).__init__() self.n_chars = n_chars self.n_embed = n_embed self.n_out = n_out self.pad_index = pad_index # the embedding layer self.embed = nn.Embedding(num_embeddings=n_chars, embedding_dim=n_embed) # the lstm layer self.lstm = nn.LSTM(input_size=n_embed, hidden_size=n_out // 2, direction="bidirectional") def forward(self, x): """Forward network""" mask = paddle.any(x != self.pad_index, axis=-1) lens = paddle.sum(paddle.cast(mask, 'int32'), axis=-1) select = paddle.nonzero(mask) masked_x = paddle.gather_nd(x, select) char_mask = masked_x != self.pad_index emb = self.embed(masked_x) word_lens = paddle.sum(paddle.cast(char_mask, 'int32'), axis=-1) _, (h, _) = self.lstm(emb, sequence_length=word_lens) h = paddle.concat(paddle.unstack(h), axis=-1) feat_embed = pad_sequence_paddle(h, lens, pad_index=self.pad_index) return feat_embed
35.431138
80
0.591178
6b7656e03eb6c32f43adc7e2653b0ba1f5e86dd0
1,233
py
Python
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/bx_python-0.7.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/table_add_column.py
poojavade/Genomics_Docker
829b5094bba18bbe03ae97daf925fee40a8476e8
[ "Apache-2.0" ]
1
2019-07-29T02:53:51.000Z
2019-07-29T02:53:51.000Z
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/bx_python-0.7.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/table_add_column.py
poojavade/Genomics_Docker
829b5094bba18bbe03ae97daf925fee40a8476e8
[ "Apache-2.0" ]
1
2021-09-11T14:30:32.000Z
2021-09-11T14:30:32.000Z
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/bx_python-0.7.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/table_add_column.py
poojavade/Genomics_Docker
829b5094bba18bbe03ae97daf925fee40a8476e8
[ "Apache-2.0" ]
2
2016-12-19T02:27:46.000Z
2019-07-29T02:53:54.000Z
#!/usr/bin/python2.7 """ Tool for adding a column to a table. Expressions for the column are similar to those supported by table_filter.py usage: %prog expression colname < table -H, --header: keep header in output -C, --comments: keep comments in output """ import psyco_full import sys import sys import bx.tabular.io from bx.cookbook import doc_optparse def __main__(): # Parse command line arguments options, args = doc_optparse.parse( __doc__ ) try: keep_header = bool( options.header ) keep_comments = bool( options.comments ) expr = args[0] colname = args[1] except: doc_optparse.exception() # Compile expression for SPEED if expr: expr = compile( expr, '<expr arg>', 'eval' ) for element in bx.tabular.io.Reader( sys.stdin ): if type( element ) is bx.tabular.io.Header: if keep_header: print str( element ) + "\t" + colname elif type( element ) is bx.tabular.io.Comment: if keep_comments: print element else: val = eval( expr, dict( row=element ) ) print str( element ) + "\t" + str( val ) if __name__ == "__main__": __main__()
26.234043
75
0.614761
aa3ecdc215b7b10cef1e0f56c2f8be4d75966fb6
647
py
Python
src/733-flood-fill.py
sahilrider/LeetCode-Solutions
9cac844c27b5dbf37a70c2981a09cd92457f7ff1
[ "MIT" ]
2
2020-03-06T11:44:25.000Z
2020-03-13T20:07:48.000Z
src/733-flood-fill.py
sahilrider/LeetCode-Solutions
9cac844c27b5dbf37a70c2981a09cd92457f7ff1
[ "MIT" ]
null
null
null
src/733-flood-fill.py
sahilrider/LeetCode-Solutions
9cac844c27b5dbf37a70c2981a09cd92457f7ff1
[ "MIT" ]
null
null
null
'''https://leetcode.com/problems/flood-fill/''' class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: visited = [] target = image[sr][sc] def dfs(i, j): if i<0 or j<0 or i>=len(image) or j>=len(image[0]) or (i,j) in visited: return # print(visited) visited.append((i,j)) if image[i][j]==target: image[i][j] = newColor dfs(i, j+1) dfs(i, j-1) dfs(i-1, j) dfs(i+1, j) dfs(sr, sc) return image
32.35
100
0.446677
ed1515a410b8b1cfdb343df0320d29690ef7ff1b
9,194
py
Python
moneytronAlternativeData2.py
JorisMeertBambrugge/scraping
dd22f30ba8a19a5bb73b90aa388c5385bfccfc46
[ "MIT" ]
null
null
null
moneytronAlternativeData2.py
JorisMeertBambrugge/scraping
dd22f30ba8a19a5bb73b90aa388c5385bfccfc46
[ "MIT" ]
null
null
null
moneytronAlternativeData2.py
JorisMeertBambrugge/scraping
dd22f30ba8a19a5bb73b90aa388c5385bfccfc46
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np import datetime from math import pi from bokeh.plotting import figure,show from bokeh.models import Column,ColumnDataSource,Row from bokeh.palettes import Category20 from bokeh.transform import cumsum def nearest(date,timeSeries,findSeries): """ This function will return the datetime in items which is the closest to the date pivot. """ nearDate= min(timeSeries, key=lambda x: abs(x - date)) index=list(timeSeries).index(nearDate) return list(findSeries)[index] df=pd.read_csv(r'C:\Users\joris\.spyder-py3\good code\scraping\scraping.csv',parse_dates=[0]) df['time_interval']=[np.nan]+[(df['date'][i]-df['date'][i-1]).days for i in range(1,len(df))] #############CANADA GOOSE###################################################### df['CanadaGoose_newFollowers_Weibo']=[np.nan]+[df['CanadaGoose_followers_Weibo'][i]-df['CanadaGoose_followers_Weibo'][i-1] for i in range(1,len(df))] df['CanadaGoose_newFollowers_Instagram']=[np.nan]+[df['CanadaGoose_followers_Instagram'][i]-df['CanadaGoose_followers_Instagram'][i-1] for i in range(1,len(df))] df['CanadaGoose_newFollowers_Pinterest']=[np.nan]+[df['CanadaGoose_followers_Pinterest'][i]-df['CanadaGoose_followers_Pinterest'][i-1] for i in range(1,len(df))] df['CanadaGoose_newFollowersADay_Weibo']=df['CanadaGoose_newFollowers_Weibo']/df['time_interval'] df['CanadaGoose_newFollowersADay_Instagram']=df['CanadaGoose_newFollowers_Instagram']/df['time_interval'] df['CanadaGoose_newFollowersADay_Pinterest']=df['CanadaGoose_newFollowers_Pinterest']/df['time_interval'] df['CanadaGoose_newFollowersADay_Instagram'][df['CanadaGoose_newFollowersADay_Instagram'].first_valid_index()]=np.nan#replace the first measurement with nan df['CanadaGoose_newFollowersADay_Pinterest'][df['CanadaGoose_newFollowersADay_Pinterest'].first_valid_index()]=np.nan#replace the first measurement with nan gooseDF=pd.DataFrame() gooseDF['date'] = [df['date'][0] + datetime.timedelta(days=x) for x in range(int((list(df['date'])[-1]-df['date'][0]).days))] gooseDF['Weibo']=gooseDF['date'].apply(nearest,timeSeries=df['date'],findSeries=df['CanadaGoose_newFollowersADay_Weibo']) gooseDF['Instagram']=gooseDF['date'].apply(nearest,timeSeries=df['date'],findSeries=df['CanadaGoose_newFollowersADay_Instagram']) gooseDF['Pinterest']=gooseDF['date'].apply(nearest,timeSeries=df['date'],findSeries=df['CanadaGoose_newFollowersADay_Pinterest']) gooseSource=ColumnDataSource(gooseDF) canadaGoosePlot=figure(title='Cananda Goose',width=800,height=400,x_axis_type='datetime') canadaGoosePlot.vbar(x='date',top='Weibo',width=datetime.timedelta(1),color='red',legend_label='New Weibo followers',source=gooseSource,alpha=0.5) canadaGoosePlot.vbar(x='date',top='Instagram',width=datetime.timedelta(1),color='blue',legend_label='New Instagram followers',source=gooseSource,alpha=0.5) canadaGoosePlot.vbar(x='date',top='Pinterest',width=datetime.timedelta(1),color='green',legend_label='New Pinterest followers',source=gooseSource,alpha=0.5) #############SMARTPHOTO##############INSTAGRAM########################## keyListInstagram=[] nameListInstagram=[] pieDictInstagram={} for i in df.columns.values: if i.startswith('SmartPhoto') and 'Instagram' in i: keyListInstagram.append(i) name=i[i.rfind('_')+1:] nameListInstagram.append(name) pieDictInstagram[name]=list(df[i])[-1] if np.isnan(pieDictInstagram[name]):#replace with previous number in case of NaN pieDictInstagram[name]=list(df[i])[-2] #print(i[i.rfind('_')+1:],list(df[i])[-1]) data = pd.Series(pieDictInstagram).reset_index(name='value').rename(columns={'index':'country'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = Category20[len(pieDictInstagram)] pieInstagram = figure(plot_height=350, title="Smartphoto Instagram followers", toolbar_location=None, tools="hover", tooltips="@country: @value", x_range=(-0.5, 1.0)) pieInstagram.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend_field='country', source=data) pieInstagram.axis.axis_label=None pieInstagram.axis.visible=False pieInstagram.grid.grid_line_color = None def newFollowers(df,keyList=['SmartPhoto_followers_Instagram_Belgium'],nameList=['Belgium']): smartDF=pd.DataFrame() smartDF['date'] = [df['date'][0] + datetime.timedelta(days=x) for x in range(int((list(df['date'])[-1]-df['date'][0]).days))] for key,name in zip(keyList,nameList): df[key+'new']=[np.nan]+[df[key][i]-df[key][i-1] for i in range(1,len(df))] df[key+'newDaily']=df[key+'new']/df['time_interval'] df[key+'newDaily'][df[key+'newDaily'].first_valid_index()]=np.nan#replace the first measurement with nan smartDF[name]=smartDF['date'].apply(nearest,timeSeries=df['date'],findSeries=df[key+'newDaily']) smartDF['all']=smartDF.sum(axis=1) return smartDF smartDF=newFollowers(df,keyList=keyListInstagram,nameList=nameListInstagram) smartSource=ColumnDataSource(smartDF) smartphotoPlotInstagram=figure(title='Smartphoto Instagram: new followers',width=800,height=400,x_axis_type='datetime',x_range=(list(smartDF['date'])[smartDF[nameListInstagram[0]].first_valid_index()],list(smartDF['date'])[-1])) smartphotoPlotInstagram.vbar(x='date',top='all',width=datetime.timedelta(1),color='black',legend_label='total',source=smartSource,alpha=0.5) for name,color in zip(nameListInstagram,Category20[len(nameListInstagram)]): smartphotoPlotInstagram.line(x='date',y=name,color=color,legend_label=name,source=smartSource,line_width=2) #plot the total Instagram followers for index, row in df.iterrows(): df['smartphotoTotalInstagramFollowers']=0 for name in nameListInstagram: df['smartphotoTotalInstagramFollowers']=df['smartphotoTotalInstagramFollowers']+df['SmartPhoto_followers_Instagram_'+name] smartphotoTotalInstagramPlot=figure(title='Smartphoto Instagram: total followers',width=800,height=400,x_axis_type='datetime') smartphotoTotalInstagramPlot.line(df['date'],df['smartphotoTotalInstagramFollowers']) smartphotoInstagramRow=Row(pieInstagram,smartphotoPlotInstagram,smartphotoTotalInstagramPlot) #############SMARTPHOTO##############PINTEREST########################## df=pd.read_csv(r'E:\financieel\beleggingen\scraping.csv',parse_dates=[0]) print(df.columns) print(len(df)) df['time_interval']=[np.nan]+[(df['date'][i]-df['date'][i-1]).days for i in range(1,len(df))] keyListPinterest=[] nameListPinterest=[] pieDictPinterest={} for i in df.columns.values: if i.startswith('SmartPhoto') and 'Pinterest' in i: keyListPinterest.append(i) name=i[i.rfind('_')+1:] nameListPinterest.append(name) pieDictPinterest[name]=list(df[i])[-1] #print(i[i.rfind('_')+1:],list(df[i])[-1]) print(pieDictPinterest) data = pd.Series(pieDictPinterest).reset_index(name='value').rename(columns={'index':'country'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = Category20[len(nameListPinterest)] piePinterest=figure(plot_height=350, title="Smartphoto Pinterest followers", toolbar_location=None, tools="hover", tooltips="@country: @value", x_range=(-0.5, 1.0)) piePinterest.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend_field='country', source=data) piePinterest.axis.axis_label=None piePinterest.axis.visible=False piePinterest.grid.grid_line_color = None smartDF=newFollowers(df,keyList=keyListPinterest,nameList=nameListPinterest) smartSource=ColumnDataSource(smartDF) print(list(smartDF['date'])[smartDF[nameListPinterest[0]].first_valid_index()]) print(list(smartDF['date'])[-1]) smartphotoPlotPinterest=figure(title='Smartphoto Pinterest: new followers',width=800,height=400,x_axis_type='datetime',x_range=(list(smartDF['date'])[smartDF[nameListPinterest[0]].first_valid_index()],list(smartDF['date'])[-1])) smartphotoPlotPinterest.vbar(x='date',top='all',width=datetime.timedelta(1),color='black',legend_label='total',source=smartSource,alpha=0.5) for name,color in zip(nameListPinterest,Category20[len(nameListPinterest)]): smartphotoPlotPinterest.line(x='date',y=name,color=color,legend_label=name,source=smartSource,line_width=2) #plot the total Instagram followers for index, row in df.iterrows(): df['smartphotoTotalPinterestFollowers']=0 for name in nameListPinterest: df['smartphotoTotalPinterestFollowers']=df['smartphotoTotalPinterestFollowers']+df['SmartPhoto_followers_Pinterest_'+name] smartphotoTotalPinterestPlot=figure(title='Smartphoto Pinterest: total followers',width=800,height=400,x_axis_type='datetime') smartphotoTotalPinterestPlot.line(df['date'],df['smartphotoTotalPinterestFollowers']) smartphotoPinterestRow=Row(piePinterest,smartphotoPlotPinterest,smartphotoTotalPinterestPlot) ######################SUMMARY################################################# layout=Column(canadaGoosePlot,smartphotoInstagramRow,smartphotoPinterestRow) show(layout)
55.385542
228
0.739722
47e243600a4a4f5821cb4f357ef0081ef0100df5
7,452
py
Python
rcnn_dff/core/metric.py
tonysy/mx-rcnn-flow
b78c3c964c802bb874d673170d7452e7a573a998
[ "Apache-2.0" ]
2
2018-01-31T02:47:42.000Z
2019-07-05T03:48:54.000Z
rcnn_dff/core/metric.py
tonysy/mx-rcnn-flow
b78c3c964c802bb874d673170d7452e7a573a998
[ "Apache-2.0" ]
null
null
null
rcnn_dff/core/metric.py
tonysy/mx-rcnn-flow
b78c3c964c802bb874d673170d7452e7a573a998
[ "Apache-2.0" ]
null
null
null
import mxnet as mx import numpy as np from ..config import config def get_rpn_names(): if config.TRAIN.RPN_OHEM: pred = ['rpn_cls_prob', 'rpn_bbox_loss', 'rpn_cls_mask', 'rpn_bbox_mask'] else: pred = ['rpn_cls_prob', 'rpn_bbox_loss'] label = ['rpn_label', 'rpn_bbox_target', 'rpn_bbox_weight'] return pred, label def get_rcnn_names(): if config.TRAIN.RCNN_OHEM: pred = ['rcnn_cls_prob', 'rcnn_bbox_loss', 'rcnn_cls_mask', 'rcnn_bbox_mask'] else: pred = ['rcnn_cls_prob', 'rcnn_bbox_loss'] label = ['rcnn_label', 'rcnn_bbox_target', 'rcnn_bbox_weight'] if config.TRAIN.END2END: pred.append('rcnn_label') rpn_pred, rpn_label = get_rpn_names() pred = rpn_pred + pred label = rpn_label return pred, label class RPNAccMetric(mx.metric.EvalMetric): def __init__(self): super(RPNAccMetric, self).__init__('RPNAcc') self.rpn_ohem = config.TRAIN.RPN_OHEM self.pred, self.label = get_rpn_names() def update(self, labels, preds): pred = preds[self.pred.index('rpn_cls_prob')] label = labels[self.label.index('rpn_label')] # pred (b, c, p) or (b, c, h, w) pred_label = mx.ndarray.argmax_channel(pred).asnumpy().astype('int32') pred_label = pred_label.reshape((pred_label.shape[0], -1)) # label (b, p) label = label.asnumpy().astype('int32') # filter with keep_inds if self.rpn_ohem: cls_mask = preds[self.pred.index('rpn_cls_mask')].asnumpy()[:, 0, :].reshape(label.shape) keep_inds = np.where(cls_mask > 0) else: keep_inds = np.where(label != -1) pred_label = pred_label[keep_inds] label = label[keep_inds] self.sum_metric += np.sum(pred_label.flat == label.flat) self.num_inst += len(pred_label.flat) class RCNNAccMetric(mx.metric.EvalMetric): def __init__(self): super(RCNNAccMetric, self).__init__('RCNNAcc') self.e2e = config.TRAIN.END2END self.rcnn_ohem = config.TRAIN.RCNN_OHEM self.pred, self.label = get_rcnn_names() def update(self, labels, preds): pred = preds[self.pred.index('rcnn_cls_prob')] if self.e2e: label = preds[self.pred.index('rcnn_label')] else: label = labels[self.label.index('rcnn_label')] last_dim = pred.shape[-1] pred_label = pred.asnumpy().reshape(-1, last_dim).argmax(axis=1).astype('int32') label = label.asnumpy().reshape(-1,).astype('int32') if self.rcnn_ohem: cls_mask = preds[self.pred.index('rcnn_cls_mask')].asnumpy().reshape(-1, last_dim) keep_inds = np.where(cls_mask.sum(axis=1) > 0)[0] pred_label = pred_label[keep_inds] label = label[keep_inds] self.sum_metric += np.sum(pred_label.flat == label.flat) self.num_inst += len(pred_label.flat) class RPNLogLossMetric(mx.metric.EvalMetric): def __init__(self): super(RPNLogLossMetric, self).__init__('RPNLogLoss') self.rpn_ohem = config.TRAIN.RPN_OHEM self.pred, self.label = get_rpn_names() def update(self, labels, preds): pred = preds[self.pred.index('rpn_cls_prob')] label = labels[self.label.index('rpn_label')] # label (b, p) label = label.asnumpy().astype('int32').reshape((-1)) # pred (b, c, p) or (b, c, h, w) --> (b, p, c) --> (b*p, c) pred = pred.asnumpy().reshape((pred.shape[0], pred.shape[1], -1)).transpose((0, 2, 1)) pred = pred.reshape((label.shape[0], -1)) # filter with keep_inds if self.rpn_ohem: # induce the keep_inds from argmax_channel to cls_prob cls_mask = preds[self.pred.index('rpn_cls_mask')].asnumpy() cls_mask = cls_mask[:, 0, :].reshape((-1)) keep_inds = np.where(cls_mask > 0)[0] else: keep_inds = np.where(label != -1)[0] label = label[keep_inds] cls = pred[keep_inds, label] cls += 1e-14 cls_loss = -1 * np.log(cls) cls_loss = np.sum(cls_loss) self.sum_metric += cls_loss self.num_inst += label.shape[0] class RCNNLogLossMetric(mx.metric.EvalMetric): def __init__(self): super(RCNNLogLossMetric, self).__init__('RCNNLogLoss') self.e2e = config.TRAIN.END2END self.rcnn_ohem = config.TRAIN.RCNN_OHEM self.pred, self.label = get_rcnn_names() def update(self, labels, preds): pred = preds[self.pred.index('rcnn_cls_prob')] if self.e2e: label = preds[self.pred.index('rcnn_label')] else: label = labels[self.label.index('rcnn_label')] last_dim = pred.shape[-1] pred = pred.asnumpy().reshape(-1, last_dim) label = label.asnumpy().reshape(-1,).astype('int32') if self.rcnn_ohem: cls_mask = preds[self.pred.index('rcnn_cls_mask')].asnumpy().reshape(-1, last_dim) keep_inds = np.where(cls_mask.sum(axis=1) > 0)[0] pred = pred[keep_inds, :] label = label[keep_inds] cls = pred[np.arange(label.shape[0]), label] cls += 1e-14 cls_loss = -1 * np.log(cls) cls_loss = np.sum(cls_loss) self.sum_metric += cls_loss self.num_inst += label.shape[0] class RPNRegLossMetric(mx.metric.EvalMetric): def __init__(self): name = 'RPNIoULoss' if config.RPN_IOU_LOSS else 'RPNL1Loss' super(RPNRegLossMetric, self).__init__(name) self.rpn_ohem = config.TRAIN.RPN_OHEM self.pred, self.label = get_rpn_names() def update(self, labels, preds): bbox_loss = preds[self.pred.index('rpn_bbox_loss')].asnumpy() bbox_weight = labels[self.label.index('rpn_bbox_weight')].asnumpy() # calculate num_inst (average on those fg anchors) if self.rpn_ohem: bbox_mask = preds[self.pred.index('rpn_bbox_mask')].asnumpy() bbox_loss *= bbox_mask num_inst = np.sum((bbox_mask > 0) & (bbox_weight > 0)) / 4 else: num_inst = np.sum(bbox_weight > 0) / 4 self.sum_metric += np.sum(bbox_loss) self.num_inst += num_inst class RCNNRegLossMetric(mx.metric.EvalMetric): def __init__(self): name = 'RCNNIoULoss' if config.RCNN_IOU_LOSS else 'RCNNL1Loss' super(RCNNRegLossMetric, self).__init__(name) self.e2e = config.TRAIN.END2END self.rcnn_ohem = config.TRAIN.RCNN_OHEM self.pred, self.label = get_rcnn_names() def update(self, labels, preds): bbox_loss = preds[self.pred.index('rcnn_bbox_loss')].asnumpy() if self.e2e: label = preds[self.pred.index('rcnn_label')].asnumpy() else: label = labels[self.label.index('rcnn_label')].asnumpy() last_dim = bbox_loss.shape[-1] bbox_loss = bbox_loss.reshape((-1, last_dim)) label = label.reshape(-1) # calculate num_inst if self.rcnn_ohem: bbox_mask = preds[self.pred.index('rcnn_bbox_mask')].asnumpy().reshape((-1, last_dim)) bbox_loss *= bbox_mask keep_inds = np.where((bbox_mask.sum(axis=1) > 0) & (label != 0))[0] else: keep_inds = np.where(label != 0)[0] num_inst = len(keep_inds) self.sum_metric += np.sum(bbox_loss) self.num_inst += num_inst
36
101
0.607622
c1a7bec307e79b321946279e7a181db02c526d20
23,926
py
Python
tensorflow_probability/python/experimental/mcmc/particle_filter_test.py
awav/probability
c833ee5cd9f60f3257366b25447b9e50210b0590
[ "Apache-2.0" ]
null
null
null
tensorflow_probability/python/experimental/mcmc/particle_filter_test.py
awav/probability
c833ee5cd9f60f3257366b25447b9e50210b0590
[ "Apache-2.0" ]
null
null
null
tensorflow_probability/python/experimental/mcmc/particle_filter_test.py
awav/probability
c833ee5cd9f60f3257366b25447b9e50210b0590
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 The TensorFlow Probability 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. # ============================================================================ """Tests for particle filtering.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.experimental.mcmc.particle_filter import SampleParticles from tensorflow_probability.python.internal import prefer_static from tensorflow_probability.python.internal import tensorshape_util from tensorflow_probability.python.internal import test_util tfb = tfp.bijectors tfd = tfp.distributions def do_not_compile(f): """The identity function decorator.""" return f def xla_compile(f): """Decorator for XLA compilation.""" return tf.function(f, autograph=False, experimental_compile=True) @test_util.test_all_tf_execution_regimes class SampleParticlesTest(test_util.TestCase): def test_sample_particles_works_with_joint_distributions(self): num_particles = 3 jd = tfd.JointDistributionNamed({'x': tfd.Normal(0., 1.)}) sp = SampleParticles(jd, num_particles=num_particles) # Check that SampleParticles has the correct shapes. self.assertAllEqualNested(jd.event_shape, sp.event_shape) self.assertAllEqualNested( *self.evaluate((jd.event_shape_tensor(), sp.event_shape_tensor()))) self.assertAllEqualNested( tf.nest.map_structure( lambda x: np.concatenate([[num_particles], x], axis=0), jd.batch_shape), tf.nest.map_structure(tensorshape_util.as_list, sp.batch_shape)) self.assertAllEqualNested( *self.evaluate( (tf.nest.map_structure( lambda x: tf.concat([[num_particles], x], axis=0), jd.batch_shape_tensor()), sp.batch_shape_tensor()))) # Check that sample and log-prob work, and that we can take the log-prob # of a sample. x = self.evaluate(sp.sample()) lp = self.evaluate(sp.log_prob(x)) self.assertAllEqual( [part.shape for part in tf.nest.flatten(x)], [[num_particles]]) self.assertAllEqual( [part.shape for part in tf.nest.flatten(lp)], [[num_particles]]) def test_sample_particles_works_with_batch_and_event_shape(self): num_particles = 3 d = tfd.MultivariateNormalDiag(loc=tf.zeros([2, 4]), scale_diag=tf.ones([2, 4])) sp = SampleParticles(d, num_particles=num_particles) # Check that SampleParticles has the correct shapes. self.assertAllEqual(sp.event_shape, d.event_shape) self.assertAllEqual(sp.batch_shape, np.concatenate([[num_particles], d.batch_shape], axis=0)) # Draw a sample, combining sample shape, batch shape, num_particles, *and* # event_shape, and check that it has the correct shape, and that we can # compute a log_prob with the correct shape. sample_shape = [5, 1] x = self.evaluate(sp.sample(sample_shape, seed=test_util.test_seed())) self.assertAllEqual(x.shape, # [5, 3, 1, 2, 4] np.concatenate([sample_shape, [num_particles], d.batch_shape, d.event_shape], axis=0)) lp = self.evaluate(sp.log_prob(x)) self.assertAllEqual(lp.shape, np.concatenate([sample_shape, [num_particles], d.batch_shape], axis=0)) @test_util.test_all_tf_execution_regimes class _ParticleFilterTest(test_util.TestCase): def test_random_walk(self): initial_state_prior = tfd.JointDistributionNamed({ 'position': tfd.Deterministic(0.)}) # Biased random walk. def particle_dynamics(_, previous_state): state_shape = tf.shape(previous_state['position']) return tfd.JointDistributionNamed({ 'position': tfd.TransformedDistribution( tfd.Bernoulli(probs=tf.broadcast_to(0.75, state_shape), dtype=self.dtype), tfb.Shift(previous_state['position']))}) # Completely uninformative observations allowing a test # of the pure dynamics. def particle_observations(_, state): state_shape = tf.shape(state['position']) return tfd.Uniform(low=tf.broadcast_to(-100.0, state_shape), high=tf.broadcast_to(100.0, state_shape)) observations = tf.zeros((9,), dtype=self.dtype) trajectories, _ = self.evaluate( tfp.experimental.mcmc.infer_trajectories( observations=observations, initial_state_prior=initial_state_prior, transition_fn=particle_dynamics, observation_fn=particle_observations, num_particles=16384, seed=test_util.test_seed())) position = trajectories['position'] # The trajectories have the following properties: # 1. they lie completely in the range [0, 8] self.assertAllInRange(position, 0., 8.) # 2. each step lies in the range [0, 1] self.assertAllInRange(position[1:] - position[:-1], 0., 1.) # 3. the expectation and variance of the final positions are 6 and 1.5. self.assertAllClose(tf.reduce_mean(position[-1]), 6., atol=0.1) self.assertAllClose(tf.math.reduce_variance(position[-1]), 1.5, atol=0.1) def test_batch_of_filters(self): batch_shape = [3, 2] num_particles = 1000 num_timesteps = 40 # Batch of priors on object 1D positions and velocities. initial_state_prior = tfd.JointDistributionNamed({ 'position': tfd.Normal(loc=0., scale=tf.ones(batch_shape)), 'velocity': tfd.Normal(loc=0., scale=tf.ones(batch_shape) * 0.1)}) def transition_fn(_, previous_state): return tfd.JointDistributionNamed({ 'position': tfd.Normal( loc=previous_state['position'] + previous_state['velocity'], scale=0.1), 'velocity': tfd.Normal(loc=previous_state['velocity'], scale=0.01)}) def observation_fn(_, state): return tfd.Normal(loc=state['position'], scale=0.1) # Batch of synthetic observations, . true_initial_positions = np.random.randn(*batch_shape).astype(self.dtype) true_velocities = 0.1 * np.random.randn( *batch_shape).astype(self.dtype) observed_positions = ( true_velocities * np.arange(num_timesteps).astype( self.dtype)[..., tf.newaxis, tf.newaxis] + true_initial_positions) (particles, log_weights, parent_indices, incremental_log_marginal_likelihoods) = self.evaluate( tfp.experimental.mcmc.particle_filter( observations=observed_positions, initial_state_prior=initial_state_prior, transition_fn=transition_fn, observation_fn=observation_fn, num_particles=num_particles, seed=test_util.test_seed())) self.assertAllEqual(particles['position'].shape, [num_timesteps, num_particles] + batch_shape) self.assertAllEqual(particles['velocity'].shape, [num_timesteps, num_particles] + batch_shape) self.assertAllEqual(parent_indices.shape, [num_timesteps, num_particles] + batch_shape) self.assertAllEqual(incremental_log_marginal_likelihoods.shape, [num_timesteps] + batch_shape) self.assertAllClose( self.evaluate( tf.reduce_sum(tf.exp(log_weights) * particles['position'], axis=1)), observed_positions, atol=0.1) velocity_means = tf.reduce_sum(tf.exp(log_weights) * particles['velocity'], axis=1) self.assertAllClose( self.evaluate(tf.reduce_mean(velocity_means, axis=0)), true_velocities, atol=0.05) # Uncertainty in velocity should decrease over time. velocity_stddev = self.evaluate( tf.math.reduce_std(particles['velocity'], axis=1)) self.assertAllLess((velocity_stddev[-1] - velocity_stddev[0]), 0.) trajectories = self.evaluate( tfp.experimental.mcmc.reconstruct_trajectories(particles, parent_indices)) self.assertAllEqual([num_timesteps, num_particles] + batch_shape, trajectories['position'].shape) self.assertAllEqual([num_timesteps, num_particles] + batch_shape, trajectories['velocity'].shape) # Verify that `infer_trajectories` also works on batches. trajectories, incremental_log_marginal_likelihoods = self.evaluate( tfp.experimental.mcmc.infer_trajectories( observations=observed_positions, initial_state_prior=initial_state_prior, transition_fn=transition_fn, observation_fn=observation_fn, num_particles=num_particles, seed=test_util.test_seed())) self.assertAllEqual([num_timesteps, num_particles] + batch_shape, trajectories['position'].shape) self.assertAllEqual([num_timesteps, num_particles] + batch_shape, trajectories['velocity'].shape) self.assertAllEqual(incremental_log_marginal_likelihoods.shape, [num_timesteps] + batch_shape) def test_reconstruct_trajectories_toy_example(self): particles = tf.convert_to_tensor([[1, 2, 3], [4, 5, 6,], [7, 8, 9]]) # 1 -- 4 -- 7 # 2 \/ 5 .- 8 # 3 /\ 6 /-- 9 parent_indices = tf.convert_to_tensor([[0, 1, 2], [0, 2, 1], [0, 2, 2]]) trajectories = self.evaluate( tfp.experimental.mcmc.reconstruct_trajectories(particles, parent_indices)) self.assertAllEqual( np.array([[1, 2, 2], [4, 6, 6], [7, 8, 9]]), trajectories) def test_epidemiological_model(self): # A toy, discrete version of an SIR (Susceptible, Infected, Recovered) # model (https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology) population_size = 1000 infection_rate = tf.convert_to_tensor(1.1) infectious_period = tf.convert_to_tensor(8.0) initial_state_prior = tfd.JointDistributionNamed({ 'susceptible': tfd.Deterministic(999.), 'infected': tfd.Deterministic(1.), 'new_infections': tfd.Deterministic(1.), 'new_recoveries': tfd.Deterministic(0.)}) # Dynamics model: new infections and recoveries are given by the SIR # model with Poisson noise. def infection_dynamics(_, previous_state): new_infections = tfd.Poisson( infection_rate * previous_state['infected'] * previous_state['susceptible'] / population_size) new_recoveries = tfd.Poisson(previous_state['infected'] / infectious_period) def susceptible(new_infections): return tfd.Deterministic( prefer_static.maximum( 0., previous_state['susceptible'] - new_infections)) def infected(new_infections, new_recoveries): return tfd.Deterministic( prefer_static.maximum( 0., previous_state['infected'] + new_infections - new_recoveries)) return tfd.JointDistributionNamed({ 'new_infections': new_infections, 'new_recoveries': new_recoveries, 'susceptible': susceptible, 'infected': infected}) # Observation model: each day we detect new cases, noisily. def infection_observations(_, state): return tfd.Poisson(state['infected']) # pylint: disable=bad-whitespace observations = tf.convert_to_tensor([ 0., 4., 1., 5., 23., 27., 75., 127., 248., 384., 540., 683., 714., 611., 561., 493., 385., 348., 300., 277., 249., 219., 216., 174., 132., 122., 115., 99., 76., 84., 77., 56., 42., 56., 46., 38., 34., 44., 25., 27.]) # pylint: enable=bad-whitespace trajectories, _ = self.evaluate( tfp.experimental.mcmc.infer_trajectories( observations=observations, initial_state_prior=initial_state_prior, transition_fn=infection_dynamics, observation_fn=infection_observations, num_particles=100, seed=test_util.test_seed())) # The susceptible population should decrease over time. self.assertAllLessEqual( trajectories['susceptible'][1:, ...] - trajectories['susceptible'][:-1, ...], 0.0) def test_data_driven_proposal(self): num_particles = 100 observations = tf.convert_to_tensor([60., -179.2, 1337.42]) # Define a system constrained primarily by observations, where proposing # from the dynamics would be a bad fit. initial_state_prior = tfd.Normal(loc=0., scale=1e6) transition_fn = ( lambda _, previous_state: tfd.Normal(loc=previous_state, scale=1e6)) observation_fn = lambda _, state: tfd.Normal(loc=state, scale=0.1) initial_state_proposal = tfd.Normal(loc=observations[0], scale=0.1) proposal_fn = (lambda step, state: tfd.Normal( # pylint: disable=g-long-lambda loc=tf.ones_like(state) * observations[step + 1], scale=1.0)) trajectories, _ = self.evaluate( tfp.experimental.mcmc.infer_trajectories( observations=observations, initial_state_prior=initial_state_prior, transition_fn=transition_fn, observation_fn=observation_fn, num_particles=num_particles, initial_state_proposal=initial_state_proposal, proposal_fn=proposal_fn, seed=test_util.test_seed())) self.assertAllClose(trajectories, tf.convert_to_tensor( tf.convert_to_tensor( observations)[..., tf.newaxis] * tf.ones([num_particles])), atol=1.0) def test_estimated_prob_approximates_true_prob(self): # Draw simulated data from a 2D linear Gaussian system. initial_state_prior = tfd.MultivariateNormalDiag( loc=0., scale_diag=(1., 1.)) transition_matrix = tf.convert_to_tensor([[1., -0.5], [0.4, -1.]]) transition_noise = tfd.MultivariateNormalTriL( loc=1., scale_tril=tf.convert_to_tensor([[0.3, 0], [-0.1, 0.2]])) observation_matrix = tf.convert_to_tensor([[0.1, 1.], [1., 0.2]]) observation_noise = tfd.MultivariateNormalTriL( loc=-0.3, scale_tril=tf.convert_to_tensor([[0.5, 0], [0.1, 0.5]])) model = tfd.LinearGaussianStateSpaceModel( num_timesteps=20, initial_state_prior=initial_state_prior, transition_matrix=transition_matrix, transition_noise=transition_noise, observation_matrix=observation_matrix, observation_noise=observation_noise) observations = self.evaluate( model.sample(seed=test_util.test_seed())) (lps, filtered_means, _, _, _, _, _) = self.evaluate(model.forward_filter(observations)) # Approximate the filtering means and marginal likelihood(s) using # the particle filter. # pylint: disable=g-long-lambda (particles, log_weights, _, estimated_incremental_log_marginal_likelihoods) = self.evaluate( tfp.experimental.mcmc.particle_filter( observations=observations, initial_state_prior=initial_state_prior, transition_fn=lambda _, previous_state: tfd.MultivariateNormalTriL( loc=transition_noise.loc + tf.linalg.matvec( transition_matrix, previous_state), scale_tril=transition_noise.scale_tril), observation_fn=lambda _, state: tfd.MultivariateNormalTriL( loc=observation_noise.loc + tf.linalg.matvec( observation_matrix, state), scale_tril=observation_noise.scale_tril), num_particles=1024, seed=test_util.test_seed())) # pylint: enable=g-long-lambda particle_means = np.sum( particles * np.exp(log_weights)[..., np.newaxis], axis=1) self.assertAllClose(filtered_means, particle_means, atol=0.1, rtol=0.1) self.assertAllClose( lps, estimated_incremental_log_marginal_likelihoods, atol=0.6) def test_proposal_weights_dont_affect_marginal_likelihood(self): observation = np.array([-1.3, 0.7]).astype(self.dtype) # This particle filter has proposals different from the dynamics, # so internally it will use proposal weights in addition to observation # weights. It should still get the observation likelihood correct. _, lps = self.evaluate(tfp.experimental.mcmc.infer_trajectories( observation, initial_state_prior=tfd.Normal(loc=0., scale=1.), transition_fn=lambda _, x: tfd.Normal(loc=x, scale=1.), observation_fn=lambda _, x: tfd.Normal(loc=x, scale=1.), initial_state_proposal=tfd.Normal(loc=0., scale=5.), proposal_fn=lambda _, x: tfd.Normal(loc=x, scale=5.), num_particles=1024, seed=test_util.test_seed())) # Compare marginal likelihood against that # from the true (jointly normal) marginal distribution. y1_marginal_dist = tfd.Normal(loc=0., scale=np.sqrt(1. + 1.)) y2_conditional_dist = ( lambda y1: tfd.Normal(loc=y1 / 2., scale=np.sqrt(5. / 2.))) true_lps = [y1_marginal_dist.log_prob(observation[0]), y2_conditional_dist(observation[0]).log_prob(observation[1])] # The following line passes at atol = 0.01 if num_particles = 32768. self.assertAllClose(true_lps, lps, atol=0.1) def test_can_step_dynamics_faster_than_observations(self): initial_state_prior = tfd.JointDistributionNamed({ 'position': tfd.Deterministic(1.), 'velocity': tfd.Deterministic(0.) }) # Use 100 steps between observations to integrate a simple harmonic # oscillator. dt = 0.01 def simple_harmonic_motion_transition_fn(_, state): return tfd.JointDistributionNamed({ 'position': tfd.Normal( loc=state['position'] + dt * state['velocity'], scale=dt*0.01), 'velocity': tfd.Normal( loc=state['velocity'] - dt * state['position'], scale=dt*0.01) }) def observe_position(_, state): return tfd.Normal(loc=state['position'], scale=0.01) particles, _, _, lps = self.evaluate(tfp.experimental.mcmc.particle_filter( # 'Observing' the values we'd expect from a proper integrator should # give high likelihood if our discrete approximation is good. observations=tf.convert_to_tensor([tf.math.cos(0.), tf.math.cos(1.)]), initial_state_prior=initial_state_prior, transition_fn=simple_harmonic_motion_transition_fn, observation_fn=observe_position, num_particles=1024, num_transitions_per_observation=100, seed=test_util.test_seed())) self.assertLen(particles['position'], 101) self.assertAllClose(np.mean(particles['position'], axis=-1), tf.math.cos(dt * np.arange(101)), atol=0.04) self.assertLen(lps, 101) self.assertGreater(lps[0], 3.) self.assertGreater(lps[-1], 3.) def test_custom_trace_fn(self): def trace_fn(step_results): # Traces the mean and stddev of the particle population at each step. weights = tf.exp(step_results.log_weights) mean = tf.reduce_sum(weights * step_results.particles, axis=0) variance = tf.reduce_sum( weights * (step_results.particles - mean[tf.newaxis, ...])**2) return {'mean': mean, 'stddev': tf.sqrt(variance), # In real usage we would likely not track the particles and # weights. We keep them here just so we can double-check the # stats, below. 'particles': step_results.particles, 'weights': weights} results = self.evaluate( tfp.experimental.mcmc.particle_filter( observations=tf.convert_to_tensor([1., 3., 5., 7., 9.]), initial_state_prior=tfd.Normal(0., 1.), transition_fn=lambda _, state: tfd.Normal(state, 1.), observation_fn=lambda _, state: tfd.Normal(state, 1.), num_particles=1024, trace_fn=trace_fn, seed=test_util.test_seed())) # Verify that posterior means are increasing. self.assertAllGreater(results['mean'][1:] - results['mean'][:-1], 0.) # Check that our traced means and scales match values computed # by averaging over particles after the fact. all_means = self.evaluate(tf.reduce_sum( results['weights'] * results['particles'], axis=1)) all_variances = self.evaluate( tf.reduce_sum( results['weights'] * (results['particles'] - all_means[..., tf.newaxis])**2, axis=1)) self.assertAllClose(results['mean'], all_means) self.assertAllClose(results['stddev'], np.sqrt(all_variances)) def test_step_indices_to_trace(self): num_particles = 1024 (particles_1_3, log_weights_1_3, parent_indices_1_3, incremental_log_marginal_likelihood_1_3) = self.evaluate( tfp.experimental.mcmc.particle_filter( observations=tf.convert_to_tensor([1., 3., 5., 7., 9.]), initial_state_prior=tfd.Normal(0., 1.), transition_fn=lambda _, state: tfd.Normal(state, 10.), observation_fn=lambda _, state: tfd.Normal(state, 0.1), num_particles=num_particles, step_indices_to_trace=[1, 3], seed=test_util.test_seed())) self.assertLen(particles_1_3, 2) self.assertLen(log_weights_1_3, 2) self.assertLen(parent_indices_1_3, 2) self.assertLen(incremental_log_marginal_likelihood_1_3, 2) means = np.sum(np.exp(log_weights_1_3) * particles_1_3, axis=1) self.assertAllClose(means, [3., 7.], atol=1.) (final_particles, final_log_weights, final_cumulative_lp) = self.evaluate( tfp.experimental.mcmc.particle_filter( observations=tf.convert_to_tensor([1., 3., 5., 7., 9.]), initial_state_prior=tfd.Normal(0., 1.), transition_fn=lambda _, state: tfd.Normal(state, 10.), observation_fn=lambda _, state: tfd.Normal(state, 0.1), num_particles=num_particles, trace_fn=lambda r: (r.particles, # pylint: disable=g-long-lambda r.log_weights, r.accumulated_log_marginal_likelihood), step_indices_to_trace=-1, seed=test_util.test_seed())) self.assertLen(final_particles, num_particles) self.assertLen(final_log_weights, num_particles) self.assertEqual(final_cumulative_lp.shape, ()) means = np.sum(np.exp(final_log_weights) * final_particles) self.assertAllClose(means, 9., atol=1.5) class ParticleFilterTestFloat32(_ParticleFilterTest): dtype = np.float32 del _ParticleFilterTest if __name__ == '__main__': tf.test.main()
42.497336
91
0.644822
d23e82bb18520cfe923e6480091a9110fd42b7e5
1,979
py
Python
pywal/image.py
deviantfero/pywal
2d7662dfe0a9d49d0634d68ee244bb31462332cb
[ "MIT" ]
null
null
null
pywal/image.py
deviantfero/pywal
2d7662dfe0a9d49d0634d68ee244bb31462332cb
[ "MIT" ]
null
null
null
pywal/image.py
deviantfero/pywal
2d7662dfe0a9d49d0634d68ee244bb31462332cb
[ "MIT" ]
null
null
null
""" Get the image file. """ import logging import os import random import re import sys from .settings import CACHE_DIR from . import util from . import wallpaper def get_image_dir(img_dir): """Get all images in a directory.""" current_wall = wallpaper.get() current_wall = os.path.basename(current_wall) file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif") return [img.name for img in os.scandir(img_dir) if img.name.lower().endswith(file_types)], current_wall def get_random_image(img_dir): """Pick a random image file from a directory.""" images, current_wall = get_image_dir(img_dir) if len(images) > 2 and current_wall in images: images.remove(current_wall) elif not images: logging.error("No images found in directory.") sys.exit(1) random.shuffle(images) return os.path.join(img_dir, images[0]) def get_next_image(img_dir): """Get the next image in a dir.""" images, current_wall = get_image_dir(img_dir) images.sort(key=lambda img: [int(x) if x.isdigit() else x for x in re.split('([0-9]+)', img)]) try: next_index = images.index(current_wall) + 1 except ValueError: next_index = 0 try: image = images[next_index] except IndexError: image = images[0] return os.path.join(img_dir, image) def get(img, cache_dir=CACHE_DIR, iterative=False): """Validate image input.""" if os.path.isfile(img): wal_img = img elif os.path.isdir(img): if iterative: wal_img = get_next_image(img) else: wal_img = get_random_image(img) else: logging.error("No valid image file found.") sys.exit(1) wal_img = os.path.abspath(wal_img) # Cache the image file path. util.save_file(wal_img, os.path.join(cache_dir, "wal")) logging.info("Using image \033[1;37m%s\033[0m.", wal_img) return wal_img
23.282353
69
0.630622
2b7d0fa851d72d306e36b3418025101045e24373
1,834
py
Python
0010_RegularExpressionMatching.py
yingzhuo1994/LeetCode
636eef90867d21e3439d258ec99fbb8e5ad5a742
[ "MIT" ]
null
null
null
0010_RegularExpressionMatching.py
yingzhuo1994/LeetCode
636eef90867d21e3439d258ec99fbb8e5ad5a742
[ "MIT" ]
null
null
null
0010_RegularExpressionMatching.py
yingzhuo1994/LeetCode
636eef90867d21e3439d258ec99fbb8e5ad5a742
[ "MIT" ]
null
null
null
class Solution: # 1st solution def isMatch(self, s: str, p: str) -> bool: if not p: return not s if s and p[0] in {s[0], '.'}: first_match = True else: first_match = False if len(p) >= 2 and p[1] == '*': return (self.isMatch(s, p[2:]) or first_match and self.isMatch(s[1:], p)) else: return first_match and self.isMatch(s[1:], p[1:]) # 2nd solution, Top-Down # O(TP) time | O(TP) space # where T, P are the lengths of the s and p respectively. def isMatch(self, s: str, p: str) -> bool: memo = {} def dp(i, j): if (i, j) not in memo: if j == len(p): ans = i == len(s) else: first_match = i < len(s) and p[j] in {s[i], '.'} if j + 1 < len(p) and p[j + 1] == '*': ans = dp(i, j + 2) or first_match and dp(i + 1, j) else: ans = first_match and dp(i + 1, j + 1) memo[i, j] = ans return memo[i, j] return dp(0, 0) # 3rd solution, Bottom-Up # O(TP) time | O(TP) space # where T, P are the lengths of the s and p respectively. def isMatch(self, s: str, p: str) -> bool: dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] dp[-1][-1] = True for i in range(len(s), -1, -1): for j in range(len(p) - 1, -1, -1): first_match = i < len(s) and p[j] in {s[i], '.'} if j + 1 < len(p) and p[j + 1] == '*': dp[i][j] = dp[i][j + 2] or first_match and dp[i + 1][j] else: dp[i][j] = first_match and dp[i + 1][j + 1] return dp[0][0]
37.428571
75
0.416576
a9530e28966c8a69f396db5d22f40a4a08fec381
266
py
Python
quality/config/desktop.py
creador30/Quality
dde1a9dc327982077fe0a7bd069c7a85686d763a
[ "MIT" ]
1
2021-05-21T14:44:27.000Z
2021-05-21T14:44:27.000Z
quality/config/desktop.py
creador30/Quality
dde1a9dc327982077fe0a7bd069c7a85686d763a
[ "MIT" ]
null
null
null
quality/config/desktop.py
creador30/Quality
dde1a9dc327982077fe0a7bd069c7a85686d763a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "module_name": "Quality", "color": "#c0382b", "icon": "octicon octicon-zap", "type": "module", "label": _("Quality Management") } ]
17.733333
39
0.612782
f25123ca087f12fc284a866222267cba60a640fe
6,530
py
Python
recipe_modules/os_utils/api.py
cbracken/flutter_recipes
377482c7e1058d1ef2d9c946f4144c01c2a588ce
[ "BSD-3-Clause" ]
2
2021-04-09T06:07:28.000Z
2021-04-10T01:42:23.000Z
recipe_modules/os_utils/api.py
cbracken/flutter_recipes
377482c7e1058d1ef2d9c946f4144c01c2a588ce
[ "BSD-3-Clause" ]
null
null
null
recipe_modules/os_utils/api.py
cbracken/flutter_recipes
377482c7e1058d1ef2d9c946f4144c01c2a588ce
[ "BSD-3-Clause" ]
1
2021-09-28T16:26:46.000Z
2021-09-28T16:26:46.000Z
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from contextlib import contextmanager from recipe_engine import recipe_api from PB.go.chromium.org.luci.buildbucket.proto import common as common_pb2 class FlutterDepsApi(recipe_api.RecipeApi): """Operating system utilities.""" def _kill_win(self, name, exe_name): """Kills all the windows processes with a given name. Args: name(str): The name of the step. exe_name(str): The name of the windows executable. """ self.m.step( name, ['taskkill', '/f', '/im', exe_name, '/t'], ok_ret='any', ) def clean_derived_data(self): """Cleans the derived data folder in mac builders. Derived data caches fail very frequently when different version of mac/ios sdks are used in the same bot. To prevent those failures we will start deleting the folder before every task. """ derived_data_path = self.m.path['home'].join( 'Library', 'Developer', 'Xcode', 'DerivedData' ) if self.m.platform.is_mac: self.m.step( 'Delete mac deriveddata', ['rm', '-rf', derived_data_path], infra_step=True, ) def collect_os_info(self): """Collects meminfo, cpu, processes for mac""" if self.m.platform.is_mac: self.m.step( 'OS info', cmd=['top', '-l', '3', '-o', 'mem'], infra_step=True, ) # These are temporary steps to collect xattr info for triage purpose. # See issue: https://github.com/flutter/flutter/issues/68322#issuecomment-740264251 self.m.step( 'python xattr info', cmd=['xattr', '/opt/s/w/ir/cipd_bin_packages/python'], ok_ret='any', infra_step=True, ) self.m.step( 'git xattr info', cmd=['xattr', '/opt/s/w/ir/cipd_bin_packages/git'], ok_ret='any', infra_step=True, ) elif self.m.platform.is_linux: self.m.step( 'OS info', cmd=['top', '-b', '-n', '3', '-o', '%MEM'], infra_step=True, ) def kill_processes(self): """Kills processes. Windows uses exclusive file locking. On LUCI, if these processes remain they will cause the build to fail because the builder won't be able to clean up. Linux and Mac have leaking processes after task executions, potentially causing the build to fail if without clean up. This might fail if there's not actually a process running, which is fine. If it actually fails to kill the task, the job will just fail anyway. """ with self.m.step.nest('Killing Processes') as presentation: if self.m.platform.is_win: self._kill_win('stop gradle daemon', 'java.exe') self._kill_win('stop dart', 'dart.exe') self._kill_win('stop adb', 'adb.exe') self._kill_win('stop flutter_tester', 'flutter_tester.exe') elif self.m.platform.is_mac: self.m.step( 'kill dart', ['killall', '-9', 'dart'], ok_ret='any', infra_step=True ) self.m.step( 'kill flutter', ['killall', '-9', 'flutter'], ok_ret='any', infra_step=True ) self.m.step( 'kill Chrome', ['killall', '-9', 'Chrome'], ok_ret='any', infra_step=True ) self.m.step( 'kill Safari', ['killall', '-9', 'Safari'], ok_ret='any', infra_step=True ) self.m.step( 'kill Safari', ['killall', '-9', 'java'], ok_ret='any', infra_step=True ) self.m.step( 'kill Safari', ['killall', '-9', 'adb'], ok_ret='any', infra_step=True ) else: self.m.step( 'kill chrome', ['pkill', 'chrome'], ok_ret='any', infra_step=True ) self.m.step( 'kill dart', ['pkill', 'dart'], ok_ret='any', infra_step=True ) self.m.step( 'kill flutter', ['pkill', 'flutter'], ok_ret='any', infra_step=True ) self.m.step( 'kill java', ['pkill', 'java'], ok_ret='any', infra_step=True ) self.m.step('kill adb', ['pkill', 'adb'], ok_ret='any', infra_step=True) # Ensure we always pass this step as killing non existing processes # may create errors. presentation.status = 'SUCCESS' @contextmanager def make_temp_directory(self, label): """Makes a temporary directory that is automatically deleted. Args: label: (str) Part of the step name that removes the directory after is used. """ temp_dir = self.m.path.mkdtemp('tmp') try: yield temp_dir finally: self.m.file.rmtree('temp dir for %s' % label, temp_dir) def shutdown_simulators(self): """It stops simulators if task is running on a devicelab bot.""" if str(self.m.swarming.bot_id ).startswith('flutter-devicelab') and self.m.platform.is_mac: with self.m.step.nest('Shutdown simulators'): self.m.step( 'Shutdown simulators', ['sudo', 'xcrun', 'simctl', 'shutdown', 'all'] ) self.m.step( 'Erase simulators', ['sudo', 'xcrun', 'simctl', 'erase', 'all'] ) def dismiss_dialogs(self): """Dismisses iOS dialogs to avoid problems. Args: flutter_path(Path): A path to the checkout of the flutter sdk repository. """ if str(self.m.swarming.bot_id ).startswith('flutter-devicelab') and self.m.platform.is_mac: with self.m.step.nest('Dismiss dialogs'): cocoon_path = self.m.path['cache'].join('cocoon') self.m.repo_util.checkout( 'cocoon', cocoon_path, ref='refs/heads/master' ) resource_name = self.resource('dismiss_dialogs.sh') self.m.step( 'Set execute permission', ['chmod', '755', resource_name], infra_step=True, ) with self.m.context( cwd=cocoon_path.join('agent', 'tool', 'infra-dialog'), infra_steps=True, ): device_id = self.m.step( 'Find device id', ['idevice_id', '-l'], stdout=self.m.raw_io.output() ).stdout.rstrip() cmd = [resource_name, device_id] self.m.step('Run app to dismiss dialogs', cmd)
32.81407
89
0.575957
3729c927f0aa93ae3a350b7324cc5180d7441906
493
py
Python
sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/version.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/version.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
226
2019-07-24T07:57:21.000Z
2019-10-15T01:07:24.000Z
sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/version.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
2
2021-05-23T16:46:31.000Z
2021-05-26T23:51:09.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- VERSION = "1.5.0"
35.214286
76
0.51927
f78347778b858f957b167a0e68d65c8cf7d9429b
715
py
Python
verilog/dv/common/python/fwnoc_tests/fwnoc/single_inflight_00_01_sz_zero.py
Featherweight-IP/fwnoc
c1d8558e97fff1c125a1ef8f3519bd48735fe1a5
[ "Apache-2.0" ]
null
null
null
verilog/dv/common/python/fwnoc_tests/fwnoc/single_inflight_00_01_sz_zero.py
Featherweight-IP/fwnoc
c1d8558e97fff1c125a1ef8f3519bd48735fe1a5
[ "Apache-2.0" ]
null
null
null
verilog/dv/common/python/fwnoc_tests/fwnoc/single_inflight_00_01_sz_zero.py
Featherweight-IP/fwnoc
c1d8558e97fff1c125a1ef8f3519bd48735fe1a5
[ "Apache-2.0" ]
null
null
null
''' Created on May 7, 2021 @author: mballance ''' import cocotb from fwnoc_tests.fwnoc.fwnoc_test_base import FwnocTestBase from fwnoc_bfms.fwnoc_channel_bfm import FwNocPacket class SingleInflightP2P(FwnocTestBase): async def run(self): pkt = FwNocPacket() pkt.src_tile_x = 0 pkt.src_tile_y = 0 pkt.src_tile_x = 0 pkt.src_tile_y = 0 pkt.dst_tile_x = 0 pkt.dst_tile_y = 0 pkt.dst_tile_x = 0 pkt.dst_tile_y = 1 await self.senders[(0,0)].send(pkt) r_pkt = await self.bfms[(0,1)].recv() @cocotb.test() async def entry(dut): test = SingleInflightP2P() await test.init() await test.run()
21.029412
59
0.61958
db9c49b9f0c1570e23aa57599fbff7ea1f95904e
1,310
py
Python
research/setup.py
nilskk/models
dfb8bd66b54aa7f3c574089ed24b30b2e5ffa41c
[ "Apache-2.0" ]
null
null
null
research/setup.py
nilskk/models
dfb8bd66b54aa7f3c574089ed24b30b2e5ffa41c
[ "Apache-2.0" ]
null
null
null
research/setup.py
nilskk/models
dfb8bd66b54aa7f3c574089ed24b30b2e5ffa41c
[ "Apache-2.0" ]
null
null
null
"""Setup script for object_detection with TF2.0.""" import os from setuptools import find_packages from setuptools import setup # Note: adding apache-beam to required packages causes conflict with # tf-models-offical requirements. These packages request for incompatible # oauth2client package. REQUIRED_PACKAGES = [ # Required for apache-beam with PY3 'avro-python3', 'apache-beam', 'pillow', 'lxml', 'matplotlib', 'Cython', 'contextlib2', 'tf-slim', 'six', 'pycocotools @ git+https://github.com/nilskk/cocoapi.git#subdirectory=PythonAPI', 'lvis', 'scipy', 'pandas', 'tf-models-official' ] setup( name='object_detection', version='0.1', install_requires=REQUIRED_PACKAGES, include_package_data=True, packages=( [p for p in find_packages() if p.startswith('object_detection')] + find_packages(where=os.path.join('.', 'slim'))), package_dir={ 'datasets': os.path.join('slim', 'datasets'), 'nets': os.path.join('slim', 'nets'), 'preprocessing': os.path.join('slim', 'preprocessing'), 'deployment': os.path.join('slim', 'deployment'), 'scripts': os.path.join('slim', 'scripts'), }, description='Tensorflow Object Detection Library', python_requires='>3.6', )
29.111111
85
0.651908
b4861fa2151ce7256aff10ea0cdf9da929f2a0fe
811
py
Python
ecommerce_api/urls.py
HemanthKumar-Thope/ecommerce-api
a93603b6b9db2e16ae4511f2643662200d11b85e
[ "MIT" ]
null
null
null
ecommerce_api/urls.py
HemanthKumar-Thope/ecommerce-api
a93603b6b9db2e16ae4511f2643662200d11b85e
[ "MIT" ]
null
null
null
ecommerce_api/urls.py
HemanthKumar-Thope/ecommerce-api
a93603b6b9db2e16ae4511f2643662200d11b85e
[ "MIT" ]
null
null
null
"""ecommerce_api URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('project_apis.urls')) ]
35.26087
77
0.707768
a5121fd01ba8147fde523f6ea8d89481e28f3b7c
478
py
Python
pyredfish/console/console_disband.py
vaideesg/pyopenapi
f233bb27a31e811510a76759c5c15e76ba08684e
[ "Apache-2.0" ]
null
null
null
pyredfish/console/console_disband.py
vaideesg/pyopenapi
f233bb27a31e811510a76759c5c15e76ba08684e
[ "Apache-2.0" ]
null
null
null
pyredfish/console/console_disband.py
vaideesg/pyopenapi
f233bb27a31e811510a76759c5c15e76ba08684e
[ "Apache-2.0" ]
null
null
null
import os, sys sys.path.append(os.getcwd()) from console.console_api import * def printx(response): print(json.dumps(response, indent=4, separators=(',', ': '))) scom = ConsoleRemote() print("==== Disbanding Console") my_data = { 'type' : 'SCOM', 'name' : 'Anusha SCOM Server', 'hop_server' : '100.96.21.86', 'creds' : { 'username' : 'Dell123', 'password' : 'scomdev0\\administrator' } } printx(scom.delete(name = my_data['name']))
25.157895
69
0.604603
275106b0f337022521e0830be081f85db72b57b8
34,002
py
Python
nikola/plugin_categories.py
jonasstein/nikola
9b94d4581f66d72f8ceb3772e458ca66cb7eb869
[ "MIT" ]
null
null
null
nikola/plugin_categories.py
jonasstein/nikola
9b94d4581f66d72f8ceb3772e458ca66cb7eb869
[ "MIT" ]
null
null
null
nikola/plugin_categories.py
jonasstein/nikola
9b94d4581f66d72f8ceb3772e458ca66cb7eb869
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright © 2012-2018 Roberto Alsina and others. # 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. """Nikola plugin categories.""" import io import os import sys import doit import logbook from doit.cmd_base import Command as DoitCommand from yapsy.IPlugin import IPlugin from .utils import LOGGER, first_line, get_logger, req_missing try: import typing # NOQA if typing.TYPE_CHECKING: # NOQA import nikola # NOQA import nikola.post # NOQA except ImportError: pass __all__ = ( 'Command', 'LateTask', 'PageCompiler', 'RestExtension', 'MarkdownExtension', 'MetadataExtractor', 'Task', 'TaskMultiplier', 'TemplateSystem', 'SignalHandler', 'ConfigPlugin', 'PostScanner', 'Taxonomy', ) class BasePlugin(IPlugin): """Base plugin class.""" logger = None def set_site(self, site): """Set site, which is a Nikola instance.""" self.site = site self.inject_templates() self.logger = get_logger(self.name) if not site.debug: self.logger.level = logbook.base.INFO def inject_templates(self): """Inject 'templates/<engine>' (if exists) very early in the theme chain.""" try: # Sorry, found no other way to get this mod_path = sys.modules[self.__class__.__module__].__file__ mod_dir = os.path.dirname(mod_path) tmpl_dir = os.path.join( mod_dir, 'templates', self.site.template_system.name ) if os.path.isdir(tmpl_dir): # Inject tmpl_dir low in the theme chain self.site.template_system.inject_directory(tmpl_dir) except AttributeError: # In some cases, __builtin__ becomes the module of a plugin. # We couldn’t reproduce that, and really find the reason for this, # so let’s just ignore it and be done with it. pass def inject_dependency(self, target, dependency): """Add 'dependency' to the target task's task_deps.""" self.site.injected_deps[target].append(dependency) def get_deps(self, filename): """Find the dependencies for a file.""" return [] class PostScanner(BasePlugin): """The scan method of these plugins is called by Nikola.scan_posts.""" def scan(self) -> 'typing.List[nikola.post.Post]': """Create a list of posts from some source. Returns a list of Post objects.""" raise NotImplementedError() def supported_extensions(self) -> 'typing.Optional[typing.List]': """Return a list of supported file extensions, or None if such a list isn't known beforehand.""" return None class Command(BasePlugin, DoitCommand): """Doit command implementation.""" name = "dummy_command" doc_purpose = "A short explanation." doc_usage = "" doc_description = None # None value will completely omit line from doc # see http://python-doit.sourceforge.net/cmd_run.html#parameters cmd_options = () needs_config = True def __init__(self, *args, **kwargs): """Initialize a command.""" BasePlugin.__init__(self, *args, **kwargs) DoitCommand.__init__(self) def __call__(self, config=None, **kwargs): """Reset doit arguments (workaround).""" self._doitargs = kwargs DoitCommand.__init__(self, config, **kwargs) return self def execute(self, options=None, args=None) -> int: """Check if the command can run in the current environment, fail if needed, or call _execute.""" options = options or {} args = args or [] if self.needs_config and not self.site.configured: LOGGER.error("This command needs to run inside an existing Nikola site.") return False return self._execute(options, args) def _execute(self, options, args) -> int: """Do whatever this command does. @param options (dict) with values from cmd_options @param args (list) list of positional arguments """ raise NotImplementedError() def help(self): """Return help text for a command.""" text = [] text.append("Purpose: %s" % self.doc_purpose) text.append("Usage: nikola %s %s" % (self.name, self.doc_usage)) text.append('') text.append("Options:") for opt in self.cmdparser.options: text.extend(opt.help_doc()) if self.doc_description is not None: text.append("") text.append("Description:") text.append(self.doc_description) return "\n".join(text) # we need to patch DoitCommand.help with doit <0.31.0 if doit.__version__ < (0, 31, 0): DoitCommand.help = help class BaseTask(BasePlugin): """Base for task generators.""" name = "dummy_task" # default tasks are executed by default. # the others have to be specifie in the command line. is_default = True def gen_tasks(self) -> 'typing.List[dict]': """Generate tasks.""" raise NotImplementedError() def group_task(self) -> dict: """Return dict for group task.""" return { 'basename': self.name, 'name': None, 'doc': first_line(self.__doc__), } class Task(BaseTask): """Task generator.""" name = "dummy_task" class LateTask(BaseTask): """Late task generator (plugin executed after all Task plugins).""" name = "dummy_latetask" class TemplateSystem(BasePlugin): """Provide support for templating systems.""" name = "dummy_templates" def set_directories(self, directories: 'typing.List[str]', cache_folder: str): """Set the list of folders where templates are located and cache.""" raise NotImplementedError() def template_deps(self, template_name: str): """Return filenames which are dependencies for a template.""" raise NotImplementedError() def get_deps(self, filename: str): """Return paths to dependencies for the template loaded from filename.""" raise NotImplementedError() def get_string_deps(self, text: str): """Find dependencies for a template string.""" raise NotImplementedError() def render_template(self, template_name: str, output_name: str, context: 'typing.Dict[str, str]'): """Render template to a file using context. This must save the data to output_name *and* return it so that the caller may do additional processing. """ raise NotImplementedError() def render_template_to_string(self, template: str, context: 'typing.Dict[str, str]') -> str: """Render template to a string using context.""" raise NotImplementedError() def inject_directory(self, directory: str): """Inject the directory with the lowest priority in the template search mechanism.""" raise NotImplementedError() def get_template_path(self, template_name: str) -> str: """Get the path to a template or return None.""" raise NotImplementedError() class TaskMultiplier(BasePlugin): """Take a task and return *more* tasks.""" name = "dummy multiplier" def process(self, task) -> list: """Examine task and create more tasks. Returns extra tasks only.""" return [] class PageCompiler(BasePlugin): """Compile text files into HTML.""" name = "dummy_compiler" friendly_name = '' demote_headers = False supports_onefile = True use_dep_file = True # If set to false, the .dep file is never written and not automatically added as a target supports_metadata = False metadata_conditions = [] default_metadata = { 'title': '', 'slug': '', 'date': '', 'tags': '', 'category': '', 'link': '', 'description': '', 'type': 'text', } config_dependencies = [] def get_dep_filename(self, post: 'nikola.post.Post', lang: str) -> str: """Return the .dep file's name for the given post and language.""" return post.translated_base_path(lang) + '.dep' def _read_extra_deps(self, post: 'nikola.post.Post', lang: str) -> 'typing.List[str]': """Read contents of .dep file and return them as a list.""" dep_path = self.get_dep_filename(post, lang) if os.path.isfile(dep_path): with io.open(dep_path, 'r+', encoding='utf8') as depf: deps = [l.strip() for l in depf.readlines()] return deps return [] def register_extra_dependencies(self, post: 'nikola.post.Post'): """Add dependency to post object to check .dep file.""" def create_lambda(lang: str) -> 'typing.Callable': # We create a lambda like this so we can pass `lang` to it, because if we didn’t # add that function, `lang` would always be the last language in TRANSLATIONS. # (See http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures) return lambda: self._read_extra_deps(post, lang) for lang in self.site.config['TRANSLATIONS']: post.add_dependency(create_lambda(lang), 'fragment', lang=lang) def get_extra_targets(self, post: 'nikola.post.Post', lang: str, dest: str) -> 'typing.List[str]': """Return a list of extra targets for the render_posts task when compiling the post for the specified language.""" if self.use_dep_file: return [self.get_dep_filename(post, lang)] else: return [] def compile(self, source: str, dest: str, is_two_file=True, post=None, lang=None): """Compile the source file into HTML and save as dest.""" raise NotImplementedError() def compile_string(self, data: str, source_path=None, is_two_file=True, post=None, lang=None) -> str: """Compile the source file into HTML strings (with shortcode support). Returns a tuple of at least two elements: HTML string [0] and shortcode dependencies [last]. """ # This function used to have some different APIs in different places. raise NotImplementedError() def create_post(self, path: str, content=None, onefile=False, is_page=False, **kw): """Create post file with optional metadata.""" raise NotImplementedError() def extension(self) -> str: """Return the preferred extension for the output of this compiler.""" return ".html" def read_metadata(self, post: 'nikola.post.Post', lang=None) -> 'typing.Dict[str, str]': """Read the metadata from a post, and return a metadata dict.""" return {} def split_metadata(self, data: str, post=None, lang=None) -> (str, str): """Split data from metadata in the raw post content.""" if lang and post: extractor = post.used_extractor[lang] else: import nikola.metadata_extractors extractor = nikola.metadata_extractors.DEFAULT_EXTRACTOR if isinstance(extractor, MetadataExtractor): return extractor.split_metadata_from_text(data) else: return data, data def get_compiler_extensions(self) -> list: """Activate all the compiler extension plugins for a given compiler and return them.""" plugins = [] for plugin_info in self.site.compiler_extensions: if plugin_info.plugin_object.compiler_name == self.name: plugins.append(plugin_info) return plugins class CompilerExtension(BasePlugin): """An extension for a Nikola compiler. If you intend to implement those in your own compiler, you can: (a) create a new plugin class for them; or (b) use this class and filter them yourself. If you choose (b), you should the compiler name to the .plugin file in the Nikola/Compiler section and filter all plugins of this category, getting the compiler name with: p.details.get('Nikola', 'Compiler') Note that not all compiler plugins have this option and you might need to catch configparser.NoOptionError exceptions. """ name = "dummy_compiler_extension" compiler_name = "dummy_compiler" class RestExtension(CompilerExtension): """Extensions for reStructuredText.""" name = "dummy_rest_extension" compiler_name = "rest" class MarkdownExtension(CompilerExtension): """Extensions for Markdown.""" name = "dummy_markdown_extension" compiler_name = "markdown" class MetadataExtractor(BasePlugin): """Plugins that can extract meta information from post files.""" # Name of the extractor. (required) name = "unknown" # Where to get metadata from. (MetaSource; required) source = None # Priority of extractor. (MetaPriority; required) priority = None # List of tuples (MetaCondition, arg) with conditions used to select this extractor. conditions = [] # Regular expression used for splitting metadata, or None if not applicable. split_metadata_re = None # List of tuples (import name, pip name, friendly name) of Python packages required for this extractor. requirements = [] # Name of METADATA_MAPPING to use, if any. map_from = None # Whether or not the extractor supports writing metadata. supports_write = False def _extract_metadata_from_text(self, source_text: str) -> 'typing.Dict[str, str]': """Extract metadata from text.""" raise NotImplementedError() def split_metadata_from_text(self, source_text: str) -> (str, str): """Split text into metadata and content (both strings).""" if self.split_metadata_re is None: return source_text else: split_result = self.split_metadata_re.split(source_text.lstrip(), maxsplit=1) if len(split_result) == 1: return split_result[0], split_result[0] else: # Necessary? return split_result[0], split_result[-1] def extract_text(self, source_text: str) -> 'typing.Dict[str, str]': """Split file, return metadata and the content.""" split = self.split_metadata_from_text(source_text) if not split: return {} meta = self._extract_metadata_from_text(split[0]) return meta def extract_filename(self, filename: str, lang: str) -> 'typing.Dict[str, str]': """Extract metadata from filename.""" return {} def write_metadata(self, metadata: 'typing.Dict[str, str]', comment_wrap=False) -> str: """Write metadata in this extractor’s format. ``comment_wrap`` is either True, False, or a 2-tuple of comments to use for wrapping, if necessary. If it’s set to True, defaulting to ``('<!--', '-->')`` is recommended. This function should insert comment markers (if applicable) and must insert trailing newlines. """ raise NotImplementedError() def check_requirements(self): """Check if requirements for an extractor are satisfied.""" for import_name, pip_name, friendly_name in self.requirements: try: __import__(import_name) except ImportError: req_missing([pip_name], "use {0} metadata".format(friendly_name), python=True, optional=False) class SignalHandler(BasePlugin): """Signal handlers.""" name = "dummy_signal_handler" class ConfigPlugin(BasePlugin): """A plugin that can edit config (or modify the site) on-the-fly.""" name = "dummy_config_plugin" class ShortcodePlugin(BasePlugin): """A plugin that adds a shortcode.""" name = "dummy_shortcode_plugin" def set_site(self, site): """Set Nikola site.""" self.site = site site.register_shortcode(self.name, self.handler) return super(ShortcodePlugin, self).set_site(site) class Importer(Command): """Basic structure for importing data into Nikola. The flow is: read_data preprocess_data parse_data generate_base_site populate_context create_config filter_data process_data process_data can branch into: import_story (may use import_file and save_post) import_post (may use import_file and save_post) import_attachment (may use import_file) Finally: write_urlmap """ name = "dummy_importer" def _execute(self, options={}, args=[]): """Import the data into Nikola.""" raise NotImplementedError() def generate_base_site(self, path: str): """Create the base site.""" raise NotImplementedError() def populate_context(self): """Use data to fill context for configuration.""" raise NotImplementedError() def create_config(self): """Use the context to create configuration.""" raise NotImplementedError() def read_data(self, source): """Fetch data into self.data.""" raise NotImplementedError() def preprocess_data(self): """Modify data if needed.""" pass def parse_data(self): """Convert self.data into self.items.""" raise NotImplementedError() def filter_data(self): """Remove data that's not to be imported.""" pass def process_data(self): """Go through self.items and save them.""" def import_story(self): """Create a page.""" raise NotImplementedError() def import_post(self): """Create a post.""" raise NotImplementedError() def import_attachment(self): """Create an attachment.""" raise NotImplementedError() def import_file(self): """Import a file.""" raise NotImplementedError() def save_post(self): """Save a post to disk.""" raise NotImplementedError() class Taxonomy(BasePlugin): """Taxonomy for posts. A taxonomy plugin allows to classify posts (see #2107) by classification strings. Classification plugins must adjust a set of options to determine certain aspects. The following options are class attributes with their default values. These variables should be set in the class definition, in the constructor or latest in the `set_site` function. classification_name = "taxonomy": The classification name to be used for path handlers. Must be overridden! overview_page_items_variable_name = "items": When rendering the overview page, its template will have a list of pairs (friendly_name, link) for the classifications available in a variable by this name. The template will also have a list (friendly_name, link, post_count) for the classifications available in a variable by the name `overview_page_items_variable_name + '_with_postcount'`. overview_page_variable_name = "taxonomy": When rendering the overview page, its template will have a list of classifications available in a variable by this name. overview_page_hierarchy_variable_name = "taxonomy_hierarchy": When rendering the overview page, its template will have a list of tuples (friendly_name, classification, classification_path, link, indent_levels, indent_change_before, indent_change_after) available in a variable by this name. These tuples can be used to render the hierarchy as a tree. The template will also have a list (friendly_name, classification, classification_path, link, indent_levels, indent_change_before, indent_change_after, number_of_children, post_count) available in the variable by the name `overview_page_hierarchy_variable_name + '_with_postcount'`. more_than_one_classifications_per_post = False: If True, there can be more than one classification per post; in that case, the classification data in the metadata is stored as a list. If False, the classification data in the metadata is stored as a string, or None when no classification is given. has_hierarchy = False: Whether the classification has a hierarchy. include_posts_from_subhierarchies = False: If True, the post list for a classification includes all posts with a sub-classification (in case has_hierarchy is True). include_posts_into_hierarchy_root = False: If True, include_posts_from_subhierarchies == True will also insert posts into the post list for the empty hierarchy []. show_list_as_subcategories_list = False: If True, for every classification which has at least one subclassification, create a list of subcategories instead of a list/index of posts. This is only used when has_hierarchy = True. The template specified in subcategories_list_template will be used. If this is set to True, it is recommended to set include_posts_from_subhierarchies to True to get correct post counts. show_list_as_index = False: Whether to show the posts for one classification as an index or as a post list. subcategories_list_template = "taxonomy_list.tmpl": The template to use for the subcategories list when show_list_as_subcategories_list is True. template_for_single_list = "tagindex.tmpl": The template to use for the post list for one classification. template_for_classification_overview = "list.tmpl": The template to use for the classification overview page. Set to None to avoid generating overviews. always_disable_atom = False: Whether to always disable Atom feed generation. always_disable_rss = False: Whether to always disable RSS feed generation. apply_to_posts = True: Whether this classification applies to posts. apply_to_pages = False: Whether this classification applies to pages. minimum_post_count_per_classification_in_overview = 1: The minimum number of posts a classification must have to be listed in the overview. omit_empty_classifications = False: Whether post lists resp. indexes should be created for empty classifications. add_other_languages_variable = False: In case this is `True`, each classification page will get a list of triples `(other_lang, other_classification, title)` of classifications in other languages which should be linked. The list will be stored in the variable `other_languages`. path_handler_docstrings: A dictionary of docstrings for path handlers. See eg. nikola.py for examples. Must be overridden, keys are "taxonomy_index", "taxonomy", "taxonomy_atom", "taxonomy_rss" (but using classification_name instead of "taxonomy"). If one of the values is False, the corresponding path handler will not be created. """ name = "dummy_taxonomy" # Adjust the following values in your plugin! classification_name = "taxonomy" overview_page_variable_name = "taxonomy" overview_page_items_variable_name = "items" overview_page_hierarchy_variable_name = "taxonomy_hierarchy" more_than_one_classifications_per_post = False has_hierarchy = False include_posts_from_subhierarchies = False include_posts_into_hierarchy_root = False show_list_as_subcategories_list = False show_list_as_index = False subcategories_list_template = "taxonomy_list.tmpl" template_for_single_list = "tagindex.tmpl" template_for_classification_overview = "list.tmpl" always_disable_atom = False always_disable_rss = False apply_to_posts = True apply_to_pages = False minimum_post_count_per_classification_in_overview = 1 omit_empty_classifications = False add_other_languages_variable = False path_handler_docstrings = { 'taxonomy_index': '', 'taxonomy': '', 'taxonomy_atom': '', 'taxonomy_rss': '', } def is_enabled(self, lang=None) -> bool: """Return True if this taxonomy is enabled, or False otherwise. If lang is None, this determins whether the classification is made at all. If lang is not None, this determines whether the overview page and the classification lists are created for this language. """ return True def get_implicit_classifications(self, lang: str) -> 'typing.List[str]': """Return a list of classification strings which should always appear in posts_per_classification.""" return [] def classify(self, post: 'nikola.post.Post', lang: str) -> 'typing.Iterable[str]': """Classify the given post for the given language. Must return a list or tuple of strings. """ raise NotImplementedError() def sort_posts(self, posts: 'typing.List[nikola.post.Post]', classification: str, lang: str): """Sort the given list of posts. Allows the plugin to order the posts per classification as it wants. The posts will be ordered by date (latest first) before calling this function. This function must sort in-place. """ pass def sort_classifications(self, classifications: 'typing.List[str]', lang: str, level=None): """Sort the given list of classification strings. Allows the plugin to order the classifications as it wants. The classifications will be ordered by `natsort` before calling this function. This function must sort in-place. For hierarchical taxonomies, the elements of the list are a single path element of the path returned by `extract_hierarchy()`. The index of the path element in the path will be provided in `level`. """ pass def get_classification_friendly_name(self, classification: str, lang: str, only_last_component=False) -> str: """Extract a friendly name from the classification. The result of this function is usually displayed to the user, instead of using the classification string. The argument `only_last_component` is only relevant to hierarchical taxonomies. If it is set, the printable name should only describe the last component of `classification` if possible. """ raise NotImplementedError() def get_overview_path(self, lang: str, dest_type='page') -> str: """Return path for classification overview. This path handler for the classification overview must return one or two values (in this order): * a list or tuple of strings: the path relative to OUTPUT_DIRECTORY; * a string with values 'auto', 'always' or 'never', indicating whether INDEX_FILE should be added or not. Note that this function must always return a list or tuple of strings; the other return value is optional with default value `'auto'`. In case INDEX_FILE should potentially be added, the last element in the returned path must have no extension, and the PRETTY_URLS config must be ignored by this handler. The return value will be modified based on the PRETTY_URLS and INDEX_FILE settings. `dest_type` can be either 'page', 'feed' (for Atom feed) or 'rss'. """ raise NotImplementedError() def get_path(self, classification: str, lang: str, dest_type='page') -> str: """Return path to the classification page. This path handler for the given classification must return one to three values (in this order): * a list or tuple of strings: the path relative to OUTPUT_DIRECTORY; * a string with values 'auto', 'always' or 'never', indicating whether INDEX_FILE should be added or not; * an integer if a specific page of the index is to be targeted (will be ignored for post lists), or `None` if the most current page is targeted. Note that this function must always return a list or tuple of strings; the other two return values are optional with default values `'auto'` and `None`. In case INDEX_FILE should potentially be added, the last element in the returned path must have no extension, and the PRETTY_URLS config must be ignored by this handler. The return value will be modified based on the PRETTY_URLS and INDEX_FILE settings. `dest_type` can be either 'page', 'feed' (for Atom feed) or 'rss'. For hierarchical taxonomies, the result of extract_hierarchy is provided as `classification`. For non-hierarchical taxonomies, the classification string itself is provided as `classification`. """ raise NotImplementedError() def extract_hierarchy(self, classification: str) -> 'typing.List[str]': """Given a classification, return a list of parts in the hierarchy. For non-hierarchical taxonomies, it usually suffices to return `[classification]`. """ return [classification] def recombine_classification_from_hierarchy(self, hierarchy: 'typing.List[str]') -> str: """Given a list of parts in the hierarchy, return the classification string. For non-hierarchical taxonomies, it usually suffices to return hierarchy[0]. """ return hierarchy[0] def provide_overview_context_and_uptodate(self, lang: str) -> str: """Provide data for the context and the uptodate list for the classification overview. Must return a tuple of two dicts. The first is merged into the page's context, the second will be put into the uptodate list of all generated tasks. Context must contain `title`. """ raise NotImplementedError() def provide_context_and_uptodate(self, classification: str, lang: str, node=None) -> 'typing.Tuple[typing.Dict]': """Provide data for the context and the uptodate list for the list of the given classification. Must return a tuple of two dicts. The first is merged into the page's context, the second will be put into the uptodate list of all generated tasks. For hierarchical taxonomies, node is the `hierarchy_utils.TreeNode` element corresponding to the classification. Context must contain `title`, which should be something like 'Posts about <classification>'. """ raise NotImplementedError() def should_generate_classification_page(self, classification: str, post_list: 'typing.List[nikola.post.Post]', lang: str) -> bool: """Only generates list of posts for classification if this function returns True.""" return True def should_generate_atom_for_classification_page(self, classification: str, post_list: 'typing.List[nikola.post.Post]', lang: str) -> bool: """Only generates Atom feed for list of posts for classification if this function returns True.""" return self.should_generate_classification_page(classification, post_list, lang) def should_generate_rss_for_classification_page(self, classification: str, post_list: 'typing.List[nikola.post.Post]', lang: str) -> bool: """Only generates RSS feed for list of posts for classification if this function returns True.""" return self.should_generate_classification_page(classification, post_list, lang) def postprocess_posts_per_classification(self, posts_per_classification_per_language: 'typing.List[nikola.post.Post]', flat_hierarchy_per_lang=None, hierarchy_lookup_per_lang=None) -> 'typing.List[nikola.post.Post]': """Rearrange, modify or otherwise use the list of posts per classification and per language. For compatibility reasons, the list could be stored somewhere else as well. In case `has_hierarchy` is `True`, `flat_hierarchy_per_lang` is the flat hierarchy consisting of `hierarchy_utils.TreeNode` elements, and `hierarchy_lookup_per_lang` is the corresponding hierarchy lookup mapping classification strings to `hierarchy_utils.TreeNode` objects. """ pass def get_other_language_variants(self, classification: str, lang: str, classifications_per_language: 'typing.List[str]') -> 'typing.List[str]': """Return a list of variants of the same classification in other languages. Given a `classification` in a language `lang`, return a list of pairs `(other_lang, other_classification)` with `lang != other_lang` such that `classification` should be linked to `other_classification`. Classifications where links to other language versions makes no sense should simply return an empty list. Provided is a set of classifications per language (`classifications_per_language`). """ return []
37.738069
220
0.673255
424201ecefd17117a7682f762921fdc52613d1f6
3,272
py
Python
tests/command_line/test_export_best.py
dials-src/dials
25055c1f6164dc33e672e7c5c6a9c5a35e870660
[ "BSD-3-Clause" ]
null
null
null
tests/command_line/test_export_best.py
dials-src/dials
25055c1f6164dc33e672e7c5c6a9c5a35e870660
[ "BSD-3-Clause" ]
null
null
null
tests/command_line/test_export_best.py
dials-src/dials
25055c1f6164dc33e672e7c5c6a9c5a35e870660
[ "BSD-3-Clause" ]
null
null
null
from __future__ import annotations import procrunner def test_export_best(dials_data, tmp_path): result = procrunner.run( [ "dials.import", "template=" + str(dials_data("centroid_test_data", pathlib=True) / "centroid_####.cbf"), ], working_directory=tmp_path, ) assert not result.returncode and not result.stderr result = procrunner.run( ["dials.find_spots", "imported.expt", "nproc=1"], working_directory=tmp_path ) assert not result.returncode and not result.stderr result = procrunner.run( ["dials.index", "imported.expt", "strong.refl", "space_group=P422"], working_directory=tmp_path, ) assert not result.returncode and not result.stderr result = procrunner.run( [ "dials.integrate", "nproc=1", "indexed.expt", "indexed.refl", "prediction.padding=0", "sigma_m_algorithm=basic", ], working_directory=tmp_path, ) assert not result.returncode and not result.stderr result = procrunner.run( ["dials.export_best", "integrated.expt", "integrated.refl"], working_directory=tmp_path, ) assert not result.returncode and not result.stderr assert tmp_path.joinpath("best.dat").is_file() assert tmp_path.joinpath("best.hkl").is_file() assert tmp_path.joinpath("best.par").is_file() with tmp_path.joinpath("best.dat").open("r") as f: lines = "".join(f.readlines()[:10]) assert ( lines == """\ 181.8877 0.77 1.60 63.1895 1.59 1.81 38.2372 1.87 1.71 27.4131 1.84 1.55 21.3655 1.89 1.51 17.5043 1.88 1.49 14.8254 1.89 1.45 12.8580 1.91 1.45 11.3518 1.89 1.42 10.1617 1.87 1.41 """ ) with tmp_path.joinpath("best.hkl").open("r") as f: lines = "".join(f.readlines()[:10]) assert ( lines == """\ -20 27 -8 20.17 20.00 -20 27 -7 74.13 21.59 -20 27 -6 22.34 19.57 -20 27 -5 6.33 19.72 -20 28 -10 19.77 18.77 -20 28 -9 50.37 20.28 -20 28 -7 69.23 21.42 -20 28 -6 24.42 19.56 -20 28 -4 -10.35 19.51 -20 28 -2 47.53 20.49 """ ) lines = tmp_path.joinpath("best.par").read_text() assert ( lines == """\ # parameter file for BEST TITLE From DIALS DETECTOR PILA SITE Not set DIAMETER 434.64 PIXEL 0.172 ROTAXIS 0.01 0.00 1.00 FAST POLAXIS 0.00 1.00 0.00 GAIN 1.00 CMOSAIC 0.54 PHISTART 0.00 PHIWIDTH 0.20 DISTANCE 191.09 WAVELENGTH 0.97950 POLARISATION 0.99900 SYMMETRY P422 UB -0.012248 -0.020067 0.003152 -0.005029 -0.000351 -0.024623 0.019651 -0.012597 -0.004336 CELL 42.20 42.20 39.68 90.00 90.00 90.00 RASTER 7 7 5 3 3 SEPARATION 0.665 0.665 BEAM 219.875 212.612 # end of parameter file for BEST """ )
28.955752
88
0.523839
cb2b9b002fa0c55119d48c325a2fdf82d6743cfa
5,471
py
Python
modules/dbnd/src/dbnd/_core/utils/http/reliable_http_client.py
busunkim96/dbnd
0191fdcd4c4fbd35006f1026d1a55b2abab9097b
[ "Apache-2.0" ]
224
2020-01-02T10:46:37.000Z
2022-03-02T13:54:08.000Z
modules/dbnd/src/dbnd/_core/utils/http/reliable_http_client.py
busunkim96/dbnd
0191fdcd4c4fbd35006f1026d1a55b2abab9097b
[ "Apache-2.0" ]
16
2020-03-11T09:37:58.000Z
2022-01-26T10:22:08.000Z
modules/dbnd/src/dbnd/_core/utils/http/reliable_http_client.py
busunkim96/dbnd
0191fdcd4c4fbd35006f1026d1a55b2abab9097b
[ "Apache-2.0" ]
24
2020-03-24T13:53:50.000Z
2022-03-22T11:55:18.000Z
import json import logging from time import sleep import requests from dbnd._core.errors import DatabandError, DatabandConfigError from dbnd._core.utils.http import constants # copypasted from sparkmagic package # Copyright (c) 2015 aggftw@gmail.com # Distributed under the terms of the Modified BSD License. # logger = logging.getLogger(__name__) class HttpClientException(DatabandError): pass class ReliableHttpClient(object): """Http client that is reliable in its requests. Uses requests library.""" def __init__(self, endpoint, headers, retry_policy, ignore_ssl_errors=False): self._endpoint = endpoint self._headers = headers self._retry_policy = retry_policy if self._endpoint.auth == constants.AUTH_KERBEROS: from requests_kerberos import HTTPKerberosAuth, REQUIRED self._auth = HTTPKerberosAuth(mutual_authentication=REQUIRED) elif self._endpoint.auth == constants.AUTH_BASIC: self._auth = (self._endpoint.username, self._endpoint.password) elif self._endpoint.auth != constants.NO_AUTH: raise DatabandConfigError("Unsupported auth %s" % self._endpoint.auth) self.logger = logger self.verify_ssl = not ignore_ssl_errors if not self.verify_ssl: self.logger.debug( "ATTENTION: Will ignore SSL errors. This might render you vulnerable to attacks." ) requests.packages.urllib3.disable_warnings() def get_headers(self): return self._headers def compose_url(self, relative_url): r_u = "/{}".format(relative_url.rstrip("/").lstrip("/")) return self._endpoint.url + r_u def get(self, relative_url, accepted_status_codes, retry_policy=None): """Sends a get request. Returns a response.""" logger.debug("Sending GET request to %s", self.compose_url(relative_url)) return self._send_request(relative_url, accepted_status_codes, requests.get) def post(self, relative_url, accepted_status_codes, data): """Sends a post request. Returns a response.""" logger.debug( "Sending POST request to %s, with data: %s", self.compose_url(relative_url), data, ) return self._send_request( relative_url, accepted_status_codes, requests.post, data ) def delete(self, relative_url, accepted_status_codes): """Sends a delete request. Returns a response.""" return self._send_request(relative_url, accepted_status_codes, requests.delete) def _send_request( self, relative_url, accepted_status_codes, function, data=None, retry_policy=None, ): response = self._send_request_helper( self.compose_url(relative_url), accepted_status_codes, function, data, 0, retry_policy, ) logger.debug("Received response: %s", response) return response def _send_request_helper( self, url, accepted_status_codes, function, data, retry_count, retry_policy ): while True: try: if self._endpoint.auth == constants.NO_AUTH: if data is None: r = function(url, headers=self._headers, verify=self.verify_ssl) else: r = function( url, headers=self._headers, data=json.dumps(data), verify=self.verify_ssl, ) else: if data is None: r = function( url, headers=self._headers, auth=self._auth, verify=self.verify_ssl, ) else: r = function( url, headers=self._headers, auth=self._auth, data=json.dumps(data), verify=self.verify_ssl, ) except requests.exceptions.RequestException as e: error = True r = None status = None text = None self.logger.warning("Request to '{}' failed with '{}'".format(url, e)) else: error = False status = r.status_code text = r.text if error or status not in accepted_status_codes: retry_policy = retry_policy or self._retry_policy if retry_policy.should_retry(status, error, retry_count): sleep(retry_policy.seconds_to_sleep(retry_count)) retry_count += 1 continue if error: raise HttpClientException( "Error sending http request and maximum retry encountered." ) else: raise HttpClientException( "Invalid status code '{}' from {} with error payload: {}".format( status, url, text ) ) return r
35.296774
97
0.545056
c7d7024b06f8b152a0a8735258c16854aadba82c
2,400
py
Python
hash_hardlink.py
voussoir/cmd
9ecfc43751c42d4cdd288b8a1b28ba3a7fa6c650
[ "BSD-3-Clause" ]
6
2020-01-30T13:36:53.000Z
2022-02-05T08:14:56.000Z
hash_hardlink.py
voussoir/cmd
9ecfc43751c42d4cdd288b8a1b28ba3a7fa6c650
[ "BSD-3-Clause" ]
null
null
null
hash_hardlink.py
voussoir/cmd
9ecfc43751c42d4cdd288b8a1b28ba3a7fa6c650
[ "BSD-3-Clause" ]
1
2020-01-30T13:36:33.000Z
2020-01-30T13:36:33.000Z
import argparse import hashlib import os import send2trash import sys from voussoirkit import bytestring from voussoirkit import lazychain from voussoirkit import pathclass from voussoirkit import pipeable from voussoirkit import spinal from voussoirkit import vlogging log = vlogging.getLogger(__name__, 'hash_hardlink') def hash_file(file): hasher = hashlib.md5() with file.open('rb') as handle: while True: chunk = handle.read(2**20) if not chunk: break hasher.update(chunk) return hasher.hexdigest() @pipeable.ctrlc_return1 def hash_hardlink_argparse(args): paths = [pathclass.Path(p) for p in pipeable.input_many(args.paths, strip=True, skip_blank=True)] drives = set(path.stat.st_dev for path in paths) if len(drives) != 1: raise ValueError('All paths must be on the same drive.') files = lazychain.LazyChain() for path in paths: if path.is_file: files.append(path) elif path.is_dir: files.extend(spinal.walk(path)) inodes = set() hashes = {} if args.if_larger_than: larger = bytestring.parsebytes(args.if_larger_than) else: larger = None for file in files: if file.stat.st_ino in inodes: # This file is already a hardlink of another file we've seen. continue if larger is not None and file.size < larger: continue inodes.add(file.stat.st_ino) h = hash_file(file) print(file.absolute_path, h) hashes.setdefault(h, []).append(file) hashes = {h: files for (h, files) in hashes.items() if len(files) > 1} for (h, files) in hashes.items(): leader = files.pop(0) for follower in files: print(f'{leader.absolute_path} -> {follower.absolute_path}') send2trash.send2trash(follower.absolute_path) os.link(leader.absolute_path, follower.absolute_path) return 0 @vlogging.main_decorator def main(argv): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('paths', nargs='+') parser.add_argument('--if_larger_than', '--if-larger-than', default=None) parser.set_defaults(func=hash_hardlink_argparse) args = parser.parse_args(argv) return args.func(args) if __name__ == '__main__': raise SystemExit(main(sys.argv[1:]))
28.915663
101
0.658333
11c26c726fa5661230a5fea4aa92883480b1e275
29,029
py
Python
rlkit/launchers/launcher_util.py
richardrl/rlkit
088dae169a8d5ba1430094eee66f27b2cb7c4998
[ "MIT" ]
null
null
null
rlkit/launchers/launcher_util.py
richardrl/rlkit
088dae169a8d5ba1430094eee66f27b2cb7c4998
[ "MIT" ]
null
null
null
rlkit/launchers/launcher_util.py
richardrl/rlkit
088dae169a8d5ba1430094eee66f27b2cb7c4998
[ "MIT" ]
null
null
null
import datetime import json import os import os.path as osp import pickle import random import sys import time from collections import namedtuple import __main__ as main import dateutil.tz import numpy as np from rlkit.core import logger from rlkit.launchers import config from rlkit.torch.pytorch_util import set_gpu_mode import rlkit.pythonplusplus as ppp # print("importing gym fetch stack") # import gym_fetch_stack # (this line is causing the mujoco import error) GitInfo = namedtuple( 'GitInfo', [ 'directory', 'code_diff', 'code_diff_staged', 'commit_hash', 'branch_name', ], ) def get_git_infos(dirs): try: import git git_infos = [] for directory in dirs: # Idk how to query these things, so I'm just doing try-catch try: repo = git.Repo(directory) try: branch_name = repo.active_branch.name except TypeError: branch_name = '[DETACHED]' git_infos.append(GitInfo( directory=directory, code_diff=repo.git.diff(None), code_diff_staged=repo.git.diff('--staged'), commit_hash=repo.head.commit.hexsha, branch_name=branch_name, )) except git.exc.InvalidGitRepositoryError as e: print("Not a valid git repo: {}".format(directory)) except ImportError: git_infos = None return git_infos def recursive_items(dictionary): """ Get all (key, item) recursively in a potentially recursive dictionary. Usage: ``` x = { 'foo' : { 'bar' : 5 } } recursive_items(x) # output: # ('foo', {'bar' : 5}) # ('bar', 5) ``` :param dictionary: :return: """ for key, value in dictionary.items(): yield key, value if type(value) is dict: yield from recursive_items(value) def save_experiment_data(dictionary, log_dir): with open(log_dir + '/experiment.pkl', 'wb') as handle: pickle.dump(dictionary, handle, protocol=pickle.HIGHEST_PROTOCOL) def run_experiment_here( experiment_function, variant=None, exp_id=0, seed=None, use_gpu=True, # Logger params: exp_prefix="default", snapshot_mode='last', snapshot_gap=1, git_infos=None, script_name=None, base_log_dir=None, force_randomize_seed=False, log_dir=None, **setup_logger_kwargs ): import faulthandler faulthandler.enable() """ Run an experiment locally without any serialization. :param experiment_function: Function. `variant` will be passed in as its only argument. :param exp_prefix: Experiment prefix for the save file. :param variant: Dictionary passed in to `experiment_function`. :param exp_id: Experiment ID. Should be unique across all experiments. Note that one experiment may correspond to multiple seeds,. :param seed: Seed used for this experiment. :param use_gpu: Run with GPU. By default False. :param script_name: Name of the running script :param log_dir: If set, set the log directory to this. Otherwise, the directory will be auto-generated based on the exp_prefix. :return: """ if variant is None: variant = {} variant['exp_id'] = str(exp_id) if force_randomize_seed or seed is None: seed = random.randint(0, 100000) variant['seed'] = str(seed) reset_execution_environment() actual_log_dir = setup_logger( exp_prefix=exp_prefix, variant=variant, exp_id=exp_id, seed=seed, snapshot_mode=snapshot_mode, snapshot_gap=snapshot_gap, base_log_dir=base_log_dir, log_dir=log_dir, git_infos=git_infos, script_name=script_name, **setup_logger_kwargs ) set_seed(seed) set_gpu_mode(use_gpu) run_experiment_here_kwargs = dict( variant=variant, exp_id=exp_id, seed=seed, use_gpu=use_gpu, exp_prefix=exp_prefix, snapshot_mode=snapshot_mode, snapshot_gap=snapshot_gap, git_infos=git_infos, script_name=script_name, base_log_dir=base_log_dir, **setup_logger_kwargs ) save_experiment_data( dict( run_experiment_here_kwargs=run_experiment_here_kwargs ), actual_log_dir ) # print("variant: \n") # print(variant) return experiment_function(variant) def create_exp_name(exp_prefix, exp_id=0, seed=0): """ Create a semi-unique experiment name that has a timestamp :param exp_prefix: :param exp_id: :return: """ now = datetime.datetime.now(dateutil.tz.tzlocal()) timestamp = now.strftime('%Y_%m_%d_%H_%M_%S') return "%s_%s_%04d--s-%d" % (exp_prefix, timestamp, exp_id, seed) def create_log_dir( exp_prefix, exp_id=0, seed=0, base_log_dir=None, include_exp_prefix_sub_dir=True, ): """ Creates and returns a unique log directory. :param exp_prefix: All experiments with this prefix will have log directories be under this directory. :param exp_id: The number of the specific experiment run within this experiment. :param base_log_dir: The directory where all log should be saved. :return: """ exp_name = create_exp_name(exp_prefix, exp_id=exp_id, seed=seed) if base_log_dir is None: base_log_dir = config.LOCAL_LOG_DIR if include_exp_prefix_sub_dir: log_dir = osp.join(base_log_dir, exp_prefix.replace("_", "-"), exp_name) else: log_dir = osp.join(base_log_dir, exp_name) if osp.exists(log_dir): print("WARNING: Log directory already exists {}".format(log_dir)) os.makedirs(log_dir, exist_ok=True) return log_dir def setup_logger( exp_prefix="default", variant=None, text_log_file="debug.log", variant_log_file="variant.json", tabular_log_file="progress.csv", snapshot_mode="last", snapshot_gap=1, log_tabular_only=False, log_dir=None, git_infos=None, script_name=None, **create_log_dir_kwargs ): """ Set up logger to have some reasonable default settings. Will save log output to based_log_dir/exp_prefix/exp_name. exp_name will be auto-generated to be unique. If log_dir is specified, then that directory is used as the output dir. :param exp_prefix: The sub-directory for this specific experiment. :param variant: :param text_log_file: :param variant_log_file: :param tabular_log_file: :param snapshot_mode: :param log_tabular_only: :param snapshot_gap: :param log_dir: :param git_infos: :param script_name: If set, save the script name to this. :return: """ if git_infos is None: git_infos = get_git_infos(config.CODE_DIRS_TO_MOUNT) first_time = log_dir is None if first_time: log_dir = create_log_dir(exp_prefix, **create_log_dir_kwargs) if variant is not None: logger.log("Variant:") logger.log(json.dumps(dict_to_safe_json(variant), indent=2)) variant_log_path = osp.join(log_dir, variant_log_file) logger.log_variant(variant_log_path, variant) tabular_log_path = osp.join(log_dir, tabular_log_file) text_log_path = osp.join(log_dir, text_log_file) logger.add_text_output(text_log_path) if first_time: logger.add_tabular_output(tabular_log_path) else: logger._add_output(tabular_log_path, logger._tabular_outputs, logger._tabular_fds, mode='a') for tabular_fd in logger._tabular_fds: logger._tabular_header_written.add(tabular_fd) logger.set_snapshot_dir(log_dir) logger.set_snapshot_mode(snapshot_mode) logger.set_snapshot_gap(snapshot_gap) logger.set_log_tabular_only(log_tabular_only) exp_name = log_dir.split("/")[-1] logger.push_prefix("[%s] " % exp_name) if git_infos is not None: for ( directory, code_diff, code_diff_staged, commit_hash, branch_name ) in git_infos: if directory[-1] == '/': directory = directory[:-1] diff_file_name = directory[1:].replace("/", "-") + ".patch" diff_staged_file_name = ( directory[1:].replace("/", "-") + "_staged.patch" ) if code_diff is not None and len(code_diff) > 0: with open(osp.join(log_dir, diff_file_name), "w") as f: f.write(code_diff + '\n') if code_diff_staged is not None and len(code_diff_staged) > 0: with open(osp.join(log_dir, diff_staged_file_name), "w") as f: try: f.write(code_diff_staged + '\n') except UnicodeEncodeError as e: print(e) f.write(code_diff_staged.encode('utf-8', 'surrogateescape').decode('ISO-8859-1') + '\n') with open(osp.join(log_dir, "git_infos.txt"), "a") as f: f.write("directory: {}\n".format(directory)) f.write("git hash: {}\n".format(commit_hash)) f.write("git branch name: {}\n\n".format(branch_name)) if script_name is not None: with open(osp.join(log_dir, "script_name.txt"), "w") as f: f.write(script_name) return log_dir def dict_to_safe_json(d): """ Convert each value in the dictionary into a JSON'able primitive. :param d: :return: """ new_d = {} for key, item in d.items(): if safe_json(item): new_d[key] = item else: if isinstance(item, dict): new_d[key] = dict_to_safe_json(item) else: new_d[key] = str(item) return new_d def safe_json(data): if data is None: return True elif isinstance(data, (bool, int, float)): return True elif isinstance(data, (tuple, list)): return all(safe_json(x) for x in data) elif isinstance(data, dict): return all(isinstance(k, str) and safe_json(v) for k, v in data.items()) return False def set_seed(seed): """ Set the seed for all the possible random number generators. :param seed: :return: None """ seed = int(seed) random.seed(seed) np.random.seed(seed) def reset_execution_environment(): """ Call this between calls to separate experiments. :return: """ logger.reset() def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") """ Below is doodad-specific code """ ec2_okayed = False gpu_ec2_okayed = False first_sss_launch = True try: import doodad.mount as mount from doodad.utils import REPO_DIR CODE_MOUNTS = [ mount.MountLocal(local_dir=REPO_DIR, pythonpath=True, filter_dir=['rlkit_venv', 'data', 'environment']), ] for code_dir in config.CODE_DIRS_TO_MOUNT: CODE_MOUNTS.append(mount.MountLocal(local_dir=code_dir, pythonpath=True, filter_dir=['rlkit_venv', 'data', 'environment'])) NON_CODE_MOUNTS = [] for non_code_mapping in config.DIR_AND_MOUNT_POINT_MAPPINGS: NON_CODE_MOUNTS.append(mount.MountLocal(**non_code_mapping, filter_dir=['rlkit_venv', 'data', 'environment'])) SSS_CODE_MOUNTS = [] SSS_NON_CODE_MOUNTS = [] if hasattr(config, 'SSS_DIR_AND_MOUNT_POINT_MAPPINGS'): for non_code_mapping in config.SSS_DIR_AND_MOUNT_POINT_MAPPINGS: SSS_NON_CODE_MOUNTS.append(mount.MountLocal(**non_code_mapping, filter_dir=['rlkit_venv', 'data', 'environment'])) if hasattr(config, 'SSS_CODE_DIRS_TO_MOUNT'): for code_dir in config.SSS_CODE_DIRS_TO_MOUNT: SSS_CODE_MOUNTS.append( mount.MountLocal(local_dir=code_dir, pythonpath=True, filter_dir=['rlkit_venv', 'data', 'environment']) ) except ImportError: print("doodad not detected") target_mount = None def run_experiment( method_call, mode='local', exp_prefix='default', seed=None, variant=None, exp_id=0, prepend_date_to_exp_prefix=True, use_gpu=False, snapshot_mode='last', snapshot_gap=1, base_log_dir=None, local_input_dir_to_mount_point_dict=None, # TODO(vitchyr): test this # local settings skip_wait=False, # ec2 settings sync_interval=180, region='us-east-1', instance_type=None, spot_price=None, verbose=False, num_exps_per_instance=1, # sss settings time_in_mins=None, # ssh settings ssh_host=None, # gcp gcp_kwargs=None, ): """ Usage: ``` def foo(variant): x = variant['x'] y = variant['y'] logger.log("sum", x+y) variant = { 'x': 4, 'y': 3, } run_experiment(foo, variant, exp_prefix="my-experiment") ``` Results are saved to `base_log_dir/<date>-my-experiment/<date>-my-experiment-<unique-id>` By default, the base_log_dir is determined by `config.LOCAL_LOG_DIR/` :param method_call: a function that takes in a dictionary as argument :param mode: A string: - 'local' - 'local_docker' - 'ec2' - 'here_no_doodad': Run without doodad call :param exp_prefix: name of experiment :param seed: Seed for this specific trial. :param variant: Dictionary :param exp_id: One experiment = one variant setting + multiple seeds :param prepend_date_to_exp_prefix: If False, do not prepend the date to the experiment directory. :param use_gpu: :param snapshot_mode: See railrl.core.logging.logger :param snapshot_gap: See railrl.core.logging.logger :param base_log_dir: Will over :param sync_interval: How often to sync s3 data (in seconds). :param local_input_dir_to_mount_point_dict: Dictionary for doodad. :param ssh_host: the name of the host you want to ssh onto, should correspond to an entry in config.py of the following form: SSH_HOSTS=dict( ssh_host=dict( username='username', hostname='hostname/ip address', ) ) - if ssh_host is set to None, you will use ssh_host specified by config.SSH_DEFAULT_HOST :return: """ try: import doodad import doodad.mode import doodad.ssh except ImportError: print("Doodad not set up! Running experiment here.") mode = 'here_no_doodad' global ec2_okayed global gpu_ec2_okayed global target_mount global first_sss_launch """ Sanitize inputs as needed """ if seed is None: seed = random.randint(0, 100000) if variant is None: variant = {} if mode == 'ssh' and base_log_dir is None: base_log_dir = config.SSH_LOG_DIR if base_log_dir is None: if mode == 'sss': base_log_dir = config.SSS_LOG_DIR else: base_log_dir = config.LOCAL_LOG_DIR for key, value in ppp.recursive_items(variant): # This check isn't really necessary, but it's to prevent myself from # forgetting to pass a variant through dot_map_dict_to_nested_dict. if "." in key: raise Exception( "Variants should not have periods in keys. Did you mean to " "convert {} into a nested dictionary?".format(key) ) if prepend_date_to_exp_prefix: exp_prefix = time.strftime("%m-%d") + "-" + exp_prefix variant['seed'] = str(seed) variant['exp_id'] = str(exp_id) variant['exp_prefix'] = str(exp_prefix) variant['instance_type'] = str(instance_type) try: import git doodad_path = osp.abspath(osp.join( osp.dirname(doodad.__file__), os.pardir )) dirs = config.CODE_DIRS_TO_MOUNT + [doodad_path] git_infos = [] for directory in dirs: # Idk how to query these things, so I'm just doing try-catch try: repo = git.Repo(directory) try: branch_name = repo.active_branch.name except TypeError: branch_name = '[DETACHED]' git_infos.append(GitInfo( directory=directory, code_diff=repo.git.diff(None), code_diff_staged=repo.git.diff('--staged'), commit_hash=repo.head.commit.hexsha, branch_name=branch_name, )) except git.exc.InvalidGitRepositoryError: pass except (ImportError, UnboundLocalError): git_infos = None run_experiment_kwargs = dict( exp_prefix=exp_prefix, variant=variant, exp_id=exp_id, seed=seed, use_gpu=use_gpu, snapshot_mode=snapshot_mode, snapshot_gap=snapshot_gap, git_infos=git_infos, script_name=main.__file__, ) if mode == 'here_no_doodad': run_experiment_kwargs['base_log_dir'] = base_log_dir return run_experiment_here( method_call, **run_experiment_kwargs ) """ Safety Checks """ if mode == 'ec2' or mode == 'gcp': if not ec2_okayed and not query_yes_no( "{} costs money. Are you sure you want to run?".format(mode) ): sys.exit(1) if not gpu_ec2_okayed and use_gpu: if not query_yes_no( "{} is more expensive with GPUs. Confirm?".format(mode) ): sys.exit(1) gpu_ec2_okayed = True ec2_okayed = True """ GPU vs normal configs """ if use_gpu: docker_image = config.GPU_DOODAD_DOCKER_IMAGE if instance_type is None: instance_type = config.GPU_INSTANCE_TYPE else: assert instance_type[0] == 'g' if spot_price is None: spot_price = config.GPU_SPOT_PRICE else: docker_image = config.DOODAD_DOCKER_IMAGE if instance_type is None: instance_type = config.INSTANCE_TYPE if spot_price is None: spot_price = config.SPOT_PRICE if mode == 'sss': singularity_image = config.SSS_IMAGE elif mode in ['local_singularity', 'slurm_singularity']: singularity_image = config.SINGULARITY_IMAGE else: singularity_image = None """ Get the mode """ mode_kwargs = {} if use_gpu and mode == 'ec2': image_id = config.REGION_TO_GPU_AWS_IMAGE_ID[region] if region == 'us-east-1': avail_zone = config.REGION_TO_GPU_AWS_AVAIL_ZONE.get(region, "us-east-1b") mode_kwargs['extra_ec2_instance_kwargs'] = dict( Placement=dict( AvailabilityZone=avail_zone, ), ) else: image_id = None if hasattr(config, "AWS_S3_PATH"): aws_s3_path = config.AWS_S3_PATH else: aws_s3_path = None """ Create mode """ if mode == 'local': dmode = doodad.mode.Local(skip_wait=skip_wait) elif mode == 'local_docker': dmode = doodad.mode.LocalDocker( image=docker_image, gpu=use_gpu, ) elif mode == 'ssh': if ssh_host == None: ssh_dict = config.SSH_HOSTS[config.SSH_DEFAULT_HOST] else: ssh_dict = config.SSH_HOSTS[ssh_host] credentials = doodad.ssh.credentials.SSHCredentials( username=ssh_dict['username'], hostname=ssh_dict['hostname'], identity_file=config.SSH_PRIVATE_KEY ) dmode = doodad.mode.SSHDocker( credentials=credentials, image=docker_image, gpu=use_gpu, ) elif mode == 'local_singularity': dmode = doodad.mode.LocalSingularity( image=singularity_image, gpu=use_gpu, ) elif mode == 'slurm_singularity' or mode == 'sss': assert time_in_mins is not None, "Must approximate/set time in minutes" if use_gpu: kwargs = config.SLURM_GPU_CONFIG else: kwargs = config.SLURM_CPU_CONFIG if mode == 'slurm_singularity': dmode = doodad.mode.SlurmSingularity( image=singularity_image, gpu=use_gpu, time_in_mins=time_in_mins, skip_wait=skip_wait, pre_cmd=config.SINGULARITY_PRE_CMDS, **kwargs ) else: dmode = doodad.mode.ScriptSlurmSingularity( image=singularity_image, gpu=use_gpu, time_in_mins=time_in_mins, skip_wait=skip_wait, pre_cmd=config.SSS_PRE_CMDS, **kwargs ) elif mode == 'ec2': # Do this separately in case someone does not have EC2 configured dmode = doodad.mode.EC2AutoconfigDocker( image=docker_image, image_id=image_id, region=region, instance_type=instance_type, spot_price=spot_price, s3_log_prefix=exp_prefix, # Ask Vitchyr or Steven from an explanation, but basically we # will start just making the sub-directories within railrl rather # than relying on doodad to do that. s3_log_name="", gpu=use_gpu, aws_s3_path=aws_s3_path, num_exps=num_exps_per_instance, **mode_kwargs ) elif mode == 'gcp': image_name = config.GCP_IMAGE_NAME if use_gpu: image_name = config.GCP_GPU_IMAGE_NAME if gcp_kwargs is None: gcp_kwargs = {} config_kwargs = { **config.GCP_DEFAULT_KWARGS, **dict(image_name=image_name), **gcp_kwargs } dmode = doodad.mode.GCPDocker( image=docker_image, gpu=use_gpu, gcp_bucket_name=config.GCP_BUCKET_NAME, gcp_log_prefix=exp_prefix, gcp_log_name="", **config_kwargs ) else: raise NotImplementedError("Mode not supported: {}".format(mode)) """ Get the mounts """ mounts = create_mounts( base_log_dir=base_log_dir, mode=mode, sync_interval=sync_interval, local_input_dir_to_mount_point_dict=local_input_dir_to_mount_point_dict, ) """ Get the outputs """ launch_locally = None target = config.RUN_DOODAD_EXPERIMENT_SCRIPT_PATH if mode == 'ec2': # Ignored since I'm setting the snapshot dir directly base_log_dir_for_script = None run_experiment_kwargs['force_randomize_seed'] = True # The snapshot dir needs to be specified for S3 because S3 will # automatically create the experiment director and sub-directory. snapshot_dir_for_script = config.OUTPUT_DIR_FOR_DOODAD_TARGET elif mode == 'local': base_log_dir_for_script = base_log_dir # The snapshot dir will be automatically created snapshot_dir_for_script = None elif mode == 'local_docker': base_log_dir_for_script = config.OUTPUT_DIR_FOR_DOODAD_TARGET # The snapshot dir will be automatically created snapshot_dir_for_script = None elif mode == 'ssh': base_log_dir_for_script = config.OUTPUT_DIR_FOR_DOODAD_TARGET # The snapshot dir will be automatically created snapshot_dir_for_script = None elif mode in ['local_singularity', 'slurm_singularity', 'sss']: base_log_dir_for_script = base_log_dir # The snapshot dir will be automatically created snapshot_dir_for_script = None launch_locally = True if mode == 'sss': dmode.set_first_time(first_sss_launch) first_sss_launch = False target = config.SSS_RUN_DOODAD_EXPERIMENT_SCRIPT_PATH elif mode == 'here_no_doodad': base_log_dir_for_script = base_log_dir # The snapshot dir will be automatically created snapshot_dir_for_script = None elif mode == 'gcp': # Ignored since I'm setting the snapshot dir directly base_log_dir_for_script = None run_experiment_kwargs['force_randomize_seed'] = True snapshot_dir_for_script = config.OUTPUT_DIR_FOR_DOODAD_TARGET else: raise NotImplementedError("Mode not supported: {}".format(mode)) run_experiment_kwargs['base_log_dir'] = base_log_dir_for_script target_mount = doodad.launch_python( target=target, mode=dmode, mount_points=mounts, args={ 'method_call': method_call, 'output_dir': snapshot_dir_for_script, 'run_experiment_kwargs': run_experiment_kwargs, 'mode': mode, }, use_cloudpickle=True, target_mount=target_mount, verbose=verbose, launch_locally=launch_locally, ) def create_mounts( mode, base_log_dir, sync_interval=180, local_input_dir_to_mount_point_dict=None, ): if mode == 'sss': code_mounts = SSS_CODE_MOUNTS non_code_mounts = SSS_NON_CODE_MOUNTS else: code_mounts = CODE_MOUNTS non_code_mounts = NON_CODE_MOUNTS if local_input_dir_to_mount_point_dict is None: local_input_dir_to_mount_point_dict = {} else: raise NotImplementedError("TODO(vitchyr): Implement this") mounts = [m for m in code_mounts] for dir, mount_point in local_input_dir_to_mount_point_dict.items(): mounts.append(mount.MountLocal( local_dir=dir, mount_point=mount_point, pythonpath=False, )) if mode != 'local': for m in non_code_mounts: mounts.append(m) if mode == 'ec2': output_mount = mount.MountS3( s3_path='', mount_point=config.OUTPUT_DIR_FOR_DOODAD_TARGET, output=True, sync_interval=sync_interval, include_types=('*.txt', '*.csv', '*.json', '*.gz', '*.tar', '*.log', '*.pkl', '*.mp4', '*.png', '*.jpg', '*.jpeg', '*.patch'), ) elif mode == 'gcp': output_mount = mount.MountGCP( gcp_path='', mount_point=config.OUTPUT_DIR_FOR_DOODAD_TARGET, output=True, gcp_bucket_name=config.GCP_BUCKET_NAME, sync_interval=sync_interval, include_types=('*.txt', '*.csv', '*.json', '*.gz', '*.tar', '*.log', '*.pkl', '*.mp4', '*.png', '*.jpg', '*.jpeg', '*.patch'), ) elif mode in ['local', 'local_singularity', 'slurm_singularity', 'sss']: # To save directly to local files (singularity does this), skip mounting output_mount = mount.MountLocal( local_dir=base_log_dir, mount_point=None, output=True, ) elif mode == 'local_docker': output_mount = mount.MountLocal( local_dir=base_log_dir, mount_point=config.OUTPUT_DIR_FOR_DOODAD_TARGET, output=True, ) elif mode == 'ssh': output_mount = mount.MountLocal( local_dir=base_log_dir, mount_point=config.OUTPUT_DIR_FOR_DOODAD_TARGET, output=True, ) else: raise NotImplementedError("Mode not supported: {}".format(mode)) mounts.append(output_mount) return mounts
32.182927
131
0.606738
db0260ebb25ba911e0bbcfb919a461413c381038
12,186
py
Python
Episode09-Lives/Pygame/Shmup Tutorial-11.py
Inksaver/Shmup_With_Pygame_Love2D_Monogame
84838516d9dd9d6639b1b699dca546bfdfec73dc
[ "CC0-1.0" ]
1
2022-02-01T04:05:04.000Z
2022-02-01T04:05:04.000Z
Episode09-Lives/Pygame/Shmup Tutorial-11.py
Inksaver/Shmup_With_Pygame_Love2D_Monogame
84838516d9dd9d6639b1b699dca546bfdfec73dc
[ "CC0-1.0" ]
null
null
null
Episode09-Lives/Pygame/Shmup Tutorial-11.py
Inksaver/Shmup_With_Pygame_Love2D_Monogame
84838516d9dd9d6639b1b699dca546bfdfec73dc
[ "CC0-1.0" ]
null
null
null
''' Episode 11 https://www.youtube.com/watch?v=G5-4nV6LxgU Lives # Background music: Frozen Jam by tgfcoder <https://twitter.com/tgfcoder> licensed under CC-BY-3 ''' # import libraries import pygame, os, math, random import shared, player, mob, bullet, shield, explosion class data(): new_bullet_timer:float = 0 allow_new_bullet:bool = True background:object = None background_rect:object = None player_img:object = None meteor_img:object = None bullet_img:object = None shield_bar:object = None player_mini_img:object = None death_explosion = None die_snd_channel:object = None mobs:list = [] bullets:list = [] meteor_images = [] new_bullet_interval:float = 0.2 sounds:dict = {} explosion_anim:dict = {} explosions:list = [] def circle_collides(circle1:object, circle2:object) -> bool: # pygame.draw.circle(screen, (r,g,b), (x, y), R, w) #(r, g, b) is color, (x, y) is center, R is radius and w is the thickness of the circle border. # get distance between the circle's centers # use the Pythagorean Theorem to compute the distance distX = circle1.x - circle2.x distY = circle1.y - circle2.y distance = math.sqrt((distX * distX) + (distY * distY)) # if the distance is less than the sum of the circle's # radii, the circles are touching! r1 = circle1.radius r2 = circle2.radius if distance <= circle1.radius + circle2.radius: return True return False def collides(rect1:object, rect2:object) -> bool: ''' check whether rectangles are NOT colliding ''' if rect1.x > rect2.x + rect2.width or rect2.x > rect1.x + rect1.width: return False if rect1.y > rect2.y + rect2.height or rect2.y > rect1.y + rect1.height: return False return True def draw_lives(surf:object, x:int, y:int, lives:int, img:object) -> None: ''' draw up to 3 mini ships to represent lives left ''' for i in range(lives): img_rect = img.get_rect() img_rect.x = x + 30 * i img_rect.y = y surf.blit(img, img_rect) def process_events() -> (object, object, bool): ''' get keyboard input and check if user closed window ''' key_down = None quit = False for event in pygame.event.get(): # process events if event.type == pygame.QUIT: # close button clicked quit = True elif event.type == pygame.KEYDOWN: # single press of any key key_down = event.key keystate = pygame.key.get_pressed() # get keypressed events if keystate[pygame.K_ESCAPE]: # player pressing escape continuously quit = True return keystate, key_down, quit # usage: if key_down == pygame.K_RETURN:, if keystate[pygame.K_UP]: def check_mob_bullet_collisions(dt) -> None: ''' check if any bullets are colliding with any Mobs ''' for i in range(len(bullets) -1, -1, -1): destroy = False for j in range(len(mobs) -1, -1, -1): #destroy set to true if rectangles are colliding (bullet + Mob) try: #destroy = collides(bullets[i].get_rect() , mobs[j].get_rect()) destroy = circle_collides(bullets[i].get_circle(), mobs[j].get_circle()) except: pass if destroy: radius = mobs[j].get_circle().radius shared.score += 50 - radius # higher score for small meteor if shared.audio_present: sounds["shoot"].stop() sounds[random.choice(["expl1","expl2"])].play() bullets.pop() explosion_size = 'sm' if radius > 25: explosion_size = 'lg' explosions.append(explosion.Explosion(explosion_anim, mobs[j].get_rect().center, explosion_size)) mobs[j].reset() if len(bullets) == 0: break ''' update bullets ''' for i in range(len(bullets) - 1, -1, -1): if not bullets[i].update(dt): bullets.pop() def check_mob_player_collisions(keystate:object, dt:float) -> None: ''' check if mob hit player ''' if player.alive: player.update(keystate, dt) else: if data.death_explosion == None: if not data.die_snd_channel.get_busy(): shared.gamestate = shared.gamestates["quit"] for mob in mobs: mob.update(dt) ''' check if any mobs colliding with Player ''' if not player.hidden: #if collides(mob.get_rect(), player.rect): if circle_collides(mob.get_circle(), player.circle): mob.reset() player.shield -= mob.get_circle().radius # reduce player shield sounds['shoot'].stop() if player.shield <= 0: # shield gone player.lives -= 1 player.shield = 100 if shared.audio_present: sounds["die"].play() data.death_explosion = explosion.Explosion(explosion_anim, player.rect.center, 'player') if player.lives <= 0: player.alive = False else: player.hide() else: if shared.audio_present: sounds["expl3"].play() def shoot() -> None: ''' Create a new bullet at player's position ''' if data.allow_new_bullet and not player.hidden: if shared.audio_present: sounds["shoot"].stop() newBullet = bullet.Bullet(data.bullet_img, player.rect.centerx, player.rect.top) bullets.append(newBullet) data.new_bullet_timer = 0 data.allow_new_bullet = False if shared.audio_present: sounds["shoot"].play() def update_explosions(dt:float) -> None: ''' update explosions ''' for i in range(len(explosions) - 1, -1, -1): if not explosions[i].update(dt): explosions.pop() if data.death_explosion != None: if not data.death_explosion.update(dt): data.death_explosion = None def load_animations() -> None: ''' load explosion images and scale for second list ''' img_dir = os.path.join(shared.game_folder, "img") explosion_anim['lg'] = [] # large explosion empty list explosion_anim['sm'] = [] # small explosion empty list explosion_anim['player'] = [] # player explosion for i in range(9): filename = f'regularExplosion0{i}.png' # clever way of adding sequential filenames # could also use: filename = 'regularExplosion0' + str(i) + '.png' img = pygame.image.load(os.path.join(img_dir, filename)).convert() img.set_colorkey(shared.BLACK) img_lg = pygame.transform.scale(img, (75, 75)) # create large explosion list (modify sizes to suit) explosion_anim['lg'].append(img_lg) img_sm = pygame.transform.scale(img, (32, 32)) # create small explosion list explosion_anim['sm'].append(img_sm) img = pygame.image.load(os.path.join(img_dir, filename)).convert() img.set_colorkey(shared.BLACK) explosion_anim['player'].append(img) def load_images() -> None: img_dir = os.path.join(shared.game_folder, "img") data.background = pygame.image.load(os.path.join(img_dir, "starfield.png")).convert() data.background_rect = data.background.get_rect() data.player_img = pygame.image.load(os.path.join(img_dir, "playerShip1_orange.png")).convert() data.meteor_img = pygame.image.load(os.path.join(img_dir, "meteorBrown_med1.png")).convert() data.bullet_img = pygame.image.load(os.path.join(img_dir, "laserRed16.png")).convert() data.player_mini_img = pygame.transform.scale(data.player_img,(25, 19)) data.player_mini_img.set_colorkey(shared.BLACK) meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med3.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(os.path.join(img_dir, img)).convert()) def load_audio() -> None: if shared.audio_present: snd_dir = os.path.join(shared.game_folder, "snd") sounds.update( {"shoot" : pygame.mixer.Sound(os.path.join(snd_dir,'Laser_Shoot6.wav')), "shield": pygame.mixer.Sound(os.path.join(snd_dir,'pow4.wav')), "power" : pygame.mixer.Sound(os.path.join(snd_dir,'pow5.wav')), "die" : pygame.mixer.Sound(os.path.join(snd_dir,'rumble1.ogg')), "expl1" : pygame.mixer.Sound(os.path.join(snd_dir,'expl3.wav')), "expl2" : pygame.mixer.Sound(os.path.join(snd_dir,'expl6.wav')), "expl3" : pygame.mixer.Sound(os.path.join(snd_dir,'Explosion5.wav')) }) ''' get more control over the die_sound effect If more channels needed, eg 16: (8 is the default) pygame.mixer.set_num_channels(16) use any channel, 7 chosen here: ''' data.die_snd_channel = pygame.mixer.Channel(7) # load background music pygame.mixer.music.load(os.path.join(snd_dir, 'FrozenJam.ogg')) # reduce volume for key in sounds: sounds[key].set_volume(0.2) pygame.mixer.music.set_volume(0.2) pygame.mixer.music.play(loops = -1) # start background music if loaded def load() -> None: ''' Setup pygame ''' shared.game_folder = os.getcwd() # current directory os.environ["SDL_VIDEO_CENTERED"] = "1" # Centre the Pygame window on screen pygame.init() # initialise pygame and game window try: pygame.mixer.init() # start pygame sound library except: shared.audio_present = False # audio driver not installed shared.screen = pygame.display.set_mode((shared.WIDTH, shared.HEIGHT)) pygame.display.set_caption(shared.window_title) # The window title shared.clock = pygame.time.Clock() # Keep track of framerate etc ''' Load all game assets ''' shared.debug = False load_images() load_audio() load_animations() player.init(data.player_img, 500, 0.5) for i in range(8): # make 8 mobs mobs.append(mob.Mob(meteor_images)) shared.score = 0 data.shield_bar = shield.Shield(5, 5, shared.WHITE, shared.GREEN) def update() -> None: ''' Update all game items and keyboard input delta-time used in Love2D and Monogame is measured in seconds Can be obtained from clock.tick() in ms ''' dt = shared.clock.tick(shared.FPS) / 1000 # update clock. dt can be passed to other update functions data.new_bullet_timer += dt if data.new_bullet_timer >= new_bullet_interval: data.allow_new_bullet = True data.new_bullet_timer = 0 keystate, key_down, quit = process_events() # get keypressed, keydown and close/esc user choice if quit: shared.gamestate = shared.gamestates["quit"] # set gamestate to quit else: if shared.gamestate == shared.gamestates["play"]: if key_down == pygame.K_SPACE or keystate[pygame.K_SPACE]: shoot() check_mob_player_collisions(keystate, dt) update_explosions(dt) check_mob_bullet_collisions(dt) data.shield_bar.update(player.shield) def draw() -> None: ''' Draw background and all active sprites ''' shared.screen.fill(shared.BLACK) # make screen black shared.screen.blit(data.background, data.background_rect) if shared.gamestate == shared.gamestates["play"]: if data.death_explosion == None: player.draw() else: data.death_explosion.draw() for mob in mobs: mob.draw() for bullet in bullets: bullet.draw() for explosion in explosions: explosion.draw() draw_lives(shared.screen, shared.WIDTH - 100, 5, player.lives, data.player_mini_img) #draw the score # draw_text(screen:object, text:str, size:int, x:int, y:int, align:str = 'centre', colour:tuple = WHITE) shared.draw_text(shared.screen, str(shared.score), 18, shared.WIDTH / 2, 10) data.shield_bar.draw() # draw shield bar if shared.debug: shared.draw_text(shared.screen, "Debug mode", 18, 10, shared.HEIGHT - 24, "left", shared.YELLOW) pygame.display.flip() # flip display to make it visible def main() -> None: ''' Run game loop and call other functions from here ''' shared.WIDTH = 480 # default screen width: alter as required shared.HEIGHT = 600 # default screen height: alter as required shared.window_title = "Shmup!" # default window title: change as required load() # setup window and game assets ''' gameloop ''' shared.gamestate = shared.gamestates["play"] # gamestate starting at 1 ('play': no menu) while shared.gamestate < shared.gamestates["quit"]: # 3 = quit update() # go through update functions draw() # go through draw functions pygame.quit() main()
38.08125
149
0.671919
24be67b734e19fa6d0f8fecf16d019b3ff634c00
3,237
py
Python
Talk/config/models.py
huqingsong/typeidea
9ac7c5547520f17f7747d36fc34468cd704f2f92
[ "MIT" ]
null
null
null
Talk/config/models.py
huqingsong/typeidea
9ac7c5547520f17f7747d36fc34468cd704f2f92
[ "MIT" ]
null
null
null
Talk/config/models.py
huqingsong/typeidea
9ac7c5547520f17f7747d36fc34468cd704f2f92
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import User from django.template.loader import render_to_string # Create your models here. class Link(models.Model): STATUS_NORMAL = 1 STATUS_DELETE = 0 STATUS_ITEMS = ( (STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'), ) title = models.CharField(max_length=50, verbose_name="标题") href = models.URLField(verbose_name="链接") # 默认长度200 status = models.PositiveIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态") weight = models.PositiveIntegerField(default=1, choices=zip(range(1, 6), range(1, 6)), verbose_name="权重", help_text="权重高展示顺序靠前") owner = models.ForeignKey(User, verbose_name="作者", on_delete=models.DO_NOTHING) created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") class Meta: verbose_name = verbose_name_plural = "友链" ordering = ['-weight', ] def __str__(self): return self.title class SideBar(models.Model): """ 侧边栏 """ STATUS_SHOW = 1 STATUS_HIDE = 0 STATUS_ITEMS = ( (STATUS_SHOW, '展示'), (STATUS_HIDE, '隐藏'), ) DISPLAY_HTML = 1 DISPLAY_LATEST = 2 DISPLAY_HOT = 3 DISPLAY_COMMENT = 4 SIDE_TYPE = ( (DISPLAY_HTML, 'HTML'), (DISPLAY_LATEST, '最新文章'), (DISPLAY_HOT, '最热文章'), (DISPLAY_COMMENT, '最近评论'), ) title = models.CharField(max_length=50, verbose_name="标题") display_type = models.PositiveIntegerField(default=1, choices=SIDE_TYPE, verbose_name="展示类型") content = models.CharField(max_length=500, blank=True, verbose_name="内容", help_text="如果设置的不是HTML类型,可为空") status = models.PositiveIntegerField(default=STATUS_SHOW, choices=STATUS_ITEMS, verbose_name="状态") owner = models.ForeignKey(User, verbose_name="作者", on_delete=models.DO_NOTHING) created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") class Meta: verbose_name = verbose_name_plural = "侧边栏" def __str__(self): return self.title def _render_latest(self): pass def content_html(self): """ 通过直接渲染模板 """ from blog.models import Post # 避免循环引用 from comment.models import Comment result = '' if self.display_type == self.DISPLAY_HTML: result = self.content elif self.display_type == self.DISPLAY_LATEST: context = { 'posts': Post.latest_posts() } result = render_to_string('config/blocks/sidebar_posts.html', context) elif self.display_type == self.DISPLAY_HOT: context = { 'posts': Post.hot_posts() } result = render_to_string('config/blocks/sidebar_posts.html', context) elif self.display_type == self.DISPLAY_COMMENT: context = { 'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL) } result = render_to_string('config/blocks/sidebar_comments.html', context) return result
34.806452
104
0.614458
be5407ccc64b3c3eb8f4a30be8b1af67d9e09376
58,661
py
Python
tests/language/test_visitor.py
dfee/graphql-core-next
1ada7146bd0510171ae931b68f6c77dbdf5d5c63
[ "MIT" ]
null
null
null
tests/language/test_visitor.py
dfee/graphql-core-next
1ada7146bd0510171ae931b68f6c77dbdf5d5c63
[ "MIT" ]
null
null
null
tests/language/test_visitor.py
dfee/graphql-core-next
1ada7146bd0510171ae931b68f6c77dbdf5d5c63
[ "MIT" ]
null
null
null
from copy import copy from pytest import fail from graphql.language import ( Node, FieldNode, NameNode, SelectionSetNode, parse, print_ast, visit, BREAK, REMOVE, SKIP, ParallelVisitor, TypeInfoVisitor, Visitor) from graphql.type import get_named_type, is_composite_type from graphql.utilities import TypeInfo from ..validation.harness import test_schema # noinspection PyUnresolvedReferences from . import kitchen_sink # noqa: F401 def get_node_by_path(ast, path): result = ast for key in path: if isinstance(key, int): assert isinstance(result, list) try: result = result[key] except IndexError: fail(f'invalid index {key} in node list {result}') elif isinstance(key, str): assert isinstance(result, Node) try: result = getattr(result, key) except AttributeError: fail(f'invalid key {key} in node {result}') else: fail(f'invalid key {key!r} in path {path}') return result def check_visitor_fn_args( ast, node, key, parent, path, ancestors, is_edited=False): assert isinstance(node, Node) is_root = key is None if is_root: if not is_edited: assert node is ast assert parent is None assert path == [] assert ancestors == [] return assert isinstance(key, (int, str)) assert get_node_by_path(parent, [key]) is not None assert isinstance(path, list) assert path[-1] == key assert isinstance(ancestors, list) assert len(ancestors) == len(path) - 1 if not is_edited: assert get_node_by_path(parent, [key]) is node assert get_node_by_path(ast, path) is node for i, ancestor in enumerate(ancestors): ancestor_path = path[:i] assert ancestor == get_node_by_path(ast, ancestor_path) def describe_visitor(): def validates_path_argument(): ast = parse('{ a }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) visited.append(['enter', *args[3]]) def leave(self, *args): check_visitor_fn_args(ast, *args) visited.append(['leave', *args[3]]) visit(ast, TestVisitor()) assert visited == [ ['enter'], ['enter', 'definitions', 0], ['enter', 'definitions', 0, 'selection_set'], ['enter', 'definitions', 0, 'selection_set', 'selections', 0], ['enter', 'definitions', 0, 'selection_set', 'selections', 0, 'name'], ['leave', 'definitions', 0, 'selection_set', 'selections', 0, 'name'], ['leave', 'definitions', 0, 'selection_set', 'selections', 0], ['leave', 'definitions', 0, 'selection_set'], ['leave', 'definitions', 0], ['leave']] def validates_ancestors_argument(): ast = parse('{ a }', no_location=True) visited_nodes = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, node, key, parent, path, ancestors): in_array = isinstance(key, int) if in_array: visited_nodes.append(parent) visited_nodes.append(node) expected_ancestors = visited_nodes[0:-2] assert ancestors == expected_ancestors def leave(self, node, key, parent, path, ancestors): expected_ancestors = visited_nodes[0:-2] assert ancestors == expected_ancestors in_array = isinstance(key, int) if in_array: visited_nodes.pop() visited_nodes.pop() visit(ast, TestVisitor()) def allows_editing_a_node_both_on_enter_and_on_leave(): ast = parse('{ a, b, c { a, b, c } }', no_location=True) visited = [] class TestVisitor(Visitor): selection_set = None def enter_operation_definition(self, *args): check_visitor_fn_args(ast, *args) node = copy(args[0]) assert len(node.selection_set.selections) == 3 self.selection_set = node.selection_set node.selection_set = SelectionSetNode(selections=[]) visited.append('enter') return node def leave_operation_definition(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = copy(args[0]) assert not node.selection_set.selections node.selection_set = self.selection_set visited.append('leave') return node edited_ast = visit(ast, TestVisitor()) assert edited_ast == ast assert visited == ['enter', 'leave'] def allows_for_editing_on_enter(): ast = parse('{ a, b, c { a, b, c } }', no_location=True) # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] if isinstance(node, FieldNode) and node.name.value == 'b': return REMOVE edited_ast = visit(ast, TestVisitor()) assert ast == parse('{ a, b, c { a, b, c } }', no_location=True) assert edited_ast == parse('{ a, c { a, c } }', no_location=True) def allows_for_editing_on_leave(): ast = parse('{ a, b, c { a, b, c } }', no_location=True) # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def leave(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = args[0] if isinstance(node, FieldNode) and node.name.value == 'b': return REMOVE edited_ast = visit(ast, TestVisitor()) assert ast == parse('{ a, b, c { a, b, c } }', no_location=True) assert edited_ast == parse('{ a, c { a, c } }', no_location=True) def visits_edited_node(): ast = parse('{ a { x } }', no_location=True) added_field = FieldNode(name=NameNode(value='__typename')) class TestVisitor(Visitor): did_visit_added_field = False def enter(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = args[0] if isinstance(node, FieldNode) and node.name.value == 'a': node = copy(node) # noinspection PyTypeChecker node.selection_set.selections = [ added_field] + node.selection_set.selections return node if node == added_field: self.did_visit_added_field = True visitor = TestVisitor() visit(ast, visitor) assert visitor.did_visit_added_field def allows_skipping_a_sub_tree(): ast = parse('{ a, b { x }, c }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) if kind == 'field' and node.name.value == 'b': return SKIP def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, TestVisitor()) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'operation_definition', None], ['leave', 'document', None]] def allows_early_exit_while_visiting(): ast = parse('{ a, b { x }, c }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) if kind == 'name' and node.value == 'x': return BREAK def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, TestVisitor()) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'x']] def allows_early_exit_while_leaving(): ast = parse('{ a, b { x }, c }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) if kind == 'name' and node.value == 'x': return BREAK visit(ast, TestVisitor()) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'x'], ['leave', 'name', 'x']] def allows_a_named_functions_visitor_api(): ast = parse('{ a, b { x }, c }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter_name(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def enter_selection_set(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave_selection_set(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, TestVisitor()) assert visited == [ ['enter', 'selection_set', None], ['enter', 'name', 'a'], ['enter', 'name', 'b'], ['enter', 'selection_set', None], ['enter', 'name', 'x'], ['leave', 'selection_set', None], ['enter', 'name', 'c'], ['leave', 'selection_set', None]] def experimental_visits_variables_defined_in_fragments(): ast = parse('fragment a($v: Boolean = false) on t { f }', no_location=True, experimental_fragment_variables=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, TestVisitor()) assert visited == [ ['enter', 'document', None], ['enter', 'fragment_definition', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['enter', 'variable_definition', None], ['enter', 'variable', None], ['enter', 'name', 'v'], ['leave', 'name', 'v'], ['leave', 'variable', None], ['enter', 'named_type', None], ['enter', 'name', 'Boolean'], ['leave', 'name', 'Boolean'], ['leave', 'named_type', None], ['enter', 'boolean_value', False], ['leave', 'boolean_value', False], ['leave', 'variable_definition', None], ['enter', 'named_type', None], ['enter', 'name', 't'], ['leave', 'name', 't'], ['leave', 'named_type', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'f'], ['leave', 'name', 'f'], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'fragment_definition', None], ['leave', 'document', None]] # noinspection PyShadowingNames def visits_kitchen_sink(kitchen_sink): # noqa: F811 ast = parse(kitchen_sink) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node, key, parent = args[:3] parent_kind = parent.kind if isinstance(parent, Node) else None visited.append(['enter', node.kind, key, parent_kind]) def leave(self, *args): check_visitor_fn_args(ast, *args) node, key, parent = args[:3] parent_kind = parent.kind if isinstance(parent, Node) else None visited.append(['leave', node.kind, key, parent_kind]) visit(ast, TestVisitor()) assert visited == [ ['enter', 'document', None, None], ['enter', 'operation_definition', 0, None], ['enter', 'name', 'name', 'operation_definition'], ['leave', 'name', 'name', 'operation_definition'], ['enter', 'variable_definition', 0, None], ['enter', 'variable', 'variable', 'variable_definition'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'variable', 'variable_definition'], ['enter', 'named_type', 'type', 'variable_definition'], ['enter', 'name', 'name', 'named_type'], ['leave', 'name', 'name', 'named_type'], ['leave', 'named_type', 'type', 'variable_definition'], ['leave', 'variable_definition', 0, None], ['enter', 'variable_definition', 1, None], ['enter', 'variable', 'variable', 'variable_definition'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'variable', 'variable_definition'], ['enter', 'named_type', 'type', 'variable_definition'], ['enter', 'name', 'name', 'named_type'], ['leave', 'name', 'name', 'named_type'], ['leave', 'named_type', 'type', 'variable_definition'], ['enter', 'enum_value', 'default_value', 'variable_definition'], ['leave', 'enum_value', 'default_value', 'variable_definition'], ['leave', 'variable_definition', 1, None], ['enter', 'selection_set', 'selection_set', 'operation_definition'], ['enter', 'field', 0, None], ['enter', 'name', 'alias', 'field'], ['leave', 'name', 'alias', 'field'], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'list_value', 'value', 'argument'], ['enter', 'int_value', 0, None], ['leave', 'int_value', 0, None], ['enter', 'int_value', 1, None], ['leave', 'int_value', 1, None], ['leave', 'list_value', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['enter', 'inline_fragment', 1, None], ['enter', 'named_type', 'type_condition', 'inline_fragment'], ['enter', 'name', 'name', 'named_type'], ['leave', 'name', 'name', 'named_type'], ['leave', 'named_type', 'type_condition', 'inline_fragment'], ['enter', 'directive', 0, None], ['enter', 'name', 'name', 'directive'], ['leave', 'name', 'name', 'directive'], ['leave', 'directive', 0, None], ['enter', 'selection_set', 'selection_set', 'inline_fragment'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['enter', 'field', 1, None], ['enter', 'name', 'alias', 'field'], ['leave', 'name', 'alias', 'field'], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'int_value', 'value', 'argument'], ['leave', 'int_value', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'argument', 1, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 1, None], ['enter', 'directive', 0, None], ['enter', 'name', 'name', 'directive'], ['leave', 'name', 'name', 'directive'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 0, None], ['leave', 'directive', 0, None], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['enter', 'fragment_spread', 1, None], ['enter', 'name', 'name', 'fragment_spread'], ['leave', 'name', 'name', 'fragment_spread'], ['leave', 'fragment_spread', 1, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 1, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'inline_fragment'], ['leave', 'inline_fragment', 1, None], ['enter', 'inline_fragment', 2, None], ['enter', 'directive', 0, None], ['enter', 'name', 'name', 'directive'], ['leave', 'name', 'name', 'directive'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 0, None], ['leave', 'directive', 0, None], ['enter', 'selection_set', 'selection_set', 'inline_fragment'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'inline_fragment'], ['leave', 'inline_fragment', 2, None], ['enter', 'inline_fragment', 3, None], ['enter', 'selection_set', 'selection_set', 'inline_fragment'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'inline_fragment'], ['leave', 'inline_fragment', 3, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'operation_definition'], ['leave', 'operation_definition', 0, None], ['enter', 'operation_definition', 1, None], ['enter', 'name', 'name', 'operation_definition'], ['leave', 'name', 'name', 'operation_definition'], ['enter', 'selection_set', 'selection_set', 'operation_definition'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'int_value', 'value', 'argument'], ['leave', 'int_value', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'directive', 0, None], ['enter', 'name', 'name', 'directive'], ['leave', 'name', 'name', 'directive'], ['leave', 'directive', 0, None], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'operation_definition'], ['leave', 'operation_definition', 1, None], ['enter', 'operation_definition', 2, None], ['enter', 'name', 'name', 'operation_definition'], ['leave', 'name', 'name', 'operation_definition'], ['enter', 'variable_definition', 0, None], ['enter', 'variable', 'variable', 'variable_definition'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'variable', 'variable_definition'], ['enter', 'named_type', 'type', 'variable_definition'], ['enter', 'name', 'name', 'named_type'], ['leave', 'name', 'name', 'named_type'], ['leave', 'named_type', 'type', 'variable_definition'], ['leave', 'variable_definition', 0, None], ['enter', 'selection_set', 'selection_set', 'operation_definition'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['enter', 'field', 1, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'selection_set', 'selection_set', 'field'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 1, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'field'], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'operation_definition'], ['leave', 'operation_definition', 2, None], ['enter', 'fragment_definition', 3, None], ['enter', 'name', 'name', 'fragment_definition'], ['leave', 'name', 'name', 'fragment_definition'], ['enter', 'named_type', 'type_condition', 'fragment_definition'], ['enter', 'name', 'name', 'named_type'], ['leave', 'name', 'name', 'named_type'], ['leave', 'named_type', 'type_condition', 'fragment_definition'], ['enter', 'selection_set', 'selection_set', 'fragment_definition'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'argument', 1, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'variable', 'value', 'argument'], ['enter', 'name', 'name', 'variable'], ['leave', 'name', 'name', 'variable'], ['leave', 'variable', 'value', 'argument'], ['leave', 'argument', 1, None], ['enter', 'argument', 2, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'object_value', 'value', 'argument'], ['enter', 'object_field', 0, None], ['enter', 'name', 'name', 'object_field'], ['leave', 'name', 'name', 'object_field'], ['enter', 'string_value', 'value', 'object_field'], ['leave', 'string_value', 'value', 'object_field'], ['leave', 'object_field', 0, None], ['enter', 'object_field', 1, None], ['enter', 'name', 'name', 'object_field'], ['leave', 'name', 'name', 'object_field'], ['enter', 'string_value', 'value', 'object_field'], ['leave', 'string_value', 'value', 'object_field'], ['leave', 'object_field', 1, None], ['leave', 'object_value', 'value', 'argument'], ['leave', 'argument', 2, None], ['leave', 'field', 0, None], ['leave', 'selection_set', 'selection_set', 'fragment_definition'], ['leave', 'fragment_definition', 3, None], ['enter', 'operation_definition', 4, None], ['enter', 'selection_set', 'selection_set', 'operation_definition'], ['enter', 'field', 0, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['enter', 'argument', 0, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'boolean_value', 'value', 'argument'], ['leave', 'boolean_value', 'value', 'argument'], ['leave', 'argument', 0, None], ['enter', 'argument', 1, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'boolean_value', 'value', 'argument'], ['leave', 'boolean_value', 'value', 'argument'], ['leave', 'argument', 1, None], ['enter', 'argument', 2, None], ['enter', 'name', 'name', 'argument'], ['leave', 'name', 'name', 'argument'], ['enter', 'null_value', 'value', 'argument'], ['leave', 'null_value', 'value', 'argument'], ['leave', 'argument', 2, None], ['leave', 'field', 0, None], ['enter', 'field', 1, None], ['enter', 'name', 'name', 'field'], ['leave', 'name', 'name', 'field'], ['leave', 'field', 1, None], ['leave', 'selection_set', 'selection_set', 'operation_definition'], ['leave', 'operation_definition', 4, None], ['leave', 'document', None, None]] def describe_visit_in_parallel(): def allows_skipping_a_sub_tree(): # Note: nearly identical to the above test but using ParallelVisitor ast = parse('{ a, b { x }, c }') visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) if kind == 'field' and node.name.value == 'b': return SKIP def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, ParallelVisitor([TestVisitor()])) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'operation_definition', None], ['leave', 'document', None]] def allows_skipping_different_sub_trees(): ast = parse('{ a { x }, b { y} }') visited = [] class TestVisitor(Visitor): def __init__(self, name): self.name = name def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'no-{name}', 'enter', kind, value]) if kind == 'field' and node.name.value == name: return SKIP def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'no-{name}', 'leave', kind, value]) visit(ast, ParallelVisitor([TestVisitor('a'), TestVisitor('b')])) assert visited == [ ['no-a', 'enter', 'document', None], ['no-b', 'enter', 'document', None], ['no-a', 'enter', 'operation_definition', None], ['no-b', 'enter', 'operation_definition', None], ['no-a', 'enter', 'selection_set', None], ['no-b', 'enter', 'selection_set', None], ['no-a', 'enter', 'field', None], ['no-b', 'enter', 'field', None], ['no-b', 'enter', 'name', 'a'], ['no-b', 'leave', 'name', 'a'], ['no-b', 'enter', 'selection_set', None], ['no-b', 'enter', 'field', None], ['no-b', 'enter', 'name', 'x'], ['no-b', 'leave', 'name', 'x'], ['no-b', 'leave', 'field', None], ['no-b', 'leave', 'selection_set', None], ['no-b', 'leave', 'field', None], ['no-a', 'enter', 'field', None], ['no-b', 'enter', 'field', None], ['no-a', 'enter', 'name', 'b'], ['no-a', 'leave', 'name', 'b'], ['no-a', 'enter', 'selection_set', None], ['no-a', 'enter', 'field', None], ['no-a', 'enter', 'name', 'y'], ['no-a', 'leave', 'name', 'y'], ['no-a', 'leave', 'field', None], ['no-a', 'leave', 'selection_set', None], ['no-a', 'leave', 'field', None], ['no-a', 'leave', 'selection_set', None], ['no-b', 'leave', 'selection_set', None], ['no-a', 'leave', 'operation_definition', None], ['no-b', 'leave', 'operation_definition', None], ['no-a', 'leave', 'document', None], ['no-b', 'leave', 'document', None]] def allows_early_exit_while_visiting(): # Note: nearly identical to the above test but using ParallelVisitor. ast = parse('{ a, b { x }, c }') visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) if kind == 'name' and node.value == 'x': return BREAK def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) visit(ast, ParallelVisitor([TestVisitor()])) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'x']] def allows_early_exit_from_different_points(): ast = parse('{ a { y }, b { x } }') visited = [] class TestVisitor(Visitor): def __init__(self, name): self.name = name def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'break-{name}', 'enter', kind, value]) if kind == 'name' and node.value == name: return BREAK def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'break-{name}', 'leave', kind, value]) visit(ast, ParallelVisitor([TestVisitor('a'), TestVisitor('b')])) assert visited == [ ['break-a', 'enter', 'document', None], ['break-b', 'enter', 'document', None], ['break-a', 'enter', 'operation_definition', None], ['break-b', 'enter', 'operation_definition', None], ['break-a', 'enter', 'selection_set', None], ['break-b', 'enter', 'selection_set', None], ['break-a', 'enter', 'field', None], ['break-b', 'enter', 'field', None], ['break-a', 'enter', 'name', 'a'], ['break-b', 'enter', 'name', 'a'], ['break-b', 'leave', 'name', 'a'], ['break-b', 'enter', 'selection_set', None], ['break-b', 'enter', 'field', None], ['break-b', 'enter', 'name', 'y'], ['break-b', 'leave', 'name', 'y'], ['break-b', 'leave', 'field', None], ['break-b', 'leave', 'selection_set', None], ['break-b', 'leave', 'field', None], ['break-b', 'enter', 'field', None], ['break-b', 'enter', 'name', 'b']] def allows_early_exit_while_leaving(): # Note: nearly identical to the above test but using ParallelVisitor. ast = parse('{ a, b { x }, c }') visited = [] # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) if kind == 'name' and node.value == 'x': return BREAK visit(ast, ParallelVisitor([TestVisitor()])) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'x'], ['leave', 'name', 'x']] def allows_early_exit_from_leaving_different_points(): ast = parse('{ a { y }, b { x } }') visited = [] class TestVisitor(Visitor): def __init__(self, name): self.name = name def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'break-{name}', 'enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) name = self.name visited.append([f'break-{name}', 'leave', kind, value]) if kind == 'field' and node.name.value == name: return BREAK visit(ast, ParallelVisitor([TestVisitor('a'), TestVisitor('b')])) assert visited == [ ['break-a', 'enter', 'document', None], ['break-b', 'enter', 'document', None], ['break-a', 'enter', 'operation_definition', None], ['break-b', 'enter', 'operation_definition', None], ['break-a', 'enter', 'selection_set', None], ['break-b', 'enter', 'selection_set', None], ['break-a', 'enter', 'field', None], ['break-b', 'enter', 'field', None], ['break-a', 'enter', 'name', 'a'], ['break-b', 'enter', 'name', 'a'], ['break-a', 'leave', 'name', 'a'], ['break-b', 'leave', 'name', 'a'], ['break-a', 'enter', 'selection_set', None], ['break-b', 'enter', 'selection_set', None], ['break-a', 'enter', 'field', None], ['break-b', 'enter', 'field', None], ['break-a', 'enter', 'name', 'y'], ['break-b', 'enter', 'name', 'y'], ['break-a', 'leave', 'name', 'y'], ['break-b', 'leave', 'name', 'y'], ['break-a', 'leave', 'field', None], ['break-b', 'leave', 'field', None], ['break-a', 'leave', 'selection_set', None], ['break-b', 'leave', 'selection_set', None], ['break-a', 'leave', 'field', None], ['break-b', 'leave', 'field', None], ['break-b', 'enter', 'field', None], ['break-b', 'enter', 'name', 'b'], ['break-b', 'leave', 'name', 'b'], ['break-b', 'enter', 'selection_set', None], ['break-b', 'enter', 'field', None], ['break-b', 'enter', 'name', 'x'], ['break-b', 'leave', 'name', 'x'], ['break-b', 'leave', 'field', None], ['break-b', 'leave', 'selection_set', None], ['break-b', 'leave', 'field', None]] def allows_for_editing_on_enter(): ast = parse('{ a, b, c { a, b, c } }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor1(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] if node.kind == 'field' and node.name.value == 'b': return REMOVE # noinspection PyMethodMayBeStatic class TestVisitor2(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) edited_ast = visit( ast, ParallelVisitor([TestVisitor1(), TestVisitor2()])) assert ast == parse('{ a, b, c { a, b, c } }', no_location=True) assert edited_ast == parse('{ a, c { a, c } }', no_location=True) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'operation_definition', None], ['leave', 'document', None]] def allows_for_editing_on_leave(): ast = parse('{ a, b, c { a, b, c } }', no_location=True) visited = [] # noinspection PyMethodMayBeStatic class TestVisitor1(Visitor): def leave(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = args[0] if node.kind == 'field' and node.name.value == 'b': return REMOVE # noinspection PyMethodMayBeStatic class TestVisitor2(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['enter', kind, value]) def leave(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) node = args[0] kind, value = node.kind, getattr(node, 'value', None) visited.append(['leave', kind, value]) edited_ast = visit( ast, ParallelVisitor([TestVisitor1(), TestVisitor2()])) assert ast == parse('{ a, b, c { a, b, c } }', no_location=True) assert edited_ast == parse('{ a, c { a, c } }', no_location=True) assert visited == [ ['enter', 'document', None], ['enter', 'operation_definition', None], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['enter', 'selection_set', None], ['enter', 'field', None], ['enter', 'name', 'a'], ['leave', 'name', 'a'], ['leave', 'field', None], ['enter', 'field', None], ['enter', 'name', 'b'], ['leave', 'name', 'b'], ['enter', 'field', None], ['enter', 'name', 'c'], ['leave', 'name', 'c'], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'field', None], ['leave', 'selection_set', None], ['leave', 'operation_definition', None], ['leave', 'document', None]] def describe_visit_with_type_info(): def maintains_type_info_during_visit(): visited = [] ast = parse( '{ human(id: 4) { name, pets { ... { name } }, unknown } }') type_info = TypeInfo(test_schema) # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args) parent_type = type_info.get_parent_type() type_ = type_info.get_type() input_type = type_info.get_input_type() node = args[0] visited.append([ 'enter', node.kind, node.value if node.kind == 'name' else None, str(parent_type) if parent_type else None, str(type_) if type_ else None, str(input_type) if input_type else None]) def leave(self, *args): check_visitor_fn_args(ast, *args) parent_type = type_info.get_parent_type() type_ = type_info.get_type() input_type = type_info.get_input_type() node = args[0] visited.append([ 'leave', node.kind, node.value if node.kind == 'name' else None, str(parent_type) if parent_type else None, str(type_) if type_ else None, str(input_type) if input_type else None]) visit(ast, TypeInfoVisitor(type_info, TestVisitor())) assert visited == [ ['enter', 'document', None, None, None, None], ['enter', 'operation_definition', None, None, 'QueryRoot', None], ['enter', 'selection_set', None, 'QueryRoot', 'QueryRoot', None], ['enter', 'field', None, 'QueryRoot', 'Human', None], ['enter', 'name', 'human', 'QueryRoot', 'Human', None], ['leave', 'name', 'human', 'QueryRoot', 'Human', None], ['enter', 'argument', None, 'QueryRoot', 'Human', 'ID'], ['enter', 'name', 'id', 'QueryRoot', 'Human', 'ID'], ['leave', 'name', 'id', 'QueryRoot', 'Human', 'ID'], ['enter', 'int_value', None, 'QueryRoot', 'Human', 'ID'], ['leave', 'int_value', None, 'QueryRoot', 'Human', 'ID'], ['leave', 'argument', None, 'QueryRoot', 'Human', 'ID'], ['enter', 'selection_set', None, 'Human', 'Human', None], ['enter', 'field', None, 'Human', 'String', None], ['enter', 'name', 'name', 'Human', 'String', None], ['leave', 'name', 'name', 'Human', 'String', None], ['leave', 'field', None, 'Human', 'String', None], ['enter', 'field', None, 'Human', '[Pet]', None], ['enter', 'name', 'pets', 'Human', '[Pet]', None], ['leave', 'name', 'pets', 'Human', '[Pet]', None], ['enter', 'selection_set', None, 'Pet', '[Pet]', None], ['enter', 'inline_fragment', None, 'Pet', 'Pet', None], ['enter', 'selection_set', None, 'Pet', 'Pet', None], ['enter', 'field', None, 'Pet', 'String', None], ['enter', 'name', 'name', 'Pet', 'String', None], ['leave', 'name', 'name', 'Pet', 'String', None], ['leave', 'field', None, 'Pet', 'String', None], ['leave', 'selection_set', None, 'Pet', 'Pet', None], ['leave', 'inline_fragment', None, 'Pet', 'Pet', None], ['leave', 'selection_set', None, 'Pet', '[Pet]', None], ['leave', 'field', None, 'Human', '[Pet]', None], ['enter', 'field', None, 'Human', None, None], ['enter', 'name', 'unknown', 'Human', None, None], ['leave', 'name', 'unknown', 'Human', None, None], ['leave', 'field', None, 'Human', None, None], ['leave', 'selection_set', None, 'Human', 'Human', None], ['leave', 'field', None, 'QueryRoot', 'Human', None], ['leave', 'selection_set', None, 'QueryRoot', 'QueryRoot', None], ['leave', 'operation_definition', None, None, 'QueryRoot', None], ['leave', 'document', None, None, None, None], ] def maintains_type_info_during_edit(): visited = [] type_info = TypeInfo(test_schema) ast = parse('{ human(id: 4) { name, pets }, alien }') # noinspection PyMethodMayBeStatic class TestVisitor(Visitor): def enter(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) parent_type = type_info.get_parent_type() type_ = type_info.get_type() input_type = type_info.get_input_type() node = args[0] visited.append([ 'enter', node.kind, node.value if node.kind == 'name' else None, str(parent_type) if parent_type else None, str(type_) if type_ else None, str(input_type) if input_type else None]) # Make a query valid by adding missing selection sets. if (node.kind == 'field' and not node.selection_set and is_composite_type(get_named_type(type_))): return FieldNode( alias=node.alias, name=node.name, arguments=node.arguments, directives=node.directives, selection_set=SelectionSetNode(selections=[ FieldNode(name=NameNode(value='__typename'))])) def leave(self, *args): check_visitor_fn_args(ast, *args, is_edited=True) parent_type = type_info.get_parent_type() type_ = type_info.get_type() input_type = type_info.get_input_type() node = args[0] visited.append([ 'leave', node.kind, node.value if node.kind == 'name' else None, str(parent_type) if parent_type else None, str(type_) if type_ else None, str(input_type) if input_type else None]) edited_ast = visit(ast, TypeInfoVisitor(type_info, TestVisitor())) assert ast == parse('{ human(id: 4) { name, pets }, alien }') assert print_ast(edited_ast) == print_ast(parse( '{ human(id: 4) { name, pets { __typename } },' ' alien { __typename } }')) assert visited == [ ['enter', 'document', None, None, None, None], ['enter', 'operation_definition', None, None, 'QueryRoot', None], ['enter', 'selection_set', None, 'QueryRoot', 'QueryRoot', None], ['enter', 'field', None, 'QueryRoot', 'Human', None], ['enter', 'name', 'human', 'QueryRoot', 'Human', None], ['leave', 'name', 'human', 'QueryRoot', 'Human', None], ['enter', 'argument', None, 'QueryRoot', 'Human', 'ID'], ['enter', 'name', 'id', 'QueryRoot', 'Human', 'ID'], ['leave', 'name', 'id', 'QueryRoot', 'Human', 'ID'], ['enter', 'int_value', None, 'QueryRoot', 'Human', 'ID'], ['leave', 'int_value', None, 'QueryRoot', 'Human', 'ID'], ['leave', 'argument', None, 'QueryRoot', 'Human', 'ID'], ['enter', 'selection_set', None, 'Human', 'Human', None], ['enter', 'field', None, 'Human', 'String', None], ['enter', 'name', 'name', 'Human', 'String', None], ['leave', 'name', 'name', 'Human', 'String', None], ['leave', 'field', None, 'Human', 'String', None], ['enter', 'field', None, 'Human', '[Pet]', None], ['enter', 'name', 'pets', 'Human', '[Pet]', None], ['leave', 'name', 'pets', 'Human', '[Pet]', None], ['enter', 'selection_set', None, 'Pet', '[Pet]', None], ['enter', 'field', None, 'Pet', 'String!', None], ['enter', 'name', '__typename', 'Pet', 'String!', None], ['leave', 'name', '__typename', 'Pet', 'String!', None], ['leave', 'field', None, 'Pet', 'String!', None], ['leave', 'selection_set', None, 'Pet', '[Pet]', None], ['leave', 'field', None, 'Human', '[Pet]', None], ['leave', 'selection_set', None, 'Human', 'Human', None], ['leave', 'field', None, 'QueryRoot', 'Human', None], ['enter', 'field', None, 'QueryRoot', 'Alien', None], ['enter', 'name', 'alien', 'QueryRoot', 'Alien', None], ['leave', 'name', 'alien', 'QueryRoot', 'Alien', None], ['enter', 'selection_set', None, 'Alien', 'Alien', None], ['enter', 'field', None, 'Alien', 'String!', None], ['enter', 'name', '__typename', 'Alien', 'String!', None], ['leave', 'name', '__typename', 'Alien', 'String!', None], ['leave', 'field', None, 'Alien', 'String!', None], ['leave', 'selection_set', None, 'Alien', 'Alien', None], ['leave', 'field', None, 'QueryRoot', 'Alien', None], ['leave', 'selection_set', None, 'QueryRoot', 'QueryRoot', None], ['leave', 'operation_definition', None, None, 'QueryRoot', None], ['leave', 'document', None, None, None, None], ]
43.484804
79
0.477779
d674a3c1d3258ca70ba8eabfaee17bfa449a39a8
11,269
py
Python
doc/conf.py
cboos/trac
c0d42829d719dd82fde489611344ced97597aebd
[ "BSD-3-Clause" ]
null
null
null
doc/conf.py
cboos/trac
c0d42829d719dd82fde489611344ced97597aebd
[ "BSD-3-Clause" ]
null
null
null
doc/conf.py
cboos/trac
c0d42829d719dd82fde489611344ced97597aebd
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright (C) 2008-2018 Edgewall Software # Copyright (C) 2008 Noah Kantrowitz <noah@coderanger.net> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/. # Trac documentation build configuration file, created by # sphinx-quickstart on Wed May 14 09:05:13 2008. # # This file is execfile()d with the current directory set to its # containing dir. # # The contents of this file are pickled, so don't put values in the # namespace that aren't pickleable (module imports are okay, they're # removed automatically). # # All configuration values have a default value; values that are # commented out serve to show the default value. import os import sys from datetime import datetime from trac.util import get_pkginfo try: from pygments.lexers.templates import DjangoLexer html_jinja_lexer = DjangoLexer() except ImportError: html_jinja_lexer = None pkg_info = get_pkginfo(sys.modules['trac']) # General substitutions. project = 'Trac' copyright = '%s, Edgewall Software' % datetime.now().year url = pkg_info['home_page'] # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = pkg_info['version'].split('dev')[0] # The full version, including alpha/beta/rc tags. release = pkg_info['version'] # Devel or Release mode for the documentation (if devel, include TODOs, # can also be used in conditionals: .. ifconfig :: devel) devel = 'dev' in pkg_info['version'] # If your extensions are in another directory, add it here. If the # directory is relative to the documentation root, use os.path.abspath # to make it absolute, like shown here. # sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') # or your custom ones. extensions = [] # -- Autodoc extensions.append('sphinx.ext.autodoc') autodoc_default_flags = ['members', 'show-inheritance'] autoclass_content = 'both' autodoc_member_order = 'bysource' # -- Conditional content (see setup() below) extensions.append('sphinx.ext.ifconfig') # -- Link to other Sphinx documentations extensions.append('sphinx.ext.intersphinx') intersphinx_mapping = {'python': ('https://docs.python.org/2.7', None)} # -- Keep track of :todo: items extensions.append('sphinx.ext.todo') todo_include_todos = devel # -- PDF support via http://code.google.com/p/rst2pdf/ try: import rst2pdf extensions.append('rst2pdf.pdfbuilder') except ImportError: pass # -- Documentation coverage (`make apidoc-coverage`) extensions.append('sphinx.ext.coverage') coverage_skip_undoc_in_source = True # Add any paths that contain templates here, relative to this directory. #templates_path = ['utils/templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. unused_docs = [] # List of directories, relative to source directories, that shouldn't be searched # for source files. exclude_patterns = [ ] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'trac' # The default role is a reference to some Python object default_role = 'py:obj' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'tracsphinx.css' html_theme = 'sphinxdoc' html_theme_options = { # 'linkcolor': '#B00', # 'visitedlinkcolor': '#B00', } # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. html_logo = 'images/trac_logo.png' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['utils/'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_use_modindex = True # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Tracdoc' modindex_common_prefix = ['trac.', 'tracopt.'] # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'Trac.tex', 'Trac API Documentation', 'The Trac Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True # Options for PDF output # ---------------------- # (initially copied from # http://rst2pdf.googlecode.com/svn/tags/0.16/doc/manual.txt) # Grouping the document tree into PDF files. List of tuples # (source start file, target name, title, author, options). # # If there is more than one author, separate them with \\. # For example: r'Guido van Rossum\\Fred L. Drake, Jr., editor' # # The options element is a dictionary that lets you override # this config per-document. # For example, # ('index', u'MyProject', u'My Project', u'Author Name', # dict(pdf_compressed = True)) # would mean that specific document would be compressed # regardless of the global pdf_compressed setting. pdf_documents = [ ('index', 'trac_dev', project, u'The Trac Team'), ] # A comma-separated list of custom stylesheets (latest has higher precedence) pdf_stylesheets = [ 'sphinx', 'a4', 'trac', os.path.join(os.path.dirname(__file__), 'utils', 'trac_dev_pdf.style') ] # Create a compressed PDF # Use True/False or 1/0 # Example: compressed=True pdf_compressed = True # A colon-separated list of folders to search for fonts. Example: # pdf_font_path = ['/usr/share/fonts', '/usr/share/texmf-dist/fonts/'] # Language to be used for hyphenation support pdf_language = "en_US" # Mode for literal blocks wider than the frame. Can be # overflow, shrink or truncate pdf_fit_mode = "shrink" # Section level that forces a break page. # For example: 1 means top-level sections start in a new page # 0 means disabled pdf_break_level = 1 # When a section starts in a new page, force it to be 'even', 'odd', # or just use 'any' #pdf_breakside = 'any' # Insert footnotes where they are defined instead of # at the end. #pdf_inline_footnotes = True # verbosity level. 0 1 or 2 #pdf_verbosity = 0 # If false, no index is generated. pdf_use_index = True # If false, no modindex is generated. pdf_use_modindex = True # If false, no coverpage is generated. #pdf_use_coverpage = True # Name of the cover page template to use #pdf_cover_template = 'sphinxcover.tmpl' # Documents to append as an appendix to all manuals. #pdf_appendices = [] # Enable experimental feature to split table cells. Use it # if you get "DelayedTable too big" errors #pdf_splittables = False # Set the default DPI for images #pdf_default_dpi = 72 # Enable rst2pdf extension modules (default is only vectorpdf) # you need vectorpdf if you want to use sphinx's graphviz support #pdf_extensions = ['vectorpdf'] # Page template name for "regular" pages #pdf_page_template = 'cutePage' # Show Table Of Contents at the beginning? #pdf_use_toc = True # How many levels deep should the table of contents be? pdf_toc_depth = 9999 # Add section number to section references pdf_use_numbered_links = False # Background images fitting mode pdf_fit_background_mode = 'scale' def setup(app): # adding role for linking to InterTrac targets on t.e.o from docutils import nodes from docutils.parsers.rst import roles def teo_role(name, rawtext, text, lineno, inliner, options={}, content=[]): # special case ticket references if text[0] == '#': ref = url + '/ticket/' + text[1:] else: ref = url + '/intertrac/' + text roles.set_classes(options) node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] roles.register_canonical_role('teo', teo_role) def extensionpoints_role(name, rawtext, text, lineno, inliner, options={}, content=[]): ref = url + '/wiki/TracDev/PluginDevelopment/ExtensionPoints/' + text roles.set_classes(options) node = nodes.reference(rawtext, text + " extension point", refuri=ref, **options) return [node], [] roles.register_canonical_role('extensionpoints', extensionpoints_role) # ifconfig variables app.add_config_value('devel', True, '') if html_jinja_lexer: app.add_lexer('html+jinja', html_jinja_lexer)
29.655263
81
0.71923
b39a406b138e35465c9c128c7f2914e7b5f6c955
665
py
Python
ACME/layer/TLayer.py
mauriziokovacic/ACME
2615b66dd4addfd5c03d9d91a24c7da414294308
[ "MIT" ]
3
2019-10-23T23:10:55.000Z
2021-09-01T07:30:14.000Z
ACME/layer/TLayer.py
mauriziokovacic/ACME-Python
2615b66dd4addfd5c03d9d91a24c7da414294308
[ "MIT" ]
null
null
null
ACME/layer/TLayer.py
mauriziokovacic/ACME-Python
2615b66dd4addfd5c03d9d91a24c7da414294308
[ "MIT" ]
1
2020-07-11T11:35:43.000Z
2020-07-11T11:35:43.000Z
import torch class TLayer(torch.nn.Module): def __init__(self, K=3, bias=False): super(TLayer, self).__init__() self.weight = torch.nn.Parameter(data=torch.eye(K, dtype=torch.float, requires_grad=True), requires_grad=True) if bias: self.bias = torch.nn.Parameter(data=torch.eye(K, dtype=torch.float, requires_grad=True), requires_grad=True) else: self.register_parameter('bias', None) self.init_parameters() def init_parameters(self): if self.bias is not None: self.weight.data.fill_(0) def forward(self, x): return torch.matmul(x, self.weight) + self.bias
33.25
120
0.645113
3ccb0b0311dcc6aeecbcca9718e56ac1cc0494ee
15,347
py
Python
pw_console/py/window_manager_test.py
octml/pigweed
e273d46024ef7b5a7c7ec584e4aaada41c541fc4
[ "Apache-2.0" ]
86
2021-03-09T23:49:40.000Z
2022-03-30T08:14:51.000Z
pw_console/py/window_manager_test.py
octml/pigweed
e273d46024ef7b5a7c7ec584e4aaada41c541fc4
[ "Apache-2.0" ]
4
2021-07-27T20:32:03.000Z
2022-03-08T10:39:07.000Z
pw_console/py/window_manager_test.py
octml/pigweed
e273d46024ef7b5a7c7ec584e4aaada41c541fc4
[ "Apache-2.0" ]
22
2021-03-11T15:15:47.000Z
2022-02-09T06:16:36.000Z
# Copyright 2021 The Pigweed 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 # # https://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 pw_console.console_app""" import logging import unittest from unittest.mock import MagicMock from prompt_toolkit.application import create_app_session from prompt_toolkit.output import ColorDepth # inclusive-language: ignore from prompt_toolkit.output import DummyOutput as FakeOutput from pw_console.console_app import ConsoleApp from pw_console.window_manager import _WINDOW_SPLIT_ADJUST from pw_console.window_list import _WINDOW_HEIGHT_ADJUST def _create_console_app(logger_count=2): console_app = ConsoleApp(color_depth=ColorDepth.DEPTH_8_BIT) loggers = {} for i in range(logger_count): loggers['Log{}'.format(i)] = [ logging.getLogger('test_log{}'.format(i)) ] for window_title, logger_instances in loggers.items(): console_app.add_log_handler(window_title, logger_instances) return console_app _DEFAULT_WINDOW_WIDTH = 10 _DEFAULT_WINDOW_HEIGHT = 10 def _window_list_widths(window_manager): return [ window_list.width.preferred for window_list in window_manager.window_lists ] def _window_pane_heights(window_manager, window_list_index=0): return [ pane.height.preferred for pane in window_manager.window_lists[window_list_index].active_panes ] def _window_pane_counts(window_manager): return [ len(window_list.active_panes) for window_list in window_manager.window_lists ] def _window_pane_titles(window_manager): return [[ pane.pane_title() + ' - ' + pane.pane_subtitle() for pane in window_list.active_panes ] for window_list in window_manager.window_lists] def _target_list_and_pane(window_manager, list_index, pane_index): # pylint: disable=protected-access # Bypass prompt_toolkit has_focus() window_manager._get_active_window_list_and_pane = ( MagicMock( # type: ignore return_value=( window_manager.window_lists[list_index], window_manager.window_lists[list_index]. active_panes[pane_index], ))) class TestWindowManager(unittest.TestCase): # pylint: disable=protected-access """Tests for window management functions.""" def setUp(self): self.maxDiff = None # pylint: disable=invalid-name def test_find_window_list_and_pane(self) -> None: """Test getting the window list for a given pane.""" with create_app_session(output=FakeOutput()): console_app = _create_console_app(logger_count=3) window_manager = console_app.window_manager self.assertEqual([4], _window_pane_counts(window_manager)) # Move 2 windows to the right into their own splits _target_list_and_pane(window_manager, 0, 0) window_manager.move_pane_right() _target_list_and_pane(window_manager, 0, 0) window_manager.move_pane_right() _target_list_and_pane(window_manager, 1, 0) window_manager.move_pane_right() # 3 splits, first split has 2 windows self.assertEqual([2, 1, 1], _window_pane_counts(window_manager)) # Move the first window in the first split left _target_list_and_pane(window_manager, 0, 0) window_manager.move_pane_left() # 4 splits, each with their own window self.assertEqual([1, 1, 1, 1], _window_pane_counts(window_manager)) # Move the first window to the right _target_list_and_pane(window_manager, 0, 0) window_manager.move_pane_right() # 3 splits, first split has 2 windows self.assertEqual([2, 1, 1], _window_pane_counts(window_manager)) target_pane = window_manager.window_lists[2].active_panes[0] result_window_list, result_pane_index = ( window_manager._find_window_list_and_pane_index(target_pane)) self.assertEqual( (result_window_list, result_pane_index), (window_manager.window_lists[2], 0), ) window_manager.remove_pane(target_pane) self.assertEqual([2, 1], _window_pane_counts(window_manager)) def test_window_list_moving_and_resizing(self) -> None: """Test window split movement resizing.""" with create_app_session(output=FakeOutput()): console_app = _create_console_app(logger_count=3) window_manager = console_app.window_manager _target_list_and_pane(window_manager, 0, 0) # Should have one window list split of size 50. self.assertEqual( _window_list_widths(window_manager), [_DEFAULT_WINDOW_WIDTH], ) # Move one pane to the right, creating a new window_list split. window_manager.move_pane_right() self.assertEqual( _window_list_widths(window_manager), [_DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH], ) # Move another pane to the right twice, creating a third # window_list split. _target_list_and_pane(window_manager, 0, 0) window_manager.move_pane_right() # Above window pane is at a new location _target_list_and_pane(window_manager, 1, 0) window_manager.move_pane_right() # Should have 3 splits now self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH, ], ) # Total of 4 active panes self.assertEqual(len(list(window_manager.active_panes())), 4) # Target the middle split _target_list_and_pane(window_manager, 1, 0) # Shrink the middle split twice window_manager.shrink_split() window_manager.shrink_split() self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH - (2 * _WINDOW_SPLIT_ADJUST), _DEFAULT_WINDOW_WIDTH + (2 * _WINDOW_SPLIT_ADJUST), ], ) # Target the first split _target_list_and_pane(window_manager, 0, 0) window_manager.reset_split_sizes() # Shrink the first split twice window_manager.shrink_split() self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH - (1 * _WINDOW_SPLIT_ADJUST), _DEFAULT_WINDOW_WIDTH + (1 * _WINDOW_SPLIT_ADJUST), _DEFAULT_WINDOW_WIDTH, ], ) # Target the third (last) split _target_list_and_pane(window_manager, 2, 0) window_manager.reset_split_sizes() # Shrink the third split once window_manager.shrink_split() self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH + (1 * _WINDOW_SPLIT_ADJUST), _DEFAULT_WINDOW_WIDTH - (1 * _WINDOW_SPLIT_ADJUST), ], ) window_manager.reset_split_sizes() # Enlarge the third split a few times. window_manager.enlarge_split() window_manager.enlarge_split() window_manager.enlarge_split() self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH - (3 * _WINDOW_SPLIT_ADJUST), _DEFAULT_WINDOW_WIDTH + (3 * _WINDOW_SPLIT_ADJUST), ], ) # Target the middle split _target_list_and_pane(window_manager, 1, 0) # Move the middle window pane left window_manager.move_pane_left() # Middle split should be removed self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, # This split is removed _DEFAULT_WINDOW_WIDTH + (3 * _WINDOW_SPLIT_ADJUST), ], ) # Revert sizes to default window_manager.reset_split_sizes() self.assertEqual( _window_list_widths(window_manager), [ _DEFAULT_WINDOW_WIDTH, _DEFAULT_WINDOW_WIDTH, ], ) def test_get_pane_titles(self) -> None: """Test window resizing.""" with create_app_session(output=FakeOutput()): console_app = _create_console_app(logger_count=3) window_manager = console_app.window_manager list_pane_titles = [ # Remove mouse click handler partials in tup[2] [(tup[0], tup[1]) for tup in window_list.get_pane_titles()] for window_list in window_manager.window_lists ] self.assertEqual( list_pane_titles[0], [('', ' '), ('class:window-tab-inactive', ' Log2 test_log2 '), ('', ' '), ('class:window-tab-inactive', ' Log1 test_log1 '), ('', ' '), ('class:window-tab-inactive', ' Log0 test_log0 '), ('', ' '), ('class:window-tab-inactive', ' Python Repl '), ('', ' ')], ) def test_window_pane_movement_resizing(self) -> None: """Test window resizing.""" with create_app_session(output=FakeOutput()): console_app = _create_console_app(logger_count=3) window_manager = console_app.window_manager # 4 panes, 3 for the loggers and 1 for the repl. self.assertEqual( len(window_manager.first_window_list().active_panes), 4) def target_window_pane(index: int): # Bypass prompt_toolkit has_focus() window_manager._get_active_window_list_and_pane = ( MagicMock( # type: ignore return_value=( window_manager.window_lists[0], window_manager.window_lists[0].active_panes[index], ))) window_list = console_app.window_manager.first_window_list() window_list.get_current_active_pane = ( MagicMock( # type: ignore return_value=window_list.active_panes[index])) # Target the first window pane target_window_pane(0) # Shrink the first pane window_manager.shrink_pane() self.assertEqual( _window_pane_heights(window_manager), [ _DEFAULT_WINDOW_HEIGHT - (1 * _WINDOW_HEIGHT_ADJUST), _DEFAULT_WINDOW_HEIGHT + (1 * _WINDOW_HEIGHT_ADJUST), _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT, ], ) # Reset pane sizes window_manager.window_lists[0].current_window_list_height = ( 4 * _DEFAULT_WINDOW_HEIGHT) window_manager.reset_pane_sizes() self.assertEqual( _window_pane_heights(window_manager), [ _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT, ], ) # Shrink last pane target_window_pane(3) window_manager.shrink_pane() self.assertEqual( _window_pane_heights(window_manager), [ _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT + (1 * _WINDOW_HEIGHT_ADJUST), _DEFAULT_WINDOW_HEIGHT - (1 * _WINDOW_HEIGHT_ADJUST), ], ) # Enlarge second pane target_window_pane(1) window_manager.reset_pane_sizes() window_manager.enlarge_pane() window_manager.enlarge_pane() self.assertEqual( _window_pane_heights(window_manager), [ _DEFAULT_WINDOW_HEIGHT, _DEFAULT_WINDOW_HEIGHT + (2 * _WINDOW_HEIGHT_ADJUST), _DEFAULT_WINDOW_HEIGHT - (2 * _WINDOW_HEIGHT_ADJUST), _DEFAULT_WINDOW_HEIGHT, ], ) # Check window pane ordering self.assertEqual( _window_pane_titles(window_manager), [ [ 'Log2 - test_log2', 'Log1 - test_log1', 'Log0 - test_log0', 'Python Repl - ', ], ], ) target_window_pane(0) window_manager.move_pane_down() self.assertEqual( _window_pane_titles(window_manager), [ [ 'Log1 - test_log1', 'Log2 - test_log2', 'Log0 - test_log0', 'Python Repl - ', ], ], ) target_window_pane(2) window_manager.move_pane_up() target_window_pane(1) window_manager.move_pane_up() self.assertEqual( _window_pane_titles(window_manager), [ [ 'Log0 - test_log0', 'Log1 - test_log1', 'Log2 - test_log2', 'Python Repl - ', ], ], ) target_window_pane(0) window_manager.move_pane_up() self.assertEqual( _window_pane_titles(window_manager), [ [ 'Log0 - test_log0', 'Log1 - test_log1', 'Log2 - test_log2', 'Python Repl - ', ], ], ) if __name__ == '__main__': unittest.main()
36.715311
79
0.563302
1724926fe0a2d72c27c5f7d81fae5736b1e13c2a
16,919
py
Python
sds/sdsfile.py
ltrani/DMPilot-RuleManager
2c9a5fa7016203440bd7a2318eef71d5a4ee2381
[ "MIT" ]
4
2019-05-16T11:13:56.000Z
2022-01-11T10:43:39.000Z
sds/sdsfile.py
ltrani/DMPilot-RuleManager
2c9a5fa7016203440bd7a2318eef71d5a4ee2381
[ "MIT" ]
null
null
null
sds/sdsfile.py
ltrani/DMPilot-RuleManager
2c9a5fa7016203440bd7a2318eef71d5a4ee2381
[ "MIT" ]
1
2020-05-26T11:02:17.000Z
2020-05-26T11:02:17.000Z
""" orfeus/sdsfile class for handling SDS type files. Author: Mathijs Koymans, 2017 Copyright: ORFEUS Data Center, 2017 Modified: 2019 """ import os import requests import subprocess import base64 import logging import ctypes from datetime import datetime, timedelta from zlib import adler32 from obspy import read_inventory, UTCDateTime from configuration import config class SDSFile(): """ Public Class SDSFile Class for handling files in SDS structure. Attributes ---------- filename : `str` Name of file. net : `str` Network code. sta : `str` Station code. loc : `str` Location code. cha : `str` Channel code. quality : `str` Quality parameter. year : `str` Year in YYYY format. day : `str` Day of the year, in DDD format (i.e., it goes from "001" to "366"). """ # Save some configuration to the class irods_root = config["IRODS_ROOT"] fdsnws = config["FDSNWS_ADDRESS"] s3_prefix = config["S3"]["PREFIX"] def __init__(self, filename, archive_root): """ Create a filestream from a given filename """ try: # Extract stream identification (self.net, self.sta, self.loc, self.cha, self.quality, self.year, self.day) = filename.split(".") except ValueError: raise ValueError("Invalid SDS file submitted.") self.archive_root = archive_root # Initialize logger self.logger = logging.getLogger("RuleManager") # Initialize costly properties self._checksum = None self._inventory = None self._traces = None self._location = None # Returns the filename @property def filename(self): return self.custom_quality_filename(self.quality) def custom_quality_filename(self, quality): """Returns the filename of the file related to this one but with another quality.""" return ".".join([self.net, self.sta, self.loc, self.cha, quality, self.year, self.day]) def custom_quality_subdir(self, quality): """Returns the subdirectory of the archived file related to this one but with another quality.""" return os.path.join( self.year, self.net, self.sta, ".".join([self.cha, quality]) ) # Returns custom filepath for a given file def custom_path(self, root): return os.path.join(self.custom_directory(root), self.filename) # Returns filepath for a given file @property def filepath(self): return self.custom_path(self.archive_root) # Returns iRODS filepath for a given file @property def irods_path(self): return self.custom_path(self.irods_root) # Returns the S3 key for a given file @property def s3_key(self): return self.custom_path(self.s3_prefix) # Returns the stream identifier @property def id(self): return ".".join([ self.net, self.sta, self.loc, self.cha ]) # Returns the subdirectory @property def sub_directory(self): return os.path.join( self.year, self.net, self.sta, self.channel_directory ) def custom_directory(self, root): return os.path.join( root, self.sub_directory ) @property def irods_directory(self): return self.custom_directory(self.irods_root) # Returns the file directory based on SDS structure @property def directory(self): return self.custom_directory(self.archive_root) # Returns channel directory @property def channel_directory(self): return ".".join([self.cha, self.quality]) # Returns next file in stream @property def next(self): return self._get_adjacent_file(1) # Returns previous file in stream @property def previous(self): return self._get_adjacent_file(-1) # Returns start time of file @property def start(self): return datetime.strptime(self.year + " " + self.day, "%Y %j") # Returns end time of file @property def end(self): return self.start + timedelta(days=1) # Start for dataselect pruning (start is INCLUSIVE) @property def sample_start(self): return self.start.strftime("%Y,%j,00,00,00.000000") # End for dataselect pruning (end is INCLUSIVE) @property def sample_end(self): return self.start.strftime("%Y,%j,23,59,59.999999") # Returns list of files neighbouring a file @property def neighbours(self): return filter(lambda x: os.path.isfile(x.filepath), [self.previous, self, self.next]) @property def stats(self): try: return os.stat(self.filepath) except FileNotFoundError: return None def get_stat(self, enum): # Check if none and propagate if self.stats is None: return None if enum == "size": return self.stats.st_size elif enum == "created": return datetime.fromtimestamp(self.stats.st_ctime) elif enum == "modified": return datetime.fromtimestamp(self.stats.st_mtime) @property def size(self): return self.get_stat("size") @property def created(self): return self.get_stat("created") @property def modified(self): return self.get_stat("modified") @property def checksum(self): """ def SDSFile::checksum Calculates the Adler-32 checksum for a given file, converting it to a signed int32 to save space in MongoDB documents """ if self._checksum is not None: return self._checksum if self.stats is None: return None checksum = None with open(self.filepath, "rb") as f: checksum = adler32(f.read()) & 0xffffffff checksum = ctypes.c_int32(checksum).value self._checksum = checksum return self._checksum @property def query_string_txt(self): return self.query_string + "&" + "&".join([ "format=text", "level=channel" ]) @property def query_string_xml(self): return self.query_string + "&" + "&".join([ "format=fdsnxml", "level=response" ]) @property def query_string(self): """Return the query string for a particular SDS file.""" return "?" + "&".join([ "start=%s" % self.start.isoformat(), "end=%s" % self.end.isoformat(), "network=%s" % self.net, "station=%s" % self.sta, "location=%s" % self.loc, "channel=%s" % self.cha ]) @property def samples(self): """ def SDSFile::samples Returns number of samples in the SDS file """ return sum(map(lambda x: x["samples"], self.traces)) @property def continuous(self): """ def SDSFile::continuous Returns True when a SDS file is considered continuous and the record start time & end time come before and after the file ending respectively """ return len( self.traces) == 1 and ( self.traces[0]["start"] <= self.start) and ( self.traces[0]["end"] >= self.end) @property def traces(self): """ def SDSFile::traces Returns a list of traces """ if self._traces is not None: return self._traces def parse_msi_output(line): """Parse the MSI output.""" # Format for seed dates e.g. 2005,068,00:00:01.000000 SEED_DATE_FMT = "%Y,%j,%H:%M:%S.%f" (stream, start, end, rate, samples) = map(lambda x: x.decode("ascii"), line.split()) # Return a simple dict with some information return { "samples": int(samples), "rate": float(rate), "start": datetime.strptime(start, SEED_DATE_FMT), "end": datetime.strptime(end, SEED_DATE_FMT) } # Cut to day boundary on sample level dataselect = subprocess.Popen([ "dataselect", "-ts", self.sample_start, "-te", self.sample_end, "-Ps", "-szs", "-o", "-", ] + list(map(lambda x: x.filepath, self.neighbours)), stdout=subprocess.PIPE) lines = subprocess.check_output([ "msi", "-ts", self.sample_start, "-te", self.sample_end, "-T", "-" ], stdin=dataselect.stdout, stderr=subprocess.DEVNULL).splitlines() # Not sure why we need this dataselect.stdout.close() # Avoid warning when status code for child process is not read (for Python 3.6): # Introduced in https://github.com/python/cpython/commit/5a48e21ff163107a6f1788050b2f1ffc8bce2b6d#diff-cc136486b4a8e112e64b57436a0619eb dataselect.wait() # Skip first header & final line self._traces = list(map(parse_msi_output, lines[1:-1])) return self._traces @property def is_pressure_channel(self): """Return true when the channel is an infrasound channel.""" return self.cha.endswith("DF") @property def inventory(self): """ def SDSFile::inventory Returns the FDSNWSXML inventory """ if self._inventory is not None: return self._inventory # Query our FDSNWS Webservice for the station location request = os.path.join(self.fdsnws, self.query_string_xml) try: self._inventory = read_inventory(request) # Re-raise in case this is the Rule Manager timeout going off except TimeoutError: raise # Deal with an Exception from read_inventory except Exception: return None return self._inventory @property def location(self): """ def SDSFile::location Returns the geographical location of the stream """ if self._location is not None: return self._location # Query our FDSNWS Webservice for the station location try: request = requests.get(os.path.join(self.fdsnws, self.query_string_txt)) except requests.exceptions.RequestException: return None # Any error just ignore if request.status_code != 200: return None lines = request.text.split("\n") # Multiple lines means that the location is somehow ambiguous if len(lines) != 3: return None # Some magic parsing: fields 4, 5, 6 on the 2nd line (latitude, longitude, elevation) = lines[1].split("|")[4:7] self._location = { "longitude": float(longitude), "latitude": float(latitude), "elevation": float(elevation) } return self._location @property def psd_bins(self): """Return 48 times starting at the start of the SDSFile with 30 minute increments.""" return map(UTCDateTime, map(lambda x: self.start + timedelta(minutes=(30 * x)), range(48))) def prune(self, cut_boundaries=True, remove_overlap=False, repack=False, record_length=4096): """Preprocess file using IRIS dataselect and msrepack, and saves the resulting file with the quality indicator set to Q. Due to `dataselect` running as the first step, always sorts the records. `msrepack` only runs when `repack` is set to True. Qualities: D - The state of quality control of the data is indeterminate R - Raw Waveform Data with no Quality Control Q - Quality Controlled Data, some processes have been applied to the data. M - Data center modified, time-series values have not been changed. Parameters ---------- `cut_boundaries` : `bool` Whether or not to cut the file at the day boundaries --- 00:00 of the day and of the following day. (default `True`) `remove_overlap` : `bool` Whether or not to prune the file and remove overlaps at the sample level --- equates to the "-Ps" option of dataselect. (default `False`) `repack` : `bool` Whether or not to repack records using msrepack. (default `False`) `record_length` : `int` Size of record to repack if `repack` is `True`. (default 4096) """ # Record length within some bounds if record_length < 512 or record_length > 65536: raise ValueError("Record length is invalid") # Confirm record length is power of two if record_length & (record_length - 1) != 0: raise ValueError("Record length is not is a power of two") # Create a phantom SDSFile with a different quality idenfier quality_file = SDSFile(self.filename, self.archive_root) quality_file.quality = "Q" # Create directories for the pruned file (quality Q) if not os.path.exists(quality_file.directory): os.makedirs(quality_file.directory) # Get neighbours neighbours = list(map(lambda x: x.filepath, self.neighbours)) # Define dataselect arguments # -Ps prunes to sample level # -Q set quality indicator to Q # -ts, -te are start & end time of sample respectively (INCLUSIVE) # -szs remove records with 0 samples (may result in empty pruned files) # -o - write to stdout dataselect_args = ["-Q", "Q", "-szs"] # Cut file at the day boundaries if requested if cut_boundaries: dataselect_args.extend(["-ts", self.sample_start, "-te", self.sample_end]) # Check if overlap needs to be removed if remove_overlap: dataselect_args.append("-Ps") else: dataselect_args.append("-Pe") # If the file is going to be repacked, write to stdout if repack: dataselect_args.extend(["-o", "-"]) else: dataselect_args.extend(["-o", quality_file.filepath]) # Create a dataselect process dataselect = subprocess.Popen(["dataselect"] + dataselect_args + neighbours, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) # Open a msrepack process and connect stdin to dataselect stdout # -R repack record size to record_length # -o output file for pruned data # - read from STDIN if repack: msrepack = subprocess.Popen([ "msrepack", "-R", str(record_length), "-o", quality_file.filepath, "-" ], stdin=dataselect.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Not sure why we need this dataselect.stdout.close() # Wait for child processes to terminate if dataselect.wait() != 0 or (repack and msrepack.wait() != 0): if repack: raise Exception(("Unable to prune file " "(dataselect returned %s, msrepack returned %s)") % (str(dataselect.returncode), str(msrepack.returncode))) else: raise Exception("Unable to prune file (dataselect returned %s)" % (str(dataselect.returncode))) # Check that quality file has been created if os.path.exists(quality_file.filepath): self.logger.debug("Created pruned file %s" % quality_file.filename) else: raise Exception("Pruned file %s has not been created!" % quality_file.filename) def _get_adjacent_file(self, direction): """Private function that returns adjacent SDSFile based on direction.""" new_date = self.start + timedelta(days=direction) # The year and day may change new_year = new_date.strftime("%Y") new_day = new_date.strftime("%j") new_filename = ".".join([ self.net, self.sta, self.loc, self.cha, self.quality, new_year, new_day ]) return SDSFile(new_filename, self.archive_root) def __str__(self): return "%s (%s)" % (self.filename, self.modified)
29.998227
143
0.580353
7fc5d93432c942d0c195790acb1a9d28eec3960c
7,090
py
Python
pontoon/insights/utils.py
dothq/pontoon
fa85710f56e50d500e6bf8e6c82626ce64440a62
[ "BSD-3-Clause" ]
1
2021-10-03T20:48:42.000Z
2021-10-03T20:48:42.000Z
pontoon/insights/utils.py
dothq/pontoon
fa85710f56e50d500e6bf8e6c82626ce64440a62
[ "BSD-3-Clause" ]
14
2021-06-05T00:09:20.000Z
2021-09-03T01:48:36.000Z
pontoon/insights/utils.py
dothq/pontoon
fa85710f56e50d500e6bf8e6c82626ce64440a62
[ "BSD-3-Clause" ]
null
null
null
from datetime import datetime from django.db.models.functions import TruncMonth from django.db.models import Avg, Sum from pontoon.base.utils import convert_to_unix_time from pontoon.insights.models import ( LocaleInsightsSnapshot, ProjectInsightsSnapshot, active_users_default, ) def get_insight_start_date(from2021=False): """Include at most the last year of data in insights. For project insights, data is only available from 2020-12-14 onwards, so limit queries to start from 2021-01-01 at earliest. """ now = datetime.now() if from2021 and now.year == 2021: return datetime(2021, 1, 1) if now.month == 12: return datetime(now.year, 1, 1) return datetime(now.year - 1, now.month + 1, 1) def get_locale_insights(query_filters=None): """Get data required by the Locale Insights tab. :param django.db.models.Q query_filters: filters insights by given query_filters. """ start_date = get_insight_start_date(False) snapshots = LocaleInsightsSnapshot.objects.filter(created_at__gte=start_date) if query_filters: snapshots = snapshots.filter(query_filters) insights = ( snapshots # Truncate to month and add to select list .annotate(month=TruncMonth("created_at")) # Group By month .values("month") # Select the avg/sum of the grouping .annotate(unreviewed_lifespan_avg=Avg("unreviewed_suggestions_lifespan")) .annotate(completion_avg=Avg("completion")) .annotate(human_translations_sum=Sum("human_translations")) .annotate(machinery_sum=Sum("machinery_translations")) .annotate(new_source_strings_sum=Sum("new_source_strings")) .annotate(unreviewed_avg=Avg("unreviewed_strings")) .annotate(peer_approved_sum=Sum("peer_approved")) .annotate(self_approved_sum=Sum("self_approved")) .annotate(rejected_sum=Sum("rejected")) .annotate(new_suggestions_sum=Sum("new_suggestions")) # Select month and values .values( "month", "unreviewed_lifespan_avg", "completion_avg", "human_translations_sum", "machinery_sum", "new_source_strings_sum", "unreviewed_avg", "peer_approved_sum", "self_approved_sum", "rejected_sum", "new_suggestions_sum", ) .order_by("month") ) output = {} latest = snapshots.latest("created_at") if snapshots else None if latest: output.update( { "total_users": { "managers": latest.total_managers, "reviewers": latest.total_reviewers, "contributors": latest.total_contributors, }, "active_users_last_month": latest.active_users_last_month, "active_users_last_3_months": latest.active_users_last_3_months, "active_users_last_6_months": latest.active_users_last_6_months, "active_users_last_12_months": latest.active_users_last_12_months, } ) else: output.update( { "total_users": active_users_default(), "active_users_last_month": active_users_default(), "active_users_last_3_months": active_users_default(), "active_users_last_6_months": active_users_default(), "active_users_last_12_months": active_users_default(), } ) output.update( { "dates": [convert_to_unix_time(x["month"]) for x in insights], "unreviewed_lifespans": [ x["unreviewed_lifespan_avg"].days for x in insights ], "translation_activity": { "completion": [round(x["completion_avg"], 2) for x in insights], "human_translations": [x["human_translations_sum"] for x in insights], "machinery_translations": [x["machinery_sum"] for x in insights], "new_source_strings": [x["new_source_strings_sum"] for x in insights], }, "review_activity": { "unreviewed": [int(round(x["unreviewed_avg"])) for x in insights], "peer_approved": [x["peer_approved_sum"] for x in insights], "self_approved": [x["self_approved_sum"] for x in insights], "rejected": [x["rejected_sum"] for x in insights], "new_suggestions": [x["new_suggestions_sum"] for x in insights], }, } ) return output def get_project_insights(query_filters=None): """Get data required by the Project Insights tab. :param django.db.models.Q query_filters: filters insights by given query_filters. """ start_date = get_insight_start_date(True) snapshots = ProjectInsightsSnapshot.objects.filter(created_at__gte=start_date) if query_filters: snapshots = snapshots.filter(query_filters) insights = ( snapshots # Truncate to month and add to select list .annotate(month=TruncMonth("created_at")) # Group By month .values("month") # Select the avg/sum of the grouping .annotate(completion_avg=Avg("completion")) .annotate(human_translations_sum=Sum("human_translations")) .annotate(machinery_sum=Sum("machinery_translations")) .annotate(new_source_strings_sum=Sum("new_source_strings")) .annotate(unreviewed_avg=Avg("unreviewed_strings")) .annotate(peer_approved_sum=Sum("peer_approved")) .annotate(self_approved_sum=Sum("self_approved")) .annotate(rejected_sum=Sum("rejected")) .annotate(new_suggestions_sum=Sum("new_suggestions")) # Select month and values .values( "month", "completion_avg", "human_translations_sum", "machinery_sum", "new_source_strings_sum", "unreviewed_avg", "peer_approved_sum", "self_approved_sum", "rejected_sum", "new_suggestions_sum", ) .order_by("month") ) return { "dates": [convert_to_unix_time(x["month"]) for x in insights], "translation_activity": { "completion": [round(x["completion_avg"], 2) for x in insights], "human_translations": [x["human_translations_sum"] for x in insights], "machinery_translations": [x["machinery_sum"] for x in insights], "new_source_strings": [x["new_source_strings_sum"] for x in insights], }, "review_activity": { "unreviewed": [int(round(x["unreviewed_avg"])) for x in insights], "peer_approved": [x["peer_approved_sum"] for x in insights], "self_approved": [x["self_approved_sum"] for x in insights], "rejected": [x["rejected_sum"] for x in insights], "new_suggestions": [x["new_suggestions_sum"] for x in insights], }, }
38.532609
86
0.621016
fab2672c5bf76ec5cdfcfaed4ee197321aa00173
205
py
Python
MapAPP/views.py
MHuiG/Karat-Django-Backend
8887417bb3eee302a1639e247957539479d2ef67
[ "MIT" ]
null
null
null
MapAPP/views.py
MHuiG/Karat-Django-Backend
8887417bb3eee302a1639e247957539479d2ef67
[ "MIT" ]
null
null
null
MapAPP/views.py
MHuiG/Karat-Django-Backend
8887417bb3eee302a1639e247957539479d2ef67
[ "MIT" ]
null
null
null
from django.shortcuts import render # Create your views here. from Karat.settings import RequestHost def SchoolHistoryMuseum(request): return render(request, 'test.html',{"RequestHost":RequestHost})
25.625
67
0.790244
16b76118bf010ef05151e277efd7bb1b165fc18b
3,673
py
Python
brick_data/queryprocessor/querysynthesizer.py
jbkoh/brick_data
bab392b8b0b83c7a0c5427c08f3d9f2b22a8ab06
[ "Apache-2.0" ]
3
2020-09-24T18:53:55.000Z
2021-02-22T07:30:04.000Z
brick_data/queryprocessor/querysynthesizer.py
jbkoh/brick-federation
bab392b8b0b83c7a0c5427c08f3d9f2b22a8ab06
[ "Apache-2.0" ]
2
2019-03-31T01:22:13.000Z
2019-05-28T00:49:36.000Z
brick_data/queryprocessor/querysynthesizer.py
jbkoh/brick-federation
bab392b8b0b83c7a0c5427c08f3d9f2b22a8ab06
[ "Apache-2.0" ]
1
2019-05-28T18:58:51.000Z
2019-05-28T18:58:51.000Z
import pdb from functools import reduce from copy import deepcopy from moz_sql_parser import parse adder = lambda x,y: x+y class QuerySynthesizer(object): def __init__(self): pass class BrickSynthesizer(QuerySynthesizer): def __init__(self): super(BrickSynthesizer, self).__init__() def synthesize_query(self, qstr, common_vars, curr_vars, curr_values): return [qstr] class TimescaledbSynthesizer(QuerySynthesizer): def __init__(self): super(TimescaledbSynthesizer, self).__init__() def modify_query_dfs(self, parsed, var_type, filters): # TODO This should be formalized later. for q_k in parsed.keys(): q_v = parsed[q_k] if q_k == 'eq' and isinstance(q_v, list): if var_type == 'uuid': var_name = q_v[1] new_statement = ['uuid', [{'literal': val} for val in values]] del parsed[q_k] parsed['in'] = new_statement elif isinstance(q_v, dict): self.inplace_replace_dfs(q_v, var_type, filters) elif isinstance(q_v, list): parsed[q_k] = [self.inplace_replace_dfs(q_v_elem) for q_v_elem in q_v] return parsed def naive_replace(self, qstr, var_type, filters): """ Many assumptions on qstr 1. each line has one statement. """ variables = filters.keys() lines = qstr.split('\n') for i, line in enumerate(lines): for var_name, values in filters.items(): if var_name in line: if var_type == 'uuid': lines[i] = 'uuid IN ({0})'.format(str(values)[1:-1]) return '\n'.join(lines) def synthesize_query(self, qstr, common_vars, curr_vars, curr_values): """ """ common_var_idxs = [curr_vars.index(common_var) for common_var in common_vars] #value_template = [None] * len(var_locs) #found_values_list = [] #prev_found_values_list = [deepcopy(value_template)] #for common_vars, common_values in zip(common_vars_set, common_values_set): res_qstrs = [] #for found_values in found_values_list: for value_tuple in curr_values: q = qstr for common_var_idx, common_var in zip(common_var_idxs, common_vars): q = q.replace(common_var, value_tuple[common_var_idx]) res_qstrs.append(q) return res_qstrs def synthesize_dep(self, qstr, var_type, filters): """ E.g., filters = { "uuid": ['uuid1', 'uuid2', ...], "time": [' # ORed inside the lists. # ANDed across different keys. """ synthesized = self.naive_replace(qstr, var_type, filters) return synthesized if __name__ == '__main__': synth = TimescaledbSynthesizer() #query = 'select (uuid, time, value) from brick_data\nwhere uuid = "?znt"\n' #filters = { # '?znt': ['znt1', 'znt2'] #} #res = synth.synthesize(query, 'uuid', filters) #print('Original Query: \n{0}\n'.format(query)) #print('Modeified: \n{0}'.format(res)) qstr = """select (uuid, time, value) from brick_data where uuid = '?znt' AND time = '?ttt' """ common_vars_set = (('?znt',), ('?ttt',)) #common_vars_set = (('?znt',), ('?ttt', 'xxx',)) common_values_set = ( [('znt1',), ('znt2',)], [('ttt1',), ('ttt2',)] ) res = synth.synthesize_query(qstr, common_vars_set, common_values_set)
32.794643
85
0.569017
5c90cdcf9395e41cd0165185d0fb47fbc1d0b687
16,901
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_11_01/_network_management_client.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_11_01/_network_management_client.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_11_01/_network_management_client.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from ._configuration import NetworkManagementClientConfiguration from .operations import ApplicationGatewaysOperations from .operations import ApplicationSecurityGroupsOperations from .operations import NetworkManagementClientOperationsMixin from .operations import AvailableEndpointServicesOperations from .operations import ExpressRouteCircuitAuthorizationsOperations from .operations import ExpressRouteCircuitPeeringsOperations from .operations import ExpressRouteCircuitsOperations from .operations import ExpressRouteServiceProvidersOperations from .operations import LoadBalancersOperations from .operations import LoadBalancerBackendAddressPoolsOperations from .operations import LoadBalancerFrontendIPConfigurationsOperations from .operations import InboundNatRulesOperations from .operations import LoadBalancerLoadBalancingRulesOperations from .operations import LoadBalancerNetworkInterfacesOperations from .operations import LoadBalancerProbesOperations from .operations import NetworkInterfacesOperations from .operations import NetworkInterfaceIPConfigurationsOperations from .operations import NetworkInterfaceLoadBalancersOperations from .operations import NetworkSecurityGroupsOperations from .operations import SecurityRulesOperations from .operations import DefaultSecurityRulesOperations from .operations import NetworkWatchersOperations from .operations import PacketCapturesOperations from .operations import ConnectionMonitorsOperations from .operations import Operations from .operations import PublicIPAddressesOperations from .operations import RouteFiltersOperations from .operations import RouteFilterRulesOperations from .operations import RouteTablesOperations from .operations import RoutesOperations from .operations import BgpServiceCommunitiesOperations from .operations import UsagesOperations from .operations import VirtualNetworksOperations from .operations import SubnetsOperations from .operations import VirtualNetworkPeeringsOperations from .operations import VirtualNetworkGatewaysOperations from .operations import VirtualNetworkGatewayConnectionsOperations from .operations import LocalNetworkGatewaysOperations from . import models class NetworkManagementClient(NetworkManagementClientOperationsMixin): """Network Client. :ivar application_gateways: ApplicationGatewaysOperations operations :vartype application_gateways: azure.mgmt.network.v2017_11_01.operations.ApplicationGatewaysOperations :ivar application_security_groups: ApplicationSecurityGroupsOperations operations :vartype application_security_groups: azure.mgmt.network.v2017_11_01.operations.ApplicationSecurityGroupsOperations :ivar available_endpoint_services: AvailableEndpointServicesOperations operations :vartype available_endpoint_services: azure.mgmt.network.v2017_11_01.operations.AvailableEndpointServicesOperations :ivar express_route_circuit_authorizations: ExpressRouteCircuitAuthorizationsOperations operations :vartype express_route_circuit_authorizations: azure.mgmt.network.v2017_11_01.operations.ExpressRouteCircuitAuthorizationsOperations :ivar express_route_circuit_peerings: ExpressRouteCircuitPeeringsOperations operations :vartype express_route_circuit_peerings: azure.mgmt.network.v2017_11_01.operations.ExpressRouteCircuitPeeringsOperations :ivar express_route_circuits: ExpressRouteCircuitsOperations operations :vartype express_route_circuits: azure.mgmt.network.v2017_11_01.operations.ExpressRouteCircuitsOperations :ivar express_route_service_providers: ExpressRouteServiceProvidersOperations operations :vartype express_route_service_providers: azure.mgmt.network.v2017_11_01.operations.ExpressRouteServiceProvidersOperations :ivar load_balancers: LoadBalancersOperations operations :vartype load_balancers: azure.mgmt.network.v2017_11_01.operations.LoadBalancersOperations :ivar load_balancer_backend_address_pools: LoadBalancerBackendAddressPoolsOperations operations :vartype load_balancer_backend_address_pools: azure.mgmt.network.v2017_11_01.operations.LoadBalancerBackendAddressPoolsOperations :ivar load_balancer_frontend_ip_configurations: LoadBalancerFrontendIPConfigurationsOperations operations :vartype load_balancer_frontend_ip_configurations: azure.mgmt.network.v2017_11_01.operations.LoadBalancerFrontendIPConfigurationsOperations :ivar inbound_nat_rules: InboundNatRulesOperations operations :vartype inbound_nat_rules: azure.mgmt.network.v2017_11_01.operations.InboundNatRulesOperations :ivar load_balancer_load_balancing_rules: LoadBalancerLoadBalancingRulesOperations operations :vartype load_balancer_load_balancing_rules: azure.mgmt.network.v2017_11_01.operations.LoadBalancerLoadBalancingRulesOperations :ivar load_balancer_network_interfaces: LoadBalancerNetworkInterfacesOperations operations :vartype load_balancer_network_interfaces: azure.mgmt.network.v2017_11_01.operations.LoadBalancerNetworkInterfacesOperations :ivar load_balancer_probes: LoadBalancerProbesOperations operations :vartype load_balancer_probes: azure.mgmt.network.v2017_11_01.operations.LoadBalancerProbesOperations :ivar network_interfaces: NetworkInterfacesOperations operations :vartype network_interfaces: azure.mgmt.network.v2017_11_01.operations.NetworkInterfacesOperations :ivar network_interface_ip_configurations: NetworkInterfaceIPConfigurationsOperations operations :vartype network_interface_ip_configurations: azure.mgmt.network.v2017_11_01.operations.NetworkInterfaceIPConfigurationsOperations :ivar network_interface_load_balancers: NetworkInterfaceLoadBalancersOperations operations :vartype network_interface_load_balancers: azure.mgmt.network.v2017_11_01.operations.NetworkInterfaceLoadBalancersOperations :ivar network_security_groups: NetworkSecurityGroupsOperations operations :vartype network_security_groups: azure.mgmt.network.v2017_11_01.operations.NetworkSecurityGroupsOperations :ivar security_rules: SecurityRulesOperations operations :vartype security_rules: azure.mgmt.network.v2017_11_01.operations.SecurityRulesOperations :ivar default_security_rules: DefaultSecurityRulesOperations operations :vartype default_security_rules: azure.mgmt.network.v2017_11_01.operations.DefaultSecurityRulesOperations :ivar network_watchers: NetworkWatchersOperations operations :vartype network_watchers: azure.mgmt.network.v2017_11_01.operations.NetworkWatchersOperations :ivar packet_captures: PacketCapturesOperations operations :vartype packet_captures: azure.mgmt.network.v2017_11_01.operations.PacketCapturesOperations :ivar connection_monitors: ConnectionMonitorsOperations operations :vartype connection_monitors: azure.mgmt.network.v2017_11_01.operations.ConnectionMonitorsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.network.v2017_11_01.operations.Operations :ivar public_ip_addresses: PublicIPAddressesOperations operations :vartype public_ip_addresses: azure.mgmt.network.v2017_11_01.operations.PublicIPAddressesOperations :ivar route_filters: RouteFiltersOperations operations :vartype route_filters: azure.mgmt.network.v2017_11_01.operations.RouteFiltersOperations :ivar route_filter_rules: RouteFilterRulesOperations operations :vartype route_filter_rules: azure.mgmt.network.v2017_11_01.operations.RouteFilterRulesOperations :ivar route_tables: RouteTablesOperations operations :vartype route_tables: azure.mgmt.network.v2017_11_01.operations.RouteTablesOperations :ivar routes: RoutesOperations operations :vartype routes: azure.mgmt.network.v2017_11_01.operations.RoutesOperations :ivar bgp_service_communities: BgpServiceCommunitiesOperations operations :vartype bgp_service_communities: azure.mgmt.network.v2017_11_01.operations.BgpServiceCommunitiesOperations :ivar usages: UsagesOperations operations :vartype usages: azure.mgmt.network.v2017_11_01.operations.UsagesOperations :ivar virtual_networks: VirtualNetworksOperations operations :vartype virtual_networks: azure.mgmt.network.v2017_11_01.operations.VirtualNetworksOperations :ivar subnets: SubnetsOperations operations :vartype subnets: azure.mgmt.network.v2017_11_01.operations.SubnetsOperations :ivar virtual_network_peerings: VirtualNetworkPeeringsOperations operations :vartype virtual_network_peerings: azure.mgmt.network.v2017_11_01.operations.VirtualNetworkPeeringsOperations :ivar virtual_network_gateways: VirtualNetworkGatewaysOperations operations :vartype virtual_network_gateways: azure.mgmt.network.v2017_11_01.operations.VirtualNetworkGatewaysOperations :ivar virtual_network_gateway_connections: VirtualNetworkGatewayConnectionsOperations operations :vartype virtual_network_gateway_connections: azure.mgmt.network.v2017_11_01.operations.VirtualNetworkGatewayConnectionsOperations :ivar local_network_gateways: LocalNetworkGatewaysOperations operations :vartype local_network_gateways: azure.mgmt.network.v2017_11_01.operations.LocalNetworkGatewaysOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str base_url=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None if not base_url: base_url = 'https://management.azure.com' self._config = NetworkManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.application_gateways = ApplicationGatewaysOperations( self._client, self._config, self._serialize, self._deserialize) self.application_security_groups = ApplicationSecurityGroupsOperations( self._client, self._config, self._serialize, self._deserialize) self.available_endpoint_services = AvailableEndpointServicesOperations( self._client, self._config, self._serialize, self._deserialize) self.express_route_circuit_authorizations = ExpressRouteCircuitAuthorizationsOperations( self._client, self._config, self._serialize, self._deserialize) self.express_route_circuit_peerings = ExpressRouteCircuitPeeringsOperations( self._client, self._config, self._serialize, self._deserialize) self.express_route_circuits = ExpressRouteCircuitsOperations( self._client, self._config, self._serialize, self._deserialize) self.express_route_service_providers = ExpressRouteServiceProvidersOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancers = LoadBalancersOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancer_backend_address_pools = LoadBalancerBackendAddressPoolsOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancer_frontend_ip_configurations = LoadBalancerFrontendIPConfigurationsOperations( self._client, self._config, self._serialize, self._deserialize) self.inbound_nat_rules = InboundNatRulesOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancer_load_balancing_rules = LoadBalancerLoadBalancingRulesOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancer_network_interfaces = LoadBalancerNetworkInterfacesOperations( self._client, self._config, self._serialize, self._deserialize) self.load_balancer_probes = LoadBalancerProbesOperations( self._client, self._config, self._serialize, self._deserialize) self.network_interfaces = NetworkInterfacesOperations( self._client, self._config, self._serialize, self._deserialize) self.network_interface_ip_configurations = NetworkInterfaceIPConfigurationsOperations( self._client, self._config, self._serialize, self._deserialize) self.network_interface_load_balancers = NetworkInterfaceLoadBalancersOperations( self._client, self._config, self._serialize, self._deserialize) self.network_security_groups = NetworkSecurityGroupsOperations( self._client, self._config, self._serialize, self._deserialize) self.security_rules = SecurityRulesOperations( self._client, self._config, self._serialize, self._deserialize) self.default_security_rules = DefaultSecurityRulesOperations( self._client, self._config, self._serialize, self._deserialize) self.network_watchers = NetworkWatchersOperations( self._client, self._config, self._serialize, self._deserialize) self.packet_captures = PacketCapturesOperations( self._client, self._config, self._serialize, self._deserialize) self.connection_monitors = ConnectionMonitorsOperations( self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.public_ip_addresses = PublicIPAddressesOperations( self._client, self._config, self._serialize, self._deserialize) self.route_filters = RouteFiltersOperations( self._client, self._config, self._serialize, self._deserialize) self.route_filter_rules = RouteFilterRulesOperations( self._client, self._config, self._serialize, self._deserialize) self.route_tables = RouteTablesOperations( self._client, self._config, self._serialize, self._deserialize) self.routes = RoutesOperations( self._client, self._config, self._serialize, self._deserialize) self.bgp_service_communities = BgpServiceCommunitiesOperations( self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations( self._client, self._config, self._serialize, self._deserialize) self.virtual_networks = VirtualNetworksOperations( self._client, self._config, self._serialize, self._deserialize) self.subnets = SubnetsOperations( self._client, self._config, self._serialize, self._deserialize) self.virtual_network_peerings = VirtualNetworkPeeringsOperations( self._client, self._config, self._serialize, self._deserialize) self.virtual_network_gateways = VirtualNetworkGatewaysOperations( self._client, self._config, self._serialize, self._deserialize) self.virtual_network_gateway_connections = VirtualNetworkGatewayConnectionsOperations( self._client, self._config, self._serialize, self._deserialize) self.local_network_gateways = LocalNetworkGatewaysOperations( self._client, self._config, self._serialize, self._deserialize) def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> NetworkManagementClient self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
67.06746
180
0.803444
06ac7364868000519585e8db0c299aba9c7d7257
4,371
py
Python
.waf-2.0.20-36f5354d605298f6a89c09e0c7ef6c1d/waflib/Tools/c_tests.py
nimbostratus214/FlappyBird
20c2ff59d443bf05003f680d3d5dc9d84aef7744
[ "MIT" ]
1
2022-03-22T08:08:35.000Z
2022-03-22T08:08:35.000Z
ns-3-dev/.waf3-2.0.21-c6c9a875365426e5928462b9b74d40b5/waflib/Tools/c_tests.py
Marquez607/Wireless-Perf-Sim
1086759b6dbe7da192225780d5fe6a3da0c5eb07
[ "MIT" ]
null
null
null
ns-3-dev/.waf3-2.0.21-c6c9a875365426e5928462b9b74d40b5/waflib/Tools/c_tests.py
Marquez607/Wireless-Perf-Sim
1086759b6dbe7da192225780d5fe6a3da0c5eb07
[ "MIT" ]
null
null
null
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file from waflib import Task from waflib.Configure import conf from waflib.TaskGen import feature,before_method,after_method LIB_CODE=''' #ifdef _MSC_VER #define testEXPORT __declspec(dllexport) #else #define testEXPORT #endif testEXPORT int lib_func(void) { return 9; } ''' MAIN_CODE=''' #ifdef _MSC_VER #define testEXPORT __declspec(dllimport) #else #define testEXPORT #endif testEXPORT int lib_func(void); int main(int argc, char **argv) { (void)argc; (void)argv; return !(lib_func() == 9); } ''' @feature('link_lib_test') @before_method('process_source') def link_lib_test_fun(self): def write_test_file(task): task.outputs[0].write(task.generator.code) rpath=[] if getattr(self,'add_rpath',False): rpath=[self.bld.path.get_bld().abspath()] mode=self.mode m='%s %s'%(mode,mode) ex=self.test_exec and'test_exec'or'' bld=self.bld bld(rule=write_test_file,target='test.'+mode,code=LIB_CODE) bld(rule=write_test_file,target='main.'+mode,code=MAIN_CODE) bld(features='%sshlib'%m,source='test.'+mode,target='test') bld(features='%sprogram %s'%(m,ex),source='main.'+mode,target='app',use='test',rpath=rpath) @conf def check_library(self,mode=None,test_exec=True): if not mode: mode='c' if self.env.CXX: mode='cxx' self.check(compile_filename=[],features='link_lib_test',msg='Checking for libraries',mode=mode,test_exec=test_exec) INLINE_CODE=''' typedef int foo_t; static %s foo_t static_foo () {return 0; } %s foo_t foo () { return 0; } ''' INLINE_VALUES=['inline','__inline__','__inline'] @conf def check_inline(self,**kw): self.start_msg('Checking for inline') if not'define_name'in kw: kw['define_name']='INLINE_MACRO' if not'features'in kw: if self.env.CXX: kw['features']=['cxx'] else: kw['features']=['c'] for x in INLINE_VALUES: kw['fragment']=INLINE_CODE%(x,x) try: self.check(**kw) except self.errors.ConfigurationError: continue else: self.end_msg(x) if x!='inline': self.define('inline',x,quote=False) return x self.fatal('could not use inline functions') LARGE_FRAGMENT='''#include <unistd.h> int main(int argc, char **argv) { (void)argc; (void)argv; return !(sizeof(off_t) >= 8); } ''' @conf def check_large_file(self,**kw): if not'define_name'in kw: kw['define_name']='HAVE_LARGEFILE' if not'execute'in kw: kw['execute']=True if not'features'in kw: if self.env.CXX: kw['features']=['cxx','cxxprogram'] else: kw['features']=['c','cprogram'] kw['fragment']=LARGE_FRAGMENT kw['msg']='Checking for large file support' ret=True try: if self.env.DEST_BINFMT!='pe': ret=self.check(**kw) except self.errors.ConfigurationError: pass else: if ret: return True kw['msg']='Checking for -D_FILE_OFFSET_BITS=64' kw['defines']=['_FILE_OFFSET_BITS=64'] try: ret=self.check(**kw) except self.errors.ConfigurationError: pass else: self.define('_FILE_OFFSET_BITS',64) return ret self.fatal('There is no support for large files') ENDIAN_FRAGMENT=''' #ifdef _MSC_VER #define testshlib_EXPORT __declspec(dllexport) #else #define testshlib_EXPORT #endif short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int testshlib_EXPORT use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } extern int foo; ''' class grep_for_endianness(Task.Task): color='PINK' def run(self): txt=self.inputs[0].read(flags='rb').decode('latin-1') if txt.find('LiTTleEnDian')>-1: self.generator.tmp.append('little') elif txt.find('BIGenDianSyS')>-1: self.generator.tmp.append('big') else: return-1 @feature('grep_for_endianness') @after_method('apply_link') def grep_for_endianness_fun(self): self.create_task('grep_for_endianness',self.link_task.outputs[0]) @conf def check_endianness(self): tmp=[] def check_msg(self): return tmp[0] self.check(fragment=ENDIAN_FRAGMENT,features='c cshlib grep_for_endianness',msg='Checking for endianness',define='ENDIANNESS',tmp=tmp,okmsg=check_msg,confcache=None) return tmp[0]
27.490566
166
0.716541
e06a24a8960c628ec08a500f279e151fe7253d54
45,669
py
Python
trident/layers/pytorch_rnn.py
cronin4392/trident
1c1eb01bcde861496ce83e265ff071fc9bcb9db2
[ "MIT" ]
68
2020-11-13T06:40:52.000Z
2022-03-28T12:40:59.000Z
trident/layers/pytorch_rnn.py
cronin4392/trident
1c1eb01bcde861496ce83e265ff071fc9bcb9db2
[ "MIT" ]
1
2021-08-15T17:06:35.000Z
2021-11-10T04:42:52.000Z
trident/layers/pytorch_rnn.py
cronin4392/trident
1c1eb01bcde861496ce83e265ff071fc9bcb9db2
[ "MIT" ]
11
2020-11-24T13:14:16.000Z
2021-12-26T07:41:29.000Z
"""Pytorch recursive layers definition in trident""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numbers import random import warnings from typing import Optional, Tuple, overload,Union import torch import torch.nn as nn from torch import Tensor, _VF from torch._jit_internal import List from torch.nn import init from torch.nn.parameter import Parameter from torch.nn.utils.rnn import PackedSequence from trident.layers.pytorch_layers import Embedding, Dense, SoftMax from trident.backend.pytorch_ops import * from trident.backend.common import * from trident.backend.pytorch_backend import Layer, get_device __all__ = ['RNNBase','RNN','LSTM','GRU','LSTMDecoder'] _rnn_impls = { 'RNN_TANH': _VF.rnn_tanh, 'RNN_RELU': _VF.rnn_relu, } def apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor: return tensor.index_select(dim, permutation) class RNNBase(Layer): __constants__ = ['mode', 'input_filters', 'hidden_size', 'num_layers', 'use_bias', 'batch_first', 'dropout_rate', 'bidirectional'] mode: str input_filters: int hidden_size: int num_layers: int use_bias: bool batch_first: bool dropout_rate: float bidirectional: bool in_sequence: bool filter_index: int def __init__(self, mode: str, hidden_size: int,proj_size: int = 0, num_layers: int = 1,stateful=False, use_bias: bool = True, batch_first: bool = False, dropout_rate: float = 0., bidirectional: bool = False,keep_output=False,in_sequence=True,filter_index=-1,name=None) -> None: super(RNNBase, self).__init__(name=name,keep_output=keep_output) self.in_sequence=in_sequence self.filter_index=filter_index self.mode = mode self.hidden_size = hidden_size self.proj_size= proj_size self.num_layers = num_layers self.use_bias = use_bias self.stateful=stateful self.hx=None self._batch_first = batch_first if not self._batch_first: self.batch_index =1 else: self.batch_index = 0 self.dropout_rate = float(dropout_rate) self.bidirectional = bidirectional self.num_directions = 2 if bidirectional else 1 if not isinstance(dropout_rate, numbers.Number) or not 0 <= dropout_rate <= 1 or \ isinstance(dropout_rate, bool): raise ValueError("dropout should be a number in range [0, 1] " "representing the probability of an element being " "zeroed") if dropout_rate > 0 and num_layers == 1: warnings.warn("dropout option adds dropout after all but last " "recurrent layer, so non-zero dropout expects " "num_layers greater than 1, but got dropout={} and " "num_layers={}".format(dropout_rate, num_layers)) if mode == 'LSTM': self.gate_size = 4 * hidden_size elif mode == 'GRU': self.gate_size = 3 * hidden_size elif mode == 'RNN_TANH': self.gate_size = hidden_size elif mode == 'RNN_RELU': self.gate_size = hidden_size else: raise ValueError("Unrecognized RNN mode: " + mode) self._flat_weights_names = [] self._all_weights = [] @property def batch_first(self): return self._batch_first @batch_first.setter def batch_first(self, value: bool): if self._batch_first != value: self._batch_first = value if not self._batch_first: self.batch_index = 1 else: self.batch_index = 0 def clear_state(self): self.hx = None def initial_state(self,input) : max_batch_size = input.size(0) if self.batch_first else input.size(1) num_directions = 2 if self.bidirectional else 1 h_zeros=torch.zeros(self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=input.dtype, device=input.device).to(get_device()) c_zeros= torch.zeros(self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=input.dtype, device=input.device).to(get_device()) if self.stateful: self.hx = (h_zeros, c_zeros) return self.hx else: return (h_zeros, c_zeros) def build(self, input_shape:TensorShape): if not self._built: for layer in range(self.num_layers): for direction in range(self.num_directions): layer_input_size = input_shape[-1] if layer == 0 else self.hidden_size * self.num_directions w_ih = Parameter(torch.Tensor(self.gate_size, layer_input_size).to(get_device())) w_hh = Parameter(torch.Tensor(self.gate_size, self.hidden_size).to(get_device())) b_ih = Parameter(torch.Tensor(self.gate_size).to(get_device())) # Second bias vector included for CuDNN compatibility. Only one # bias vector is needed in standard definition. b_hh = Parameter(torch.Tensor(self.gate_size).to(get_device())) layer_params = (w_ih, w_hh, b_ih, b_hh) suffix = '_reverse' if direction == 1 else '' param_names = ['weight_ih_l{}{}', 'weight_hh_l{}{}'] if self.use_bias: param_names += ['bias_ih_l{}{}', 'bias_hh_l{}{}'] param_names = [x.format(layer, suffix) for x in param_names] for name, param in zip(param_names, layer_params): if hasattr(self, "_flat_weights_names") and name in self._flat_weights_names: # keep self._flat_weights up to date if you do self.weight = ... idx = self._flat_weights_names.index(name) self._flat_weights[idx] = param self.register_parameter(name, param) self._flat_weights_names.extend(param_names) self._all_weights.append(param_names) self._flat_weights = [(lambda wn: getattr(self, wn) if hasattr(self, wn) else None)(wn) for wn in self._flat_weights_names] self.flatten_parameters() stdv = 1.0 / math.sqrt(self.hidden_size) for weight in self.parameters(): init.uniform_(weight, -stdv, stdv) # self.reset_parameters() # def __setattr__(self, attr, value): # if hasattr(self, "_flat_weights_names") and attr in self._flat_weights_names: # # keep self._flat_weights up to date if you do self.weight = ... # self.register_parameter(attr, value) # idx = self._flat_weights_names.index(attr) # self._flat_weights[idx] = value # #super(RNNBase, self).__setattr__(attr, value) def flatten_parameters(self) -> None: """Resets parameter data pointer so that they can use faster code paths. Right now, this works only if the module is on the GPU and cuDNN is enabled. Otherwise, it's a no-op. """ # Short-circuits if _flat_weights is only partially instantiated if len(self._flat_weights) != len(self._flat_weights_names): return for w in self._flat_weights: if not isinstance(w, Tensor): return # Short-circuits if any tensor in self._flat_weights is not acceptable to cuDNN # or the tensors in _flat_weights are of different dtypes first_fw = self._flat_weights[0] dtype = first_fw.dtype for fw in self._flat_weights: if (not isinstance(fw.data, Tensor) or not (fw.data.dtype == dtype) or not fw.data.is_cuda or not torch.backends.cudnn.is_acceptable(fw.data)): return # If any parameters alias, we fall back to the slower, copying code path. This is # a sufficient check, because overlapping parameter buffers that don't completely # alias would break the assumptions of the uniqueness check in # Module.named_parameters(). unique_data_ptrs = set(p.data_ptr() for p in self._flat_weights) if len(unique_data_ptrs) != len(self._flat_weights): return with torch.cuda.device_of(first_fw): import torch.backends.cudnn.rnn as rnn # Note: no_grad() is necessary since _cudnn_rnn_flatten_weight is # an inplace operation on self._flat_weights with torch.no_grad(): if torch._use_cudnn_rnn_flatten_weight(): num_weights = 4 if self.use_bias else 2 if self.proj_size > 0: num_weights += 1 torch._cudnn_rnn_flatten_weight( self._flat_weights, num_weights, self.input_filters, rnn.get_cudnn_mode(self.mode), self.hidden_size, self.proj_size,self.num_layers,self.batch_first, bool(self.bidirectional)) def _apply(self, fn): ret = super(RNNBase, self)._apply(fn) if self.built: # Resets _flat_weights # Note: be v. careful before removing this, as 3rd party device types # likely rely on this behavior to properly .to() modules like LSTM. self._flat_weights = [(lambda wn: getattr(self, wn) if hasattr(self, wn) else None)(wn) for wn in self._flat_weights_names] # Flattens params (on CUDA) self.flatten_parameters() return ret def reset_parameters(self) -> None: stdv = 1.0 / math.sqrt(self.hidden_size) for weight in self.parameters(): init.uniform_(weight, -stdv, stdv) def check_input(self, input: Tensor, batch_sizes: Optional[Tensor]) -> None: expected_input_dim = 2 if batch_sizes is not None else 3 if input.dim() != expected_input_dim: raise RuntimeError( 'input must have {} dimensions, got {}'.format( expected_input_dim, input.dim())) if self.input_filters != input.size(-1): raise RuntimeError( 'input.size(-1) must be equal to input_filters. Expected {}, got {}'.format( self.input_filters, input.size(-1))) def get_expected_hidden_size(self, input: Tensor, batch_sizes: Optional[Tensor]) -> Tuple[int, int, int]: if batch_sizes is not None: mini_batch = int(batch_sizes[0]) else: mini_batch = input.size(0) if self.batch_first else input.size(1) num_directions = 2 if self.bidirectional else 1 if self.proj_size > 0: expected_hidden_size = (self.num_layers * num_directions, mini_batch, self.proj_size) else: expected_hidden_size = (self.num_layers * num_directions, mini_batch, self.hidden_size) return expected_hidden_size def check_hidden_size(self, hx: Tensor, expected_hidden_size: Tuple[int, int, int], msg: str = 'Expected hidden size {}, got {}') -> None: if hx.size() != expected_hidden_size: raise RuntimeError(msg.format(expected_hidden_size, tuple(hx.size()))) def check_forward_args(self, input: Tensor, hidden: Tensor, batch_sizes: Optional[Tensor]): self.check_input(input, batch_sizes) expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes) self.check_hidden_size(hidden, expected_hidden_size) def permute_hidden(self, hx: Tensor, permutation: Optional[Tensor]): if permutation is None: return hx return apply_permutation(hx, permutation) def forward(self, input: Union[Tensor, PackedSequence], hx: Optional[Tensor] = None) -> Tuple[Union[Tensor, PackedSequence], Tensor]: is_packed = isinstance(input, PackedSequence) if is_packed: input, batch_sizes, sorted_indices, unsorted_indices = input max_batch_size = int(batch_sizes[0]) else: input = cast(Tensor, input) batch_sizes = None max_batch_size = input.size(0) if self.batch_first else input.size(1) sorted_indices = None unsorted_indices = None if hx is None: input = cast(Tensor, input) num_directions = 2 if self.bidirectional else 1 hx = torch.zeros(self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=input.dtype, device=input.device) else: # Each batch of the hidden state should match the input sequence that # the user believes he/she is passing in. hx = self.permute_hidden(hx, sorted_indices) assert hx is not None input = cast(Tensor, input) self.check_forward_args(input, hx, batch_sizes) _impl = _rnn_impls[self.mode] if batch_sizes is None: result = _impl(input, hx, self._flat_weights, self.bias, self.num_layers, self.dropout, self.training, self.bidirectional, self.batch_first) else: result = _impl(input, batch_sizes, hx, self._flat_weights, self.bias, self.num_layers, self.dropout, self.training, self.bidirectional) output: Union[Tensor, PackedSequence] output = result[0] hidden = result[1] if is_packed: output = PackedSequence(output, batch_sizes, sorted_indices, unsorted_indices) return output, self.permute_hidden(hidden, unsorted_indices) def extra_repr(self) -> str: s = '{input_filters}, {hidden_size}' if self.num_layers != 1: s += ', num_layers={num_layers}' if self.use_bias is not True: s += ', use_bias={use_bias}' if self.batch_first is not False: s += ', batch_first={batch_first}' if self.dropout_rate != 0: s += ', dropout_rate={dropout_rate}' if self.bidirectional is not False: s += ', bidirectional={bidirectional}' return s.format(**self.__dict__) def __setstate__(self, d): super(RNNBase, self).__setstate__(d) if 'all_weights' in d: self._all_weights = d['all_weights'] if isinstance(self._all_weights[0][0], str): return num_layers = self.num_layers num_directions = 2 if self.bidirectional else 1 self._flat_weights_names = [] self._all_weights = [] for layer in range(num_layers): for direction in range(num_directions): suffix = '_reverse' if direction == 1 else '' weights = ['weight_ih_l{}{}', 'weight_hh_l{}{}', 'bias_ih_l{}{}', 'bias_hh_l{}{}'] weights = [x.format(layer, suffix) for x in weights] if self.use_bias: self._all_weights += [weights] self._flat_weights_names.extend(weights) else: self._all_weights += [weights[:2]] self._flat_weights_names.extend(weights[:2]) self._flat_weights = [(lambda wn: getattr(self, wn) if hasattr(self, wn) else None)(wn) for wn in self._flat_weights_names] @property def all_weights(self) -> List[Parameter]: return [[getattr(self, weight) for weight in weights] for weights in self._all_weights] def _replicate_for_data_parallel(self): replica = super(RNNBase, self)._replicate_for_data_parallel() # Need to copy these caches, otherwise the replica will share the same # flat weights list. replica._flat_weights = replica._flat_weights[:] replica._flat_weights_names = replica._flat_weights_names[:] return replica class RNN(RNNBase): r"""Applies a multi-layer Elman RNN with :math:`\tanh` or :math:`\text{ReLU}` non-linearity to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{(t-1)} + b_{hh}) where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input at time `t`, and :math:`h_{(t-1)}` is the hidden state of the previous layer at time `t-1` or the initial hidden state at time `0`. If :attr:`nonlinearity` is ``'relu'``, then :math:`\text{ReLU}` is used instead of :math:`\tanh`. Args: input_filters: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two RNNs together to form a `stacked RNN`, with the second RNN taking in outputs of the first RNN and computing the final results. Default: 1 nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'`` bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as `(batch, seq, feature)`. Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each RNN layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional RNN. Default: ``False`` Inputs: input, h_0 - **input** of shape `(seq_len, batch, input_filters)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` or :func:`torch.nn.utils.rnn.pack_sequence` for details. - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1. Outputs: output, h_n - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features (`h_t`) from the last layer of the RNN, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. For the unpacked case, the directions can be separated using ``output.view(seq_len, batch, num_directions, hidden_size)``, with forward and backward being direction `0` and `1` respectively. Similarly, the directions can be separated in the packed case. - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the hidden state for `t = seq_len`. Like *output*, the layers can be separated using ``h_n.view(num_layers, num_directions, batch, hidden_size)``. Shape: - Input1: :math:`(L, N, H_{in})` tensor containing input features where :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length. - Input2: :math:`(S, N, H_{out})` tensor containing the initial hidden state for each element in the batch. :math:`H_{out}=\text{hidden\_size}` Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}` If the RNN is bidirectional, num_directions should be 2, else it should be 1. - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}` - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state for each element in the batch Attributes: weight_ih_l[k]: the learnable input-hidden weights of the k-th layer, of shape `(hidden_size, input_filters)` for `k = 0`. Otherwise, the shape is `(hidden_size, num_directions * hidden_size)` weight_hh_l[k]: the learnable hidden-hidden weights of the k-th layer, of shape `(hidden_size, hidden_size)` bias_ih_l[k]: the learnable input-hidden bias of the k-th layer, of shape `(hidden_size)` bias_hh_l[k]: the learnable hidden-hidden bias of the k-th layer, of shape `(hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` .. include:: ../cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.RNN(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn(input, h0) """ def __init__(self, *args, **kwargs): self.nonlinearity = kwargs.pop('nonlinearity', 'tanh') if self.nonlinearity == 'tanh': mode = 'RNN_TANH' elif self.nonlinearity == 'relu': mode = 'RNN_RELU' else: raise ValueError("Unknown nonlinearity '{}'".format(self.nonlinearity)) super(RNN, self).__init__(mode, *args, **kwargs) # XXX: LSTM and GRU implementation is different from RNNBase, this is because: # 1. we want to support nn.LSTM and nn.GRU in TorchScript and TorchScript in # its current state could not support the python Union Type or Any Type # 2. TorchScript static typing does not allow a Function or Callable type in # Dict values, so we have to separately call _VF instead of using _rnn_impls # 3. This is temporary only and in the transition state that we want to make it # on time for the release # # More discussion details in https://github.com/pytorch/pytorch/pull/23266 # # TODO: remove the overriding implementations for LSTM and GRU when TorchScript # support expressing these two modules generally. class LSTM(RNNBase): r"""Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} \\ i_t = \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{t-1} + b_{hi}) \\ f_t = \sigma(W_{if} x_t + b_{if} + W_{hf} h_{t-1} + b_{hf}) \\ g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hg} h_{t-1} + b_{hg}) \\ o_t = \sigma(W_{io} x_t + b_{io} + W_{ho} h_{t-1} + b_{ho}) \\ c_t = f_t \odot c_{t-1} + i_t \odot g_t \\ h_t = o_t \odot \tanh(c_t) \\ \end{array} where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the cell state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{t-1}` is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and :math:`i_t`, :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and output gates, respectively. :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product. In a multilayer LSTM, the input :math:`x^{(l)}_t` of the :math:`l` -th layer (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random variable which is :math:`0` with probability :attr:`dropout`. Args: input_filters: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two LSTMs together to form a `stacked LSTM`, with the second LSTM taking in outputs of the first LSTM and computing the final results. Default: 1 bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as (batch, seq, feature). Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each LSTM layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional LSTM. Default: ``False`` Inputs: input, (h_0, c_0) - **input** of shape `(seq_len, batch, input_filters)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` or :func:`torch.nn.utils.rnn.pack_sequence` for details. - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. If the LSTM is bidirectional, num_directions should be 2, else it should be 1. - **c_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial cell state for each element in the batch. If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero. Outputs: output, (h_n, c_n) - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features `(h_t)` from the last layer of the LSTM, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. For the unpacked case, the directions can be separated using ``output.view(seq_len, batch, num_directions, hidden_size)``, with forward and backward being direction `0` and `1` respectively. Similarly, the directions can be separated in the packed case. - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the hidden state for `t = seq_len`. Like *output*, the layers can be separated using ``h_n.view(num_layers, num_directions, batch, hidden_size)`` and similarly for *c_n*. - **c_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the cell state for `t = seq_len`. Attributes: weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer `(W_ii|W_if|W_ig|W_io)`, of shape `(4*hidden_size, input_filters)` for `k = 0`. Otherwise, the shape is `(4*hidden_size, num_directions * hidden_size)` weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer `(W_hi|W_hf|W_hg|W_ho)`, of shape `(4*hidden_size, hidden_size)` bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer `(b_ii|b_if|b_ig|b_io)`, of shape `(4*hidden_size)` bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer `(b_hi|b_hf|b_hg|b_ho)`, of shape `(4*hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` .. include:: ../cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.LSTM(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> c0 = torch.randn(2, 3, 20) >>> output, (hn, cn) = rnn(input, (h0, c0)) """ def __init__(self, hidden_size,proj_size=0,num_layers:int =2,stateful=False,use_bias=False,use_attention=False,attention_size=16,batch_first=False,dropout_rate=0,bidirectional=False,keep_output=False,name=None, **kwargs): super(LSTM, self).__init__(mode='LSTM', hidden_size=hidden_size, proj_size=proj_size, num_layers=num_layers, stateful = stateful, use_bias=use_bias, batch_first = batch_first, dropout_rate= dropout_rate, bidirectional = bidirectional, keep_output =keep_output, in_sequence = True, filter_index =-1, name = name) self.use_attention=use_attention self.attention_size=attention_size def get_expected_cell_size(self, input: Tensor, batch_sizes: Optional[Tensor]) -> Tuple[int, int, int]: if batch_sizes is not None: mini_batch = int(batch_sizes[0]) else: mini_batch = input.size(0) if self.batch_first else input.size(1) num_directions = 2 if self.bidirectional else 1 expected_hidden_size = (self.num_layers * num_directions, mini_batch, self.hidden_size) return expected_hidden_size def check_forward_args(self, input: Tensor, hidden: Tuple[Tensor, Tensor], batch_sizes: Optional[Tensor]): self.check_input(input, batch_sizes) expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes) try: self.check_hidden_size(hidden[0], self.get_expected_hidden_size(input, batch_sizes), 'Expected hidden[0] size {}, got {}') self.check_hidden_size(hidden[1], self.get_expected_cell_size(input, batch_sizes), 'Expected hidden[1] size {}, got {}') except: self.initial_state(input) def permute_hidden(self, hx: Tuple[Tensor, Tensor], permutation: Optional[Tensor]) -> Tuple[Tensor, Tensor]: if permutation is None: return hx return apply_permutation(hx[0], permutation), apply_permutation(hx[1], permutation) def attention(self, lstm_output): batch_size, sequence_length, channels = int_shape(lstm_output) if not hasattr(self, 'w_omega') or self.w_omega is None: self.w_omega = Parameter(torch.zeros(channels, self.attention_size).to(get_device())) self.u_omega = Parameter(torch.zeros(self.attention_size).to(get_device())) output_reshape = reshape(lstm_output, (-1, channels)) attn_tanh = torch.tanh(torch.mm(output_reshape, self.w_omega)) attn_hidden_layer = torch.mm(attn_tanh, reshape(self.u_omega, [-1, 1])) exps = reshape(torch.exp(attn_hidden_layer), [-1, sequence_length]) alphas = exps / reshape(torch.sum(exps, 1), [-1, 1]) alphas_reshape = reshape(alphas, [-1, sequence_length, 1]) return lstm_output * alphas_reshape @overload @torch._jit_internal._overload_method # noqa: F811 def forward(self, x: Tensor, hx: Optional[Tuple[Tensor, Tensor]] = None ) -> Tuple[Tensor, Tuple[Tensor, Tensor]]: # noqa: F811 pass @overload @torch._jit_internal._overload_method # noqa: F811 def forward(self, x:PackedSequence, hx: Optional[Tuple[Tensor, Tensor]] = None ) -> Tuple[PackedSequence, Tuple[Tensor, Tensor]]: # noqa: F811 pass def forward(self, x, hx=None): # helper to inject peephole connection if requested # def peep(x, c, C): # return x + C * c if use_peepholes else x # orig_input = x is_packed_sequence=isinstance(orig_input, PackedSequence) self.flatten_parameters() # xxx: isinstance check needs to be in conditional for TorchScript to compile if is_packed_sequence: x, batch_sizes, sorted_indices, unsorted_indices = x max_batch_size = batch_sizes[0] max_batch_size = int(max_batch_size) else: if not self.batch_first: x = x.transpose(1,0) batch_sizes = None #x.size(0) if self.batch_first else x.size(1) max_batch_size = x.size(0) if self.batch_first else x.size(1) sorted_indices = None unsorted_indices = None if not self.stateful: #if self.hidden_state is None or self.cell_state is None or max_batch_size!=int_shape(self.hidden_state)[1]: hx=self.initial_state(x) elif self.stateful and self.hx is None and hx is None: hx = self.initial_state(x) elif self.stateful and self.hx is None and hx is not None: self.hx=hx elif self.stateful and self.hx is not None: if batch_sizes is not None: mini_batch = int(batch_sizes[0]) else: mini_batch = x.size(0) if self.batch_first else x.size(1) #mini_batch size changed need re-initial hidden cell if self.hx[0].size(1)!=mini_batch: hx = self.initial_state(x) else: hx=self.hx hx = self.permute_hidden(hx, sorted_indices) self.check_forward_args(x, hx, batch_sizes) # if not isinstance(x, PackedSequence): # result = _VF.lstm(x,hx, self._flat_weights, self.use_bias, self.num_layers, # self.dropout_rate, self.training, self.bidirectional, self.batch_first) # else: # result = _VF.lstm(x, batch_sizes, hx, self._flat_weights, self.use_bias, # self.num_layers, self.dropout_rate, self.training, self.bidirectional) # if batch_sizes is None: result = _VF.lstm(x, hx, self._flat_weights, self.use_bias, self.num_layers, self.dropout_rate, self.training, self.bidirectional, self.batch_first) else: result = _VF.lstm(x, batch_sizes, hx, self._flat_weights, self.use_bias, self.num_layers, self.dropout_rate, self.training, self.bidirectional) output = result[0].permute(1, 0, 2) if self.batch_first == False else result[0] if self.use_attention: output = self.attention(output) hidden = result[1:] hidden=tuple([item.detach() for item in hidden]) if self.stateful: self.hx = hidden # xxx: isinstance check needs to be in conditional for TorchScript to compile if is_packed_sequence: output_packed = PackedSequence(output, batch_sizes, sorted_indices, unsorted_indices) return output_packed, self.permute_hidden(hidden, unsorted_indices) else: return output, self.permute_hidden(hidden, unsorted_indices) class LSTMDecoder(Layer): def __init__(self, num_chars, embedding_dim, h_size=512, num_layers=2,sequence_length=128,stateful=True, dropout_rate=0.2,bidirectional=False,use_attention=False,attention_size=16,teacher_forcing_ratio=1): super().__init__() self.teacher_forcing_ratio=teacher_forcing_ratio self.num_chars = num_chars self.embedding_dim=embedding_dim self.h_size = h_size self.num_layers = num_layers self.sequence_length=sequence_length self.embedding = Embedding(embedding_dim=256, num_embeddings=num_chars, sparse=False, norm_type=2, add_noise=True, noise_intensity=0.12) self.lstm = LSTM(hidden_size=h_size, num_layers=num_layers, stateful=stateful, batch_first=False, dropout_rate=dropout_rate, bidirectional=bidirectional, use_attention=use_attention, attention_size=attention_size) self.fc_out =Dense(num_chars,use_bias=False,activation=leaky_relu) self.softmax=SoftMax(axis=-1) def forward(self, input: Tensor, hx: Optional[Tuple[Tensor, Tensor]] = None ) -> Tuple[Tensor, Tuple[Tensor, Tensor]]: # noqa: F811 pass def forward(self, *x, **kwargs): # noqa: F811 # input = [batch size] # hidden = [n layers * n directions, batch size, hid dim] # cell = [n layers * n directions, batch size, hid dim] # n directions in the decoder will both always be 1, therefore: # hidden = [n layers, batch size, hid dim] # context = [n layers, batch size, hid dim] x,(self.hidden_state, self.cell_state) =unpack_singleton(x) B,N,C=int_shape(x) outputs =[] # input = [batch size,1] decoder_input =expand_dims(x[:,-1,:] ,1) # shape: (batch_size, input_size) decoder_hidden = (self.hidden_state, self.cell_state) # predict recursively for t in range(self.sequence_length): decoder_output, decoder_hidden = self.lstm(decoder_input, decoder_hidden) outputs.append(self.softmax(self.fc_out (decoder_output.squeeze(1)))) decoder_input = decoder_output return stack(outputs,1) class GRU(RNNBase): r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\ h_t = (1 - z_t) * n_t + z_t * h_{(t-1)} \end{array} where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`, :math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively. :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product. In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random variable which is :math:`0` with probability :attr:`dropout`. Args: input_filters: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two GRUs together to form a `stacked GRU`, with the second GRU taking in outputs of the first GRU and computing the final results. Default: 1 bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as (batch, seq, feature). Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each GRU layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False`` Inputs: input, h_0 - **input** of shape `(seq_len, batch, input_filters)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` for details. - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1. Outputs: output, h_n - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features h_t from the last layer of the GRU, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. For the unpacked case, the directions can be separated using ``output.view(seq_len, batch, num_directions, hidden_size)``, with forward and backward being direction `0` and `1` respectively. Similarly, the directions can be separated in the packed case. - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the hidden state for `t = seq_len` Like *output*, the layers can be separated using ``h_n.view(num_layers, num_directions, batch, hidden_size)``. Shape: - Input1: :math:`(L, N, H_{in})` tensor containing input features where :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length. - Input2: :math:`(S, N, H_{out})` tensor containing the initial hidden state for each element in the batch. :math:`H_{out}=\text{hidden\_size}` Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}` If the RNN is bidirectional, num_directions should be 2, else it should be 1. - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}` - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state for each element in the batch Attributes: weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer (W_ir|W_iz|W_in), of shape `(3*hidden_size, input_filters)` for `k = 0`. Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)` weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer (W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)` bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer (b_ir|b_iz|b_in), of shape `(3*hidden_size)` bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer (b_hr|b_hz|b_hn), of shape `(3*hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` .. include:: ../cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.GRU(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn(input, h0) """ def __init__(self, *args, **kwargs): super(GRU, self).__init__('GRU', *args, **kwargs) self.hidden_state = None self.stateful=kwargs.get('stateful',False) def initial_state(self,input) : max_batch_size = input.size(0) if self.batch_first else input.size(1) num_directions = 2 if self.bidirectional else 1 self.hidden_state = torch.zeros(self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=self.weights[0].dtype, device=self.weights[0].device, requires_grad=False) @overload @torch._jit_internal._overload_method # noqa: F811 def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: # noqa: F811 pass @overload @torch._jit_internal._overload_method # noqa: F811 def forward(self, input: PackedSequence, hx: Optional[Tensor] = None) -> Tuple[PackedSequence, Tensor]: # noqa: F811 pass def forward(self,x): # noqa: F811 orig_input = x # xxx: isinstance check needs to be in conditional for TorchScript to compile if isinstance(orig_input, PackedSequence): input, batch_sizes, sorted_indices, unsorted_indices = x max_batch_size = batch_sizes[0] max_batch_size = int(max_batch_size) else: if self.batch_first == False: x = x.permute(1, 0, 2) batch_sizes = None max_batch_size = x.size(0) if self.batch_first else x.size(1) sorted_indices = None unsorted_indices = None if self.stateful==False or self.hidden_state is None or max_batch_size!=int_shape(self.hidden_state)[1]: self.initial_state(x) else: self.hidden_state= self.permute_hidden(self.hidden_state, sorted_indices) self.check_forward_args(x, self.hidden_state, batch_sizes) if batch_sizes is None: result = _VF.gru(x, self.hidden_state, self._flat_weights, self.use_bias, self.num_layers, self.dropout_rate, self.training, self.bidirectional, self.batch_first) else: result = _VF.gru(x, batch_sizes, self.hidden_state, self._flat_weights, self.use_bias, self.num_layers, self.dropout_rate, self.training, self.bidirectional) output = result[0] self.hidden_state = result[1] # xxx: isinstance check needs to be in conditional for TorchScript to compile if isinstance(orig_input, PackedSequence): output_packed = PackedSequence(output, batch_sizes, sorted_indices, unsorted_indices) return output_packed, self.permute_hidden(self.hidden_state, unsorted_indices) else: if self.batch_first == False: x = x.permute(1, 0, 2) return output, self.permute_hidden(self.hidden_state, unsorted_indices)
47.325389
225
0.624165
3b9872471ba89cd099261e8b67c6db9c64ac79ee
1,976
py
Python
setup.py
sergiusnick/django-admin-env-notice
9fd162567d24a3c2991ea546aff06d6b03a7026a
[ "MIT" ]
null
null
null
setup.py
sergiusnick/django-admin-env-notice
9fd162567d24a3c2991ea546aff06d6b03a7026a
[ "MIT" ]
null
null
null
setup.py
sergiusnick/django-admin-env-notice
9fd162567d24a3c2991ea546aff06d6b03a7026a
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from setuptools import setup def read_file(filename): """Read a file into a string""" path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return '' def get_readme(): """Return the README file contents. Supports text,rst, and markdown""" for name in ('README', 'README.rst', 'README.md'): if os.path.exists(name): return read_file(name) return '' __import__('django_admin_env_notice') version = sys.modules['django_admin_env_notice'].get_version().replace(' ', '-') setup( name='django-admin-env-notice', version=version, description="""Visually distinguish environments in Django Admin""", long_description=get_readme(), long_description_content_type="text/markdown", author='Iurii Shikanov', author_email='dizballanze@gmail.com', url='https://github.com/dizballanze/django-admin-env-notice', packages=[ 'django_admin_env_notice', ], include_package_data=True, install_requires=[], license="MIT", zip_safe=False, keywords='django-admin-env-notice', classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
29.058824
80
0.616397
3b3c89ee73e238e0232fb31fdf17209acfad6b52
6,079
py
Python
tests/disk_metadata_test.py
Nowasky/PerfKitBenchmarker
cfa88e269eb373780910896ed4bdc8db09469753
[ "Apache-2.0" ]
3
2018-04-28T13:06:14.000Z
2020-06-09T02:39:44.000Z
tests/disk_metadata_test.py
Nowasky/PerfKitBenchmarker
cfa88e269eb373780910896ed4bdc8db09469753
[ "Apache-2.0" ]
1
2021-02-23T12:07:44.000Z
2021-02-23T12:07:44.000Z
tests/disk_metadata_test.py
Nowasky/PerfKitBenchmarker
cfa88e269eb373780910896ed4bdc8db09469753
[ "Apache-2.0" ]
6
2019-06-11T18:59:57.000Z
2021-03-02T19:14:42.000Z
# Copyright 2018 PerfKitBenchmarker 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. """Test the annotation of disk objects with metadata.""" import unittest from absl import flags import mock from perfkitbenchmarker import benchmark_spec from perfkitbenchmarker import context from perfkitbenchmarker import disk from perfkitbenchmarker import vm_util from perfkitbenchmarker.configs import benchmark_config_spec from perfkitbenchmarker.providers.aws import aws_disk from perfkitbenchmarker.providers.aws import aws_virtual_machine from perfkitbenchmarker.providers.azure import azure_disk from perfkitbenchmarker.providers.azure import azure_virtual_machine from perfkitbenchmarker.providers.azure import flags as azure_flags from perfkitbenchmarker.providers.gcp import gce_disk from tests import pkb_common_test_case FLAGS = flags.FLAGS _BENCHMARK_NAME = 'name' _BENCHMARK_UID = 'uid' _COMPONENT = 'test_component' class _DiskMetadataTestCase(pkb_common_test_case.PkbCommonTestCase): def setUp(self): super(_DiskMetadataTestCase, self).setUp() self.addCleanup(context.SetThreadBenchmarkSpec, None) p = mock.patch(vm_util.__name__ + '.GetTempDir', return_value='/tmp/dir') p.start() self.addCleanup(p.stop) config_spec = benchmark_config_spec.BenchmarkConfigSpec( _BENCHMARK_NAME, flag_values=FLAGS, vm_groups={}) self.benchmark_spec = benchmark_spec.BenchmarkSpec( mock.MagicMock(), config_spec, _BENCHMARK_UID) class GcpDiskMetadataTest(_DiskMetadataTestCase): def testPDStandard(self): disk_spec = disk.BaseDiskSpec(_COMPONENT, disk_size=2, disk_type=gce_disk.PD_STANDARD) disk_obj = gce_disk.GceDisk(disk_spec, 'name', 'zone', 'project') self.assertDictContainsSubset( {disk.MEDIA: disk.HDD, disk.REPLICATION: disk.ZONE}, disk_obj.metadata ) class AwsDiskMetadataTest(_DiskMetadataTestCase): def DoAwsDiskTest(self, disk_type, machine_type, goal_media, goal_replication): disk_spec = aws_disk.AwsDiskSpec(_COMPONENT, disk_size=2, disk_type=disk_type) vm_spec = aws_virtual_machine.AwsVmSpec( 'test_vm_spec.AWS', zone='us-east-1a', machine_type=machine_type) vm = aws_virtual_machine.Ubuntu1804BasedAwsVirtualMachine(vm_spec) vm.CreateScratchDisk(disk_spec) self.assertDictContainsSubset( {disk.MEDIA: goal_media, disk.REPLICATION: goal_replication}, vm.scratch_disks[0].metadata ) def testLocalSSD(self): self.DoAwsDiskTest( disk.LOCAL, 'c3.2xlarge', disk.SSD, disk.NONE) def testLocalHDD(self): self.DoAwsDiskTest( disk.LOCAL, 'd2.2xlarge', disk.HDD, disk.NONE) class AzureDiskMetadataTest(_DiskMetadataTestCase): def DoAzureDiskTest(self, storage_type, disk_type, machine_type, goal_media, goal_replication, goal_host_caching, disk_size=2, goal_size=2, goal_stripes=1): FLAGS.azure_storage_type = storage_type FLAGS.azure_host_caching = goal_host_caching disk_spec = disk.BaseDiskSpec(_COMPONENT, disk_size=disk_size, disk_type=disk_type, num_striped_disks=goal_stripes) vm_spec = azure_virtual_machine.AzureVmSpec( 'test_vm_spec.AZURE', zone='eastus2', machine_type=machine_type) vm = azure_virtual_machine.Ubuntu1604BasedAzureVirtualMachine(vm_spec) azure_disk.AzureDisk.Create = mock.Mock() azure_disk.AzureDisk.Attach = mock.Mock() vm.StripeDisks = mock.Mock() vm.CreateScratchDisk(disk_spec) expected = {disk.MEDIA: goal_media, disk.REPLICATION: goal_replication, 'num_stripes': goal_stripes, 'size': goal_size} if goal_host_caching: expected[azure_disk.HOST_CACHING] = goal_host_caching self.assertDictContainsSubset(expected, vm.scratch_disks[0].metadata) def testPremiumStorage(self): self.DoAzureDiskTest(azure_flags.PLRS, azure_disk.PREMIUM_STORAGE, 'Standard_D1', disk.SSD, disk.ZONE, azure_flags.READ_ONLY) def testStandardDisk(self): self.DoAzureDiskTest(azure_flags.ZRS, azure_disk.STANDARD_DISK, 'Standard_D1', disk.HDD, disk.REGION, azure_flags.NONE) def testLocalHDD(self): self.DoAzureDiskTest(azure_flags.LRS, disk.LOCAL, 'Standard_A1', disk.HDD, disk.NONE, None) def testLocalSSD(self): self.DoAzureDiskTest(azure_flags.LRS, disk.LOCAL, 'Standard_DS2', disk.SSD, disk.NONE, None) def testStripedDisk(self): self.DoAzureDiskTest(azure_flags.LRS, azure_disk.STANDARD_DISK, 'Standard_D1', disk.HDD, disk.ZONE, azure_flags.READ_ONLY, disk_size=5, goal_size=10, goal_stripes=2) if __name__ == '__main__': unittest.main()
34.344633
77
0.646817
b53fa5fea2b5eb911732df16bfac456c04a7720c
1,650
py
Python
ssd/structures/container.py
kristine-li/SSD-Server
35d680a02284feb8e4800c9ef7a2655fbc16261d
[ "MIT" ]
1
2021-04-16T15:50:26.000Z
2021-04-16T15:50:26.000Z
ssd/structures/container.py
kristine-li/SSD-Server
35d680a02284feb8e4800c9ef7a2655fbc16261d
[ "MIT" ]
6
2020-03-30T11:25:15.000Z
2022-01-13T02:27:12.000Z
ssd/structures/container.py
kristine-li/SSD-Server
35d680a02284feb8e4800c9ef7a2655fbc16261d
[ "MIT" ]
null
null
null
class Container: """ Help class for manage boxes, labels, etc... Not inherit dict due to `default_collate` will change dict's subclass to dict. """ def __init__(self, *args, **kwargs): self._data_dict = dict(*args, **kwargs) def __setattr__(self, key, value): object.__setattr__(self, key, value) def __getitem__(self, key): return self._data_dict[key] def __iter__(self): return self._data_dict.__iter__() def __setitem__(self, key, value): self._data_dict[key] = value def _call(self, name, *args, **kwargs): keys = list(self._data_dict.keys()) for key in keys: value = self._data_dict[key] if hasattr(value, name): self._data_dict[key] = getattr(value, name)(*args, **kwargs) return self def to(self, *args, **kwargs): return self._call('to', *args, **kwargs) def numpy(self): return self._call('numpy') def detach(self): return self._call('detach') def resize(self, size): """resize boxes Args: size: (width, height) Returns: self """ img_width = getattr(self, 'img_width', -1) img_height = getattr(self, 'img_height', -1) assert img_width > 0 and img_height > 0 assert 'boxes' in self._data_dict boxes = self._data_dict['boxes'] new_width, new_height = size boxes[:, 0::2] *= (new_width / img_width) boxes[:, 1::2] *= (new_height / img_height) return self def __repr__(self): return self._data_dict.__repr__()
28.448276
82
0.575758
805ca98a4030e01d6f4bcb51af8a3452f15c5819
14,395
py
Python
diofant/tests/vector/test_coordsysrect.py
project-kotinos/diofant___diofant
882549ac3a4dac238695aa620c02fce6ca33f9d3
[ "BSD-3-Clause" ]
1
2021-08-22T09:34:15.000Z
2021-08-22T09:34:15.000Z
diofant/tests/vector/test_coordsysrect.py
project-kotinos/diofant___diofant
882549ac3a4dac238695aa620c02fce6ca33f9d3
[ "BSD-3-Clause" ]
null
null
null
diofant/tests/vector/test_coordsysrect.py
project-kotinos/diofant___diofant
882549ac3a4dac238695aa620c02fce6ca33f9d3
[ "BSD-3-Clause" ]
null
null
null
import pytest from diofant import ImmutableMatrix as Matrix from diofant import Symbol, cos, pi, simplify, sin, symbols, zeros from diofant.vector.coordsysrect import CoordSysCartesian from diofant.vector.functions import express from diofant.vector.orienters import (AxisOrienter, BodyOrienter, QuaternionOrienter, SpaceOrienter) from diofant.vector.point import Point from diofant.vector.scalar import BaseScalar from diofant.vector.vector import Vector __all__ = () a, b, c, q = symbols('a b c q') q1, q2, q3, q4 = symbols('q1 q2 q3 q4') def test_func_args(): A = CoordSysCartesian('A') assert A.x.func(*A.x.args) == A.x expr = 3*A.x + 4*A.y assert expr.func(*expr.args) == expr assert A.i.func(*A.i.args) == A.i v = A.x*A.i + A.y*A.j + A.z*A.k assert v.func(*v.args) == v assert A.origin.func(*A.origin.args) == A.origin pytest.raises(TypeError, lambda: CoordSysCartesian('B', parent=A, location=Point('a'))) pytest.raises(TypeError, lambda: CoordSysCartesian('A', rotation_matrix=a)) pytest.raises(TypeError, lambda: CoordSysCartesian('B', parent=a)) pytest.raises(ValueError, lambda: CoordSysCartesian('A', vector_names=(1,))) pytest.raises(TypeError, lambda: CoordSysCartesian('A', vector_names=("a", "b", 1))) def test_point(): pytest.raises(TypeError, lambda: Point('a', position=1)) pytest.raises(TypeError, lambda: Point('a', parent_point=1)) def test_coordsyscartesian_equivalence(): A = CoordSysCartesian('A') A1 = CoordSysCartesian('A') assert A1 == A B = CoordSysCartesian('B') assert A != B def test_orienters(): A = CoordSysCartesian('A') axis_orienter = AxisOrienter(a, A.k) B = body_orienter = BodyOrienter(a, b, c, '123') assert (B.angle1, B.angle2, B.angle3) == (a, b, c) assert B.rot_order == '123' B = BodyOrienter(a, b, c, Symbol('123')) assert B.rot_order == '123' space_orienter = SpaceOrienter(a, b, c, '123') Q = q_orienter = QuaternionOrienter(q1, q2, q3, q4) assert (Q.q0, Q.q1, Q.q2, Q.q3) == (q1, q2, q3, q4) assert axis_orienter.rotation_matrix(A) == Matrix([ [ cos(a), sin(a), 0], [-sin(a), cos(a), 0], [ 0, 0, 1]]) assert body_orienter.rotation_matrix() == Matrix([ [ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a), sin(a)*sin(c) - sin(b)*cos(a)*cos(c)], [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(c) + sin(b)*sin(c)*cos(a)], [ sin(b), -sin(a)*cos(b), cos(a)*cos(b)]]) assert space_orienter.rotation_matrix() == Matrix([ [cos(b)*cos(c), sin(c)*cos(b), -sin(b)], [sin(a)*sin(b)*cos(c) - sin(c)*cos(a), sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)], [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) + sin(b)*sin(c)*cos(a), cos(a)*cos(b)]]) assert q_orienter.rotation_matrix() == Matrix([ [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4], [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) B = CoordSysCartesian('T') pytest.raises(ValueError, lambda: A.orient_new_axis('A', a, B.i)) pytest.raises(TypeError, lambda: BodyOrienter(a, b, c, '12')) pytest.raises(TypeError, lambda: BodyOrienter(a, b, c, '111')) def test_coordinate_vars(): """ Tests the coordinate variables functionality with respect to reorientation of coordinate systems. """ A = CoordSysCartesian('A') # Note that the name given on the lhs is different from A.x._name assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x assert BaseScalar('A.y', 1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y assert BaseScalar('A.z', 2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__() assert all(isinstance(_, BaseScalar) for _ in (A.x, A.y, A.z)) assert A.x*A.y == A.y*A.x pytest.raises(TypeError, lambda: BaseScalar('Ax', 0, 1, ' ', ' ')) pytest.raises(ValueError, lambda: BaseScalar('Ax', 5, A, ' ', ' ')) assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z} assert A.x.system == A assert A.x.diff(A.x) == 1 B = A.orient_new_axis('B', q, A.k) assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q), B.x: A.x*cos(q) + A.y*sin(q)} assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q) assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q) assert express(B.z, A, variables=True) == A.z assert express(B.x*B.y*B.z, A, variables=True) == \ A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q)) assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \ (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + B.y*cos(q))*A.j + B.z*A.k assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, variables=True)) == \ A.x*A.i + A.y*A.j + A.z*A.k assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \ (A.x*cos(q) + A.y*sin(q))*B.i + \ (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, variables=True)) == \ B.x*B.i + B.y*B.j + B.z*B.k pytest.raises(TypeError, lambda: express(A.x, 1)) pytest.raises(ValueError, lambda: express(A.i, B, A)) pytest.raises(TypeError, lambda: express(A.i | A.j, B, 1)) pytest.raises(ValueError, lambda: express(1, B, 1)) N = B.orient_new_axis('N', -q, B.k) assert N.scalar_map(A) == \ {N.x: A.x, N.z: A.z, N.y: A.y} C = A.orient_new_axis('C', q, A.i + A.j + A.k) mapping = A.scalar_map(C) assert mapping[A.x] == (C.x*(2*cos(q) + 1)/3 + C.y*(-2*sin(q + pi/6) + 1)/3 + C.z*(-2*cos(q + pi/3) + 1)/3) assert mapping[A.y] == (C.x*(-2*cos(q + pi/3) + 1)/3 + C.y*(2*cos(q) + 1)/3 + C.z*(-2*sin(q + pi/6) + 1)/3) assert mapping[A.z] == (C.x*(-2*sin(q + pi/6) + 1)/3 + C.y*(-2*cos(q + pi/3) + 1)/3 + C.z*(2*cos(q) + 1)/3) D = A.locate_new('D', a*A.i + b*A.j + c*A.k) assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b} E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k) assert A.scalar_map(E) == {A.z: E.z + c, A.x: E.x*cos(a) - E.y*sin(a) + a, A.y: E.x*sin(a) + E.y*cos(a) + b} assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a), E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a), E.z: A.z - c} F = A.locate_new('F', Vector.zero) assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y} def test_rotation_matrix(): N = CoordSysCartesian('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) D = N.orient_new_axis('D', q4, N.j) E = N.orient_new_space('E', q1, q2, q3, '123') F = N.orient_new_quaternion('F', q1, q2, q3, q4) G = N.orient_new_body('G', q1, q2, q3, '123') assert N.rotation_matrix(C) == Matrix([ [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) * cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) test_mat = D.rotation_matrix(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.rotation_matrix(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) assert F.rotation_matrix(N) == Matrix([[ q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4], [ -2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) assert G.rotation_matrix(N) == Matrix([[ cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [ -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) pytest.raises(TypeError, lambda: G.rotation_matrix(a)) def test_vector(): """ Tests the effects of orientation of coordinate systems on basic vector operations. """ N = CoordSysCartesian('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) # Test to_matrix v1 = a*N.i + b*N.j + c*N.k assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)], [-a*sin(q1) + b*cos(q1)], [ c]]) # Test dot assert N.i.dot(A.i) == cos(q1) assert N.i.dot(A.j) == -sin(q1) assert N.i.dot(A.k) == 0 assert N.j.dot(A.i) == sin(q1) assert N.j.dot(A.j) == cos(q1) assert N.j.dot(A.k) == 0 assert N.k.dot(A.i) == 0 assert N.k.dot(A.j) == 0 assert N.k.dot(A.k) == 1 assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \ (A.i + A.j).dot(N.i) assert A.i.dot(C.i) == cos(q3) assert A.i.dot(C.j) == 0 assert A.i.dot(C.k) == sin(q3) assert A.j.dot(C.i) == sin(q2)*sin(q3) assert A.j.dot(C.j) == cos(q2) assert A.j.dot(C.k) == -sin(q2)*cos(q3) assert A.k.dot(C.i) == -cos(q2)*sin(q3) assert A.k.dot(C.j) == sin(q2) assert A.k.dot(C.k) == cos(q2)*cos(q3) pytest.raises(TypeError, lambda: N.i.dot(A.x)) # Test cross assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j assert N.j.cross(A.i) == -cos(q1)*A.k assert N.j.cross(A.j) == sin(q1)*A.k assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j assert N.k.cross(A.i) == A.j assert N.k.cross(A.j) == -A.i assert N.k.cross(A.k) == Vector.zero assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k assert A.i.cross(C.i) == sin(q3)*C.j assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k assert A.i.cross(C.k) == -cos(q3)*C.j assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \ (-sin(q2)*sin(q3))*A.k assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j pytest.raises(TypeError, lambda: N.i.cross(A.x)) def test_orient_new_methods(): N = CoordSysCartesian('N') orienter1 = AxisOrienter(q4, N.j) orienter2 = SpaceOrienter(q1, q2, q3, '123') orienter3 = QuaternionOrienter(q1, q2, q3, q4) orienter4 = BodyOrienter(q1, q2, q3, '123') D = N.orient_new('D', (orienter1, )) E = N.orient_new('E', (orienter2, )) F = N.orient_new('F', (orienter3, )) G = N.orient_new('G', (orienter4, )) assert D == N.orient_new_axis('D', q4, N.j) assert E == N.orient_new_space('E', q1, q2, q3, '123') assert F == N.orient_new_quaternion('F', q1, q2, q3, q4) assert G == N.orient_new_body('G', q1, q2, q3, '123') pytest.raises(TypeError, lambda: AxisOrienter(q4, 1)) def test_locatenew_point(): """ Tests Point class, and locate_new method in CoordSysCartesian. """ A = CoordSysCartesian('A') assert isinstance(A.origin, Point) v = a*A.i + b*A.j + c*A.k C = A.locate_new('C', v) pytest.raises(TypeError, lambda: C.origin.position_wrt(1)) assert C.origin.position_wrt(A) == \ C.position_wrt(A) == \ C.origin.position_wrt(A.origin) == v assert A.origin.position_wrt(C) == \ A.position_wrt(C) == \ A.origin.position_wrt(C.origin) == -v assert A.origin.express_coordinates(C) == (-a, -b, -c) p = A.origin.locate_new('p', -v) assert p.express_coordinates(A) == (-a, -b, -c) assert p.position_wrt(C.origin) == p.position_wrt(C) == \ -2 * v p1 = p.locate_new('p1', 2*v) assert p1.position_wrt(C.origin) == Vector.zero assert p1.express_coordinates(C) == (0, 0, 0) p2 = p.locate_new('p2', A.i) assert p1.position_wrt(p2) == 2*v - A.i assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c) def test_evalf(): A = CoordSysCartesian('A') v = 3*A.i + 4*A.j + a*A.k assert v.evalf(subs={a: 1}) == v.subs({a: 1}).evalf()
42.588757
112
0.508093
c0f3760f0421bbb257d7bfa19911419228d23909
1,032
py
Python
sdk/python/pulumi_azure_native/datashare/v20201001preview/_inputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
31
2020-09-21T09:41:01.000Z
2021-02-26T13:21:59.000Z
sdk/python/pulumi_azure_native/datashare/v20201001preview/_inputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
231
2020-09-21T09:38:45.000Z
2021-03-01T11:16:03.000Z
sdk/python/pulumi_azure_native/datashare/v20201001preview/_inputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
4
2020-09-29T14:14:59.000Z
2021-02-10T20:38:16.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from ._enums import * __all__ = [ 'IdentityArgs', ] @pulumi.input_type class IdentityArgs: def __init__(__self__, *, type: Optional[pulumi.Input[Union[str, 'Type']]] = None): """ Identity of resource :param pulumi.Input[Union[str, 'Type']] type: Identity Type """ if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[Union[str, 'Type']]]: """ Identity Type """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[Union[str, 'Type']]]): pulumi.set(self, "type", value)
25.8
80
0.618217
88fe6525acf254d98854ace41cd5411fef9580e1
3,272
py
Python
torch/ao/quantization/fx/backend_config_dict/utils.py
ZIZUN/pytorch
f565167fbdf607f3b0b95f077b11f2f78716c217
[ "Intel" ]
183
2018-04-06T21:10:36.000Z
2022-03-30T15:05:24.000Z
torch/ao/quantization/fx/backend_config_dict/utils.py
ZIZUN/pytorch
f565167fbdf607f3b0b95f077b11f2f78716c217
[ "Intel" ]
631
2018-06-05T16:59:11.000Z
2022-03-31T16:26:57.000Z
torch/ao/quantization/fx/backend_config_dict/utils.py
ZIZUN/pytorch
f565167fbdf607f3b0b95f077b11f2f78716c217
[ "Intel" ]
58
2018-06-05T16:40:18.000Z
2022-03-16T15:37:29.000Z
import torch import torch.nn as nn from .quantize_handler import get_quantize_handler_cls from .fuse_handler import get_fuse_handler_cls from typing import Dict, Any, List, Callable, Union from ..quantization_types import Pattern, QuantizerCls def get_pattern_to_quantize_handlers( backend_config_dict: Dict[str, Any]) -> Dict[Pattern, QuantizerCls]: """ Note: Quantize handler is just a holder for some check methods like (should_insert_observer_for_output), maybe this can be a enum as well, we can refactor this after we convert the path for fbgemm/qnnpack fully to the new path, this is not exposed to backend developers """ pattern_to_quantize_handlers = dict() for config in backend_config_dict["configs"]: pattern = config["pattern"] observation_type = config["observation_type"] dtype_configs = config["dtype_configs"] pattern_to_quantize_handlers[pattern] = \ get_quantize_handler_cls(observation_type, dtype_configs) return pattern_to_quantize_handlers def get_pattern_to_dtype_configs( backend_config_dict: Dict[str, Any]) -> Dict[Pattern, List[Dict[str, torch.dtype]]]: pattern_to_dtype_configs: Dict[Pattern, List[Dict[str, torch.dtype]]] = dict() for config in backend_config_dict["configs"]: pattern = config["pattern"] dtype_configs = config["dtype_configs"] pattern_to_dtype_configs[pattern] = dtype_configs return pattern_to_dtype_configs def get_pattern_to_input_type_to_index( backend_config_dict: Dict[str, Any]) -> Dict[Pattern, Dict[str, int]]: pattern_to_input_type_to_index: Dict[Pattern, Dict[str, int]] = dict() for config in backend_config_dict["configs"]: pattern = config["pattern"] input_type_to_index = config.get("input_type_to_index", {}) pattern_to_input_type_to_index[pattern] = input_type_to_index return pattern_to_input_type_to_index def get_quantized_reference_module_mapping( backend_config_dict: Dict[str, Any]) -> Dict[Callable, Callable]: mapping: Dict[Callable, Callable] = dict() for config in backend_config_dict["configs"]: if "root_module" in config and "reference_quantized_module_for_root" in config: mapping[config["root_module"]] = config["reference_quantized_module_for_root"] return mapping def get_fusion_pattern_to_fuse_handler_cls( backend_config_dict: Dict[str, Any]) -> Dict[Pattern, Callable]: fusion_pattern_to_fuse_handlers = dict() for config in backend_config_dict["configs"]: if "fuser_method" in config: pattern = config["pattern"] fusion_pattern_to_fuse_handlers[pattern] = \ get_fuse_handler_cls() return fusion_pattern_to_fuse_handlers def get_fuser_method_mapping( backend_config_dict: Dict[str, Any]) -> Dict[Pattern, Union[nn.Sequential, Callable]]: fuser_method_mapping : Dict[Pattern, Union[nn.Sequential, Callable]] = dict() for config in backend_config_dict["configs"]: if "fuser_method" in config: pattern = config["pattern"] fuser_method = config["fuser_method"] fuser_method_mapping[pattern] = fuser_method return fuser_method_mapping
44.821918
94
0.72555
f68dd0e281ee5df6ff744821331f48c353b73a22
4,050
py
Python
ScienceCruiseDataManagement/metadata/management/commands/updatedirectoryusage.py
Swiss-Polar-Institute/science-cruise-data-management
67721a0f4a1255b8ac43e530ed95a8c324239c7c
[ "MIT" ]
6
2017-10-06T09:18:04.000Z
2022-02-10T08:54:56.000Z
ScienceCruiseDataManagement/metadata/management/commands/updatedirectoryusage.py
Swiss-Polar-Institute/science-cruise-data-management
67721a0f4a1255b8ac43e530ed95a8c324239c7c
[ "MIT" ]
12
2020-02-27T09:24:50.000Z
2021-09-22T17:39:55.000Z
ScienceCruiseDataManagement/metadata/management/commands/updatedirectoryusage.py
Swiss-Polar-Institute/science-cruise-data-management
67721a0f4a1255b8ac43e530ed95a8c324239c7c
[ "MIT" ]
1
2017-10-16T13:49:33.000Z
2017-10-16T13:49:33.000Z
from django.core.management.base import BaseCommand, CommandError from metadata.models import MetadataEntry, Distribution from django.conf import settings import os # This file is part of https://github.com/cpina/science-cruise-data-management # # This project was programmed in a hurry without any prior Django experience, # while circumnavigating the Antarctic on the ACE expedition, without proper # Internet access, with 150 scientists using the system and doing at the same # cruise other data management and system administration tasks. # # Sadly there aren't unit tests and we didn't have time to refactor the code # during the cruise, which is really needed. # # Carles Pina (carles@pina.cat) and Jen Thomas (jenny_t152@yahoo.co.uk), 2016-2017. class Command(BaseCommand): help = 'Updates directory usage on the metadata entries.' def add_arguments(self, parser): parser.add_argument('metadata_id', type=str, help="Can be all for all the metadata") parser.add_argument('--dry-run', action='store_true', dest='dry_run', default=False, help="Skips updating the database and counting everything. Useful to find directories that don't exist.") def handle(self, *args, **options): metadata_id = options['metadata_id'] if metadata_id == "all": metadata_entries = MetadataEntry.objects.all().order_by("entry_id") else: metadata_entries = MetadataEntry.objects.filter(entry_id=metadata_id) for metadata_entry in metadata_entries: distribution_size = DistributionSizeUpdater(metadata_entry, options['dry_run']) distribution_size.do() class DistributionSizeUpdater: def __init__(self, metadata_entry, dry_run): self._metadata_entry = metadata_entry self._dry_run = dry_run def do(self): print("Will start processing:", self._metadata_entry.entry_id) if self._metadata_entry.skip_update_distribution_size: print("Skips {} - see skip_update_distribution_size") return files = self._files_for_metadata_entry(self._metadata_entry) size = self.calculate_size(files) print("Total size: {:.2f} GB".format(size/1024/1024/1024)) for distribution in Distribution.objects.filter(metadata_entry=self._metadata_entry): distribution.distribution_size = size if not self._dry_run: distribution.save() def calculate_size(self, files): size = 0 for file in files: s = os.stat(file) size += s.st_size return size @staticmethod def absolute_directory(directory): if directory.path_storage is None: data_root = "/mnt/ace_data" else: data_root = directory.path_storage if directory.source_directory.endswith("/"): return os.path.join(data_root, directory.destination_directory) else: source = directory.source_directory.split("/")[-1] return os.path.join(data_root, directory.destination_directory, source) def _files_for_metadata_entry(self, metadata_entry): files = set() for directory in metadata_entry.directories(): absolute_path = self.absolute_directory(directory) print("Processing: {} (DirectoryID: {})".format(absolute_path, directory.id)) if not os.path.exists(absolute_path): print("** Path: {} doesn't exist. Skipping".format(absolute_path)) continue if not self._dry_run: for (dirpath, dirnames, filenames) in os.walk(self.absolute_directory(directory)): for filename in filenames: absolute_path_file = os.path.join(dirpath, filename) files.add(absolute_path_file) return files
39.320388
133
0.644938